{"text": "```python\nfrom IPython.core.display import display_html\nfrom urllib.request import urlopen\n\ncssurl = 'http://j.mp/1DnuN9M'\ndisplay_html(urlopen(cssurl).read(), raw=True)\n```\n\n\n\n\n\n\n\n\n\n\n# Tarea 5 - Demostración de la formula de Euler\n\nLa formula de Euler es:\n\n$$\ne^{ix} = \\cos{x} + i \\sin{x}\n$$\n\n# Tarea 6 - Determinación de las $D$-particiones del espacio de parametros\n\nDado el sistema:\n\n$$\n\\dot{x}(t) = a x(t) + b x(t - h)\n$$\n\nempezamos por obtener la transformada de Laplace del sistema, lo cual nos dará el siguiente cuasipolinomio caracteristico:\n\n$$\np(s) = s - a - b e^{-h s} = 0\n$$\n\nPara determinar los puntos en que nuestro polinomio caracterisitico tiene polos en el eje imaginario, es decir las fronteras en que los parametros dejan de definir a un sistema estable y comienzan a definir un sistema inestable, vamos a sustitur los valores $s = 0$ y $s = j \\omega$, que son los valores que caracterizan al eje imaginario.\n\nEmpezamos sustituyendo $s = 0$, por lo que obtenemos:\n\n$$\np(0) = -a - b = 0 \\implies a = -b\n$$\n\nSi ahora sustituimos $s = j \\omega$, tendremos:\n\n$$\n\\begin{align}\np(j \\omega) &= j \\omega - a - b e^{- h j \\omega} \\\\\n&= j \\omega - a - b \\left( \\cos{(\\omega h)} -j \\sin{(\\omega h)} \\right) \\\\\n&= j \\omega - a - b \\cos{(\\omega h)} + b j \\sin{(\\omega h)}\n\\end{align}\n$$\n\nde donde podemos separar la parte real de la imaginaria y obtener:\n\n$$\n\\omega + b \\sin{(\\omega h)} = 0\n$$\n\ny\n\n$$\n-a -b \\cos{(\\omega h)} = 0\n$$\n\nAqui podemos obtener una relación para $\\sin{(\\omega h)}$ y $\\cos{(\\omega h)}$:\n\n$$\n- \\omega = b \\sin{(\\omega h)} \\implies \\cos{(\\omega h)} = - \\frac{a}{b}\n$$\n\n$$\n\\omega = - b \\sin{(\\omega h)} \\implies \\sin{(\\omega h)} = - \\frac{\\omega}{b}\n$$\n\ny sabemos que $\\sin^2{(\\omega h)} + \\cos^2{(\\omega h)} = 1$, por lo que podemos sustituir los valores que obtuvimos y tenemos que:\n\n$$\n\\left( - \\frac{\\omega}{b} \\right)^2 + \\left( - \\frac{a}{b} \\right)^2 = 1 = \\frac{\\omega^2 + a^2}{b^2}\n$$\n\ndespejando $\\omega^2$ y sacando raiz cuadrada obtenemos:\n\n$$\n\\omega^2 + a^2 = b^2\n$$\n\n$$\n\\omega^2 = b^2 - a^2\n$$\n\n$$\n\\omega = \\sqrt{b^2 - a^2}\n$$\n\nal sustituir en la ecuación obtenida de la parte real del cuasipolinomio, obtenemos:\n\n$$\n-a -b \\cos{(\\sqrt{b^2 - a^2} h)} = 0\n$$\n\no bien:\n\n$$\na + b \\cos{(\\sqrt{b^2 - a^2} h)} = 0\n$$\n\nEsta es la relación entre $a$ y $b$ que nos dará las curvas de las $D$-particiones del espacio de parametros\n\n# Tarea 7 - Gráfica de las $D$-particiones del espacio de parametros\n\nSi bien las relaciones obtenidas son convenientes para su análisis, el graficarla por medio de software proporciona problemas, ya que sus variables no se pueden separar para obtener una en función de la otra, por lo que retrocederemos un poco y utilizaremos las relaciones obtenidas de separar las partes real e imaginaria del cuasipolinomio como ecuaciones parametricas para $a$ y $b$.\n\nEmpezamos obteniendo los valores para $a$ y $b$ en función de $\\omega$:\n\n$$\n\\omega + b \\sin{(\\omega h)} = 0 \\implies b = - \\frac{\\omega}{\\sin{(\\omega h)}}\n$$\n\n$$\n- a - b \\cos{(\\omega h)} = 0 \\implies a = - b \\cos{(\\omega h)} = + \\frac{\\omega}{\\sin{(\\omega h)}} \\cos{(\\omega h)} = \\frac{\\omega}{\\tan{(\\omega h)}}\n$$\n\nPor lo que procedemos a capturar estas funciones en el programa, primero importamos las librerias que necesitamos para calcular y graficar:\n\n\n```python\n# Se importan librerias para graficar, y se define un estilo especifico\n%matplotlib inline\nfrom matplotlib.pyplot import plot, style, figure, legend\nstyle.use(\"ggplot\")\n```\n\n\n```python\n# Se importan funciones de calculo numerico a utilizar\nfrom numpy import linspace, tan, sin, pi\n```\n\nAhora definimos las funciones que hemos obtenido:\n\n\n```python\na = lambda om, h: -om/sin(om*h)\nb = lambda om, h: om/tan(om*h)\nf1 = lambda x: -x\n```\n\nEsta notación es equivalente a las definiciones matematicas:\n\n$$\na(\\omega, h) := - \\frac{\\omega}{\\sin{(\\omega h)}}\n$$\n\n$$\nb(\\omega, h) := \\frac{\\omega}{\\tan{(\\omega h)}}\n$$\n\n$$\nf_1(x) := -x\n$$\n\nAhora definimos valores para $\\omega$ y $b$ para ingresar en estas funciones:\n\n\n```python\ntau = 2*pi\nw = linspace(-3*tau, 3*tau, 1000)\nbs = linspace(-15, 15, 100)\n```\n\nLo que equivale a decir que variaremos $\\omega$ en el intervalo $[-3 \\tau, 3 \\tau] = [-6 \\pi, 6 \\pi]$ y a $b$ en $[-15, 15]$.\n\nAhora graficamos $a$ contra $b$ con las funciones parametricas obtenidas y $x$ contra $f_1(x)$:\n\n\n```python\nf = figure(figsize = (10, 10))\np1, = plot(b(w, 1), a(w, 1), \".\")\np2, = plot(bs, f1(bs), \".\")\n\nax = f.gca()\nax.set_ylabel(r\"$a(\\omega)$\", fontsize=20)\nax.set_xlabel(r\"$b(\\omega)$\", fontsize=20)\nax.set_xlim(-15, 15)\nax.set_ylim(-15, 15)\n\nlegend([p1, p2], [r\"$a + b \\cos{(\\sqrt{b^2 - a^2} h)} = 0$\", r\"$a + b = 0$\"]);\n```\n\n# Tarea 8 - Teorema de la función implicita\n\nPuedes acceder a este notebook a traves de la página\n\nhttp://bit.ly/1xvpRgo\n\no escaneando el siguiente código:\n\n\n\n\n```python\n# Codigo para generar codigo :)\nfrom qrcode import make\nimg = make(\"http://bit.ly/1xvpRgo\")\nimg.save(\"codigos/codigo5678.jpg\")\n```\n", "meta": {"hexsha": "d35c49016a01c84c483fb4600af2eaf9aadf34a2", "size": 39984, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPythonNotebooks/Sistemas con retardo en la entrada/Tareas 5, 6, 7, 8.ipynb", "max_stars_repo_name": "robblack007/DCA", "max_stars_repo_head_hexsha": "0ea5f8b613e2dabe1127b857c7bfe9be64c52d20", "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": "IPythonNotebooks/Sistemas con retardo en la entrada/Tareas 5, 6, 7, 8.ipynb", "max_issues_repo_name": "robblack007/DCA", "max_issues_repo_head_hexsha": "0ea5f8b613e2dabe1127b857c7bfe9be64c52d20", "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": "IPythonNotebooks/Sistemas con retardo en la entrada/Tareas 5, 6, 7, 8.ipynb", "max_forks_repo_name": "robblack007/DCA", "max_forks_repo_head_hexsha": "0ea5f8b613e2dabe1127b857c7bfe9be64c52d20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:44:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-20T12:44:13.000Z", "avg_line_length": 88.6563192905, "max_line_length": 27016, "alphanum_fraction": 0.7953431373, "converted": true, "num_tokens": 2394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.2254166158350767, "lm_q1q2_score": 0.09956043424262655}} {"text": "
\n\n\n\n\n\n| Software | Version |
|---|---|
| Python | 3.5.2 64bit [MSC v.1900 64 bit (AMD64)] |
| IPython | 5.1.0 |
| OS | Windows 10 10.0.10586 SP0 |
| numpy | 1.11.1 |
| scipy | 0.18.0 |
| matplotlib | 1.5.3 |
| sympy | 1.0 |
| pandas | 0.18.1 |
| ipython | 5.1.0 |
| jupyter | 1.0.0 |
| Thu Sep 22 01:04:43 2016 E. South America Standard Time | |
\n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n\n**Result:**\n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n**Now it's your turn to have some Markdown fun.** In the next cell, try out some of the commands. You can just throw in some things, or do something more structured (like a small notebook).\n\n___some markdown here___\n\n### Problem 2. Formulas and LaTeX\nWriting math formulas has always been hard. But scientists don't like difficulties and prefer standards. So, thanks to Donald Knuth (a very popular computer scientist, who also invented a lot of algorithms), we have a nice typesetting system, called LaTeX (pronounced _lah_-tek). We'll be using it mostly for math formulas, but it has a lot of other things to offer.\n\nThere are two main ways to write formulas. You could enclose them in single `$` signs like this: `$ ax + b $`, which will create an **inline formula**: $ ax + b $. You can also enclose them in double `$` signs `$$ ax + b $$` to produce $$ ax + b $$.\n\nMost commands start with a backslash and accept parameters either in square brackets `[]` or in curly braces `{}`. For example, to make a fraction, you typically would write `$$ \\frac{a}{b} $$`: $$ \\frac{a}{b} $$.\n\n[Here's a resource](http://www.stat.pitt.edu/stoffer/freetex/latex%20basics.pdf) where you can look up the basics of the math syntax. You can also search StackOverflow - there are all sorts of solutions there.\n\nYou're on your own now. Research and recreate all formulas shown in the next cell. Try to make your cell look exactly the same as mine. It's an image, so don't try to cheat by copy/pasting :D.\n\nNote that you **do not** need to understand the formulas, what's written there or what it means. We'll have fun with these later in the course.\n\n\n\n$$ y = ax + b $$\n\n$$ ax^2 + bx + c = 0 $$\n\n$$ x_{1,2}= \\frac{-b \\pm\\sqrt{b^2 - 4ac}}{2a} $$\n\n\\begin{equation}\nf(x)|_{x=a} = f(a) + f\\prime(a)(x-a) + \\frac{f^n(a)}{2!}(x-a)^2 + ... + \\frac{f^n(a)}{n!}(x-a)^n + ...\n\\end{equation}\n\n\\begin{equation}\n(x + y)^n = {n\\choose 0}x^ny^0 + {n\\choose 1}x^{n-1}y^1 + ... + {n\\choose n}x^0y^n = \\sum_{k=0}^{n} {n\\choose k}x^{n-k}y^k\n\\end{equation}\n\n\\begin{equation}\n\\int_{-\\infty}^{+\\infty} e^{-x^2}dx = \\sqrt{\\pi}\n\\end{equation}\n\n\\begin{equation}\n\\left( \\begin{array}{ccc}\n2 & 1 & 3 \\\\\n2 & 6 & 8 \\\\\n6 & 8 & 18 \\end{array} \\right)\n\\end{equation}\n\n\\begin{equation}\nA = \\begin{pmatrix} \n a_{11} & a_{12} & \\dots & a_{1n} \\\\ \n a_{21} & a_{22} & \\dots & a_{2n} \\\\ \n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m1} & \\dots & a_{mn} \n \\end{pmatrix}\n\\end{equation}\n\n
Write your formulas here.
\n\n### Problem 3. Solving with Python\nLet's first do some symbolic computation. We need to import `sympy` first. \n\n**Should your imports be in a single cell at the top or should they appear as they are used?** There's not a single valid best practice. Most people seem to prefer imports at the top of the file though. **Note: If you write new code in a cell, you have to re-execute it!**\n\nLet's use `sympy` to give us a quick symbolic solution to our equation. First import `sympy` (you can use the second cell in this notebook): \n```python \nimport sympy \n```\n\nNext, create symbols for all variables and parameters. You may prefer to do this in one pass or separately:\n```python \nx = sympy.symbols('x')\na, b, c = sympy.symbols('a b c')\n```\n\nNow solve:\n```python \nsympy.solve(a * x**2 + b * x + c)\n```\n\nHmmmm... we didn't expect that :(. We got an expression for $a$ because the library tried to solve for the first symbol it saw. This is an equation and we have to solve for $x$. We can provide it as a second paramter:\n```python \nsympy.solve(a * x**2 + b * x + c, x)\n```\n\nFinally, if we use `sympy.init_printing()`, we'll get a LaTeX-formatted result instead of a typed one. This is very useful because it produces better-looking formulas.\n\n\n```python\nx = sympy.symbols('x')\na, b, c = sympy.symbols('a b c')\n\nsympy.solve(a * x**2 + b * x + c)\n\nsympy.init_printing()\n\na = 5\n```\n\nHow about a function that takes $a, b, c$ (assume they are real numbers, you don't need to do additional checks on them) and returns the **real** roots of the quadratic equation?\n\nRemember that in order to calculate the roots, we first need to see whether the expression under the square root sign is non-negative.\n\nIf $b^2 - 4ac > 0$, the equation has two real roots: $x_1, x_2$\n\nIf $b^2 - 4ac = 0$, the equation has one real root: $x_1 = x_2$\n\nIf $b^2 - 4ac < 0$, the equation has zero real roots\n\nWrite a function which returns the roots. In the first case, return a list of 2 numbers: `[2, 3]`. In the second case, return a list of only one number: `[2]`. In the third case, return an empty list: `[]`.\n\n\n```python\n\ndef solve_quadratic_equation(a, b, c):\n \"\"\"\n Returns the real solutions of the quadratic equation ax^2 + bx + c = 0\n \"\"\"\n if a == 0:\n if b == 0:\n return math.nan\n elif c == 0:\n return b\n else:\n return -c / b\n else:\n d = b**2-4*a*c\n answer = []\n if d > 0:\n answer.append((-b - math.sqrt(d)) / (2*a))\n answer.append((-b + math.sqrt(d)) / (2*a))\n elif d == 0:\n answer.append(-b / (2*a))\n return answer\n```\n\n\n```python\n# Testing: Execute this cell. The outputs should match the expected outputs. Feel free to write more tests\nprint(solve_quadratic_equation(1, -1, -2)) # [-1.0, 2.0]\nprint(solve_quadratic_equation(1, -8, 16)) # [4.0]\nprint(solve_quadratic_equation(1, 1, 1)) # []\n```\n\n [-1.0, 2.0]\n [4.0]\n []\n\n\n**Bonus:** Last time we saw how to solve a linear equation. Remember that linear equations are just like quadratic equations with $a = 0$. In this case, however, division by 0 will throw an error. Extend your function above to support solving linear equations (in the same way we did it last time).\n\n### Problem 4. Equation of a Line\nLet's go back to our linear equations and systems. There are many ways to define what \"linear\" means, but they all boil down to the same thing.\n\nThe equation $ax + b = 0$ is called *linear* because the function $f(x) = ax+b$ is a linear function. We know that there are several ways to know what one particular function means. One of them is to just write the expression for it, as we did above. Another way is to **plot** it. This is one of the most exciting parts of maths and science - when we have to fiddle around with beautiful plots (although not so beautiful in this case).\n\nThe function produces a straight line and we can see it.\n\nHow do we plot functions in general? Ww know that functions take many (possibly infinitely many) inputs. We can't draw all of them. We could, however, evaluate the function at some points and connect them with tiny straight lines. If the points are too many, we won't notice - the plot will look smooth.\n\nNow, let's take a function, e.g. $y = 2x + 3$ and plot it. For this, we're going to use `numpy` arrays. This is a special type of array which has two characteristics:\n* All elements in it must be of the same type\n* All operations are **broadcast**: if `x = [1, 2, 3, 10]` and we write `2 * x`, we'll get `[2, 4, 6, 20]`. That is, all operations are performed at all indices. This is very powerful, easy to use and saves us A LOT of looping.\n\nThere's one more thing: it's blazingly fast because all computations are done in C, instead of Python.\n\nFirst let's import `numpy`. Since the name is a bit long, a common convention is to give it an **alias**:\n```python\nimport numpy as np\n```\n\nImport that at the top cell and don't forget to re-run it.\n\nNext, let's create a range of values, e.g. $[-3, 5]$. There are two ways to do this. `np.arange(start, stop, step)` will give us evenly spaced numbers with a given step, while `np.linspace(start, stop, num)` will give us `num` samples. You see, one uses a fixed step, the other uses a number of points to return. When plotting functions, we usually use the latter. Let's generate, say, 1000 points (we know a straight line only needs two but we're generalizing the concept of plotting here :)).\n```python\nx = np.linspace(-3, 5, 1000)\n```\nNow, let's generate our function variable\n```python\ny = 2 * x + 3\n```\n\nWe can print the values if we like but we're more interested in plotting them. To do this, first let's import a plotting library. `matplotlib` is the most commnly used one and we usually give it an alias as well.\n```python\nimport matplotlib.pyplot as plt\n```\n\nNow, let's plot the values. To do this, we just call the `plot()` function. Notice that the top-most part of this notebook contains a \"magic string\": `%matplotlib inline`. This hints Jupyter to display all plots inside the notebook. However, it's a good practice to call `show()` after our plot is ready.\n```python\nplt.plot(x, y)\nplt.show()\n```\n\n\n```python\nx = np.linspace(-3, 5, 1000)\ny = 2 * x + 3\nplt.plot(x, y)\nplt.show()\n```\n\nIt doesn't look too bad bit we can do much better. See how the axes don't look like they should? Let's move them to zeto. This can be done using the \"spines\" of the plot (i.e. the borders).\n\nAll `matplotlib` figures can have many plots (subfigures) inside them. That's why when performing an operation, we have to specify a target figure. There is a default one and we can get it by using `plt.gca()`. We usually call it `ax` for \"axis\".\nLet's save it in a variable (in order to prevent multiple calculations and to make code prettier). Let's now move the bottom and left spines to the origin $(0, 0)$ and hide the top and right one.\n```python\nax = plt.gca()\nax.spines[\"bottom\"].set_position(\"zero\")\nax.spines[\"left\"].set_position(\"zero\")\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n```\n\n**Note:** All plot manipulations HAVE TO be done before calling `show()`. It's up to you whether they should be before or after the function you're plotting.\n\nThis should look better now. We can, of course, do much better (e.g. remove the double 0 at the origin and replace it with a single one), but this is left as an exercise for the reader :).\n\n\n```python\nx = np.linspace(-3, 5, 1000)\ny = 2 * x + 3\nplt.plot(x, y)\nax = plt.gca()\nax.spines[\"bottom\"].set_position(\"zero\")\nax.spines[\"left\"].set_position(\"zero\")\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nplt.show()\n```\n\n### * Problem 5. Linearizing Functions\nWhy is the line equation so useful? The main reason is because it's so easy to work with. Scientists actually try their best to linearize functions, that is, to make linear functions from non-linear ones. There are several ways of doing this. One of them involves derivatives and we'll talk about it later in the course. \n\nA commonly used method for linearizing functions is through algebraic transformations. Try to linearize \n$$ y = ae^{bx} $$\n\nHint: The inverse operation of $e^{x}$ is $\\ln(x)$. Start by taking $\\ln$ of both sides and see what you can do. Your goal is to transform the function into another, linear function. You can look up more hints on the Internet :).\n\n$$ ln(y) = ln(a e^{bx}) $$\n\n$$ ln(y) = ln(a) + ln(e^{bx}) $$\n\n$$ ln(y) = ln(a) + bx $$\n\n### * Problem 6. Generalizing the Plotting Function\nLet's now use the power of Python to generalize the code we created to plot. In Python, you can pass functions as parameters to other functions. We'll utilize this to pass the math function that we're going to plot.\n\nNote: We can also pass *lambda expressions* (anonymous functions) like this: \n```python\nlambda x: x + 2```\nThis is a shorter way to write\n```python\ndef some_anonymous_function(x):\n return x + 2\n```\n\nWe'll also need a range of x values. We may also provide other optional parameters which will help set up our plot. These may include titles, legends, colors, fonts, etc. Let's stick to the basics now.\n\nWrite a Python function which takes another function, x range and number of points, and plots the function graph by evaluating it at every point.\n\n**BIG hint:** If you want to use not only `numpy` functions for `f` but any one function, a very useful (and easy) thing to do, is to vectorize the function `f` (e.g. to allow it to be used with `numpy` broadcasting):\n```python\nf_vectorized = np.vectorize(f)\ny = f_vectorized(x)\n```\n\n\n```python\ndef plot_math_function(f, min_x, max_x, num_points):\n xpts = np.linspace(min_x, max_x, num_points) \n plt.plot(xpts, [f(x) for x in xpts])\n ax = plt.gca()\n ax.spines[\"bottom\"].set_position(\"zero\")\n ax.spines[\"left\"].set_position(\"zero\")\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n plt.show()\n```\n\n\n```python\nplot_math_function(lambda x: 2 * x + 3, -3, 5, 1000)\nplot_math_function(lambda x: -x + 8, -1, 10, 1000)\nplot_math_function(lambda x: x**2 - x - 2, -3, 4, 1000)\nplot_math_function(lambda x: np.sin(x), -np.pi, np.pi, 1000)\nplot_math_function(lambda x: np.sin(x) / x, -4 * np.pi, 4 * np.pi, 1000)\n```\n\n### * Problem 7. Solving Equations Graphically\nNow that we have a general plotting function, we can use it for more interesting things. Sometimes we don't need to know what the exact solution is, just to see where it lies. We can do this by plotting the two functions around the \"=\" sign ans seeing where they intersect. Take, for example, the equation $2x + 3 = 0$. The two functions are $f(x) = 2x + 3$ and $g(x) = 0$. Since they should be equal, the point of their intersection is the solution of the given equation. We don't need to bother marking the point of intersection right now, just showing the functions.\n\nTo do this, we'll need to improve our plotting function yet once. This time we'll need to take multiple functions and plot them all on the same graph. Note that we still need to provide the $[x_{min}; x_{max}]$ range and it's going to be the same for all functions.\n\n```python\nvectorized_fs = [np.vectorize(f) for f in functions]\nys = [vectorized_f(x) for vectorized_f in vectorized_fs]\n```\n\n\n```python\ndef plot_math_functions(functions, min_x, max_x, num_points): \n xpts = np.linspace(min_x, max_x, num_points) \n vectorized_fs = [np.vectorize(f) for f in functions]\n ys = [vectorized_f(xpts) for vectorized_f in vectorized_fs]\n for f in ys:\n plt.plot(xpts, f)\n ax = plt.gca()\n ax.spines[\"bottom\"].set_position(\"zero\")\n ax.spines[\"left\"].set_position(\"zero\")\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n plt.show()\n```\n\n\n```python\nplot_math_functions([lambda x: 2 * x + 3, lambda x: 0], -3, 5, 1000)\nplot_math_functions([lambda x: 3 * x**2 - 2 * x + 5, lambda x: 3 * x + 7], -2, 3, 1000)\n```\n\nThis is also a way to plot the solutions of systems of equation, like the one we solved last time. Let's actually try it.\n\n\n```python\nplot_math_functions([lambda x: (-4 * x + 7) / 3, lambda x: (-3 * x + 8) / 5, lambda x: (-x - 1) / -2], -1, 4, 1000)\n```\n\n### Problem 8. Trigonometric Functions\nWe already saw the graph of the function $y = \\sin(x)$. But, how do we define the trigonometric functions once again? Let's quickly review that.\n\n\n\nThe two basic trigonometric functions are defined as the ratio of two sides:\n$$ \\sin(x) = \\frac{\\text{opposite}}{\\text{hypotenuse}} $$\n$$ \\cos(x) = \\frac{\\text{adjacent}}{\\text{hypotenuse}} $$\n\nAnd also:\n$$ \\tan(x) = \\frac{\\text{opposite}}{\\text{adjacent}} = \\frac{\\sin(x)}{\\cos(x)} $$\n$$ \\cot(x) = \\frac{\\text{adjacent}}{\\text{opposite}} = \\frac{\\cos(x)}{\\sin(x)} $$\n\nThis is fine, but using this, \"right-triangle\" definition, we're able to calculate the trigonometric functions of angles up to $90^\\circ$. But we can do better. Let's now imagine a circle centered at the origin of the coordinate system, with radius $r = 1$. This is called a \"unit circle\".\n\n\n\nWe can now see exactly the same picture. The $x$-coordinate of the point in the circle corresponds to $\\cos(\\alpha)$ and the $y$-coordinate - to $\\sin(\\alpha)$. What did we get? We're now able to define the trigonometric functions for all degrees up to $360^\\circ$. After that, the same values repeat: these functions are **periodic**: \n$$ \\sin(k.360^\\circ + \\alpha) = \\sin(\\alpha), k = 0, 1, 2, \\dots $$\n$$ \\cos(k.360^\\circ + \\alpha) = \\cos(\\alpha), k = 0, 1, 2, \\dots $$\n\nWe can, of course, use this picture to derive other identities, such as:\n$$ \\sin(90^\\circ + \\alpha) = \\cos(\\alpha) $$\n\nA very important property of the sine and cosine is that they accept values in the range $(-\\infty; \\infty)$ and produce values in the range $[-1; 1]$. The two other functions take values in the range $(-\\infty; \\infty)$ **except when their denominators are zero** and produce values in the same range. \n\n#### Radians\nA degree is a geometric object, $1/360$th of a full circle. This is quite inconvenient when we work with angles. There is another, natural and intrinsic measure of angles. It's called the **radian** and can be written as $\\text{rad}$ or without any designation, so $\\sin(2)$ means \"sine of two radians\".\n\n\nIt's defined as *the central angle of an arc with length equal to the circle's radius* and $1\\text{rad} \\approx 57.296^\\circ$.\n\nWe know that the circle circumference is $C = 2\\pi r$, therefore we can fit exactly $2\\pi$ arcs with length $r$ in $C$. The angle corresponding to this is $360^\\circ$ or $2\\pi\\ \\text{rad}$. Also, $\\pi rad = 180^\\circ$.\n\n(Some people prefer using $\\tau = 2\\pi$ to avoid confusion with always multiplying by 2 or 0.5 but we'll use the standard notation here.)\n\n**NOTE:** All trigonometric functions in `math` and `numpy` accept radians as arguments. In order to convert between radians and degrees, you can use the relations $\\text{[deg]} = 180/\\pi.\\text{[rad]}, \\text{[rad]} = \\pi/180.\\text{[deg]}$. This can be done using `np.deg2rad()` and `np.rad2deg()` respectively.\n\n#### Inverse trigonometric functions\nAll trigonometric functions have their inverses. If you plug in, say $\\pi/4$ in the $\\sin(x)$ function, you get $\\sqrt{2}/2$. The inverse functions (also called, arc-functions) take arguments in the interval $[-1; 1]$ and return the angle that they correspond to. Take arcsine for example:\n$$ \\arcsin(y) = x: sin(y) = x $$\n$$ \\arcsin\\left(\\frac{\\sqrt{2}}{2}\\right) = \\frac{\\pi}{4} $$\n\nPlease note that this is NOT entirely correct. From the relations we found:\n$$\\sin(x) = sin(2k\\pi + x), k = 0, 1, 2, \\dots $$\n\nit follows that $\\arcsin(x)$ has infinitely many values, separated by $2k\\pi$ radians each:\n$$ \\arcsin\\left(\\frac{\\sqrt{2}}{2}\\right) = \\frac{\\pi}{4} + 2k\\pi, k = 0, 1, 2, \\dots $$\n\nIn most cases, however, we're interested in the first value (when $k = 0$). It's called the **principal value**.\n\nNote 1: There are inverse functions for all four basic trigonometric functions: $\\arcsin$, $\\arccos$, $\\arctan$, $\\text{arccot}$. These are sometimes written as $\\sin^{-1}(x)$, $cos^{-1}(x)$, etc. These definitions are completely equivalent. \n\nJust notice the difference between $\\sin^{-1}(x) := \\arcsin(x)$ and $\\sin(x^{-1}) = \\sin(1/x)$.\n\n#### Exercise\nUse the plotting function you wrote above to plot the inverse trigonometric functions. Use `numpy` (look up how to use inverse trigonometric functions).\n\n\n```python\ndef plot_math_functions(min_x, max_x, num_points): \n xpts = np.linspace(min_x, max_x)\n plt.plot(xpts, np.arcsin(xpts))\n plt.plot(xpts, np.arccos(xpts))\n plt.plot(xpts, np.arctan(xpts))\n# plt.plot(xpts, np.arccos(xpts) / np.arcsin(xpts))\n ax = plt.gca()\n ax.spines[\"bottom\"].set_position(\"zero\")\n ax.spines[\"left\"].set_position(\"zero\")\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n plt.show()\nplot_math_functions(1, -1, 20)\n```\n\n### ** Problem 9. Perlin Noise\nThis algorithm has many applications in computer graphics and can serve to demonstrate several things... and help us learn about math, algorithms and Python :).\n#### Noise\nNoise is just random values. We can generate noise by just calling a random generator. Note that these are actually called *pseudorandom generators*. We'll talk about this later in this course.\nWe can generate noise in however many dimensions we want. For example, if we want to generate a single dimension, we just pick N random values and call it a day. If we want to generate a 2D noise space, we can take an approach which is similar to what we already did with `np.meshgrid()`.\n\n$$ \\text{noise}(x, y) = N, N \\in [n_{min}, n_{max}] $$\n\nThis function takes two coordinates and returns a single number N between $n_{min}$ and $n_{max}$. (This is what we call a \"scalar field\").\n\nRandom variables are always connected to **distributions**. We'll talk about these a great deal but now let's just say that these define what our noise will look like. In the most basic case, we can have \"uniform noise\" - that is, each point in our little noise space $[n_{min}, n_{max}]$ will have an equal chance (probability) of being selected.\n\n#### Perlin noise\nThere are many more distributions but right now we'll want to have a look at a particular one. **Perlin noise** is a kind of noise which looks smooth. It looks cool, especially if it's colored. The output may be tweaked to look like clouds, fire, etc. 3D Perlin noise is most widely used to generate random terrain.\n\n#### Algorithm\n... Now you're on your own :). Research how the algorithm is implemented (note that this will require that you understand some other basic concepts like vectors and gradients).\n\n#### Your task\n1. Research about the problem. See what articles, papers, Python notebooks, demos, etc. other people have created\n2. Create a new notebook and document your findings. Include any assumptions, models, formulas, etc. that you're using\n3. Implement the algorithm. Try not to copy others' work, rather try to do it on your own using the model you've created\n4. Test and improve the algorithm\n5. (Optional) Create a cool demo :), e.g. using Perlin noise to simulate clouds. You can even do an animation (hint: you'll need gradients not only in space but also in time)\n6. Communicate the results (e.g. in the Softuni forum)\n\nHint: [This](http://flafla2.github.io/2014/08/09/perlinnoise.html) is a very good resource. It can show you both how to organize your notebook (which is important) and how to implement the algorithm.\n", "meta": {"hexsha": "61c2b2a523f30e24a88fb1e6569a9ea003d2b973", "size": 203540, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MathConcepts/a_highSchollMath/High-School Maths Exercise.ipynb", "max_stars_repo_name": "KaPrimov/ai-module", "max_stars_repo_head_hexsha": "d0a40482830085ddf020aa5dece88b791699325f", "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": "MathConcepts/a_highSchollMath/High-School Maths Exercise.ipynb", "max_issues_repo_name": "KaPrimov/ai-module", "max_issues_repo_head_hexsha": "d0a40482830085ddf020aa5dece88b791699325f", "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": "MathConcepts/a_highSchollMath/High-School Maths Exercise.ipynb", "max_forks_repo_name": "KaPrimov/ai-module", "max_forks_repo_head_hexsha": "d0a40482830085ddf020aa5dece88b791699325f", "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": 220.9989142237, "max_line_length": 18206, "alphanum_fraction": 0.8849906652, "converted": true, "num_tokens": 7761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.09854479298915515}} {"text": "```python\nfrom IPython.display import Image\nImage('../../Python_probability_statistics_machine_learning_2E.png',width=200)\n```\n\nWe considered Maximum Likelihood Estimation (MLE) and Maximum A-Posteriori\n(MAP)\nestimation and in each case we started out with a probability density\nfunction\nof some kind and we further assumed that the samples were identically\ndistributed and independent (iid). The idea behind robust statistics\n[[maronna2006robust]](#maronna2006robust) is to construct estimators that can\nsurvive the\nweakening of either or both of these assumptions. More concretely,\nsuppose you\nhave a model that works great except for a few outliers. The\ntemptation is to\njust ignore the outliers and proceed. Robust estimation methods\nprovide a\ndisciplined way to handle outliers without cherry-picking data that\nworks for\nyour favored model.\n\n### The Notion of Location\n\nThe first notion we\nneed is *location*, which is a generalization of the idea\nof *central value*.\nTypically, we just use an estimate of the mean for this,\nbut we will see later\nwhy this could be a bad idea. The general idea of\nlocation satisfies the\nfollowing requirements Let $X$ be a random variable with\ndistribution $F$, and\nlet $\\theta(X)$ be some descriptive measure of $F$. Then\n$\\theta(X)$ is said to\nbe a measure of *location* if for any constants *a* and\n*b*, we have the\nfollowing:\n\n\n\n\n$$\n\\begin{equation}\n\\theta(X+b) = \\theta(X) +b \n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\n\n\n\n$$\n\\begin{equation} \\\n\\theta(-X) = -\\theta(X) \n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\n\n\n\n$$\n\\begin{equation} \\\nX \\ge 0 \\Rightarrow \\theta(X) \\ge 0 \n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\n\n\n\n$$\n\\begin{equation} \\\n\\theta(a X) = a\\theta(X)\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\n The first condition is called *location equivariance* (or *shift-invariance* in\nsignal processing lingo). The fourth condition is called *scale equivariance*,\nwhich means that the units that $X$ is measured in should not effect the value\nof the location estimator. These requirements capture the intuition of\n*centrality* of a distribution, or where most of the\nprobability mass is\nlocated.\n\nFor example, the sample mean estimator is $ \\hat{\\mu}=\\frac{1}{n}\\sum\nX_i $. The first\nrequirement is obviously satisfied as $\n\\hat{\\mu}=\\frac{1}{n}\\sum (X_i+b) = b +\n\\frac{1}{n}\\sum X_i =b+\\hat{\\mu}$. Let\nus consider the second requirement:$\n\\hat{\\mu}=\\frac{1}{n}\\sum -X_i =\n-\\hat{\\mu}$. Finally, the last requirement is\nsatisfied with $\n\\hat{\\mu}=\\frac{1}{n}\\sum a X_i =a \\hat{\\mu}$.\n\n### Robust Estimation and Contamination\n\nNow that we have the generalized location of centrality embodied\nin the\n*location* parameter, what can we do with it? Previously, we assumed\nthat our samples\nwere all identically distributed. The key idea is that the\nsamples might be\nactually coming from a *single* distribution that is\ncontaminated by another nearby\ndistribution, as in the following:\n\n$$\nF(X) = \\epsilon G(X) + (1-\\epsilon)H(X)\n$$\n\n where $ \\epsilon $ randomly toggles between zero and one. This means\nthat our\ndata samples $\\lbrace X_i \\rbrace$ actually derived from two separate\ndistributions, $ G(X) $ and $ H(X) $. We just don't know how they are mixed\ntogether. What we really want is an estimator that captures the location of $\nG(X) $ in the face of random intermittent contamination by $ H(X)$. For\nexample, it may be that this contamination is responsible for the outliers in a\nmodel that otherwise works well with the dominant $F$ distribution. It can get\neven worse than that because we don't know that there is only one contaminating\n$H(X)$ distribution out there. There may be a whole family of distributions\nthat\nare contaminating $G(X)$. This means that whatever estimators we construct\nhave\nto be derived from a more generalized family of distributions instead of\nfrom a\nsingle distribution, as the maximum-likelihood method assumes. This is\nwhat\nmakes robust estimation so difficult --- it has to deal with *spaces* of\nfunction distributions instead of parameters from a particular probability\ndistribution.\n\n### Generalized Maximum Likelihood Estimators\n\nM-estimators are\ngeneralized maximum likelihood estimators. Recall that for\nmaximum likelihood,\nwe want to maximize the likelihood function as in the\nfollowing:\n\n$$\nL_{\\mu}(x_i) = \\prod f_0(x_i-\\mu)\n$$\n\n and then to find the estimator $\\hat{\\mu}$ so that\n\n$$\n\\hat{\\mu} = \\arg \\max_{\\mu} L_{\\mu}(x_i)\n$$\n\n So far, everything is the same as our usual maximum-likelihood\nderivation\nexcept for the fact that we don't assume a specific $f_0$ as the\ndistribution of\nthe $\\lbrace X_i\\rbrace$. Making the definition of\n\n$$\n\\rho = -\\log f_0\n$$\n\n we obtain the more convenient form of the likelihood product and the\noptimal\n$\\hat{\\mu}$ as\n\n$$\n\\hat{\\mu} = \\arg \\min_{\\mu} \\sum \\rho(x_i-\\mu)\n$$\n\n If $\\rho$ is differentiable, then differentiating this with respect\nto $\\mu$\ngives\n\n\n\n\n$$\n\\begin{equation}\n\\sum \\psi(x_i-\\hat{\\mu}) = 0 \n\\label{eq:muhat} \\tag{5}\n\\end{equation}\n$$\n\n with $\\psi = \\rho^\\prime$, the first derivative of $\\rho$ , and for technical\nreasons we will assume that\n$\\psi$ is increasing. So far, it looks like we just\npushed some definitions\naround, but the key idea is we want to consider general\n$\\rho$ functions that\nmay not be maximum likelihood estimators for *any*\ndistribution. Thus, our\nfocus is now on uncovering the nature of $\\hat{\\mu}$.\n\n### Distribution of M-estimates\n\nFor a given distribution $F$, we define\n$\\mu_0=\\mu(F)$ as the solution to the\nfollowing\n\n$$\n\\mathbb{E}_F(\\psi(x-\\mu_0))= 0\n$$\n\n It is technical to show, but it turns out that $\\hat{\\mu} \\sim\n\\mathcal{N}(\\mu_0,\\frac{v}{n})$ with\n\n$$\nv =\n\\frac{\\mathbb{E}_F(\\psi(x-\\mu_0)^2)}{(\\mathbb{E}_F(\\psi^\\prime(x-\\mu_0)))^2}\n$$\n\n Thus, we can say that $\\hat{\\mu}$ is asymptotically normal with asymptotic\nvalue $\\mu_0$ and asymptotic variance $v$. This leads to the efficiency ratio\nwhich is defined as the following:\n\n$$\n\\texttt{Eff}(\\hat{\\mu})= \\frac{v_0}{v}\n$$\n\n where $v_0$ is the asymptotic variance of the MLE and measures how\nnear\n$\\hat{\\mu}$ is to the optimum. In other words, this provides a sense of\nhow much\noutlier contamination costs in terms of samples. For example, if for\ntwo\nestimates with asymptotic variances $v_1$ and $v_2$, we have $v_1=3v_2$,\nthen\nfirst estimate requires three times as many observations to obtain the\nsame\nvariance as the second. Furthermore, for the sample mean (i.e.,\n$\\hat{\\mu}=\\frac{1}{n} \\sum X_i$) with $F=\\mathcal{N}$, we have $\\rho=x^2/2$\nand\n$\\psi=x$ and also $\\psi'=1$. Thus, we have $v=\\mathbb{V}(x)$.\nAlternatively,\nusing the sample median as the estimator for the location, we\nhave $v=1/(4\nf(\\mu_0)^2)$. Thus, if we have $F=\\mathcal{N}(0,1)$, for the\nsample median, we\nobtain $v={2\\pi}/{4} \\approx 1.571$. This means that the\nsample median takes\napproximately 1.6 times as many samples to obtain the same\nvariance for the\nlocation as the sample mean. The sample median is \nfar more immune to the\neffects of outliers than the sample mean, so this \ngives a sense of how much\nthis robustness costs in samples.\n\n** M-Estimates as Weighted Means.** One way\nto think about M-estimates is a\nweighted means. Operationally, this\nmeans that\nwe want weight functions that can circumscribe the\ninfluence of the individual\ndata points, but, when taken as a whole,\nstill provide good estimated\nparameters. Most of the time, we have $\\psi(0)=0$ and $\\psi'(0)$ exists so\nthat\n$\\psi$ is approximately linear at the origin. Using the following\ndefinition:\n\n$$\nW(x) = \\begin{cases}\n \\psi(x)/x & \\text{if} \\: x \\neq 0 \\\\\\\n\\psi'(x) & \\text{if} \\: x =0 \n \\end{cases}\n$$\n\n We can write our Equation [5](#eq:muhat) as follows:\n\n\n\n\n$$\n\\begin{equation}\n\\sum W(x_i-\\hat{\\mu})(x_i-\\hat{\\mu}) = 0 \n\\label{eq:Wmuhat}\n\\tag{6}\n\\end{equation}\n$$\n\n Solving this for $\\hat{\\mu} $ yields the following,\n\n$$\n\\hat{\\mu} = \\frac{\\sum w_{i} x_i}{\\sum w_{i}}\n$$\n\n where $w_{i}=W(x_i-\\hat{\\mu})$. This is not practically useful\nbecause the\n$w_i$ contains $\\hat{\\mu}$, which is what we are trying to solve\nfor. The\nquestion that remains is how to pick the $\\psi$ functions. This is\nstill an open\nquestion, but the Huber functions are a well-studied choice.\n\n### Huber\nFunctions\n\nThe family of Huber functions is defined by the following:\n\n$$\n\\rho_k(x ) = \\begin{cases}\n x^2 & \\mbox{if } |x|\\leq\nk \\\\\\\n 2 k |x|-k^2 & \\mbox{if } |x| > k\n\\end{cases}\n$$\n\n with corresponding derivatives $2\\psi_k(x)$ with\n\n$$\n\\psi_k(x ) = \\begin{cases}\n x & \\mbox{if } \\: |x|\n\\leq k \\\\\\\n \\text{sgn}(x)k & \\mbox{if } \\: |x| > k\n\\end{cases}\n$$\n\n where the limiting cases $k \\rightarrow \\infty$ and $k \\rightarrow 0$\ncorrespond to the mean and median, respectively. To see this, take\n$\\psi_{\\infty} = x$ and therefore $W(x) = 1$ and thus the defining Equation\n[6](#eq:Wmuhat) results in\n\n$$\n\\sum_{i=1}^{n} (x_i-\\hat{\\mu}) = 0\n$$\n\n and then solving this leads to $\\hat{\\mu} = \\frac{1}{n}\\sum x_i$.\nNote that\nchoosing $k=0$ leads to the sample median, but that is not so\nstraightforward\nto solve for. Nonetheless, Huber functions provide a way\nto move between two\nextremes of estimators for location (namely, \nthe mean vs. the median) with a\ntunable parameter $k$. \nThe $W$ function corresponding to Huber's $\\psi$ is the\nfollowing:\n\n$$\nW_k(x) = \\min\\Big{\\lbrace} 1, \\frac{k}{|x|} \\Big{\\rbrace}\n$$\n\n [Figure](#fig:Robust_Statistics_0001) shows the Huber weight\nfunction for $k=2$\nwith some sample points. The idea is that the computed\nlocation, $\\hat{\\mu}$ is\ncomputed from Equation [6](#eq:Wmuhat) to lie somewhere\nin the middle of the\nweight function so that those terms (i.e., *insiders*)\nhave their values fully\nreflected in the location estimate. The black circles\nare the *outliers* that\nhave their values attenuated by the weight function so\nthat only a fraction of\ntheir presence is represented in the location estimate.\n\n\n\n\n\nThis shows the Huber weight function,\n$W_2(x)$ and some cartoon data points that are insiders or outsiders as far as\nthe robust location estimate is concerned.
\n\n\n\n\n\n###\nBreakdown Point\n\nSo far, our discussion of robustness has been very abstract. A\nmore concrete\nconcept of robustness comes from the breakdown point. In the\nsimplest terms,\nthe breakdown point describes what happens when a single data\npoint in an\nestimator is changed in the most damaging way possible. For example,\nsuppose we\nhave the sample mean, $\\hat{\\mu}=\\sum x_i/n$, and we take one of the\n$x_i$\npoints to be infinite. What happens to this estimator? It also goes\ninfinite.\nThis means that the breakdown point of the estimator is 0%. On the\nother hand,\nthe median has a breakdown point of 50%, meaning that half of the\ndata for\ncomputing the median could go infinite without affecting the median\nvalue. The median\nis a *rank* statistic that cares more about the relative\nranking of the data\nthan the values of the data, which explains its robustness.\nThe simpliest but still formal way to express the breakdown point is to\ntake $n$\ndata points, $\\mathcal{D} = \\lbrace (x_i,y_i) \\rbrace$. Suppose $T$\nis a\nregression estimator that yields a vector of regression coefficients,\n$\\boldsymbol{\\theta}$,\n\n$$\nT(\\mathcal{D}) = \\boldsymbol{\\theta}\n$$\n\n Likewise, consider all possible corrupted samples of the data\n$\\mathcal{D}^\\prime$. The maximum *bias* caused by this contamination is\nthe\nfollowing:\n\n$$\n\\texttt{bias}_{m} = \\sup_{\\mathcal{D}^\\prime} \\Vert\nT(\\mathcal{D^\\prime})-T(\\mathcal{D}) \\Vert\n$$\n\n where the $\\sup$ sweeps over all possible sets of $m$ contaminated samples.\nUsing this, the breakdown point is defined as the following:\n\n$$\n\\epsilon_m = \\min \\Big\\lbrace \\frac{m}{n} \\colon \\texttt{bias}_{m}\n\\rightarrow \\infty \\Big\\rbrace\n$$\n\n For example, in our least-squares regression, even one point at\ninfinity causes\nan infinite $T$. Thus, for least-squares regression,\n$\\epsilon_m=1/n$. In the\nlimit $n \\rightarrow \\infty$, we have $\\epsilon_m\n\\rightarrow 0$.\n\n###\nEstimating Scale\n\nIn robust statistics, the concept of *scale* refers to a\nmeasure of the\ndispersion of the data. Usually, we use the\nestimated standard\ndeviation for this, but this has a terrible breakdown point.\nEven more\ntroubling, in order to get a good estimate of location, we have to\neither\nsomehow know the scale ahead of time, or jointly estimate it. None of\nthese\nmethods have easy-to-compute closed form solutions and must be computed\nnumerically.\n\nThe most popular method for estimating scale is the *median\nabsolute deviation*\n\n$$\n\\texttt{MAD} = \\texttt{Med} (\\vert \\mathbf{x} -\n\\texttt{Med}(\\mathbf{x})\\vert)\n$$\n\n In words, take the median of the data $\\mathbf{x}$ and\nthen subtract that\nmedian from the data itself, and then take the median of the\nabsolute value of\nthe result. Another good dispersion estimate is the *interquartile range*,\n\n$$\n\\texttt{IQR} = x_{(n-m+1)} - x_{(n)}\n$$\n\n where $m= [n/4]$. The $x_{(n)}$ notation means the $n^{th}$ data\nelement after\nthe data have been sorted. Thus, in this notation,\n$\\texttt{max}(\\mathbf{x})=x_{(n)}$. In the case where $x \\sim\n\\mathcal{N}(\\mu,\\sigma^2)$, then $\\texttt{MAD}$ and $\\texttt{IQR}$ are constant\nmultiples of $\\sigma$ such that the normalized $\\texttt{MAD}$ is the following,\n\n$$\n\\texttt{MADN}(x) = \\frac{\\texttt{MAD} }{0.675}\n$$\n\n The number comes from the inverse CDF of the normal distribution\ncorresponding\nto the $0.75$ level. Given the complexity of the\ncalculations, *jointly*\nestimating both location and scale is a purely\nnumerical matter. Fortunately,\nthe Statsmodels module has many of these\nready to use. Let's create some\ncontaminated data in the following code,\n\n\n```python\nimport statsmodels.api as sm\nimport numpy as np\n\nfrom scipy import stats\ndata=np.hstack([stats.norm(10,1).rvs(10),\n stats.norm(0,1).rvs(100)])\n```\n\nThese data correspond to our model of contamination that we started\nthis\nsection with. As shown in the histogram in\n[Figure](#fig:Robust_Statistics_0002), there are two normal distributions, one\ncentered neatly at zero, representing the majority of the samples, and another\ncoming less regularly from the normal distribution on the right. Notice that\nthe\ngroup of infrequent samples on the right separates the mean and median\nestimates\n(vertical dotted and dashed lines). In the absence of the\ncontaminating\ndistribution on the right, the standard deviation for this data\nshould be close\nto one. However, the usual non-robust estimate for standard\ndeviation (`np.std`)\ncomes out to approximately three. Using the\n$\\texttt{MADN}$ estimator\n(`sm.robust.scale.mad(data)`) we obtain approximately\n1.25. Thus, the robust\nestimate of dispersion is less moved by the presence of\nthe contaminating\ndistribution.\n\n\n\n\nHistogram of sample data. Notice that the group of infrequent samples on the\nright separates the mean and median estimates indicated by the vertical\nlines.
\n\n\n\n\n\nThe generalized maximum likelihood M-estimation extends to\njoint\nscale and location estimation using Huber functions. For example,\n\n\n```python\nhuber = sm.robust.scale.Huber()\nloc,scl=huber(data)\n```\n\nwhich implements Huber's *proposal two* method of joint estimation of\nlocation\nand scale. This kind of estimation is the key ingredient to robust\nregression\nmethods, many of which are implemented in Statsmodels in\n`statsmodels.formula.api.rlm`. The corresponding documentation has more\ninformation.\n", "meta": {"hexsha": "9f7c38e6ba987f7c0bc99a6106676af9d5c72fb1", "size": 199747, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter/statistics/Robust_Statistics.ipynb", "max_stars_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_stars_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224, "max_stars_repo_stars_event_min_datetime": "2019-05-07T08:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:50:41.000Z", "max_issues_repo_path": "chapter/statistics/Robust_Statistics.ipynb", "max_issues_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_issues_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-08-27T12:57:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T15:45:13.000Z", "max_forks_repo_path": "chapter/statistics/Robust_Statistics.ipynb", "max_forks_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_forks_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 73, "max_forks_repo_forks_event_min_datetime": "2019-05-25T07:15:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:22:37.000Z", "avg_line_length": 317.0587301587, "max_line_length": 176652, "alphanum_fraction": 0.9212403691, "converted": true, "num_tokens": 4677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894545235253, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.09844122497805259}} {"text": "# Implementing Neural Networks with Numpy for Absolute Beginners - Part 1: Introduction\n\n##### In this tutorial, you will get a brief understanding of what Neural Networks are and how they have been developed. In the end, you will gain a brief intuition as to how the network learns.\n\nThe field of Artificial Intelligence has gained a lot of popularity and momentum during the past 10 years, largely due to a huge increase in the computational capacity of computers with the use of GPUs and the availability of gigantic amounts of data. Deep Learning has become the buzzword everywhere!!\n>>>>> \n\n\nAlthough Artificial Intelligence (AI) resonates with the notion of the machines to think and behave impersonating humans, it is rather restricted to very nascent and small task-specific functions while the term Artificial General Intelligence (AGI) obliges to the terms of impersonating a human. Above these is the concept of Artificial Super Intelligence (ASI) which gives me the shrills as it represents intelligence of machines far exceeding human levels!!\n\nThe main concept for Artificial Intelligence currently holds that you have to train it before it learns to perform the task much like humans, except that here… you have to train it even for the simplest of the tasks like seeing and identifying objects!(This is surely a complex problem for our computers).\n\nThere are 3 situations that you can encounter in this domain:\n1. When you have a lot of data...\n\n> - Either your data is tagged, labelled, maintained or it is not.\n If the data is available and is fully labelled or tagged, you can train the model based on the given set of input-output pairs and ask the model to predict the output for a new set of data. This type of learning is called **Supervised Learning** (Since, you are giving the input and also mentioning that this is the correct output for the data).\n\n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n\n**Result:**\n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n**Now it's your turn to have some Markdown fun.** In the next cell, try out some of the commands. You can just throw in some things, or do something more structured (like a small notebook).\n\n# This is just a test title\n## With a subtitle\n### And an even smaller subtitle\n
Write your formulas here.
\n\nEquation of a line: $$ y = ax + b $$\n\nRoots of the quadratic equation $ax^{2}+bx+c=0$: $$ x_{1,2}=\\frac{-b\\pm\\sqrt[2]{b^{2}-4ac}}{2a} $$\n\nTaylor series expansion: $$f(x)\\mid_{x=a}=f(a)+f'(a)(x-a)+\\frac{f''(a)}{2!}(x-a)^{2}+...+\\frac{f^{n}(a)}{n!}(x-a)^{n}+...$$\n\nBinomial theorem: $$ (x+y)^{n}=\\biggl({n \\atop 0}\\biggr)x^{n}y^{0}+\\biggl({n \\atop 1}\\biggr)x^{n-1}y^{1}+...+\\biggl({n \\atop n}\\biggr)x^{0}y^{n}=\\sum^{n}_{k=0}\\biggl({n \\atop k}\\biggr)x^{n-k}y^{k} $$\n\nAn integral (this one is a lot of fun to solve :D): $$ \\int_{+\\infty}^{-\\infty} e^{-x^{2}} \\,dx=\\sqrt{\\pi}$$\n\nA short matrix: $$\\begin{pmatrix} 2 & 1 & 3 \\\\ 2 & 6 & 8 \\\\ 6 & 8 & 18\\end{pmatrix}$$\n\nA long matrix: $$\\begin{pmatrix} a_{11} & a_{12} & \\cdots & a_{1n}\\\\ a_{21} & a_{22} & \\cdots & a_{2n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\a_{m1} & a_{m2} & \\cdots & a_{mn}\\end{pmatrix}$$\n\n### Problem 3. Solving with Python\nLet's first do some symbolic computation. We need to import `sympy` first. \n\n**Should your imports be in a single cell at the top or should they appear as they are used?** There's not a single valid best practice. Most people seem to prefer imports at the top of the file though. **Note: If you write new code in a cell, you have to re-execute it!**\n\nLet's use `sympy` to give us a quick symbolic solution to our equation. First import `sympy` (you can use the second cell in this notebook): \n```python \nimport sympy \n```\n\nNext, create symbols for all variables and parameters. You may prefer to do this in one pass or separately:\n```python \nx = sympy.symbols('x')\na, b, c = sympy.symbols('a b c')\n```\n\nNow solve:\n```python \nsympy.solve(a * x**2 + b * x + c)\n```\n\n\n```python\n# High-School Maths Exercise\n## Getting to Know Jupyter Notebook. Python Libraries and Best Practices. Basic Workflow\n```\n\n\n```python\n# Write your code here\nx = sympy.symbols('x')\na, b, c = sympy.symbols('a b c')\nsympy.solve(a * x**2 + b * x + c)\n```\n\n\n\n\n [{a: (-b*x - c)/x**2}]\n\n\n\n\n```python\n# Write your code here\nsympy.init_printing()\nsympy.solve(a * x**2 + b * x + c, x)\n```\n\nHmmmm... we didn't expect that :(. We got an expression for $a$ because the library tried to solve for the first symbol it saw. This is an equation and we have to solve for $x$. We can provide it as a second parameter:\n```python \nsympy.solve(a * x**2 + b * x + c, x)\n```\n\nFinally, if we start with `sympy.init_printing()`, we'll get a LaTeX-formatted result instead of a typed one. This is very useful because it produces better-looking formulas. **Note:** This means we have to add the line BEFORE we start working with `sympy`.\n\nHow about a function that takes $a, b, c$ (assume they are real numbers, you don't need to do additional checks on them) and returns the **real** roots of the quadratic equation?\n\nRemember that in order to calculate the roots, we first need to see whether the expression under the square root sign is non-negative.\n\nIf $b^2 - 4ac > 0$, the equation has two real roots: $x_1, x_2$\n\nIf $b^2 - 4ac = 0$, the equation has one real root: $x_1 = x_2$\n\nIf $b^2 - 4ac < 0$, the equation has zero real roots\n\nWrite a function which returns the roots. In the first case, return a list of 2 numbers: `[2, 3]`. In the second case, return a list of only one number: `[2]`. In the third case, return an empty list: `[]`.\n\n\n```python\ndef format_decimal(func):\n \"\"\"\n Decorator to convert the sympy output to Python float format\n \"\"\"\n def inner(*args, **kwargs):\n raw_res = func(*args, **kwargs)\n if isinstance(raw_res, list) and len(raw_res) > 0:\n retval = []\n for el in raw_res:\n retval.append(float(el))\n return retval\n return raw_res\n return inner\n\n@format_decimal\ndef solve_quadratic_equation(a, b, c):\n \"\"\"\n Returns the real solutions of the quadratic equation ax^2 + bx + c = 0\n \"\"\"\n # Delete the \"pass\" statement below and write your code\n def sqrt_part():\n return b**2 - 4 * a * c\n \n if a == 0:\n return sympy.solve(b * x + c, x)\n if sqrt_part() < 0:\n return []\n return sympy.solve(a * x**2 + b * x + c, x)\n```\n\n\n```python\n# Testing: Execute this cell. The outputs should match the expected outputs. Feel free to write more tests\nprint(solve_quadratic_equation(1, -1, -2)) # [-1.0, 2.0]\nprint(solve_quadratic_equation(1, -8, 16)) # [4.0]\nprint(solve_quadratic_equation(1, 1, 1)) # []\n```\n\n [-1.0, 2.0]\n [4.0]\n []\n\n\n**Bonus:** Last time we saw how to solve a linear equation. Remember that linear equations are just like quadratic equations with $a = 0$. In this case, however, division by 0 will throw an error. Extend your function above to support solving linear equations (in the same way we did it last time).\n\n\n```python\n# Bonus: Calling the function with a = 0 for a linear equation\nprint(solve_quadratic_equation(0, -1, -2)) # [-2.0]\nprint(solve_quadratic_equation(0, -8, 16)) # [2.0]\nprint(solve_quadratic_equation(0, 1, 1)) # [-1.0]\n```\n\n [-2.0]\n [2.0]\n [-1.0]\n\n\n### Problem 4. Equation of a Line\nLet's go back to our linear equations and systems. There are many ways to define what \"linear\" means, but they all boil down to the same thing.\n\nThe equation $ax + b = 0$ is called *linear* because the function $f(x) = ax+b$ is a linear function. We know that there are several ways to know what one particular function means. One of them is to just write the expression for it, as we did above. Another way is to **plot** it. This is one of the most exciting parts of maths and science - when we have to fiddle around with beautiful plots (although not so beautiful in this case).\n\nThe function produces a straight line and we can see it.\n\nHow do we plot functions in general? We know that functions take many (possibly infinitely many) inputs. We can't draw all of them. We could, however, evaluate the function at some points and connect them with tiny straight lines. If the points are too many, we won't notice - the plot will look smooth.\n\nNow, let's take a function, e.g. $y = 2x + 3$ and plot it. For this, we're going to use `numpy` arrays. This is a special type of array which has two characteristics:\n* All elements in it must be of the same type\n* All operations are **broadcast**: if `x = [1, 2, 3, 10]` and we write `2 * x`, we'll get `[2, 4, 6, 20]`. That is, all operations are performed at all indices. This is very powerful, easy to use and saves us A LOT of looping.\n\nThere's one more thing: it's blazingly fast because all computations are done in C, instead of Python.\n\nFirst let's import `numpy`. Since the name is a bit long, a common convention is to give it an **alias**:\n```python\nimport numpy as np\n```\n\nImport that at the top cell and don't forget to re-run it.\n\nNext, let's create a range of values, e.g. $[-3, 5]$. There are two ways to do this. `np.arange(start, stop, step)` will give us evenly spaced numbers with a given step, while `np.linspace(start, stop, num)` will give us `num` samples. You see, one uses a fixed step, the other uses a number of points to return. When plotting functions, we usually use the latter. Let's generate, say, 1000 points (we know a straight line only needs two but we're generalizing the concept of plotting here :)).\n```python\nx = np.linspace(-3, 5, 1000)\n```\nNow, let's generate our function variable\n```python\ny = 2 * x + 3\n```\n\nWe can print the values if we like but we're more interested in plotting them. To do this, first let's import a plotting library. `matplotlib` is the most commnly used one and we usually give it an alias as well.\n```python\nimport matplotlib.pyplot as plt\n```\n\nNow, let's plot the values. To do this, we just call the `plot()` function. Notice that the top-most part of this notebook contains a \"magic string\": `%matplotlib inline`. This hints Jupyter to display all plots inside the notebook. However, it's a good practice to call `show()` after our plot is ready.\n```python\nplt.plot(x, y)\nplt.show()\n```\n\n\n```python\n# Write your code here\nx = np.linspace(-3, 5, 1000)\ny = 2 * x + 3\nplt.plot(x, y)\nplt.show()\n```\n\nIt doesn't look too bad bit we can do much better. See how the axes don't look like they should? Let's move them to zero. This can be done using the \"spines\" of the plot (i.e. the borders).\n\nAll `matplotlib` figures can have many plots (subfigures) inside them. That's why when performing an operation, we have to specify a target figure. There is a default one and we can get it by using `plt.gca()`. We usually call it `ax` for \"axis\".\nLet's save it in a variable (in order to prevent multiple calculations and to make code prettier). Let's now move the bottom and left spines to the origin $(0, 0)$ and hide the top and right one.\n```python\nax = plt.gca()\nax.spines[\"bottom\"].set_position(\"zero\")\nax.spines[\"left\"].set_position(\"zero\")\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n```\n\n**Note:** All plot manipulations HAVE TO be done before calling `show()`. It's up to you whether they should be before or after the function you're plotting.\n\nThis should look better now. We can, of course, do much better (e.g. remove the double 0 at the origin and replace it with a single one), but this is left as an exercise for the reader :).\n\n\n```python\n# Copy and edit your code here\nplt.clf()\nax = plt.gca()\nax.spines[\"bottom\"].set_position('zero')\nax.spines[\"left\"].set_position(\"zero\")\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nxticks = ax.xaxis.get_major_ticks()\nyticks = ax.yaxis.get_major_ticks()\n\nplt.plot(x, y)\n\n# Let's try to remove the double 0 at the origin.\nxloc, labels = plt.xticks()\nyloc, labels = plt.yticks()\nx_zero_loc = np.where(xloc==0)[0][0]\ny_zero_loc = np.where(yloc==0)[0][0]\n\nxticks[x_zero_loc].set_visible(False)\nyticks[y_zero_loc].set_visible(False)\n\nplt.show()\n```\n\n### * Problem 5. Linearizing Functions\nWhy is the line equation so useful? The main reason is because it's so easy to work with. Scientists actually try their best to linearize functions, that is, to make linear functions from non-linear ones. There are several ways of doing this. One of them involves derivatives and we'll talk about it later in the course. \n\nA commonly used method for linearizing functions is through algebraic transformations. Try to linearize \n$$ y = ae^{bx} $$\n\nHint: The inverse operation of $e^{x}$ is $\\ln(x)$. Start by taking $\\ln$ of both sides and see what you can do. Your goal is to transform the function into another, linear function. You can look up more hints on the Internet :).\n\nWrite your result here.
\nWe start by taking the ln of both sides: $ \\ln(y) = \\ln(a) + bx\\ln(e) $\n\nThe resulting linear function is: $ \\ln(y) = \\ln(a) + bx $\n\nWhere **ln(y)** is the dependent that we plot on the y-axis, **ln(a)** is the constant and **b** is the slope. This equation is commontly presented as $y = mx + b$\n\n### * Problem 6. Generalizing the Plotting Function\nLet's now use the power of Python to generalize the code we created to plot. In Python, you can pass functions as parameters to other functions. We'll utilize this to pass the math function that we're going to plot.\n\nNote: We can also pass *lambda expressions* (anonymous functions) like this: \n```python\nlambda x: x + 2```\nThis is a shorter way to write\n```python\ndef some_anonymous_function(x):\n return x + 2\n```\n\nWe'll also need a range of x values. We may also provide other optional parameters which will help set up our plot. These may include titles, legends, colors, fonts, etc. Let's stick to the basics now.\n\nWrite a Python function which takes another function, x range and number of points, and plots the function graph by evaluating it at every point.\n\n**BIG hint:** If you want to use not only `numpy` functions for `f` but any one function, a very useful (and easy) thing to do, is to vectorize the function `f` (e.g. to allow it to be used with `numpy` broadcasting):\n```python\nf_vectorized = np.vectorize(f)\ny = f_vectorized(x)\n```\n\n\n```python\ndef remove_zero_tick(loc, axticks):\n \"\"\"\n This function will be used in this book to remove the 0 at origin\n \"\"\"\n try:\n zero_loc = np.where(loc==0)[0][0]\n axticks[zero_loc].set_visible(False)\n except IndexError:\n ax.spines[\"bottom\"].set_position(('data', 1))\n\ndef plot_math_function(f, min_x, max_x, num_points):\n x_array = np.linspace(min_x, max_x, num_points)\n f_vectorized = np.vectorize(f)\n y = f_vectorized(x_array)\n\n \n plt.clf()\n plt.cla()\n ax = plt.gca()\n ax.spines[\"bottom\"].set_position('zero')\n ax.spines[\"left\"].set_position(\"zero\")\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n xticks = ax.xaxis.get_major_ticks()\n yticks = ax.yaxis.get_major_ticks()\n \n plt.plot(x_array, y)\n\n xloc, labels = plt.xticks()\n yloc, labels = plt.yticks()\n remove_zero_tick(xloc, xticks)\n remove_zero_tick(yloc, yticks)\n\n plt.show()\n \n```\n\n\n```python\nplot_math_function(lambda x: 2 * x + 3, -3, 5, 1000)\nplot_math_function(lambda x: -x + 8, -1, 10, 1000)\nplot_math_function(lambda x: x**2 - x - 2, -3, 4, 1000)\nplot_math_function(lambda x: np.sin(x), -np.pi, np.pi, 1000)\nplot_math_function(lambda x: np.sin(x) / x, -4 * np.pi, 4 * np.pi, 1000)\n```\n\n### * Problem 7. Solving Equations Graphically\nNow that we have a general plotting function, we can use it for more interesting things. Sometimes we don't need to know what the exact solution is, just to see where it lies. We can do this by plotting the two functions around the \"=\" sign ans seeing where they intersect. Take, for example, the equation $2x + 3 = 0$. The two functions are $f(x) = 2x + 3$ and $g(x) = 0$. Since they should be equal, the point of their intersection is the solution of the given equation. We don't need to bother marking the point of intersection right now, just showing the functions.\n\nTo do this, we'll need to improve our plotting function yet once. This time we'll need to take multiple functions and plot them all on the same graph. Note that we still need to provide the $[x_{min}; x_{max}]$ range and it's going to be the same for all functions.\n\n```python\nvectorized_fs = [np.vectorize(f) for f in functions]\nys = [vectorized_f(x) for vectorized_f in vectorized_fs]\n```\n\n\n```python\ndef plot_math_functions(functions, min_x, max_x, num_points):\n \n x_array = np.linspace(min_x, max_x, num_points)\n if hasattr(functions, \"__iter__\"):\n vectorized_fs = [np.vectorize(func) for func in functions]\n ys = [vectorized_f(x_array) for vectorized_f in vectorized_fs]\n else:\n ys = [np.vectorize(functions)(x_array)]\n \n ax = plt.gca()\n ax.spines[\"bottom\"].set_position('zero')\n ax.spines[\"left\"].set_position(\"zero\")\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n xticks = ax.xaxis.get_major_ticks()\n yticks = ax.yaxis.get_major_ticks()\n\n for y in ys:\n plt.plot(x_array, y)\n\n xloc, labels = plt.xticks()\n yloc, labels = plt.yticks()\n remove_zero_tick(xloc, xticks)\n remove_zero_tick(yloc, yticks)\n \n plt.show()\n```\n\n\n```python\n# plot_math_functions(4, -3, 5, 1000)\nplot_math_functions([lambda x: 3 * x**2 - 2 * x + 5, lambda x: 3 * x + 7], -2, 3, 1000)\n```\n\nThis is also a way to plot the solutions of systems of equation, like the one we solved last time. Let's actually try it.\n\n\n```python\nplot_math_functions([lambda x: (-4 * x + 7) / 3, lambda x: (-3 * x + 8) / 5, lambda x: (-x - 1) / -2], -1, 4, 1000)\n```\n\n### Problem 8. Trigonometric Functions\nWe already saw the graph of the function $y = \\sin(x)$. But then again, how do we define the trigonometric functions? Let's quickly review that.\n\n\n\nThe two basic trigonometric functions are defined as the ratio of two sides:\n$$ \\sin(x) = \\frac{\\text{opposite}}{\\text{hypotenuse}} $$\n$$ \\cos(x) = \\frac{\\text{adjacent}}{\\text{hypotenuse}} $$\n\nAnd also:\n$$ \\tan(x) = \\frac{\\text{opposite}}{\\text{adjacent}} = \\frac{\\sin(x)}{\\cos(x)} $$\n$$ \\cot(x) = \\frac{\\text{adjacent}}{\\text{opposite}} = \\frac{\\cos(x)}{\\sin(x)} $$\n\nThis is fine, but using this, \"right-triangle\" definition, we're able to calculate the trigonometric functions of angles up to $90^\\circ$. But we can do better. Let's now imagine a circle centered at the origin of the coordinate system, with radius $r = 1$. This is called a \"unit circle\".\n\n\n\nWe can now see exactly the same picture. The $x$-coordinate of the point in the circle corresponds to $\\cos(\\alpha)$ and the $y$-coordinate - to $\\sin(\\alpha)$. What did we get? We're now able to define the trigonometric functions for all degrees up to $360^\\circ$. After that, the same values repeat: these functions are **periodic**: \n$$ \\sin(k.360^\\circ + \\alpha) = \\sin(\\alpha), k = 0, 1, 2, \\dots $$\n$$ \\cos(k.360^\\circ + \\alpha) = \\cos(\\alpha), k = 0, 1, 2, \\dots $$\n\nWe can, of course, use this picture to derive other identities, such as:\n$$ \\sin(90^\\circ + \\alpha) = \\cos(\\alpha) $$\n\nA very important property of the sine and cosine is that they accept values in the range $(-\\infty; \\infty)$ and produce values in the range $[-1; 1]$. The two other functions take values in the range $(-\\infty; \\infty)$ **except when their denominators are zero** and produce values in the same range. \n\n#### Radians\nA degree is a geometric object, $1/360$th of a full circle. This is quite inconvenient when we work with angles. There is another, natural and intrinsic measure of angles. It's called the **radian** and can be written as $\\text{rad}$ or without any designation, so $\\sin(2)$ means \"sine of two radians\".\n\n\nIt's defined as *the central angle of an arc with length equal to the circle's radius* and $1\\text{rad} \\approx 57.296^\\circ$.\n\nWe know that the circle circumference is $C = 2\\pi r$, therefore we can fit exactly $2\\pi$ arcs with length $r$ in $C$. The angle corresponding to this is $360^\\circ$ or $2\\pi\\ \\text{rad}$. Also, $\\pi rad = 180^\\circ$.\n\n(Some people prefer using $\\tau = 2\\pi$ to avoid confusion with always multiplying by 2 or 0.5 but we'll use the standard notation here.)\n\n**NOTE:** All trigonometric functions in `math` and `numpy` accept radians as arguments. In order to convert between radians and degrees, you can use the relations $\\text{[deg]} = 180/\\pi.\\text{[rad]}, \\text{[rad]} = \\pi/180.\\text{[deg]}$. This can be done using `np.deg2rad()` and `np.rad2deg()` respectively.\n\n#### Inverse trigonometric functions\nAll trigonometric functions have their inverses. If you plug in, say $\\pi/4$ in the $\\sin(x)$ function, you get $\\sqrt{2}/2$. The inverse functions (also called, arc-functions) take arguments in the interval $[-1; 1]$ and return the angle that they correspond to. Take arcsine for example:\n$$ \\arcsin(y) = x: sin(y) = x $$\n$$ \\arcsin\\left(\\frac{\\sqrt{2}}{2}\\right) = \\frac{\\pi}{4} $$\n\nPlease note that this is NOT entirely correct. From the relations we found:\n$$\\sin(x) = sin(2k\\pi + x), k = 0, 1, 2, \\dots $$\n\nit follows that $\\arcsin(x)$ has infinitely many values, separated by $2k\\pi$ radians each:\n$$ \\arcsin\\left(\\frac{\\sqrt{2}}{2}\\right) = \\frac{\\pi}{4} + 2k\\pi, k = 0, 1, 2, \\dots $$\n\nIn most cases, however, we're interested in the first value (when $k = 0$). It's called the **principal value**.\n\nNote 1: There are inverse functions for all four basic trigonometric functions: $\\arcsin$, $\\arccos$, $\\arctan$, $\\text{arccot}$. These are sometimes written as $\\sin^{-1}(x)$, $\\cos^{-1}(x)$, etc. These definitions are completely equivalent. \n\nJust notice the difference between $\\sin^{-1}(x) := \\arcsin(x)$ and $\\sin(x^{-1}) = \\sin(1/x)$.\n\n#### Exercise\nUse the plotting function you wrote above to plot the inverse trigonometric functions. Use `numpy` (look up how to use inverse trigonometric functions).\n\n\n```python\n# Write your code here\nplot_math_functions([lambda x: np.arcsin(x), lambda x: np.arccos(x)], -1, 1, 1000)\nplot_math_functions(lambda x: np.arctan(x), -1, 1, 1000)\n\nplot_math_functions(lambda x: np.arctan(1 / x), -1, 1, 1000)\nplot_math_functions(lambda x: (3.14 / 2) - np.arctan(x), -1, 1, 1000)\n```\n\n### ** Problem 9. Perlin Noise\nThis algorithm has many applications in computer graphics and can serve to demonstrate several things... and help us learn about math, algorithms and Python :).\n#### Noise\nNoise is just random values. We can generate noise by just calling a random generator. Note that these are actually called *pseudorandom generators*. We'll talk about this later in this course.\nWe can generate noise in however many dimensions we want. For example, if we want to generate a single dimension, we just pick N random values and call it a day. If we want to generate a 2D noise space, we can take an approach which is similar to what we already did with `np.meshgrid()`.\n\n$$ \\text{noise}(x, y) = N, N \\in [n_{min}, n_{max}] $$\n\nThis function takes two coordinates and returns a single number N between $n_{min}$ and $n_{max}$. (This is what we call a \"scalar field\").\n\nRandom variables are always connected to **distributions**. We'll talk about these a great deal but now let's just say that these define what our noise will look like. In the most basic case, we can have \"uniform noise\" - that is, each point in our little noise space $[n_{min}, n_{max}]$ will have an equal chance (probability) of being selected.\n\n#### Perlin noise\nThere are many more distributions but right now we'll want to have a look at a particular one. **Perlin noise** is a kind of noise which looks smooth. It looks cool, especially if it's colored. The output may be tweaked to look like clouds, fire, etc. 3D Perlin noise is most widely used to generate random terrain.\n\n#### Algorithm\n... Now you're on your own :). Research how the algorithm is implemented (note that this will require that you understand some other basic concepts like vectors and gradients).\n\n#### Your task\n1. Research about the problem. See what articles, papers, Python notebooks, demos, etc. other people have created\n2. Create a new notebook and document your findings. Include any assumptions, models, formulas, etc. that you're using\n3. Implement the algorithm. Try not to copy others' work, rather try to do it on your own using the model you've created\n4. Test and improve the algorithm\n5. (Optional) Create a cool demo :), e.g. using Perlin noise to simulate clouds. You can even do an animation (hint: you'll need gradients not only in space but also in time)\n6. Communicate the results (e.g. in the Softuni forum)\n\nHint: [This](http://flafla2.github.io/2014/08/09/perlinnoise.html) is a very good resource. It can show you both how to organize your notebook (which is important) and how to implement the algorithm.\n", "meta": {"hexsha": "d9f585fbf3da4e67e9e5ca586b0fe671e2f5b9d8", "size": 231148, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Math/High School Math/High-School Maths Exercise.ipynb", "max_stars_repo_name": "tankishev/Python_Fundamentals", "max_stars_repo_head_hexsha": "dce38de592ff06ec68153a4fcd4d609af2c1cf83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-07T21:12:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T21:12:35.000Z", "max_issues_repo_path": "Math/High School Math/High-School Maths Exercise.ipynb", "max_issues_repo_name": "tankishev/Python_Fundamentals", "max_issues_repo_head_hexsha": "dce38de592ff06ec68153a4fcd4d609af2c1cf83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/High School Math/High-School Maths Exercise.ipynb", "max_forks_repo_name": "tankishev/Python_Fundamentals", "max_forks_repo_head_hexsha": "dce38de592ff06ec68153a4fcd4d609af2c1cf83", "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": 215.4221808015, "max_line_length": 17132, "alphanum_fraction": 0.8951407756, "converted": true, "num_tokens": 8396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.09756351151985276}} {"text": "# Introduction to Neural Networks and Pytorch \n\n Notebook version: 0.1 (Nov 14, 2020)\n\n Authors: Jerónimo Arenas García (jarenas@ing.uc3m.es)\n\n Changes: v.0.1. (Nov 14, 2020) - First version\n \n Pending changes: - Use epochs instead of iters in first part of notebook\n - Add an example with dropout\n - Add theory about CNNs\n - Define functions for the training of neural nets and display of the results\n in order to simplify code cells\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n\nsize=18\nparams = {'legend.fontsize': 'Large',\n 'axes.labelsize': size,\n 'axes.titlesize': size,\n 'xtick.labelsize': size*0.75,\n 'ytick.labelsize': size*0.75}\nplt.rcParams.update(params)\n```\n\n## 1. Introduction and purpose of this Notebook \n\n### 1.1. About Neural Networks \n\n* Neural Networks (NN) have become the state of the art for many machine learning problems\n * Natural Language Processing\n * Computer Vision\n * Image Recognition\n\n\n* They are in widespread use for many applications, e.g.,\n * Language Translantion (Google Neural Machine Translation System) \n * Automatic Speech recognition (Hey Siri! DNN overview)\n * Autonomous Navigation (Facebook Robot Autonomous 3D Navigation)\n * Automatic Plate recognition\n \n\n \n\nFeed Forward Neural Networks have been around since 1960 but only recently (last 10-12 years) have they met their expectations, and improve other machine learning algorithms\n\n* Computation resources are now available at large scale\n* Cloud Computing (AWS, Azure)\n* From MultiLayer Perceptrons to Deep Learning\n* Big Data sets\n* This has also made possible an intense research effort resulting in\n * Topologies better suited to particular problems (CNNs, RNNs)\n * New training strategies providing better generalization\n\nIn parallel, Deep Learning Platforms have emerged that make design, implementation, training, and production of DNNs feasible for everyone\n\n### 1.2. Scope\n\n* To provide just an overview of most important NNs and DNNs concepts\n* Connecting with already studied methods as starting point\n* Introduction to PyTorch\n* Providing links to external sources for further study\n\n### 1.3. Outline\n\n1. Introduction and purpose of this Notebook\n2. Introduction to Neural Networks\n3. Implementing Deep Networks with PyTorch\n\n### 1.4. Other resources \n\n* We point here to external resources and tutorials that are excellent material for further study of the topic\n* Most of them include examples and exercises using numpy and PyTorch\n* This notebook uses examples and other material from some of these sources\n\n|Tutorial|Description|\n|-----|---------------------|\n| |Very general tutorial including videos and an overview of top deep learning platforms|\n| |Very complete book with a lot of theory and examples for MxNET, PyTorch, and TensorFlow|\n| |Official tutorials from the PyTorch project. Contains a 60 min overview, and a very practical *learning PyTorch with examples* tutorial|\n| |Kaggle tutorials covering an introduction to Neural Networks using Numpy, and a second one offering a PyTorch tutorial|\n\n\n\n\n\n\nIn addition to this, PyTorch MOOCs can be followed for free in main sites: edX, Coursera, Udacity\n\n## 2. Introduction to Neural Networks \n\nIn this section, we will implement neural networks from scratch using Numpy arrays\n\n* No need to learn any new Python libraries\n* But we need to deal with complexity of multilayer networks\n* Low-level implementation will be useful to grasp the most important concepts concerning DNNs\n * Back-propagation\n * Activation functions\n * Loss functions\n * Optimization methods\n * Generalization\n * Special layers and configurations\n\n### 2.0. Data preparation \n\nWe start by loading some data sets that will be used to carry out the exercises\n\n### Sign language digits data set\n\n* Dataset is taken from Kaggle and used in the above referred tutorial\n* 2062 digits in sign language. $64 \\times 64$ images\n* Problem with 10 classes. One hot encoding for the label matrix\n* Input data are images, we create also a flattened version\n\n\n```python\ndigitsX = np.load('./data/Sign-language-digits-dataset/X.npy')\ndigitsY = np.load('./data/Sign-language-digits-dataset/Y.npy')\nK = digitsX.shape[0]\nimg_size = digitsX.shape[1]\ndigitsX_flatten = digitsX.reshape(K,img_size*img_size)\n\nprint('Size of Input Data Matrix:', digitsX.shape)\nprint('Size of Flattned Input Data Matrix:', digitsX_flatten.shape)\nprint('Size of label Data Matrix:', digitsY.shape)\nselected = [260, 1400]\nplt.subplot(1, 2, 1), plt.imshow(digitsX[selected[0]].reshape(img_size, img_size)), plt.axis('off')\nplt.subplot(1, 2, 2), plt.imshow(digitsX[selected[1]].reshape(img_size, img_size)), plt.axis('off')\nplt.show()\nprint('Labels corresponding to figures:', digitsY[selected,])\n```\n\n### Dogs vs Cats data set\n\n* Dataset is taken from Kaggle\n* 25000 pictures of dogs and cats\n* Binary problem\n* Input data are images, we create also a flattened version\n* Original images are RGB, and arbitrary size\n* Preprocessed images are $64 \\times 64$ and gray scale\n\n\n```python\n# Preprocessing of original Dogs and Cats Pictures\n# Adapted from https://medium.com/@mrgarg.rajat/kaggle-dogs-vs-cats-challenge-complete-step-by-step-guide-part-1-a347194e55b1\n# RGB channels are collapsed in GRAYSCALE\n# Images are resampled to 64x64\n\n\"\"\"\nimport os, cv2 # cv2 -- OpenCV\n\ntrain_dir = './data/DogsCats/train/'\nrows = 64\ncols = 64\ntrain_images = sorted([train_dir+i for i in os.listdir(train_dir)])\n\ndef read_image(file_path):\n image = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)\n return cv2.resize(image, (rows, cols),interpolation=cv2.INTER_CUBIC)\n\ndef prep_data(images):\n m = len(images)\n X = np.ndarray((m, rows, cols), dtype=np.uint8)\n y = np.zeros((m,))\n print(\"X.shape is {}\".format(X.shape))\n \n for i,image_file in enumerate(images) :\n image = read_image(image_file)\n X[i,] = np.squeeze(image.reshape((rows, cols)))\n if 'dog' in image_file.split('/')[-1].lower():\n y[i] = 1\n elif 'cat' in image_file.split('/')[-1].lower():\n y[i] = 0\n \n if i%5000 == 0 :\n print(\"Proceed {} of {}\".format(i, m))\n \n return X,y\n\nX_train, y_train = prep_data(train_images)\nnp.save('./data/DogsCats/X.npy', X_train)\nnp.save('./data/DogsCats/Y.npy', y_train)\n\"\"\"\n```\n\n\n```python\nDogsCatsX = np.load('./data/DogsCats/X.npy')\nDogsCatsY = np.load('./data/DogsCats/Y.npy')\nK = DogsCatsX.shape[0]\nimg_size = DogsCatsX.shape[1]\nDogsCatsX_flatten = DogsCatsX.reshape(K,img_size*img_size)\n\nprint('Size of Input Data Matrix:', DogsCatsX.shape)\nprint('Size of Flattned Input Data Matrix:', DogsCatsX_flatten.shape)\nprint('Size of label Data Matrix:', DogsCatsY.shape)\nselected = [260, 16000]\nplt.subplot(1, 2, 1), plt.imshow(DogsCatsX[selected[0]].reshape(img_size, img_size)), plt.axis('off')\nplt.subplot(1, 2, 2), plt.imshow(DogsCatsX[selected[1]].reshape(img_size, img_size)), plt.axis('off')\nplt.show()\nprint('Labels corresponding to figures:', DogsCatsY[selected,])\n```\n\n### 2.1. Logistic Regression as a Simple Neural Network \n\n* We can consider logistic regression as an extremely simple (1 layer) neural network\n\n\n\n* In this context, $\\text{NLL}({\\bf w})$ is normally referred to as cross-entropy loss\n\n\n* We need to find parameters $\\bf w$ and $b$ to minimize the loss $\\rightarrow$ GD / SGD\n* Gradient computation can be simplified using the **chain rule**\n\n| \n View on TensorFlow.org\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
| Rappresentazione schematica del sistema di controllo dell'azimut di una antenna | \nDiagramma a blocchi del sistema di controllo dell'azimut di una antenna | \n
|---|---|
| \n | \n |
| \n | Legenda: RP = potenziometro di riferimento, MP = potenziometro di misurazione, dw = disturbo dovuto al vento. | \n
\n\n
\n\n\n
\n\n\n
\n\n\n
\n| \n | UV | \nConductivity | \nVolume | \n
|---|---|---|---|
| Time | \n\n | \n | \n |
| 0.0 | \n-0.000730 | \n1.04 | \n0.0 | \n
| 0.2 | \n-0.000724 | \n1.04 | \n0.0 | \n
| \n | Abbr. | \nAbbr..1 | \nMolecular Weight | \nMolecular Formula | \nResidue Formula | \nResidue Weight (-H2O) | \npKa1 | \npKb2 | \npKx3 | \npl4 | \n
|---|---|---|---|---|---|---|---|---|---|---|
| Name | \n\n | \n | \n | \n | \n | \n | \n | \n | \n | \n |
| Alanine | \nAla | \nA | \n89.10 | \nC3H7NO2 | \nC3H5NO | \n71.08 | \n2.34 | \n9.69 | \nNaN | \n6.00 | \n
| Aspartic acid | \nAsp | \nD | \n133.11 | \nC4H7NO4 | \nC4H5NO3 | \n115.09 | \n1.88 | \n9.60 | \n3.65 | \n2.77 | \n
| Glutamine | \nGln | \nQ | \n146.15 | \nC5H10N2O3 | \nC5H8N2O2 | \n128.13 | \n2.17 | \n9.13 | \nNaN | \n5.65 | \n
| Hydroxyproline | \nHyp | \nO | \n131.13 | \nC5H9NO3 | \nC5H7NO2 | \n113.11 | \n1.82 | \n9.65 | \nNaN | \nNaN | \n
| Lysine | \nLys | \nK | \n146.19 | \nC6H14N2O2 | \nC6H12N2O | \n128.18 | \n2.18 | \n8.95 | \n10.53 | \n9.74 | \n
| Proline | \nPro | \nP | \n115.13 | \nC5H9NO2 | \nC5H7NO | \n97.12 | \n1.99 | \n10.60 | \nNaN | \n6.30 | \n
| Threonine | \nThr | \nT | \n119.12 | \nC4H9NO3 | \nC4H7NO2 | \n101.11 | \n2.09 | \n9.10 | \nNaN | \n5.60 | \n
| Valine | \nVal | \nV | \n117.15 | \nC5H11NO2 | \nC5H9NO | \n99.13 | \n2.32 | \n9.62 | \nNaN | \n5.96 | \n
| \n | pKa1 | \npKb2 | \npKx3 | \n
|---|---|---|---|
| Name | \n\n | \n | \n |
| Arginine | \n2.17 | \n9.04 | \n12.48 | \n
| Asparagine | \n2.02 | \n8.80 | \nNaN | \n
| Aspartic acid | \n1.88 | \n9.60 | \n3.65 | \n
| Cysteine | \n1.96 | \n10.28 | \n8.18 | \n
| Glutamic acid | \n2.19 | \n9.67 | \n4.25 | \n
| \n | Abbr. | \nAbbr..1 | \nMolecular Weight | \nMolecular Formula | \nResidue Formula | \nResidue Weight (-H2O) | \npKa1 | \npKb2 | \npKx3 | \npl4 | \n
|---|---|---|---|---|---|---|---|---|---|---|
| Name | \n\n | \n | \n | \n | \n | \n | \n | \n | \n | \n |
| Arginine | \nArg | \nR | \n174.20 | \nC6H14N4O2 | \nC6H12N4O | \n156.19 | \n2.17 | \n9.04 | \n12.48 | \n10.76 | \n
| Histidine | \nHis | \nH | \n155.16 | \nC6H9N3O2 | \nC6H7N3O | \n137.14 | \n1.82 | \n9.17 | \n6.00 | \n7.59 | \n
| Lysine | \nLys | \nK | \n146.19 | \nC6H14N2O2 | \nC6H12N2O | \n128.18 | \n2.18 | \n8.95 | \n10.53 | \n9.74 | \n
Diffraction and crystallography
\n\n\n11.2 Describe the “phase problem” in X-ray crystallography, and at least one way the problem can be addressed (or at least circumvented to solve X-ray structures).
\n\nSee Page 420 for phase problem, See Page 421 for the way the problem can be addressed.
\n\n\n\n11.20 Draw a set of points as a rectangular array based on unit cells of side a and b, and mark the planes with Miller indices (1,0,0), (0,1,0), (1,1,0), (1,2,0), (2,3,0), (4,1,0).\n
\n\nHere's an example...\n\n$$(1,2,0) = (k,h,l) \\implies (\\frac{a}{h},\\frac{b}{k},0) = (\\frac{a}{1},\\frac{b}{2},0) \\\\ \\implies 2\\times(\\frac{a}{1},\\frac{b}{2},0) = (2a,b,0)$$\n\nWhat kind of information can be obtained using FRET spectroscopy? What is the distance dependence of the FRET effect?
\n\nFörster resonance energy transfer (FRET) spectroscopy is useful for studying processes involving inter and intra-molecular energy transfer and can be used to measure distances (ranging from 1 to 9 nm) in biological systems. Furthermore, conformational changes can be studied, and also good for studying bulk distances. Single molecule FRET —create histograms of binned FRET distances, ultimately revealing states.See Pages 500,501 for more information.
\n\n| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nmedian_house_value | \nocean_proximity | \n
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n-122.23 | \n37.88 | \n41.0 | \n880.0 | \n129.0 | \n322.0 | \n126.0 | \n8.3252 | \n452600.0 | \nNEAR BAY | \n
| 1 | \n-122.22 | \n37.86 | \n21.0 | \n7099.0 | \n1106.0 | \n2401.0 | \n1138.0 | \n8.3014 | \n358500.0 | \nNEAR BAY | \n
| 2 | \n-122.24 | \n37.85 | \n52.0 | \n1467.0 | \n190.0 | \n496.0 | \n177.0 | \n7.2574 | \n352100.0 | \nNEAR BAY | \n
| 3 | \n-122.25 | \n37.85 | \n52.0 | \n1274.0 | \n235.0 | \n558.0 | \n219.0 | \n5.6431 | \n341300.0 | \nNEAR BAY | \n
| 4 | \n-122.25 | \n37.85 | \n52.0 | \n1627.0 | \n280.0 | \n565.0 | \n259.0 | \n3.8462 | \n342200.0 | \nNEAR BAY | \n
| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nmedian_house_value | \n
|---|---|---|---|---|---|---|---|---|---|
| count | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n20433.000000 | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n
| mean | \n-119.569704 | \n35.631861 | \n28.639486 | \n2635.763081 | \n537.870553 | \n1425.476744 | \n499.539680 | \n3.870671 | \n206855.816909 | \n
| std | \n2.003532 | \n2.135952 | \n12.585558 | \n2181.615252 | \n421.385070 | \n1132.462122 | \n382.329753 | \n1.899822 | \n115395.615874 | \n
| min | \n-124.350000 | \n32.540000 | \n1.000000 | \n2.000000 | \n1.000000 | \n3.000000 | \n1.000000 | \n0.499900 | \n14999.000000 | \n
| 25% | \n-121.800000 | \n33.930000 | \n18.000000 | \n1447.750000 | \n296.000000 | \n787.000000 | \n280.000000 | \n2.563400 | \n119600.000000 | \n
| 50% | \n-118.490000 | \n34.260000 | \n29.000000 | \n2127.000000 | \n435.000000 | \n1166.000000 | \n409.000000 | \n3.534800 | \n179700.000000 | \n
| 75% | \n-118.010000 | \n37.710000 | \n37.000000 | \n3148.000000 | \n647.000000 | \n1725.000000 | \n605.000000 | \n4.743250 | \n264725.000000 | \n
| max | \n-114.310000 | \n41.950000 | \n52.000000 | \n39320.000000 | \n6445.000000 | \n35682.000000 | \n6082.000000 | \n15.000100 | \n500001.000000 | \n
| \n | Overall | \nStratified tr | \nRandom tr | \nStratified ts | \nRandom ts | \nRand. tr %error | \nRand. ts %error | \nStrat. tr %error | \nStrat. ts %error | \n
|---|---|---|---|---|---|---|---|---|---|
| 1.0 | \n0.039826 | \n0.039850 | \n0.039729 | \n0.039729 | \n0.040213 | \n-0.243309 | \n0.973236 | \n0.060827 | \n-0.243309 | \n
| 2.0 | \n0.318847 | \n0.318859 | \n0.317466 | \n0.318798 | \n0.324370 | \n-0.433065 | \n1.732260 | \n0.003799 | \n-0.015195 | \n
| 3.0 | \n0.350581 | \n0.350594 | \n0.348595 | \n0.350533 | \n0.358527 | \n-0.566611 | \n2.266446 | \n0.003455 | \n-0.013820 | \n
| 4.0 | \n0.176308 | \n0.176296 | \n0.178537 | \n0.176357 | \n0.167393 | \n1.264084 | \n-5.056334 | \n-0.006870 | \n0.027480 | \n
| 5.0 | \n0.114438 | \n0.114402 | \n0.115673 | \n0.114583 | \n0.109496 | \n1.079594 | \n-4.318374 | \n-0.031753 | \n0.127011 | \n
| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nmedian_house_value | \n
|---|---|---|---|---|---|---|---|---|---|
| longitude | \n1.000000 | \n-0.924478 | \n-0.105848 | \n0.048871 | \n0.076598 | \n0.108030 | \n0.063070 | \n-0.019583 | \n-0.047432 | \n
| latitude | \n-0.924478 | \n1.000000 | \n0.005766 | \n-0.039184 | \n-0.072419 | \n-0.115222 | \n-0.077647 | \n-0.075205 | \n-0.142724 | \n
| housing_median_age | \n-0.105848 | \n0.005766 | \n1.000000 | \n-0.364509 | \n-0.325047 | \n-0.298710 | \n-0.306428 | \n-0.111360 | \n0.114110 | \n
| total_rooms | \n0.048871 | \n-0.039184 | \n-0.364509 | \n1.000000 | \n0.929379 | \n0.855109 | \n0.918392 | \n0.200087 | \n0.135097 | \n
| total_bedrooms | \n0.076598 | \n-0.072419 | \n-0.325047 | \n0.929379 | \n1.000000 | \n0.876320 | \n0.980170 | \n-0.009740 | \n0.047689 | \n
| population | \n0.108030 | \n-0.115222 | \n-0.298710 | \n0.855109 | \n0.876320 | \n1.000000 | \n0.904637 | \n0.002380 | \n-0.026920 | \n
| households | \n0.063070 | \n-0.077647 | \n-0.306428 | \n0.918392 | \n0.980170 | \n0.904637 | \n1.000000 | \n0.010781 | \n0.064506 | \n
| median_income | \n-0.019583 | \n-0.075205 | \n-0.111360 | \n0.200087 | \n-0.009740 | \n0.002380 | \n0.010781 | \n1.000000 | \n0.687160 | \n
| median_house_value | \n-0.047432 | \n-0.142724 | \n0.114110 | \n0.135097 | \n0.047689 | \n-0.026920 | \n0.064506 | \n0.687160 | \n1.000000 | \n
| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nocean_proximity | \n
|---|---|---|---|---|---|---|---|---|---|
| 17606 | \n-121.89 | \n37.29 | \n38.0 | \n1568.0 | \n351.0 | \n710.0 | \n339.0 | \n2.7042 | \n<1H OCEAN | \n
| 18632 | \n-121.93 | \n37.05 | \n14.0 | \n679.0 | \n108.0 | \n306.0 | \n113.0 | \n6.4214 | \n<1H OCEAN | \n
| 14650 | \n-117.20 | \n32.77 | \n31.0 | \n1952.0 | \n471.0 | \n936.0 | \n462.0 | \n2.8621 | \nNEAR OCEAN | \n
| 3230 | \n-119.61 | \n36.31 | \n25.0 | \n1847.0 | \n371.0 | \n1460.0 | \n353.0 | \n1.8839 | \nINLAND | \n
| 3555 | \n-118.59 | \n34.23 | \n17.0 | \n6592.0 | \n1525.0 | \n4459.0 | \n1463.0 | \n3.0347 | \n<1H OCEAN | \n
| ... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n
| 6563 | \n-118.13 | \n34.20 | \n46.0 | \n1271.0 | \n236.0 | \n573.0 | \n210.0 | \n4.9312 | \nINLAND | \n
| 12053 | \n-117.56 | \n33.88 | \n40.0 | \n1196.0 | \n294.0 | \n1052.0 | \n258.0 | \n2.0682 | \nINLAND | \n
| 13908 | \n-116.40 | \n34.09 | \n9.0 | \n4855.0 | \n872.0 | \n2098.0 | \n765.0 | \n3.2723 | \nINLAND | \n
| 11159 | \n-118.01 | \n33.82 | \n31.0 | \n1960.0 | \n380.0 | \n1356.0 | \n356.0 | \n4.0625 | \n<1H OCEAN | \n
| 15775 | \n-122.45 | \n37.77 | \n52.0 | \n3095.0 | \n682.0 | \n1269.0 | \n639.0 | \n3.5750 | \nNEAR BAY | \n
16512 rows × 9 columns
\n| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nocean_proximity | \n
|---|---|---|---|---|---|---|---|---|---|
| 17606 | \n-121.89 | \n37.29 | \n38.0 | \n1568.0 | \n351.0 | \n710.0 | \n339.0 | \n2.7042 | \n<1H OCEAN | \n
| 18632 | \n-121.93 | \n37.05 | \n14.0 | \n679.0 | \n108.0 | \n306.0 | \n113.0 | \n6.4214 | \n<1H OCEAN | \n
| 14650 | \n-117.20 | \n32.77 | \n31.0 | \n1952.0 | \n471.0 | \n936.0 | \n462.0 | \n2.8621 | \nNEAR OCEAN | \n
| 3230 | \n-119.61 | \n36.31 | \n25.0 | \n1847.0 | \n371.0 | \n1460.0 | \n353.0 | \n1.8839 | \nINLAND | \n
| 3555 | \n-118.59 | \n34.23 | \n17.0 | \n6592.0 | \n1525.0 | \n4459.0 | \n1463.0 | \n3.0347 | \n<1H OCEAN | \n
| ... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n
| 6563 | \n-118.13 | \n34.20 | \n46.0 | \n1271.0 | \n236.0 | \n573.0 | \n210.0 | \n4.9312 | \nINLAND | \n
| 12053 | \n-117.56 | \n33.88 | \n40.0 | \n1196.0 | \n294.0 | \n1052.0 | \n258.0 | \n2.0682 | \nINLAND | \n
| 13908 | \n-116.40 | \n34.09 | \n9.0 | \n4855.0 | \n872.0 | \n2098.0 | \n765.0 | \n3.2723 | \nINLAND | \n
| 11159 | \n-118.01 | \n33.82 | \n31.0 | \n1960.0 | \n380.0 | \n1356.0 | \n356.0 | \n4.0625 | \n<1H OCEAN | \n
| 15775 | \n-122.45 | \n37.77 | \n52.0 | \n3095.0 | \n682.0 | \n1269.0 | \n639.0 | \n3.5750 | \nNEAR BAY | \n
16512 rows × 9 columns
\n| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nmedian_house_value | \n
|---|---|---|---|---|---|---|---|---|---|
| longitude | \n1.000000 | \n-0.924478 | \n-0.105848 | \n0.048871 | \n0.076598 | \n0.108030 | \n0.063070 | \n-0.019583 | \n-0.047432 | \n
| latitude | \n-0.924478 | \n1.000000 | \n0.005766 | \n-0.039184 | \n-0.072419 | \n-0.115222 | \n-0.077647 | \n-0.075205 | \n-0.142724 | \n
| housing_median_age | \n-0.105848 | \n0.005766 | \n1.000000 | \n-0.364509 | \n-0.325047 | \n-0.298710 | \n-0.306428 | \n-0.111360 | \n0.114110 | \n
| total_rooms | \n0.048871 | \n-0.039184 | \n-0.364509 | \n1.000000 | \n0.929379 | \n0.855109 | \n0.918392 | \n0.200087 | \n0.135097 | \n
| total_bedrooms | \n0.076598 | \n-0.072419 | \n-0.325047 | \n0.929379 | \n1.000000 | \n0.876320 | \n0.980170 | \n-0.009740 | \n0.047689 | \n
| population | \n0.108030 | \n-0.115222 | \n-0.298710 | \n0.855109 | \n0.876320 | \n1.000000 | \n0.904637 | \n0.002380 | \n-0.026920 | \n
| households | \n0.063070 | \n-0.077647 | \n-0.306428 | \n0.918392 | \n0.980170 | \n0.904637 | \n1.000000 | \n0.010781 | \n0.064506 | \n
| median_income | \n-0.019583 | \n-0.075205 | \n-0.111360 | \n0.200087 | \n-0.009740 | \n0.002380 | \n0.010781 | \n1.000000 | \n0.687160 | \n
| median_house_value | \n-0.047432 | \n-0.142724 | \n0.114110 | \n0.135097 | \n0.047689 | \n-0.026920 | \n0.064506 | \n0.687160 | \n1.000000 | \n
| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nmedian_house_value | \nocean_proximity | \n
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n-122.23 | \n37.88 | \n41.0 | \n880.0 | \n129.0 | \n322.0 | \n126.0 | \n8.3252 | \n452600.0 | \nNEAR BAY | \n
| 1 | \n-122.22 | \n37.86 | \n21.0 | \n7099.0 | \n1106.0 | \n2401.0 | \n1138.0 | \n8.3014 | \n358500.0 | \nNEAR BAY | \n
| 2 | \n-122.24 | \n37.85 | \n52.0 | \n1467.0 | \n190.0 | \n496.0 | \n177.0 | \n7.2574 | \n352100.0 | \nNEAR BAY | \n
| 3 | \n-122.25 | \n37.85 | \n52.0 | \n1274.0 | \n235.0 | \n558.0 | \n219.0 | \n5.6431 | \n341300.0 | \nNEAR BAY | \n
| 4 | \n-122.25 | \n37.85 | \n52.0 | \n1627.0 | \n280.0 | \n565.0 | \n259.0 | \n3.8462 | \n342200.0 | \nNEAR BAY | \n
| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nmedian_house_value | \n
|---|---|---|---|---|---|---|---|---|---|
| count | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n20433.000000 | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n20640.000000 | \n
| mean | \n-119.569704 | \n35.631861 | \n28.639486 | \n2635.763081 | \n537.870553 | \n1425.476744 | \n499.539680 | \n3.870671 | \n206855.816909 | \n
| std | \n2.003532 | \n2.135952 | \n12.585558 | \n2181.615252 | \n421.385070 | \n1132.462122 | \n382.329753 | \n1.899822 | \n115395.615874 | \n
| min | \n-124.350000 | \n32.540000 | \n1.000000 | \n2.000000 | \n1.000000 | \n3.000000 | \n1.000000 | \n0.499900 | \n14999.000000 | \n
| 25% | \n-121.800000 | \n33.930000 | \n18.000000 | \n1447.750000 | \n296.000000 | \n787.000000 | \n280.000000 | \n2.563400 | \n119600.000000 | \n
| 50% | \n-118.490000 | \n34.260000 | \n29.000000 | \n2127.000000 | \n435.000000 | \n1166.000000 | \n409.000000 | \n3.534800 | \n179700.000000 | \n
| 75% | \n-118.010000 | \n37.710000 | \n37.000000 | \n3148.000000 | \n647.000000 | \n1725.000000 | \n605.000000 | \n4.743250 | \n264725.000000 | \n
| max | \n-114.310000 | \n41.950000 | \n52.000000 | \n39320.000000 | \n6445.000000 | \n35682.000000 | \n6082.000000 | \n15.000100 | \n500001.000000 | \n
| \n | Overall | \nStratified tr | \nRandom tr | \nStratified ts | \nRandom ts | \nRand. tr %error | \nRand. ts %error | \nStrat. tr %error | \nStrat. ts %error | \n
|---|---|---|---|---|---|---|---|---|---|
| 1.0 | \n0.039826 | \n0.039850 | \n0.039729 | \n0.039729 | \n0.040213 | \n-0.243309 | \n0.973236 | \n0.060827 | \n-0.243309 | \n
| 2.0 | \n0.318847 | \n0.318859 | \n0.317466 | \n0.318798 | \n0.324370 | \n-0.433065 | \n1.732260 | \n0.003799 | \n-0.015195 | \n
| 3.0 | \n0.350581 | \n0.350594 | \n0.348595 | \n0.350533 | \n0.358527 | \n-0.566611 | \n2.266446 | \n0.003455 | \n-0.013820 | \n
| 4.0 | \n0.176308 | \n0.176296 | \n0.178537 | \n0.176357 | \n0.167393 | \n1.264084 | \n-5.056334 | \n-0.006870 | \n0.027480 | \n
| 5.0 | \n0.114438 | \n0.114402 | \n0.115673 | \n0.114583 | \n0.109496 | \n1.079594 | \n-4.318374 | \n-0.031753 | \n0.127011 | \n
| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nmedian_house_value | \n
|---|---|---|---|---|---|---|---|---|---|
| longitude | \n1.000000 | \n-0.924478 | \n-0.105848 | \n0.048871 | \n0.076598 | \n0.108030 | \n0.063070 | \n-0.019583 | \n-0.047432 | \n
| latitude | \n-0.924478 | \n1.000000 | \n0.005766 | \n-0.039184 | \n-0.072419 | \n-0.115222 | \n-0.077647 | \n-0.075205 | \n-0.142724 | \n
| housing_median_age | \n-0.105848 | \n0.005766 | \n1.000000 | \n-0.364509 | \n-0.325047 | \n-0.298710 | \n-0.306428 | \n-0.111360 | \n0.114110 | \n
| total_rooms | \n0.048871 | \n-0.039184 | \n-0.364509 | \n1.000000 | \n0.929379 | \n0.855109 | \n0.918392 | \n0.200087 | \n0.135097 | \n
| total_bedrooms | \n0.076598 | \n-0.072419 | \n-0.325047 | \n0.929379 | \n1.000000 | \n0.876320 | \n0.980170 | \n-0.009740 | \n0.047689 | \n
| population | \n0.108030 | \n-0.115222 | \n-0.298710 | \n0.855109 | \n0.876320 | \n1.000000 | \n0.904637 | \n0.002380 | \n-0.026920 | \n
| households | \n0.063070 | \n-0.077647 | \n-0.306428 | \n0.918392 | \n0.980170 | \n0.904637 | \n1.000000 | \n0.010781 | \n0.064506 | \n
| median_income | \n-0.019583 | \n-0.075205 | \n-0.111360 | \n0.200087 | \n-0.009740 | \n0.002380 | \n0.010781 | \n1.000000 | \n0.687160 | \n
| median_house_value | \n-0.047432 | \n-0.142724 | \n0.114110 | \n0.135097 | \n0.047689 | \n-0.026920 | \n0.064506 | \n0.687160 | \n1.000000 | \n
| \n | longitude | \nlatitude | \nhousing_median_age | \ntotal_rooms | \ntotal_bedrooms | \npopulation | \nhouseholds | \nmedian_income | \nocean_proximity | \nrooms_per_household | \nbedrooms_per_household | \npopulation_per_household | \nbedrooms_per_rooms | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n-121.89 | \n37.29 | \n38 | \n1568 | \n351 | \n710 | \n339 | \n2.7042 | \n<1H OCEAN | \n4.62537 | \n1.0354 | \n2.0944 | \n0.223852 | \n
| 1 | \n-121.93 | \n37.05 | \n14 | \n679 | \n108 | \n306 | \n113 | \n6.4214 | \n<1H OCEAN | \n6.00885 | \n0.955752 | \n2.70796 | \n0.159057 | \n
| 2 | \n-117.2 | \n32.77 | \n31 | \n1952 | \n471 | \n936 | \n462 | \n2.8621 | \nNEAR OCEAN | \n4.22511 | \n1.01948 | \n2.02597 | \n0.241291 | \n
| 3 | \n-119.61 | \n36.31 | \n25 | \n1847 | \n371 | \n1460 | \n353 | \n1.8839 | \nINLAND | \n5.23229 | \n1.05099 | \n4.13598 | \n0.200866 | \n
| 4 | \n-118.59 | \n34.23 | \n17 | \n6592 | \n1525 | \n4459 | \n1463 | \n3.0347 | \n<1H OCEAN | \n4.50581 | \n1.04238 | \n3.04785 | \n0.231341 | \n
| 在 TensorFlow.org 上查看\n | \n在 Google Colab 运行\n | \n在 Github 上查看源代码\n | \n下载笔记本 | \n
This shows the Huber weight function, $W_2(x)$ and some cartoon data points that are insiders or outsiders as far as the robust location estimate is concerned.
\n\n\n\n\n\n### Breakdown Point\n\nSo far, our discussion of robustness has been very abstract. A more concrete\nconcept of robustness comes from the breakdown point. In the simplest terms,\nthe breakdown point describes what happens when a single data point in an\nestimator is changed in the most damaging way possible. For example, suppose we\nhave the sample mean, $\\hat{\\mu}=\\sum x_i/n$, and we take one of the $x_i$\npoints to be infinite. What happens to this estimator? It also goes infinite.\nThis means that the breakdown point of the estimator is 0%. On the other hand,\nthe median has a breakdown point of 50%, meaning that half of the data for\ncomputing the median could go infinite without affecting the median value. The median\nis a *rank* statistic that cares more about the relative ranking of the data\nthan the values of the data, which explains its robustness.\n\nThe simpliest but still formal way to express the breakdown point is to\ntake $n$ data points, $\\mathcal{D} = \\lbrace (x_i,y_i) \\rbrace$. Suppose $T$\nis a regression estimator that yields a vector of regression coefficients,\n$\\boldsymbol{\\theta}$,\n\n$$\nT(\\mathcal{D}) = \\boldsymbol{\\theta}\n$$\n\n Likewise, consider all possible corrupted samples of the data\n$\\mathcal{D}^\\prime$. The maximum *bias* caused by this contamination is\nthe following:\n\n$$\n\\texttt{bias}_{m} = \\sup_{\\mathcal{D}^\\prime} \\Vert T(\\mathcal{D^\\prime})-T(\\mathcal{D}) \\Vert\n$$\n\n where the $\\sup$ sweeps over all possible sets of $m$ contaminated samples.\nUsing this, the breakdown point is defined as the following:\n\n$$\n\\epsilon_m = \\min \\Big\\lbrace \\frac{m}{n} \\colon \\texttt{bias}_{m} \\rightarrow \\infty \\Big\\rbrace\n$$\n\n For example, in our least-squares regression, even one point at\ninfinity causes an infinite $T$. Thus, for least-squares regression,\n$\\epsilon_m=1/n$. In the limit $n \\rightarrow \\infty$, we have $\\epsilon_m\n\\rightarrow 0$.\n\n### Estimating Scale\n\nIn robust statistics, the concept of *scale* refers to a measure of the\ndispersion of the data. Usually, we use the\nestimated standard deviation for this, but this has a terrible breakdown point.\nEven more troubling, in order to get a good estimate of location, we have to\neither somehow know the scale ahead of time, or jointly estimate it. None of\nthese methods have easy-to-compute closed form solutions and must be computed\nnumerically.\n\nThe most popular method for estimating scale is the *median absolute deviation*\n\n$$\n\\texttt{MAD} = \\texttt{Med} (\\vert \\mathbf{x} - \\texttt{Med}(\\mathbf{x})\\vert)\n$$\n\n In words, take the median of the data $\\mathbf{x}$ and\nthen subtract that median from the data itself, and then take the median of the\nabsolute value of the result. Another good dispersion estimate is the *interquartile range*,\n\n$$\n\\texttt{IQR} = x_{(n-m+1)} - x_{(n)}\n$$\n\n where $m= [n/4]$. The $x_{(n)}$ notation means the $n^{th}$ data\nelement after the data have been sorted. Thus, in this notation,\n$\\texttt{max}(\\mathbf{x})=x_{(n)}$. In the case where $x \\sim\n\\mathcal{N}(\\mu,\\sigma^2)$, then $\\texttt{MAD}$ and $\\texttt{IQR}$ are constant\nmultiples of $\\sigma$ such that the normalized $\\texttt{MAD}$ is the following,\n\n$$\n\\texttt{MADN}(x) = \\frac{\\texttt{MAD} }{0.675}\n$$\n\n The number comes from the inverse CDF of the normal distribution\ncorresponding to the $0.75$ level. Given the complexity of the\ncalculations, *jointly* estimating both location and scale is a purely\nnumerical matter. Fortunately, the Statsmodels module has many of these\nready to use. Let's create some contaminated data in the following code,\n\n\n```python\nimport statsmodels.api as sm\nfrom scipy import stats\ndata=np.hstack([stats.norm(10,1).rvs(10),stats.norm(0,1).rvs(100)])\n```\n\n These data correspond to our model of contamination that we started\nthis section with. As shown in the histogram in [Figure](#fig:Robust_Statistics_0002), there are two normal distributions, one\ncentered neatly at zero, representing the majority of the samples, and another\ncoming less regularly from the normal distribution on the right. Notice that\nthe group of infrequent samples on the right separates the mean and median\nestimates (vertical dotted and dashed lines). In the absence of the\ncontaminating distribution on the right, the standard deviation for this data\nshould be close to one. However, the usual non-robust estimate for standard\ndeviation (`np.std`) comes out to approximately three. Using the\n$\\texttt{MADN}$ estimator (`sm.robust.scale.mad(data)`) we obtain approximately\n1.25. Thus, the robust estimate of dispersion is less moved by the presence of\nthe contaminating distribution.\n\n\n\n\n\nHistogram of sample data. Notice that the group of infrequent samples on the right separates the mean and median estimates indicated by the vertical lines.
\n\n\n\n\n\nThe generalized maximum likelihood M-estimation extends to joint\nscale and location estimation using Huber functions. For example,\n\n\n```python\nhuber = sm.robust.scale.Huber()\nloc,scl=huber(data)\n```\n\n which implements Huber's *proposal two* method of joint estimation of\nlocation and scale. This kind of estimation is the key ingredient to robust\nregression methods, many of which are implemented in Statsmodels in\n`statsmodels.formula.api.rlm`. The corresponding documentation has more\ninformation.\n", "meta": {"hexsha": "b452d76173f6c4a864c7634fd4b8f88d787c14df", "size": 140181, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/statistics/notebooks/Robust_Statistics.ipynb", "max_stars_repo_name": "nsydn/Python-for-Probability-Statistics-and-Machine-Learning", "max_stars_repo_head_hexsha": "d3e0f8ea475525a694a975dbfd2bf80bc2967cc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 570, "max_stars_repo_stars_event_min_datetime": "2016-05-05T19:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:09:19.000Z", "max_issues_repo_path": "chapters/statistics/notebooks/Robust_Statistics.ipynb", "max_issues_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_issues_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-12T22:18:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-06T14:37:06.000Z", "max_forks_repo_path": "chapters/statistics/notebooks/Robust_Statistics.ipynb", "max_forks_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_forks_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276, "max_forks_repo_forks_event_min_datetime": "2016-05-27T01:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:20:27.000Z", "avg_line_length": 184.4486842105, "max_line_length": 114721, "alphanum_fraction": 0.8922179183, "converted": true, "num_tokens": 4580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748935136303, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.09137437236301638}} {"text": "```python\nfrom IPython.display import HTML\n\nHTML('''\n''')\n```\n\n\n\n\n\n\n\n\n\n\n```javascript\n%%javascript\n MathJax.Hub.Config({\n TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n });\n```\n\n\n| \n | B | \nIXY | \nIXZ | \nIYY | \nIYZ | \nIZZ | \nKXX | \nKXY | \nKYY | \nKZZ | \nLPP | \nS | \nV | \nXCG | \nYCG | \nZCG | \naccx | \nacto | \nb1c | \nb1cr | \nb1l | \nb1q | \nb2c | \nb2cr | \nb2l | \nb2q | \nb3c | \nb3cr | \nb3l | \nb3q | \nb4c | \nb4cr | \nb4l | \nb4q | \nb5c | \nb5cr | \nb5l | \nb5q | \nb6c | \nb6cr | \nb6l | \nb6q | \nbdens | \nbody | \nclev | \nclevel | \ncurv | \ndens | \ndensi | \ndofa | \ndofactor | \ndopa | \ndopadding | \ndopo | \ndopower | \ndown | \ndowns | \ndownst | \ndt | \nfile | \nfile_path_ts | \nfn | \nform | \nfree | \ngravi | \nheave | \nheel | \nhull | \ninter | \nk1nd | \nk2nd | \nk3nd | \nk4nd | \nk5nd | \nk6nd | \nkxx | \nkyy | \nleve | \nlevel | \nlpp | \nm | \nmaxti | \nmaxtime | \nmesh | \nname | \nnpxp | \nnpyp | \nnstep | \nnthr | \npitch | \npowe | \npower | \nrefle | \nreflen | \nrn | \nroll | \nrud1 | \nrud2 | \nrud3 | \nrud4 | \nrud5 | \nrud6 | \nrudt | \nside | \nslim | \nstre | \nstrength | \nsurge | \nsway | \nta | \ntf | \ntfnhi | \ntfnhigh | \ntfnlo | \ntfnlow | \ntitl | \ntitle | \ntrim | \nupst | \nupstr | \nvm_s | \nwlin | \nwlme | \nyaw | \nymax | \nymin | \nzcg | \nconv | \nencounters | \nid | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| kvlcc2_rolldecay_0kn | \n0.853 | \n0.0 | \n0.0 | \n26.055 | \n0.0 | \n26.055 | \n0.341 | \n7.556 | \n1.177 | \n1.177 | \n4.706 | \n5.981 | \n0.993 | \n2.519 | \n0.0 | \n0.274 | \n0.050 | \n1.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.00000 | \n0.00000 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.6 | \n0.3 | \n6.0 | \n6.0 | \n0.00002 | \n1000.0 | \n1000.0 | \n50.0 | \n50.0 | \n2.0 | \n2.0 | \n2.0 | \n2.0 | \n1.00 | \n-5.0 | \n1.00 | \n0.02 | \n.. | \nC:\\Dev\\Prediction-of-roll-damping-using-fully-... | \n1.472020e-07 | \n0.23 | \n0.3 | \n9.80665 | \n0.0 | \n0.0 | \n0.002 | \n0.000000e+00 | \n0.1 | \n0.1 | \n0.0 | \n0.0 | \n0.0 | \n0.1 | \n0.341185 | \n1.1765 | \n6.0 | \n6.0 | \n4.706 | \n993.42 | \n180.0 | \n180.0 | \n0.000000e+00 | \nTRAN | \n40.0 | \n40.0 | \n30.0 | \n32.0 | \n0.0 | \n2.0 | \n2.0 | \n4.706 | \n4.706 | \n3.957280e+00 | \n10.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n1.00 | \n30.0 | \n0.50 | \n0.50 | \n0.0 | \n0.0 | \n0.3059 | \n0.3059 | \n4.0 | \n4.0 | \n0.5 | \n0.5 | \nKVLCC2 | \nKVLCC2 | \n0.0 | \n1.00 | \n5.0 | \n0.000001 | \n0.000001 | \n0.000001 | \n0.0 | \n5.0 | \n-5.0 | \n0.2735 | \nNaN | \nNaN | \n21338.0 | \n
| kvlcc2_rolldecay_15-5kn_const_large2 | \n0.853 | \n0.0 | \n0.0 | \n26.055 | \n0.0 | \n26.055 | \n0.341 | \n7.556 | \n1.177 | \n1.177 | \n4.706 | \n5.981 | \n0.993 | \n2.519 | \n0.0 | \n0.274 | \n0.025 | \n1.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.00000 | \n0.00000 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.6 | \n0.3 | \n6.0 | \n6.0 | \n0.00002 | \n1000.0 | \n1000.0 | \n1.0 | \n1.0 | \n2.0 | \n2.0 | \n1.0 | \n1.0 | \n0.70 | \n-5.0 | \n0.70 | \n0.02 | \n.. | \nC:\\Dev\\Prediction-of-roll-damping-using-fully-... | \n1.423410e-01 | \n0.23 | \n0.3 | \n9.80665 | \n0.0 | \n0.0 | \n0.002 | \n0.000000e+00 | \n0.1 | \n0.1 | \n0.0 | \n0.0 | \n0.0 | \n0.1 | \n0.341185 | \n1.1765 | \n6.0 | \n6.0 | \n4.706 | \n993.42 | \n200.0 | \n200.0 | \n0.000000e+00 | \nTRAN | \n40.0 | \n40.0 | \n30.0 | \n32.0 | \n0.0 | \n2.0 | \n2.0 | \n4.706 | \n4.706 | \n3.826600e+06 | \n10.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.70 | \n30.0 | \n0.05 | \n0.05 | \n0.0 | \n0.0 | \n0.3059 | \n0.3059 | \n4.0 | \n4.0 | \n0.5 | \n0.5 | \nKVLCC2 | \nKVLCC2 | \n0.0 | \n0.70 | \n5.0 | \n0.966976 | \n0.000001 | \n0.000001 | \n0.0 | \n5.0 | \n-5.0 | \n0.2735 | \nNaN | \nNaN | \n21340.0 | \n
| kvlcc2_rolldecay_15-5kn_ikeda_dev | \n0.853 | \n0.0 | \n0.0 | \n26.055 | \n0.0 | \n26.055 | \n0.341 | \n7.556 | \n1.177 | \n1.177 | \n4.706 | \n5.981 | \n0.993 | \n2.519 | \n0.0 | \n0.274 | \n0.050 | \n1.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n6.07217 | \n2.74371 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.0 | \n1.0 | \n0.0 | \n0.0 | \n0.6 | \n0.3 | \n6.0 | \n6.0 | \n0.00004 | \n1000.0 | \n1000.0 | \n0.0 | \n0.0 | \n2.0 | \n2.0 | \n1.0 | \n1.0 | \n0.25 | \n-2.0 | \n0.25 | \nNaN | \n.. | \nC:\\Dev\\Prediction-of-roll-damping-using-fully-... | \n1.423410e-01 | \n0.20 | \n0.3 | \n9.80665 | \n0.0 | \n0.0 | \n0.002 | \n1.000000e-07 | \n0.1 | \n0.1 | \n0.0 | \n0.0 | \n0.0 | \n0.1 | \n0.341185 | \n1.1765 | \n6.0 | \n6.0 | \n4.706 | \n993.42 | \n600.0 | \n600.0 | \n1.000000e-07 | \nTRAN | \n24.0 | \n24.0 | \n30.0 | \n6.0 | \n0.0 | \n2.0 | \n2.0 | \n4.706 | \n4.706 | \n3.826600e+06 | \n10.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.25 | \n30.0 | \n1.00 | \n1.00 | \n0.0 | \n0.0 | \n0.3059 | \n0.3059 | \n4.0 | \n4.0 | \n0.5 | \n0.5 | \nKVLCC2 | \nKVLCC2 | \n0.0 | \n0.25 | \n2.0 | \n0.966976 | \n0.000001 | \n0.000001 | \n0.0 | \n2.0 | \n-2.0 | \n0.2735 | \n0.0001 | \n0.0 | \n21340.0 | \n
| \n | area | \nx | \nt | \nb | \nr_b | \n
|---|---|---|---|---|---|
| no | \n\n | \n | \n | \n | \n |
| 0 | \n13.826612 | \n-5.495000 | \n2.00 | \n11.638577 | \n6.636080 | \n
| 1 | \n123.851306 | \n10.159932 | \n18.25 | \n27.893522 | \n42.367175 | \n
| 2 | \n428.211409 | \n28.051284 | \n20.80 | \n41.824284 | \n45.369454 | \n
| 3 | \n683.709165 | \n43.706216 | \n20.80 | \n50.282514 | \n41.080696 | \n
| 4 | \n917.895066 | \n61.597568 | \n20.80 | \n56.159232 | \n34.146143 | \n
| \n | Province/State | \nCountry/Region | \nLat | \nLong | \n1/22/20 | \n1/23/20 | \n1/24/20 | \n1/25/20 | \n1/26/20 | \n1/27/20 | \n... | \n5/24/20 | \n5/25/20 | \n5/26/20 | \n5/27/20 | \n5/28/20 | \n5/29/20 | \n5/30/20 | \n5/31/20 | \n6/1/20 | \n6/2/20 | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \nNaN | \nAfghanistan | \n33.0000 | \n65.0000 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n10582 | \n11173 | \n11831 | \n12456 | \n13036 | \n13659 | \n14525 | \n15205 | \n15750 | \n16509 | \n
| 1 | \nNaN | \nAlbania | \n41.1533 | \n20.1683 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n998 | \n1004 | \n1029 | \n1050 | \n1076 | \n1099 | \n1122 | \n1137 | \n1143 | \n1164 | \n
| 2 | \nNaN | \nAlgeria | \n28.0339 | \n1.6596 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n8306 | \n8503 | \n8697 | \n8857 | \n8997 | \n9134 | \n9267 | \n9394 | \n9513 | \n9626 | \n
| 3 | \nNaN | \nAndorra | \n42.5063 | \n1.5218 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n762 | \n763 | \n763 | \n763 | \n763 | \n764 | \n764 | \n764 | \n765 | \n844 | \n
| 4 | \nNaN | \nAngola | \n-11.2027 | \n17.8739 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n69 | \n70 | \n70 | \n71 | \n74 | \n81 | \n84 | \n86 | \n86 | \n86 | \n
5 rows × 137 columns
\n| \n | Province/State | \nCountry/Region | \nLat | \nLong | \n1/22/20 | \n1/23/20 | \n1/24/20 | \n1/25/20 | \n1/26/20 | \n1/27/20 | \n... | \n5/24/20 | \n5/25/20 | \n5/26/20 | \n5/27/20 | \n5/28/20 | \n5/29/20 | \n5/30/20 | \n5/31/20 | \n6/1/20 | \n6/2/20 | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 217 | \nBermuda | \nUnited Kingdom | \n32.3078 | \n-64.7505 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n133 | \n133 | \n139 | \n139 | \n140 | \n140 | \n140 | \n140 | \n141 | \n141 | \n
| 218 | \nCayman Islands | \nUnited Kingdom | \n19.3133 | \n-81.2546 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n129 | \n134 | \n137 | \n140 | \n140 | \n141 | \n141 | \n141 | \n150 | \n151 | \n
| 219 | \nChannel Islands | \nUnited Kingdom | \n49.3723 | \n-2.3644 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n558 | \n559 | \n559 | \n560 | \n560 | \n560 | \n560 | \n560 | \n560 | \n560 | \n
| 220 | \nGibraltar | \nUnited Kingdom | \n36.1408 | \n-5.3536 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n154 | \n154 | \n154 | \n157 | \n158 | \n161 | \n169 | \n170 | \n170 | \n172 | \n
| 221 | \nIsle of Man | \nUnited Kingdom | \n54.2361 | \n-4.5481 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n336 | \n336 | \n336 | \n336 | \n336 | \n336 | \n336 | \n336 | \n336 | \n336 | \n
| 222 | \nMontserrat | \nUnited Kingdom | \n16.7425 | \n-62.1874 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n11 | \n11 | \n11 | \n11 | \n11 | \n11 | \n11 | \n11 | \n11 | \n11 | \n
| 223 | \nNaN | \nUnited Kingdom | \n55.3781 | \n-3.4360 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n259559 | \n261184 | \n265227 | \n267240 | \n269127 | \n271222 | \n272826 | \n274762 | \n276332 | \n277985 | \n
| 248 | \nAnguilla | \nUnited Kingdom | \n18.2206 | \n-63.0686 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n3 | \n3 | \n3 | \n3 | \n3 | \n3 | \n3 | \n3 | \n3 | \n3 | \n
| 249 | \nBritish Virgin Islands | \nUnited Kingdom | \n18.4207 | \n-64.6400 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n8 | \n8 | \n8 | \n8 | \n8 | \n8 | \n8 | \n8 | \n8 | \n8 | \n
| 250 | \nTurks and Caicos Islands | \nUnited Kingdom | \n21.6940 | \n-71.7979 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n12 | \n12 | \n12 | \n12 | \n12 | \n12 | \n12 | \n12 | \n12 | \n12 | \n
| 257 | \nFalkland Islands (Malvinas) | \nUnited Kingdom | \n-51.7963 | \n-59.5236 | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n... | \n13 | \n13 | \n13 | \n13 | \n13 | \n13 | \n13 | \n13 | \n13 | \n13 | \n
11 rows × 137 columns
\nFigure 1:
\n\n\nAnother useful Python package is\n[pandas](https://pandas.pydata.org/), which is an open source library\nproviding high-performance, easy-to-use data structures and data\nanalysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n\n**pandas** has two major classes, the **DataFrame** class with\ntwo-dimensional data objects and tabular data organized in columns and\nthe class **Series** with a focus on one-dimensional data objects. Both\nclasses allow you to index data easily as we will see in the examples\nbelow. **pandas** allows you also to perform mathematical operations on\nthe data, spanning from simple reshapings of vectors and matrices to\nstatistical operations.\n\nThe following simple example shows how we can, in an easy way make\ntables of our data. Here we define a data set which includes names,\nplace of birth and date of birth, and displays the data in an easy to\nread way. We will see repeated use of **pandas**, in particular in\nconnection with classification of data.\n\n\n```python\nimport pandas as pd\nfrom IPython.display import display\ndata = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n }\ndata_pandas = pd.DataFrame(data)\ndisplay(data_pandas)\n```\n\nIn the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\nand reorganize the above lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\nDisplaying these results, we see that the indices are given by the default numbers from zero to three.\n**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as\n\n\n```python\ndata_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\ndisplay(data_pandas)\n```\n\nThereafter we display the content of the row which begins with the index **Aragorn**\n\n\n```python\ndisplay(data_pandas.loc['Aragorn'])\n```\n\nWe can easily append data to this, for example\n\n\n```python\nnew_hobbit = {'First Name': [\"Peregrin\"],\n 'Last Name': [\"Took\"],\n 'Place of birth': [\"Shire\"],\n 'Date of Birth T.A.': [2990]\n }\ndata_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\ndisplay(data_pandas)\n```\n\nHere are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \nof dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.\n\n\n```python\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\nnp.random.seed(100)\n# setting up a 10 x 5 matrix\nrows = 10\ncols = 5\na = np.random.randn(rows,cols)\ndf = pd.DataFrame(a)\ndisplay(df)\nprint(df.mean())\nprint(df.std())\ndisplay(df**2)\n```\n\nThereafter we can select specific columns only and plot final results\n\n\n```python\ndf.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\ndf.index = np.arange(10)\n\ndisplay(df)\nprint(df['Second'].mean() )\nprint(df.info())\nprint(df.describe())\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndf.cumsum().plot(lw=2.0, figsize=(10,6))\nplt.show()\n\n\ndf.plot.bar(figsize=(10,6), rot=15)\nplt.show()\n```\n\nWe can produce a $4\\times 4$ matrix\n\n\n```python\nb = np.arange(16).reshape((4,4))\nprint(b)\ndf1 = pd.DataFrame(b)\nprint(df1)\n```\n\nand many other operations. \n\nThe **Series** class is another important class included in\n**pandas**. You can view it as a specialization of **DataFrame** but where\nwe have just a single column of data. It shares many of the same\nfeatures as **DataFrame**. As with **DataFrame**, most operations are\nvectorized, achieving thereby a high performance when dealing with\ncomputations of arrays, in particular labeled arrays. As we will see\nbelow it leads also to a very concice code close to the mathematical\noperations we may be interested in. For multidimensional arrays, we\nrecommend strongly\n[xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of\nthe same flexibility as **pandas**, but allows for the extension to\nhigher dimensions than two.\n\n## Introduction to Git and GitHub/GitLab and similar\n\n[Git](https://git-scm.com/) is a distributed version-control system\nfor tracking changes in any set of files, originally designed for\ncoordinating work among programmers cooperating on source code during\nsoftware development.\n\nThe [reference document and videos here](https://git-scm.com/doc)\ngive you an excellent introduction to the **git**.\n\nWe believe you will find version-control software very useful in your work.\n\n## GitHub, GitLab and many other\n\n[GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), [Bitbucket](https://bitbucket.org/product?&aceid=&adposition=&adgroup=92266806717&campaign=1407243017&creative=414608923671&device=c&keyword=bitbucket&matchtype=e&network=g&placement=&ds_kids=p51241248597&ds_e=GOOGLE&ds_eid=700000001551985&ds_e1=GOOGLE&gclid=Cj0KCQiA6Or_BRC_ARIsAPzuer_yrxzs-R8KDVdF0-DduJR9hTBYcjdE8L9_CkA9eyz8XT7-3bFGOpQaAqe2EALw_wcB&gclsrc=aw.ds) and other are code hosting platforms for\nversion control and collaboration. They let you and others work\ntogether on projects from anywhere.\n\nAll teaching material related to this course is open and freely\navailable via the GitHub site of the course. The video here gives a\nshort intro to\n[GitHub](https://www.youtube.com/watch/w3jLJU7DT5E?reload=9).\n\nSee also the [overview video on Git and GitHub](https://mediaspace.msu.edu/media/t/1_8mgx3cyf).\n\n## Useful Git and GitHub links\n\nThese are a couple references that we have found useful (git commands, markdown, GitPages):\n*| \n | t[s] | \ny[m] | \nv[m/s] | \na[m/s^2] | \n
|---|---|---|---|---|
| 0 | \n0.0 | \n10.000000 | \n0.000000 | \n-9.80655 | \n
| 1 | \n0.1 | \n9.950967 | \n-1.470982 | \n-9.80655 | \n
| 2 | \n0.2 | \n9.803869 | \n-2.451638 | \n-9.80655 | \n
| 3 | \n0.3 | \n9.558705 | \n-3.432292 | \n-9.80655 | \n
| 4 | \n0.4 | \n9.215476 | \n-4.412948 | \n-9.80655 | \n
| 5 | \n0.5 | \n8.774181 | \n-5.393602 | \n-9.80655 | \n
| 6 | \n0.6 | \n8.234821 | \n-6.374258 | \n-9.80655 | \n
| 7 | \n0.7 | \n7.597395 | \n-7.354913 | \n-9.80655 | \n
| 8 | \n0.8 | \n6.861904 | \n-8.335567 | \n-9.80655 | \n
| 9 | \n0.9 | \n6.028347 | \n-9.316222 | \n-9.80655 | \n
| 10 | \n1.0 | \n5.096725 | \n-10.296878 | \n-9.80655 | \n
| 11 | \n1.1 | \n4.067037 | \n-11.277533 | \n-9.80655 | \n
| 12 | \n1.2 | \n2.939284 | \n-12.258187 | \n-9.80655 | \n
Failed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\nThere is a problem with this: we haven't checked if the states on the curve can be *physically* connected to this point. That is, we haven't checked how the characteristic speed changes along the curve.\n\nHere it is obvious: we know that the characteristics must spread across the rarefaction, so $\\lambda$ must increase, and as $\\xi = \\lambda$ we must have the characteristic coordinate increasing.\n\n\n```python\ndef plot_sw_rarefaction_physical(hl, ul):\n \"Plot the rarefaction curve through the state (hl, ul)\"\n \n xil = ul - np.sqrt(hl)\n xi_physical = np.linspace(xil, xi_max)\n xi_unphysical = np.linspace(xi_min, xil)\n h_physical = ((xil - xi_physical) / 3.0 + np.sqrt(hl))**2\n u_physical = 2.0 * (xi_physical - xil) / 3.0 + ul\n h_unphysical = ((xil - xi_unphysical) / 3.0 + np.sqrt(hl))**2\n u_unphysical = 2.0 * (xi_unphysical - xil) / 3.0 + ul\n \n \n fig = plt.figure(figsize=(12,8))\n ax = fig.add_subplot(111)\n ax.plot(hl, ul, 'rx', markersize = 16, markeredgewidth = 3)\n ax.plot(h_physical, u_physical, 'k-', linewidth = 2, label=\"Physical\")\n ax.plot(h_unphysical, u_unphysical, 'k--', linewidth = 2, label=\"Unphysical\")\n ax.set_xlabel(r\"$h$\")\n ax.set_ylabel(r\"$u$\")\n dh = h_max - h_min\n du = u_max - u_min\n ax.set_xbound(h_min - 0.1 * dh, h_max + 0.1 * dh)\n ax.set_ybound(u_min - 0.1 * du, u_max + 0.1 * du)\n ax.legend()\n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_rarefaction_physical, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = 0.0))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\nWe see that along the physical part of the rarefaction curve the height $h$ decreases.\n\nInstead of writing the solution in terms of the similarity coordinate $\\xi$ we can instead write the solution in terms of any other single parameter. It is useful to write it in terms of the height, which can be done simply by re-arranging the equations giving $u$ and $h$ in terms of $\\xi$. So, a state with height $h_m$ to the right of the state $(h_l, u_l)$ can be connected across a rarefaction if\n$$\n u_m = u_l + 2 \\left( \\sqrt{h_l} - \\sqrt{h_m} \\right).\n$$\n\nIn this form we will look at the characteristic curves and the behaviour in state space to cross-check.\n\n\n```python\ndef plot_sw_rarefaction_physical_characteristics(hl, ul, hm):\n \"Plot the rarefaction curve through the state (hl, ul) finishing at (hm, um)\"\n \n um = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hm))\n \n h_maximum = np.max([h_max, hl, hm])\n h_minimum = np.min([h_min, hl, hm])\n u_maximum = np.max([u_max, ul, um])\n u_minimum = np.min([u_min, ul, um])\n dh = h_maximum - h_minimum\n du = u_maximum - u_minimum\n xi_min = u_minimum - np.sqrt(h_maximum)\n xi_max = u_maximum - np.sqrt(h_minimum)\n \n xil = ul - np.sqrt(hl)\n xim = um - np.sqrt(hm)\n xi_physical = np.linspace(xil, xi_max)\n xi_unphysical = np.linspace(xi_min, xil)\n h_physical = ((xil - xi_physical) / 3.0 + np.sqrt(hl))**2\n u_physical = 2.0 * (xi_physical - xil) / 3.0 + ul\n h_unphysical = ((xil - xi_unphysical) / 3.0 + np.sqrt(hl))**2\n u_unphysical = 2.0 * (xi_unphysical - xil) / 3.0 + ul\n \n \n fig = plt.figure(figsize=(12,8))\n ax1 = fig.add_subplot(121)\n ax1.plot(hl, ul, 'rx', markersize = 16, markeredgewidth = 3, label=r\"$(h_l, u_l)$\")\n ax1.plot(hm, um, 'b+', markersize = 16, markeredgewidth = 3, label=r\"$(h_m, u_m)$\")\n ax1.plot(h_physical, u_physical, 'k-', linewidth = 2, label=\"Physical\")\n ax1.plot(h_unphysical, u_unphysical, 'k--', linewidth = 2, label=\"Unphysical\")\n ax1.set_xlabel(r\"$h$\")\n ax1.set_ylabel(r\"$u$\")\n ax1.set_xbound(h_minimum - 0.1 * dh, h_maximum + 0.1 * dh)\n ax1.set_ybound(u_minimum - 0.1 * du, u_maximum + 0.1 * du)\n ax1.legend()\n \n ax2 = fig.add_subplot(122)\n left_edge = np.min([-1.0, -1.0 - xil])\n right_edge = np.max([1.0, 1.0 - xim])\n x_start_points_l = np.linspace(left_edge, 0.0, 20)\n x_start_points_r = np.linspace(0.0, right_edge, 20)\n x_end_points_l = x_start_points_l + xil\n x_end_points_r = x_start_points_r + xim\n \n for xs, xe in zip(x_start_points_l, x_end_points_l):\n ax2.plot([xs, xe], [0.0, 1.0], 'b-')\n for xs, xe in zip(x_start_points_r, x_end_points_r):\n ax2.plot([xs, xe], [0.0, 1.0], 'g-')\n \n # Rarefaction wave\n if (xim > xil):\n xi = np.linspace(xil, xim, 11)\n x_end_rarefaction = xi\n for xe in x_end_rarefaction:\n ax2.plot([0.0, xe], [0.0, 1.0], 'r--')\n else:\n x_fill = [x_end_points_l[-1], x_start_points_l[-1], x_end_points_r[0]]\n t_fill = [1.0, 0.0, 1.0]\n ax2.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n \n ax2.set_xbound(-1.0, 1.0)\n ax2.set_ybound(0.0, 1.0)\n ax2.set_xlabel(r\"$x$\")\n ax2.set_ylabel(r\"$t$\")\n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_rarefaction_physical_characteristics, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = 0.0), \n hm = FloatSlider(min = 0.1, max = 10.0, value = 0.5))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\nWe clearly see that only if $h_m < h_l$ do the characteristics spread as they should for a rarefaction. This is, in fact, already given by results above: we showed that $\\partial_{\\xi} h \\propto -\\sqrt{h}$. As the height $h$ is positive, this means that as $\\xi$ increase across the rarefaction, the height must decrease.\n\n## All rarefaction solution\n\nThe above exercise assumed we knew the left state and found all right states connecting it by a rarefaction. Now we assume we know both left *and* right states, and assume they connect to a central state, *both* along rarefactions.\n\nFirst, we need to find which states will connect to the right state across a rarefaction.\n\n### Exercise\n\nRepeat the above calculations for states connecting to a known right state. That is, show that, given the right state $(h_r, u_r)$, the left state that connects to it across a rarefaction satisfies\n$$\n \\begin{pmatrix} h \\\\ u \\end{pmatrix} = \\begin{pmatrix} \\left( -\\frac{\\xi_r - \\xi}{3} + \\sqrt{h_r} \\right)^2 \\\\ \\frac{2}{3} (\\xi - \\xi_r) + u_r \\end{pmatrix}. \n$$\nor equivalently, given $h_m$, that\n$$\n u_m = u_r - 2 \\left( \\sqrt{h_r} - \\sqrt{h_m} \\right).\n$$\nAlso check that $h$ decreases across the rarefaction, so for a physical solution $h_m < h_r$.\n\nThen we can plot the curve of all states that can be connected to $(h_l, u_l)$ across a left rarefaction, and the curve of all states that can be connected to $(h_r, u_r)$ across a right rarefaction. *If* they intersect along the *physical* part of the curve, then we have the solution to the Riemann problem. Clearly this only occurs if $h_m < h_l$ *and* $h_m < h_r$.\n\nIn this case (and note that this is a special case!) we can solve it analytically. We note that, using our *assumption* that both curves are rarefactions, we have that\n$$\n\\begin{align}\n u_m & = u_l + 2 \\left( \\sqrt{h_l} - \\sqrt{h_m} \\right) \\\\\n & = u_r - 2 \\left( \\sqrt{h_r} - \\sqrt{h_m} \\right)\n\\end{align}\n$$\nTherefore we have\n$$\n h_m = \\frac{1}{16} \\left( u_l - u_r + 2 \\left( \\sqrt{h_l} + \\sqrt{h_r} \\right) \\right)^2.\n$$\n\n\n```python\ndef plot_sw_all_rarefaction(hl, ul, hr, ur):\n \"Plot the all rarefaction solution curve for states (hl, ul) and (hr, ur)\"\n \n hm = (ul - ur + 2.0 * (np.sqrt(hl) + np.sqrt(hr)))**2 / 16.0\n um = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hm))\n \n h_maximum = np.max([h_max, hl, hr, hm])\n h_minimum = np.min([h_min, hl, hr, hm])\n u_maximum = np.max([u_max, ul, ur, um])\n u_minimum = np.min([u_min, ul, ur, um])\n dh = h_maximum - h_minimum\n du = u_maximum - u_minimum\n xil_min = u_minimum - np.sqrt(h_maximum)\n xil_max = u_maximum - np.sqrt(h_minimum)\n xir_min = u_minimum + np.sqrt(h_minimum)\n xir_max = u_maximum + np.sqrt(h_maximum)\n \n xil = ul - np.sqrt(hl)\n xilm = um - np.sqrt(hm)\n xil_physical = np.linspace(xil, xil_max)\n xil_unphysical = np.linspace(xil_min, xil)\n hl_physical = ((xil - xil_physical) / 3.0 + np.sqrt(hl))**2\n ul_physical = 2.0 * (xil_physical - xil) / 3.0 + ul\n hl_unphysical = ((xil - xil_unphysical) / 3.0 + np.sqrt(hl))**2\n ul_unphysical = 2.0 * (xil_unphysical - xil) / 3.0 + ul\n \n xir = ur + np.sqrt(hr)\n xirm = um + np.sqrt(hm)\n xir_unphysical = np.linspace(xir, xir_max)\n xir_physical = np.linspace(xir_min, xir)\n hr_physical = (-(xir - xir_physical) / 3.0 + np.sqrt(hr))**2\n ur_physical = 2.0 * (xir_physical - xir) / 3.0 + ur\n hr_unphysical = (-(xir - xir_unphysical) / 3.0 + np.sqrt(hr))**2\n ur_unphysical = 2.0 * (xir_unphysical - xir) / 3.0 + ur\n \n fig = plt.figure(figsize=(12,8))\n ax1 = fig.add_subplot(111)\n if (hm < np.min([hl, hr])):\n ax1.plot(hm, um, 'b+', markersize = 16, markeredgewidth = 3, \n label=r\"$(h_m, u_m)$, physical solution\")\n else:\n ax1.plot(hm, um, 'b+', markersize = 16, markeredgewidth = 3, \n label=r\"$(h_m, u_m)$, not physical solution\")\n ax1.plot(hl, ul, 'rx', markersize = 16, markeredgewidth = 3, label=r\"$(h_l, u_l)$\")\n ax1.plot(hr, ur, 'go', markersize = 16, markeredgewidth = 3, label=r\"$(h_r, u_r)$\")\n ax1.plot(hl_physical, ul_physical, 'k-', linewidth = 2, label=\"Physical (left)\")\n ax1.plot(hl_unphysical, ul_unphysical, 'k--', linewidth = 2, label=\"Unphysical (left)\")\n ax1.plot(hr_physical, ur_physical, 'c-', linewidth = 2, label=\"Physical (right)\")\n ax1.plot(hr_unphysical, ur_unphysical, 'c--', linewidth = 2, label=\"Unphysical (right)\")\n ax1.set_xlabel(r\"$h$\")\n ax1.set_ylabel(r\"$u$\")\n ax1.set_xbound(h_minimum - 0.1 * dh, h_maximum + 0.1 * dh)\n ax1.set_ybound(u_minimum - 0.1 * du, u_maximum + 0.1 * du)\n ax1.legend()\n \n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_all_rarefaction, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = -0.5), \n hr = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ur = FloatSlider(min = -1.0, max = 1.0, value = 0.5))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\nGiven the central state and the relation along rarefaction curves, we can then construct the characteristics and the solution in terms of the similarity coordinate (which, given a time $t$, gives the solution as a function of $x$).\n\n\n```python\ndef plot_sw_all_rarefaction_solution(hl, ul, hr, ur):\n \"Plot the all rarefaction solution curve for states (hl, ul) and (hr, ur)\"\n \n hm = (ul - ur + 2.0 * (np.sqrt(hl) + np.sqrt(hr)))**2 / 16.0\n um = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hm))\n \n xi1l = ul - np.sqrt(hl)\n xi1m = um - np.sqrt(hm)\n xi1r = ur - np.sqrt(hr)\n hl_raref = np.linspace(hl, hm, 20)\n ul_raref = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hl_raref))\n xil_raref = ul_raref - np.sqrt(hl_raref)\n \n xi2r = ur + np.sqrt(hr)\n xi2m = um + np.sqrt(hm)\n xi2l = ul + np.sqrt(hl)\n hr_raref = np.linspace(hm, hr)\n ur_raref = ur - 2.0 * (np.sqrt(hr) - np.sqrt(hr_raref))\n xir_raref = ur_raref + np.sqrt(hr_raref)\n \n xi_min = np.min([-1.0, xi1l, xi1m, xi2r, xi2m])\n xi_max = np.max([1.0, xi1l, xi1m, xi2r, xi2m])\n d_xi = xi_max - xi_min\n h_max = np.max([hl, hr, hm])\n h_min = np.min([hl, hr, hm])\n d_h = h_max - h_min\n u_max = np.max([ul, ur, um])\n u_min = np.min([ul, ur, um])\n d_u = u_max - u_min\n \n xi = np.array([xi_min - 0.1 * d_xi, xi1l])\n h = np.array([hl, hl])\n u = np.array([ul, ul])\n xi = np.append(xi, xil_raref)\n h = np.append(h, hl_raref)\n u = np.append(u, ul_raref)\n xi = np.append(xi, [xi1m, xi2m])\n h = np.append(h, [hm, hm])\n u = np.append(u, [um, um])\n xi = np.append(xi, xir_raref)\n h = np.append(h, hr_raref)\n u = np.append(u, ur_raref)\n xi = np.append(xi, [xi2r, xi_max + 0.1 * d_xi])\n h = np.append(h, [hr, hr])\n u = np.append(u, [ur, ur])\n \n fig = plt.figure(figsize=(12,8))\n ax1 = fig.add_subplot(221)\n if (hm < np.min([hl, hr])):\n ax1.plot(xi, h, 'b-', label = \"Physical solution\")\n else:\n ax1.plot(xi, h, 'r--', label = \"Unphysical solution\")\n ax1.set_ybound(h_min - 0.1 * d_h, h_max + 0.1 * d_h)\n ax1.set_xlabel(r\"$\\xi$\")\n ax1.set_ylabel(r\"$h$\")\n ax1.legend()\n ax2 = fig.add_subplot(222)\n if (hm < np.min([hl, hr])):\n ax2.plot(xi, u, 'b-', label = \"Physical solution\")\n else:\n ax2.plot(xi, u, 'r--', label = \"Unphysical solution\")\n ax2.set_ybound(u_min - 0.1 * d_u, u_max + 0.1 * d_u)\n ax2.set_xlabel(r\"$\\xi$\")\n ax2.set_ylabel(r\"$u$\")\n ax2.legend()\n \n ax3 = fig.add_subplot(223)\n left_end = np.min([-1.0, 1.1*xi1l])\n right_end = np.max([1.0, 1.1*xi2r])\n left_edge = left_end - xi1l\n right_edge = right_end - xi1r\n x1_start_points_l = np.linspace(np.min([left_edge, left_end]), 0.0, 20)\n x1_start_points_r = np.linspace(0.0, np.max([right_edge, right_end]), 20)\n x1_end_points_l = x1_start_points_l + xi1l\n t1_end_points_r = np.ones_like(x1_start_points_r)\n \n # Look for intersections\n t1_end_points_r = np.minimum(t1_end_points_r, x1_start_points_r / (xi2r - xi1r))\n x1_end_points_r = x1_start_points_r + xi1r * t1_end_points_r\n # Note: here we are cheating, and using the characteristic speed of the middle state, \n # ignoring howo it varies across the rarefaction\n x1_final_points_r = x1_end_points_r + (1.0 - t1_end_points_r) * xi1m\n \n for xs, xe in zip(x1_start_points_l, x1_end_points_l):\n ax3.plot([xs, xe], [0.0, 1.0], 'b-')\n for xs, xe, te in zip(x1_start_points_r, x1_end_points_r, t1_end_points_r):\n ax3.plot([xs, xe], [0.0, te], 'g-')\n for xs, xe, ts in zip(x1_end_points_r, x1_final_points_r, t1_end_points_r):\n ax3.plot([xs, xe], [ts, 1.0], 'g-')\n \n # Highlight the edges of both rarefactions\n ax3.plot([0.0, xi1l], [0.0, 1.0], 'r-', linewidth=2)\n ax3.plot([0.0, xi1m], [0.0, 1.0], 'r-', linewidth=2)\n ax3.plot([0.0, xi2m], [0.0, 1.0], 'r-', linewidth=2)\n ax3.plot([0.0, xi2r], [0.0, 1.0], 'r-', linewidth=2)\n \n # Rarefaction wave\n if (xi1l < xi1m):\n xi = np.linspace(xi1l, xi1m, 11)\n x_end_rarefaction = xi\n for xe in x_end_rarefaction:\n ax3.plot([0.0, xe], [0.0, 1.0], 'r--')\n else:\n x_fill = [xi1l, 0.0, xi1m]\n t_fill = [1.0, 0.0, 1.0]\n ax3.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n \n ax3.set_xlabel(r\"$x$\")\n ax3.set_ylabel(r\"$t$\")\n ax3.set_title(\"1-characteristics\")\n ax3.set_xbound(left_end, right_end)\n \n ax4 = fig.add_subplot(224)\n left_end = np.min([-1.0, 1.1*xi1l])\n right_end = np.max([1.0, 1.1*xi2r])\n left_edge = left_end - xi2l\n right_edge = right_end - xi2r\n x2_start_points_l = np.linspace(np.min([left_edge, left_end]), 0.0, 20)\n x2_start_points_r = np.linspace(0.0, np.max([right_edge, right_end]), 20)\n x2_end_points_r = x2_start_points_r + xi2r\n t2_end_points_l = np.ones_like(x2_start_points_l)\n \n # Look for intersections\n t2_end_points_l = np.minimum(t2_end_points_l, x2_start_points_l / (xi1l - xi2r))\n x2_end_points_l = x2_start_points_l + xi2r * t2_end_points_l\n # Note: here we are cheating, and using the characteristic speed of the middle state, \n # ignoring howo it varies across the rarefaction\n x2_final_points_l = x2_end_points_l + (1.0 - t2_end_points_l) * xi2m\n \n for xs, xe in zip(x2_start_points_r, x2_end_points_r):\n ax4.plot([xs, xe], [0.0, 1.0], 'g-')\n for xs, xe, te in zip(x2_start_points_l, x2_end_points_l, t2_end_points_l):\n ax4.plot([xs, xe], [0.0, te], 'b-')\n for xs, xe, ts in zip(x2_end_points_l, x2_final_points_l, t2_end_points_l):\n ax4.plot([xs, xe], [ts, 1.0], 'b-')\n \n # Highlight the edges of both rarefactions\n ax4.plot([0.0, xi1l], [0.0, 1.0], 'r-', linewidth=2)\n ax4.plot([0.0, xi1m], [0.0, 1.0], 'r-', linewidth=2)\n ax4.plot([0.0, xi2m], [0.0, 1.0], 'r-', linewidth=2)\n ax4.plot([0.0, xi2r], [0.0, 1.0], 'r-', linewidth=2)\n \n # Rarefaction wave\n if (xi2r > xi2m):\n xi = np.linspace(xi2m, xi2r, 11)\n x_end_rarefaction = xi\n for xe in x_end_rarefaction:\n ax4.plot([0.0, xe], [0.0, 1.0], 'r--')\n else:\n x_fill = [xi2m, 0.0, xi2r]\n t_fill = [1.0, 0.0, 1.0]\n ax4.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n \n ax4.set_xlabel(r\"$x$\")\n ax4.set_ylabel(r\"$t$\")\n ax4.set_title(\"2-characteristics\")\n ax4.set_xbound(left_end, right_end)\n \n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_all_rarefaction_solution, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = -0.5), \n hr = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ur = FloatSlider(min = -1.0, max = 1.0, value = 0.5))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\n## Shocks\n\nWe note that the [general theory](Lesson_Theory.ipynb) tells us that across a shock the Rankine-Hugoniot conditions\n$$\n V_s \\left[ {\\bf q} \\right] = \\left[ {\\bf f}({\\bf q}) \\right]\n$$\nmust be satisfied.\n\nFor the shallow water equations we will start, as with the rarefaction case, by assuming we know the left state ${\\bf q}_l = (h_l, u_l)$, and work out which states ${\\bf q}_m$ can be connected to it across a shock. \n\nNote here that the procedure is *identical* for the right state as the direction does not matter. However, there will be multiple solutions, and checking which is physically correct does require checking whether the left or the right state is known\n\nWriting out the conditions in full we see that\n$$\n\\begin{align}\n V_s \\left( h_m - h_l \\right) & = h_m u_m - h_l u_l \\\\\n V_s \\left( h_m u_m - h_l u_l \\right) & = h_m u_m^2 + \\tfrac{1}{2} h_m^2 - h_l u_l^2 - \\tfrac{1}{2} h_l^2\n\\end{align}\n$$\n\nEliminating the shock speed $V_s$ gives, using the second equation,\n$$\n u_m^2 - (2 u_l) u_m + \\left[ u_l^2 - \\tfrac{1}{2} \\left( h_l - h_m \\right) \\left( \\frac{h_l}{h_m} - \\frac{h_m}{h_l} \\right) \\right] = 0.\n$$\nThis has the solutions (assuming that $h_m$ is known!)\n$$\n u_m = u_l \\pm \\sqrt{\\tfrac{1}{2} \\left( h_l - h_m \\right) \\left( \\frac{h_l}{h_m} - \\frac{h_m}{h_l} \\right)}.\n$$\n\nWe can again use the Rankine-Hugoniot relations to find the shock speed.\n$$\n V_s = u_l \\pm \\frac{h_m}{h_m - h_l} \\sqrt{\\tfrac{1}{2} \\left( h_l - h_m \\right) \\left( \\frac{h_l}{h_m} - \\frac{h_m}{h_l} \\right)}.\n$$\n\nWe should at this point find which sign is appropriate. Comparing the shock speeds against the characteristic speed will show that\n\n* we need $h_m > h_l$ for the wave to be a shock, and\n* we take the negative sign if connected to a left state, and the positive if connected to a right state.\n\nHowever, we can see this by plotting the *Hugoniot locus*: the curve of all states that can be connected to $(h_l, u_l)$ across a shock.\n\n\n```python\ndef plot_sw_shock_physical(hl, ul):\n \"Plot the shock curve through the state (hl, ul)\"\n \n h = np.linspace(h_min, h_max, 500)\n u_negative = ul - np.sqrt(0.5 * (hl - h) * (hl / h - h / hl))\n u_positive = ul + np.sqrt(0.5 * (hl - h) * (hl / h - h / hl))\n \n vs_negative = ul - h / (h - hl) * np.sqrt(0.5 * (hl - h) * (hl / h - h / hl))\n vs_positive = ul + h / (h - hl) * np.sqrt(0.5 * (hl - h) * (hl / h - h / hl))\n \n xi1_negative = u_negative - np.sqrt(h) \n xi1_positive = u_positive - np.sqrt(h)\n xi2_negative = u_negative + np.sqrt(h) \n xi2_positive = u_positive + np.sqrt(h)\n \n xi1_l = ul - np.sqrt(hl)\n xi2_l = ul + np.sqrt(hl)\n \n h1_physical = h[np.logical_and(xi1_negative <= vs_negative, xi1_l >= vs_negative)]\n u1_physical = u_negative[np.logical_and(xi1_negative <= vs_negative, xi1_l >= vs_negative)]\n h2_physical = h[np.logical_and(xi2_positive >= vs_positive, xi2_l <= vs_positive)]\n u2_physical = u_positive[np.logical_and(xi2_positive >= vs_positive, xi2_l <= vs_positive)]\n h1_unphysical = h[np.logical_or(xi1_negative >= vs_negative, xi1_l <= vs_negative)]\n u1_unphysical = u_negative[np.logical_or(xi1_negative >= vs_negative, xi1_l <= vs_negative)]\n h2_unphysical = h[np.logical_or(xi2_positive <= vs_positive, xi2_l >= vs_positive)]\n u2_unphysical = u_positive[np.logical_or(xi2_positive <= vs_positive, xi2_l >= vs_positive)]\n \n fig = plt.figure(figsize=(12,8))\n ax = fig.add_subplot(111)\n ax.plot(hl, ul, 'rx', markersize = 16, markeredgewidth = 3)\n ax.plot(h1_physical, u1_physical, 'b-', linewidth = 2, \n label=\"Physical, 1-shock\")\n ax.plot(h1_unphysical, u1_unphysical, 'b--', linewidth = 2, \n label=\"Unphysical, 1-shock\")\n ax.plot(h2_physical, u2_physical, 'g-', linewidth = 2, \n label=\"Physical, 2-shock\")\n ax.plot(h2_unphysical, u2_unphysical, 'g--', linewidth = 2, \n label=\"Unphysical, 2-shock\")\n ax.plot(h[::5], u_negative[::5], 'co', markersize = 12, markeredgewidth = 2, alpha = 0.3,\n label=\"Negative branch\")\n ax.plot(h[::5], u_positive[::5], 'ro', markersize = 12, markeredgewidth = 2, alpha = 0.3,\n label=\"Positive branch\")\n ax.set_xlabel(r\"$h$\")\n ax.set_ylabel(r\"$u$\")\n dh = h_max - h_min\n du = u_max - u_min\n ax.set_xbound(h_min, h_max)\n ax.set_ybound(u_min, u_max)\n ax.legend()\n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_shock_physical, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = 0.0))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\nWe see from these results, as claimed above, that\n\n* we need $h_m > h_l$ (or $h_m > h_r$) for the wave to be a shock, and\n* we take the negative sign if connected to a left state, and the positive if connected to a right state.\n\n## All shock solution\n\nWhen we assumed the solution contained two rarefactions it was possible to write the full solution in closed form. If we assume the solution contains two shocks then it is not possible to do this. However, it is straightforward to find the solution numerically. \n\nWe assume the left state ${\\bf w}_l = (h_l, u_l)$ and the right state ${\\bf w}_r = (h_r, u_r)$ are known, and that they both connect to the central state ${\\bf w}_m = (h_m, u_m)$ through shocks. We know that\n$$\n\\begin{align}\n u_m & = u_l - \\sqrt{\\tfrac{1}{2} \\left( h_l - h_m \\right) \\left( \\frac{h_l}{h_m} - \\frac{h_m}{h_l} \\right)}, \\\\\n u_m & = u_r + \\sqrt{\\tfrac{1}{2} \\left( h_r - h_m \\right) \\left( \\frac{h_r}{h_m} - \\frac{h_m}{h_r} \\right)}.\n\\end{align}\n$$\nWe schematically write these equations as\n$$\n\\begin{align}\n u_m & = \\phi_l \\left( h_m; {\\bf w}_l \\right), \\\\\n u_m & = \\phi_r \\left( h_m; {\\bf w}_r \\right),\n\\end{align}\n$$\nto indicate that the velocity in the central state, $u_m$, can be written as a function of the single unknown $h_m$ and known data.\n\nWe immediately see that $h_m$ is a root of the nonlinear equation\n$$\n \\phi \\left( h_m; {\\bf w}_l, {\\bf w}_r \\right) = \\phi_l \\left( h_m; {\\bf w}_l \\right) - \\phi_r \\left( h_m; {\\bf w}_r \\right) = 0.\n$$\n\nFinding the roots of scalar nonlinear equations is a standard problem in numerical methods, with methods such as bisection, Newton-Raphson and more being well-known. `scipy` provides a number of standard algorithms - here we will use the recommended `brentq` method.\n\nNote that as soon as we have numerically determined $h_m$ then either formula above gives $u_m$, and the shock speeds follow.\n\n\n```python\ndef plot_sw_all_shock(hl, ul, hr, ur):\n \"Plot the all shock solution curve for states (hl, ul) and (hr, ur)\"\n \n from scipy.optimize import brentq\n \n def phi(hstar):\n \"Function defining the root\"\n \n phi_l = ul - np.sqrt(0.5 * (hl - hstar) * (hl / hstar - hstar / hl))\n phi_r = ur + np.sqrt(0.5 * (hr - hstar) * (hr / hstar - hstar / hr))\n \n return phi_l - phi_r\n \n # There is a solution only in the physical case. \n physical_solution = True\n try:\n hm = brentq(phi, np.max([hl, hr]), 10.0 * h_max)\n except ValueError:\n physical_solution = False\n hm = hl\n um = ul - np.sqrt(0.5 * (hl - hm) * (hl / hm - hm / hl))\n \n h = np.linspace(h_min, h_max, 500)\n u_negative = ul - np.sqrt(0.5 * (hl - h) * (hl / h - h / hl))\n u_positive = ur + np.sqrt(0.5 * (hr - h) * (hr / h - h / hr))\n \n h_maximum = np.max([h_max, hl, hr, hm])\n h_minimum = np.min([h_min, hl, hr, hm])\n u_maximum = np.max([u_max, ul, ur, um])\n u_minimum = np.min([u_min, ul, ur, um])\n dh = h_maximum - h_minimum\n du = u_maximum - u_minimum\n xil_min = u_minimum - np.sqrt(h_maximum)\n xil_max = u_maximum - np.sqrt(h_minimum)\n xir_min = u_minimum + np.sqrt(h_minimum)\n xir_max = u_maximum + np.sqrt(h_maximum)\n \n vs_negative = ul - h / (h - hl) * np.sqrt(0.5 * (hl - h) * (hl / h - h / hl))\n vs_positive = ur + h / (h - hr) * np.sqrt(0.5 * (hr - h) * (hr / h - h / hr))\n \n xi1_negative = u_negative - np.sqrt(h) \n xi1_positive = u_positive - np.sqrt(h)\n xi2_negative = u_negative + np.sqrt(h) \n xi2_positive = u_positive + np.sqrt(h)\n \n xi1_l = ul - np.sqrt(hl)\n xi2_r = ur + np.sqrt(hr)\n \n h1_physical = h[np.logical_and(xi1_negative <= vs_negative, xi1_l >= vs_negative)]\n u1_physical = u_negative[np.logical_and(xi1_negative <= vs_negative, xi1_l >= vs_negative)]\n h2_physical = h[np.logical_and(xi2_positive >= vs_positive, xi2_r <= vs_positive)]\n u2_physical = u_positive[np.logical_and(xi2_positive >= vs_positive, xi2_r <= vs_positive)]\n h1_unphysical = h[np.logical_or(xi1_negative >= vs_negative, xi1_l <= vs_negative)]\n u1_unphysical = u_negative[np.logical_or(xi1_negative >= vs_negative, xi1_l <= vs_negative)]\n h2_unphysical = h[np.logical_or(xi2_positive <= vs_positive, xi2_r >= vs_positive)]\n u2_unphysical = u_positive[np.logical_or(xi2_positive <= vs_positive, xi2_r >= vs_positive)]\n \n fig = plt.figure(figsize=(12,8))\n ax = fig.add_subplot(111)\n ax.plot(hl, ul, 'rx', markersize = 16, markeredgewidth = 3, label = r\"${\\bf w}_l$\")\n ax.plot(hr, ur, 'r+', markersize = 16, markeredgewidth = 3, label = r\"${\\bf w}_r$\")\n if physical_solution:\n ax.plot(hm, um, 'ro', markersize = 16, markeredgewidth = 3, label = r\"${\\bf w}_m$\")\n ax.plot(h1_physical, u1_physical, 'b-', linewidth = 2, \n label=\"Physical, 1-shock\")\n ax.plot(h1_unphysical, u1_unphysical, 'b--', linewidth = 2, \n label=\"Unphysical, 1-shock\")\n ax.plot(h2_physical, u2_physical, 'g-', linewidth = 2, \n label=\"Physical, 2-shock\")\n ax.plot(h2_unphysical, u2_unphysical, 'g--', linewidth = 2, \n label=\"Unphysical, 2-shock\")\n ax.set_xlabel(r\"$h$\")\n ax.set_ylabel(r\"$u$\")\n ax.set_xbound(h_minimum - 0.1 * dh, h_maximum + 0.1 * dh)\n ax.set_ybound(u_minimum - 0.1 * du, u_maximum + 0.1 * du)\n ax.legend()\n \n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_all_shock, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = 0.2), \n hr = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ur = FloatSlider(min = -1.0, max = 1.0, value = -0.2))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\nFinally, we can plot the solution in physical space.\n\n\n```python\ndef plot_sw_all_shock_solution(hl, ul, hr, ur):\n \"Plot the all shock solution for states (hl, ul) and (hr, ur)\"\n \n from scipy.optimize import brentq\n \n def phi(hstar):\n \"Function defining the root\"\n \n phi_l = ul - np.sqrt(0.5 * (hl - hstar) * (hl / hstar - hstar / hl))\n phi_r = ur + np.sqrt(0.5 * (hr - hstar) * (hr / hstar - hstar / hr))\n \n return phi_l - phi_r\n \n # There is a solution only in the physical case. \n physical_solution = True\n try:\n hm = brentq(phi, np.max([hl, hr]), 10.0 * h_max)\n except ValueError:\n physical_solution = False\n hm = hl\n um = ul - np.sqrt(0.5 * (hl - hm) * (hl / hm - hm / hl))\n \n xi1l = ul - np.sqrt(hl)\n xi1m = um - np.sqrt(hm)\n xi1r = ur - np.sqrt(hr)\n if physical_solution:\n vsl = ul - hm / (hm - hl) * np.sqrt(0.5 * (hl - hm) * (hl / hm - hm / hl))\n else:\n vsl = xi1l\n \n xi2r = ur + np.sqrt(hr)\n xi2m = um + np.sqrt(hm)\n xi2l = ul + np.sqrt(hl)\n if physical_solution:\n vsr = ur + hm / (hm - hr) * np.sqrt(0.5 * (hr - hm) * (hr / hm - hm / hr))\n else:\n vsr = xi2r\n \n xi_min = np.min([-1.0, xi1l, xi1m, xi2r, xi2m])\n xi_max = np.max([1.0, xi1l, xi1m, xi2r, xi2m])\n d_xi = xi_max - xi_min\n h_maximum = np.max([hl, hr, hm])\n h_minimum = np.min([hl, hr, hm])\n d_h = h_maximum - h_minimum\n u_maximum = np.max([ul, ur, um])\n u_minimum = np.min([ul, ur, um])\n d_u = u_maximum - u_minimum\n \n xi = np.array([xi_min - 0.1 * d_xi, vsl, vsl, vsr, vsr, xi_max + 0.1 * d_xi])\n h = np.array([hl, hl, hm, hm, hr, hr])\n u = np.array([ul, ul, um, um, ur, ur])\n \n fig = plt.figure(figsize=(12,8))\n ax1 = fig.add_subplot(221)\n if (hm > np.max([hl, hr])):\n ax1.plot(xi, h, 'b-', label = \"Physical solution\")\n else:\n ax1.plot(xi, h, 'r--', label = \"Unphysical solution\")\n ax1.set_ybound(h_minimum - 0.1 * d_h, h_maximum + 0.1 * d_h)\n ax1.set_xlabel(r\"$\\xi$\")\n ax1.set_ylabel(r\"$h$\")\n ax1.legend()\n ax2 = fig.add_subplot(222)\n if (hm > np.max([hl, hr])):\n ax2.plot(xi, u, 'b-', label = \"Physical solution\")\n else:\n ax2.plot(xi, u, 'r--', label = \"Unphysical solution\")\n ax2.set_ybound(u_minimum - 0.1 * d_u, u_maximum + 0.1 * d_u)\n ax2.set_xlabel(r\"$\\xi$\")\n ax2.set_ylabel(r\"$u$\")\n ax2.legend()\n \n ax3 = fig.add_subplot(223)\n left_end = np.min([-1.0, 1.1*xi1l])\n right_end = np.max([1.0, 1.1*xi2r])\n left_edge = left_end - xi1l\n right_edge = right_end - xi1r\n x1_start_points_l = np.linspace(np.min([left_edge, left_end]), 0.0, 20)\n x1_start_points_r = np.linspace(0.0, np.max([right_edge, right_end]), 20)\n t1_end_points_l = np.ones_like(x1_start_points_l)\n t1_end_points_r = np.ones_like(x1_start_points_r)\n \n # Look for intersections\n t1_end_points_l = np.minimum(t1_end_points_l, x1_start_points_l / (vsl - xi1l))\n x1_end_points_l = x1_start_points_l + xi1l * t1_end_points_l\n t1_end_points_r = np.minimum(t1_end_points_r, x1_start_points_r / (vsr - xi1r))\n x1_end_points_r = x1_start_points_r + xi1r * t1_end_points_r\n # Note: here we are cheating, and using the characteristic speed of the middle state, \n # ignoring how it varies across the rarefaction\n t1_final_points_r = np.ones_like(x1_start_points_r)\n t1_final_points_r = np.minimum(t1_final_points_r, \n (x1_end_points_r - t1_end_points_r * xi1m) / (vsl - xi1m))\n x1_final_points_r = x1_end_points_r + (t1_final_points_r - t1_end_points_r) * xi1m\n \n for xs, xe, te in zip(x1_start_points_l, x1_end_points_l, t1_end_points_l):\n ax3.plot([xs, xe], [0.0, te], 'b-')\n for xs, xe, te in zip(x1_start_points_r, x1_end_points_r, t1_end_points_r):\n ax3.plot([xs, xe], [0.0, te], 'g-')\n for xs, xe, ts, te in zip(x1_end_points_r, x1_final_points_r, t1_end_points_r, \n t1_final_points_r):\n ax3.plot([xs, xe], [ts, te], 'g-')\n \n # Highlight the shocks\n ax3.plot([0.0, vsl], [0.0, 1.0], 'r-', linewidth=2)\n ax3.plot([0.0, vsr], [0.0, 1.0], 'r-', linewidth=2)\n \n # Unphysical shock\n if not physical_solution:\n x_fill = []\n if xi1l < xi1m:\n x_fill = [xi1l, 0.0, xi1m]\n elif xi1l < vsl:\n x_fill = [xi1l, 0.0, vsl]\n elif vsl < xi1m:\n x_fill = [vsl, 0.0, xi1m]\n if len(x_fill) > 0:\n t_fill = [1.0, 0.0, 1.0]\n ax3.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n \n x_fill = []\n if xi2r > xi2m:\n x_fill = [xi2m, 0.0, xi2r]\n elif xi2m < vsr:\n x_fill = [xi2m, 0.0, vsr]\n elif vsr < xi2r:\n x_fill = [vsr, 0.0, xi2r]\n if len(x_fill) > 0:\n t_fill = [1.0, 0.0, 1.0]\n ax3.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n \n ax3.set_xlabel(r\"$x$\")\n ax3.set_ylabel(r\"$t$\")\n ax3.set_title(\"1-characteristics\")\n ax3.set_xbound(left_end, right_end)\n \n ax4 = fig.add_subplot(224)\n left_end = np.min([-1.0, 1.1*xi1l])\n right_end = np.max([1.0, 1.1*xi2r])\n left_edge = left_end - xi2l\n right_edge = right_end - xi2r\n x2_start_points_l = np.linspace(np.min([left_edge, left_end]), 0.0, 20)\n x2_start_points_r = np.linspace(0.0, np.max([right_edge, right_end]), 20)\n x2_end_points_r = x2_start_points_r + xi2r\n t2_end_points_l = np.ones_like(x2_start_points_l)\n t2_end_points_r = np.ones_like(x2_start_points_r)\n \n # Look for intersections\n t2_end_points_r = np.minimum(t2_end_points_r, x2_start_points_r / (vsr - xi2r))\n x2_end_points_r = x2_start_points_r + xi2r * t2_end_points_r\n t2_end_points_l = np.minimum(t2_end_points_l, x2_start_points_l / (vsl - xi2l))\n x2_end_points_l = x2_start_points_l + xi2l * t2_end_points_l\n # Note: here we are cheating, and using the characteristic speed of the middle state, \n # ignoring how it varies across the rarefaction\n t2_final_points_l = np.ones_like(x2_start_points_l)\n t2_final_points_l = np.minimum(t2_final_points_l, \n (x2_end_points_l - t2_end_points_l * xi2m) / (vsr - xi2m))\n x2_final_points_l = x2_end_points_l + (t2_final_points_l - t2_end_points_l) * xi2m\n \n for xs, xe, te in zip(x2_start_points_r, x2_end_points_r, t2_end_points_r):\n ax4.plot([xs, xe], [0.0, te], 'b-')\n for xs, xe, te in zip(x2_start_points_l, x2_end_points_l, t2_end_points_l):\n ax4.plot([xs, xe], [0.0, te], 'g-')\n for xs, xe, ts, te in zip(x2_end_points_l, x2_final_points_l, t2_end_points_l, \n t2_final_points_l):\n ax4.plot([xs, xe], [ts, te], 'g-')\n \n # Highlight the shocks\n ax4.plot([0.0, vsl], [0.0, 1.0], 'r-', linewidth=2)\n ax4.plot([0.0, vsr], [0.0, 1.0], 'r-', linewidth=2)\n \n # Unphysical shock\n if not physical_solution:\n x_fill = []\n if xi1l < xi1m:\n x_fill = [xi1l, 0.0, xi1m]\n elif xi1l < vsl:\n x_fill = [xi1l, 0.0, vsl]\n elif vsl < xi1m:\n x_fill = [vsl, 0.0, xi1m]\n if len(x_fill) > 0:\n t_fill = [1.0, 0.0, 1.0]\n ax4.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n \n x_fill = []\n if xi2r > xi2m:\n x_fill = [xi2m, 0.0, xi2r]\n elif xi2m < vsr:\n x_fill = [xi2m, 0.0, vsr]\n elif vsr < xi2r:\n x_fill = [vsr, 0.0, xi2r]\n if len(x_fill) > 0:\n t_fill = [1.0, 0.0, 1.0]\n ax4.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n \n ax4.set_xlabel(r\"$x$\")\n ax4.set_ylabel(r\"$t$\")\n ax4.set_title(\"2-characteristics\")\n ax4.set_xbound(left_end, right_end)\n \n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_all_shock_solution, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = 0.2), \n hr = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ur = FloatSlider(min = -1.0, max = 1.0, value = -0.2))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\n## Full solution\n\nThe all shock solution illustrates how the full solution can be obtained. We know that \n\n1. the central state ${\\bf w}_m$ will be connected to the known states ${\\bf w}_{l, r}$ across waves that are either shocks or rarefactions,\n2. if $h_m > h_{l, r}$ then the wave will be a shock, otherwise it will be a rarefaction, and\n3. given $h_m$ and the known data, we can compute $u_m$ for either a shock or a rarefaction.\n\nSo, using the results above, we can find the full solution to the Riemann problem by solving the nonlinear algebraic root-finding problem\n$$\n \\Phi \\left( h_m ; {\\bf w}_l, {\\bf w}_r \\right) = 0,\n$$\nwhere\n$$\n \\Phi \\left( h_m ; {\\bf w}_l, {\\bf w}_r \\right) = \\Phi_l \\left( h_m ; {\\bf w}_l \\right) - \\Phi_r \\left( h_m ; {\\bf w}_r \\right),\n$$\nand\n$$\n\\begin{align}\n \\Phi_l & = u_m \\left( h_m ; {\\bf w}_l \\right) & \\Phi_r & = u_m \\left( h_m ; {\\bf w}_r \\right) \\\\\n & = \\begin{cases} u_l + 2 \\left( \\sqrt{h_l} - \\sqrt{h_m} \\right) & h_l > h_m \\\\ u_l - \\sqrt{\\tfrac{1}{2} \\left( h_l - h_m \\right) \\left( \\frac{h_l}{h_m} - \\frac{h_m}{h_l} \\right)} & h_l < h_m \\end{cases} & & = \\begin{cases} u_r - 2 \\left( \\sqrt{h_r} - \\sqrt{h_m} \\right) & h_r > h_m \\\\ u_r + \\sqrt{\\tfrac{1}{2} \\left( h_r - h_m \\right) \\left( \\frac{h_r}{h_m} - \\frac{h_m}{h_r} \\right)} & h_r < h_m \\end{cases}.\n\\end{align}\n$$\n\n\n```python\ndef plot_sw_Riemann_curves(hl, ul, hr, ur):\n \"Plot the solution curves for states (hl, ul) and (hr, ur)\"\n \n from scipy.optimize import brentq\n \n def phi(hstar):\n \"Function defining the root\"\n \n if hl < hstar:\n phi_l = ul - np.sqrt(0.5 * (hl - hstar) * (hl / hstar - hstar / hl))\n else:\n phi_l = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hstar))\n if hr < hstar:\n phi_r = ur + np.sqrt(0.5 * (hr - hstar) * (hr / hstar - hstar / hr))\n else:\n phi_r = ur - 2.0 * (np.sqrt(hr) - np.sqrt(hstar))\n \n return phi_l - phi_r\n \n hm = brentq(phi, 0.1 * h_min, 10.0 * h_max)\n if hl < hm:\n um = ul - np.sqrt(0.5 * (hl - hm) * (hl / hm - hm / hl))\n else:\n um = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hm))\n \n h_maximum = np.max([h_max, hl, hr, hm])\n h_minimum = np.min([h_min, hl, hr, hm])\n u_maximum = np.max([u_max, ul, ur, um])\n u_minimum = np.min([u_min, ul, ur, um])\n dh = h_maximum - h_minimum\n du = u_maximum - u_minimum\n \n # Now plot the rarefaction and shock curves as appropriate\n # Here we only plot the physical pieces.\n \n h1_shock = np.linspace(hl, h_max)\n u1_shock = ul - np.sqrt(0.5 * (hl - h1_shock) * (hl / h1_shock - h1_shock / hl))\n h2_shock = np.linspace(hr, h_max)\n u2_shock = ur + np.sqrt(0.5 * (hr - h2_shock) * (hr / h2_shock - h2_shock / hr))\n \n h1_rarefaction = np.linspace(h_min, hl)\n u1_rarefaction = ul + 2.0 * (np.sqrt(hl) - np.sqrt(h1_rarefaction))\n h2_rarefaction = np.linspace(h_min, hr)\n u2_rarefaction = ur - 2.0 * (np.sqrt(hr) - np.sqrt(h2_rarefaction))\n \n fig = plt.figure(figsize=(12,8))\n ax = fig.add_subplot(111)\n ax.plot(hl, ul, 'rx', markersize = 16, markeredgewidth = 3, label = r\"${\\bf w}_l$\")\n ax.plot(hr, ur, 'r+', markersize = 16, markeredgewidth = 3, label = r\"${\\bf w}_r$\")\n ax.plot(hm, um, 'ro', markersize = 16, markeredgewidth = 3, label = r\"${\\bf w}_m$\")\n ax.plot(h1_shock, u1_shock, 'b-', linewidth = 2, \n label=\"1-shock\")\n ax.plot(h1_rarefaction, u1_rarefaction, 'b-.', linewidth = 2, \n label=\"1-rarefaction\")\n ax.plot(h2_shock, u2_shock, 'g-', linewidth = 2, \n label=\"2-shock\")\n ax.plot(h2_rarefaction, u2_rarefaction, 'g-.', linewidth = 2, \n label=\"2-rarefaction\")\n ax.set_xlabel(r\"$h$\")\n ax.set_ylabel(r\"$u$\")\n ax.set_xbound(h_minimum - 0.1 * dh, h_maximum + 0.1 * dh)\n ax.set_ybound(u_minimum - 0.1 * du, u_maximum + 0.1 * du)\n ax.legend()\n \n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_Riemann_curves, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = 0.2), \n hr = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ur = FloatSlider(min = -1.0, max = 1.0, value = -0.2))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n\nFinally, we can plot the solution in physical space.\n\n\n```python\ndef plot_sw_Riemann_solution(hl, ul, hr, ur):\n \"Plot the Riemann problem solution for states (hl, ul) and (hr, ur)\"\n \n from scipy.optimize import brentq\n \n def phi(hstar):\n \"Function defining the root\"\n \n if hl < hstar:\n phi_l = ul - np.sqrt(0.5 * (hl - hstar) * (hl / hstar - hstar / hl))\n else:\n phi_l = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hstar))\n if hr < hstar:\n phi_r = ur + np.sqrt(0.5 * (hr - hstar) * (hr / hstar - hstar / hr))\n else:\n phi_r = ur - 2.0 * (np.sqrt(hr) - np.sqrt(hstar))\n \n return phi_l - phi_r\n \n left_raref = False\n left_shock = False\n right_raref = False\n right_shock = False\n \n hm = brentq(phi, 0.1 * h_min, 10.0 * h_max)\n if hl < hm:\n um = ul - np.sqrt(0.5 * (hl - hm) * (hl / hm - hm / hl))\n else:\n um = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hm))\n \n h_maximum = np.max([h_max, hl, hr, hm])\n h_minimum = np.min([h_min, hl, hr, hm])\n u_maximum = np.max([u_max, ul, ur, um])\n u_minimum = np.min([u_min, ul, ur, um])\n dh = h_maximum - h_minimum\n du = u_maximum - u_minimum\n \n xi1l = ul - np.sqrt(hl)\n xi1m = um - np.sqrt(hm)\n xi1r = ur - np.sqrt(hr)\n if hm > hl:\n left_shock = True\n vsl = ul - hm / (hm - hl) * np.sqrt(0.5 * (hl - hm) * (hl / hm - hm / hl))\n else:\n left_raref = True\n hl_raref = np.linspace(hl, hm, 20)\n ul_raref = ul + 2.0 * (np.sqrt(hl) - np.sqrt(hl_raref))\n xil_raref = ul_raref - np.sqrt(hl_raref)\n \n xi2r = ur + np.sqrt(hr)\n xi2m = um + np.sqrt(hm)\n xi2l = ul + np.sqrt(hl)\n if hm > hr:\n right_shock = True\n vsr = ur + hm / (hm - hr) * np.sqrt(0.5 * (hr - hm) * (hr / hm - hm / hr))\n else:\n right_raref = True\n hr_raref = np.linspace(hm, hr)\n ur_raref = ur - 2.0 * (np.sqrt(hr) - np.sqrt(hr_raref))\n xir_raref = ur_raref + np.sqrt(hr_raref)\n \n xi_min = np.min([-1.0, xi1l, xi1m, xi2r, xi2m])\n xi_max = np.max([1.0, xi1l, xi1m, xi2r, xi2m])\n d_xi = xi_max - xi_min\n h_maximum = np.max([hl, hr, hm])\n h_minimum = np.min([hl, hr, hm])\n d_h = h_maximum - h_minimum\n u_maximum = np.max([ul, ur, um])\n u_minimum = np.min([ul, ur, um])\n d_u = u_maximum - u_minimum\n \n xi = np.array([xi_min - 0.1 * d_xi])\n h = np.array([hl])\n u = np.array([ul])\n if left_shock:\n xi = np.append(xi, [vsl, vsl])\n h = np.append(h, [hl, hm])\n u = np.append(u, [ul, um])\n else:\n xi = np.append(xi, xil_raref)\n h = np.append(h, hl_raref)\n u = np.append(u, ul_raref)\n if right_shock:\n xi = np.append(xi, [vsr, vsr])\n h = np.append(h, [hm, hr])\n u = np.append(u, [um, ur])\n else:\n xi = np.append(xi, xir_raref)\n h = np.append(h, hr_raref)\n u = np.append(u, ur_raref)\n xi = np.append(xi, [xi_max + 0.1 * d_xi])\n h = np.append(h, [hr])\n u = np.append(u, [ur])\n \n fig = plt.figure(figsize=(12,8))\n ax1 = fig.add_subplot(221)\n ax1.plot(xi, h, 'b-', label = \"True solution\")\n ax1.set_ybound(h_minimum - 0.1 * d_h, h_maximum + 0.1 * d_h)\n ax1.set_xlabel(r\"$\\xi$\")\n ax1.set_ylabel(r\"$h$\")\n ax1.legend()\n ax2 = fig.add_subplot(222)\n ax2.plot(xi, u, 'b-', label = \"True solution\")\n ax2.set_ybound(u_minimum - 0.1 * d_u, u_maximum + 0.1 * d_u)\n ax2.set_xlabel(r\"$\\xi$\")\n ax2.set_ylabel(r\"$u$\")\n ax2.legend()\n \n ax3 = fig.add_subplot(223)\n left_end = np.min([-1.0, 1.1*xi1l])\n right_end = np.max([1.0, 1.1*xi2r])\n left_edge = left_end - xi1l\n right_edge = right_end - xi1r\n x1_start_points_l = np.linspace(np.min([left_edge, left_end]), 0.0, 20)\n x1_start_points_r = np.linspace(0.0, np.max([right_edge, right_end]), 20)\n t1_end_points_l = np.ones_like(x1_start_points_l)\n t1_end_points_r = np.ones_like(x1_start_points_r)\n \n # Look for intersections\n if left_shock:\n t1_end_points_l = np.minimum(t1_end_points_l, x1_start_points_l / (vsl - xi1l))\n x1_end_points_l = x1_start_points_l + xi1l * t1_end_points_l\n if right_shock:\n t1_end_points_r = np.minimum(t1_end_points_r, x1_start_points_r / (vsr - xi1r))\n else:\n t1_end_points_r = np.minimum(t1_end_points_r, x1_start_points_r / (xi2r - xi1r))\n x1_end_points_r = x1_start_points_r + xi1r * t1_end_points_r\n # Note: here we are cheating, and using the characteristic speed of the middle state, \n # ignoring how it varies across the rarefaction\n t1_final_points_r = np.ones_like(x1_start_points_r)\n if left_shock:\n t1_final_points_r = np.minimum(t1_final_points_r, \n (x1_end_points_r - t1_end_points_r * xi1m) / \n (vsl - xi1m))\n x1_final_points_r = x1_end_points_r + (t1_final_points_r - t1_end_points_r) * xi1m\n \n for xs, xe, te in zip(x1_start_points_l, x1_end_points_l, t1_end_points_l):\n ax3.plot([xs, xe], [0.0, te], 'b-')\n for xs, xe, te in zip(x1_start_points_r, x1_end_points_r, t1_end_points_r):\n ax3.plot([xs, xe], [0.0, te], 'g-')\n for xs, xe, ts, te in zip(x1_end_points_r, x1_final_points_r, t1_end_points_r, \n t1_final_points_r):\n ax3.plot([xs, xe], [ts, te], 'g-')\n \n # Highlight the waves\n if left_shock:\n ax3.plot([0.0, vsl], [0.0, 1.0], 'r-', linewidth=2)\n else:\n ax3.plot([0.0, xi1l], [0.0, 1.0], 'r-', linewidth=2)\n ax3.plot([0.0, xi1m], [0.0, 1.0], 'r-', linewidth=2)\n xi = np.linspace(xi1l, xi1m, 11)\n x_end_rarefaction = xi\n for xe in x_end_rarefaction:\n ax3.plot([0.0, xe], [0.0, 1.0], 'r--')\n if right_shock:\n ax3.plot([0.0, vsr], [0.0, 1.0], 'r-', linewidth=2)\n else:\n ax3.plot([0.0, xi2m], [0.0, 1.0], 'r-', linewidth=2)\n ax3.plot([0.0, xi2r], [0.0, 1.0], 'r-', linewidth=2)\n \n ax3.set_xlabel(r\"$x$\")\n ax3.set_ylabel(r\"$t$\")\n ax3.set_title(\"1-characteristics\")\n ax3.set_xbound(left_end, right_end)\n \n ax4 = fig.add_subplot(224)\n left_end = np.min([-1.0, 1.1*xi1l])\n right_end = np.max([1.0, 1.1*xi2r])\n left_edge = left_end - xi2l\n right_edge = right_end - xi2r\n x2_start_points_l = np.linspace(np.min([left_edge, left_end]), 0.0, 20)\n x2_start_points_r = np.linspace(0.0, np.max([right_edge, right_end]), 20)\n x2_end_points_r = x2_start_points_r + xi2r\n t2_end_points_l = np.ones_like(x2_start_points_l)\n t2_end_points_r = np.ones_like(x2_start_points_r)\n \n # Look for intersections\n if right_shock:\n t2_end_points_r = np.minimum(t2_end_points_r, x2_start_points_r / (vsr - xi2r))\n x2_end_points_r = x2_start_points_r + xi2r * t2_end_points_r\n if left_shock:\n t2_end_points_l = np.minimum(t2_end_points_l, x2_start_points_l / (vsl - xi2l))\n else:\n t2_end_points_l = np.minimum(t2_end_points_l, x2_start_points_l / (xi1l - xi2l))\n x2_end_points_l = x2_start_points_l + xi2l * t2_end_points_l\n # Note: here we are cheating, and using the characteristic speed of the middle state, \n # ignoring how it varies across the rarefaction\n t2_final_points_l = np.ones_like(x2_start_points_l)\n if right_shock:\n t2_final_points_l = np.minimum(t2_final_points_l, \n (x2_end_points_l - t2_end_points_l * xi2m) / \n (vsr - xi2m))\n x2_final_points_l = x2_end_points_l + (t2_final_points_l - t2_end_points_l) * xi2m\n \n for xs, xe, te in zip(x2_start_points_r, x2_end_points_r, t2_end_points_r):\n ax4.plot([xs, xe], [0.0, te], 'b-')\n for xs, xe, te in zip(x2_start_points_l, x2_end_points_l, t2_end_points_l):\n ax4.plot([xs, xe], [0.0, te], 'g-')\n for xs, xe, ts, te in zip(x2_end_points_l, x2_final_points_l, t2_end_points_l, \n t2_final_points_l):\n ax4.plot([xs, xe], [ts, te], 'g-')\n \n # Highlight the waves\n if left_shock:\n ax4.plot([0.0, vsl], [0.0, 1.0], 'r-', linewidth=2)\n else:\n ax4.plot([0.0, xi1l], [0.0, 1.0], 'r-', linewidth=2)\n ax4.plot([0.0, xi1m], [0.0, 1.0], 'r-', linewidth=2)\n if right_shock:\n ax4.plot([0.0, vsr], [0.0, 1.0], 'r-', linewidth=2)\n else:\n ax4.plot([0.0, xi2m], [0.0, 1.0], 'r-', linewidth=2)\n ax4.plot([0.0, xi2r], [0.0, 1.0], 'r-', linewidth=2)\n xi = np.linspace(xi2m, xi2r, 11)\n x_end_rarefaction = xi\n for xe in x_end_rarefaction:\n ax4.plot([0.0, xe], [0.0, 1.0], 'r--')\n \n ax4.set_xlabel(r\"$x$\")\n ax4.set_ylabel(r\"$t$\")\n ax4.set_title(\"2-characteristics\")\n ax4.set_xbound(left_end, right_end)\n \n fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_sw_Riemann_solution, \n hl = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ul = FloatSlider(min = -1.0, max = 1.0, value = 0.2), \n hr = FloatSlider(min = 0.1, max = 10.0, value = 1.0), \n ur = FloatSlider(min = -1.0, max = 1.0, value = -0.2))\n```\n\n\nFailed to display Jupyter Widget of type interactive.
\n If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n that the widgets JavaScript is still loading. If this message persists, it\n likely means that the widgets JavaScript library is either not installed or\n not enabled. See the Jupyter\n Widgets Documentation for setup instructions.\n
\n\n If you're reading this message in another frontend (for example, a static\n rendering on GitHub or NBViewer),\n it may mean that your frontend doesn't currently support widgets.\n
\n\n\n", "meta": {"hexsha": "c330800252791e09635d45654e049cbbe6d7f06a", "size": 93906, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lesson_04_Shallow_Water.ipynb", "max_stars_repo_name": "IanHawke/RiemannPython", "max_stars_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-08-24T01:24:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T18:26:24.000Z", "max_issues_repo_path": "Lesson_04_Shallow_Water.ipynb", "max_issues_repo_name": "IanHawke/RiemannPython", "max_issues_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "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": "Lesson_04_Shallow_Water.ipynb", "max_forks_repo_name": "IanHawke/RiemannPython", "max_forks_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-07-31T17:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-11T13:50:22.000Z", "avg_line_length": 44.0459662289, "max_line_length": 510, "alphanum_fraction": 0.5244073861, "converted": true, "num_tokens": 21853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.22000710486009023, "lm_q1q2_score": 0.0879614015685248}} {"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility here.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''''')\n# display(tag)\n```\n\n\n\nToggle cell visibility here.\n\n\n## Krmiljenje povratne zveze stanj - zmogljivost krmiljenja\n\nZa sistem:\n\n$$\n\\dot{x}=\\underbrace{\\begin{bmatrix}-0.5&1\\\\0&-0.1\\end{bmatrix}}_{A}x+\\underbrace{\\begin{bmatrix}0\\\\1\\end{bmatrix}}_{B}u\n$$\n\nnačrtuj krmilnik tako, da bo prva spremenljivka stanja sistema sledila referenčni koračni funkciji brez odstopka v stacionarnem času s časom ustalitve (odziv naj doseže 95% končne vrednosti) krajšim od 1 s.\n\nZ namenom zagotovitve zgornjim zahtevam dodamo fiktivno spremenljivko stanja $x_3$ z dinamiko $\\dot{x_3}=x_1-x_{1r}$, kjer $x_{1r}$ predstavlja referenčni signal, tako da, če je razširjen sistem asimptotično stabilen, potem konvergira nova spremenljivka stanja $x_3$ k vrednosti 0, kar zagotavlja, da gre $x_1$ k vrednosti $x_{1r}$.\n\nRazširjen sistem lahko popišemo z naslednjimi enačbami:\n\n$$\n\\dot{x}_a=\\underbrace{\\begin{bmatrix}-0.5&1&0\\\\0&-0.1&0\\\\1&0&0\\end{bmatrix}}_{A_a}x_a+\\underbrace{\\begin{bmatrix}0\\\\1\\\\0\\end{bmatrix}}_{B_a}u+\\underbrace{\\begin{bmatrix}0\\\\0\\\\-1\\end{bmatrix}}_{B_{\\text{ref}}}x_{1r}\n$$\n\nin naslednjo spoznavnostno matriko:\n\n$$\n\\begin{bmatrix}B_a&A_aB_a&A_a^2B_a\\end{bmatrix} = \\begin{bmatrix}0&1&-0.6\\\\1&-0.1&0.01\\\\0&0&1\\end{bmatrix}\n$$\n\nKer $\\text{rank}=3$ je razširjen sistem vodljiv.\n\nZ namenom zagotovitve druge zahteve, je možna rešitev ta, da s prilagajanjem polov dosežemo, da ima sistem dominanten pol pri $-3$ rad/s (opomba: $e^{\\lambda t}=e^{-3t}$ pri $t=1$ s znaša $0.4978..<0.05$). Izbrana pola sta tako $\\lambda_1=-3\\,\\text{in}\\,\\lambda_2=\\lambda_3=-30$, s pripadajočo matriko ojačanja $K_a=\\begin{bmatrix}1048.75&62.4&2700\\end{bmatrix}$.\n\nZaprtozančni sistem lahko tako zapišemo kot:\n\n$$\n\\dot{x}_a=(A_a-B_aK_a)x_a+B_av+B_{\\text{ref}}x_{1r}=\\begin{bmatrix}-0.5&1&0\\\\-1048.75&-62.5&-2700\\\\1&0&0\\end{bmatrix}x_a+\\begin{bmatrix}0\\\\1\\\\0\\end{bmatrix}v+\\begin{bmatrix}0\\\\0\\\\-1\\end{bmatrix}x_{1r}\n$$\n\n### Kako upravljati s tem interaktivnim primerom?\nPreizkusi različne rešitve s spreminjanjem ojačanja $K$ ali neposrednim določanjem vrednosti zaprtozančnih lastnih vrednosti.\n\n\n```python\n%matplotlib inline\nimport control as control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n :a: numpy array\n :returns: LaTeX bmatrix as a string\n \"\"\"\n if len(a.shape) > 2:\n raise ValueError('bmatrix can at most display two dimensions')\n lines = str(a).replace('[', '').replace(']', '').splitlines()\n rv = [r'\\begin{bmatrix}']\n rv += [' ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n rv += [r'\\end{bmatrix}']\n return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n if len(a.shape) > 2:\n raise ValueError('bmatrix can at most display two dimensions')\n lines = str(a).replace('[', '').replace(']', '').splitlines()\n rv = [r'\\begin{vmatrix}']\n rv += [' ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n rv += [r'\\end{vmatrix}']\n return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n def updateM(self,change):\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.M_[irow,icol] = self.children[irow].children[icol].value\n #print(self.M_[irow,icol])\n self.value = self.M_\n\n def dummychangecallback(self,change):\n pass\n \n \n def __init__(self,n,m):\n self.n = n\n self.m = m\n self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n self.value = self.M_\n widgets.VBox.__init__(self,\n children = [\n widgets.HBox(children = \n [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n ) \n for j in range(n)\n ])\n \n #fill in widgets and tell interact to call updateM each time a children changes value\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].value = self.M_[irow,icol]\n self.children[irow].children[icol].observe(self.updateM, names='value')\n #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n self.observe(self.updateM, names='value', type= 'All')\n \n def setM(self, newM):\n #disable callbacks, change values, and reenable\n self.unobserve(self.updateM, names='value', type= 'All')\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].unobserve(self.updateM, names='value')\n self.M_ = newM\n self.value = self.M_\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].value = self.M_[irow,icol]\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].observe(self.updateM, names='value')\n self.observe(self.updateM, names='value', type= 'All') \n\n #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n def __init__(self,*args):\n #call base class init constructor\n control.StateSpace.__init__(self,*args)\n #disable function below in base class\n def _remove_useless_states(self):\n pass\n```\n\n\n```python\n# Preparatory cell\n\nA = numpy.matrix('-0.5 1 0; 0 -0.1 0; 1 0 0')\nB = numpy.matrix('0; 1; 0')\nBr = numpy.matrix('0; 0; -1')\nC = numpy.matrix('1 0 0')\nX0 = numpy.matrix('0; 0; 0')\nK = numpy.matrix([1048.75,62.4,2700])\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nBrw = matrixWidget(3,1)\nBrw.setM(Br)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = matrixWidget(3,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-3])) \neig2c.setM(numpy.matrix([[-30],[0]]))\neig3c.setM(numpy.matrix([-30]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n description='Test',\n disabled=False,\n button_style='', # 'success', 'info', 'warning', 'danger' or ''\n tooltip='Test',\n icon='check'\n)\n \ndef on_start_button_clicked(b):\n #This is a workaround to have intreactive_output call the callback:\n # force the value of the dummy widget to change\n if DW.value> 0 :\n DW.value = -1\n else: \n DW.value = 1\n pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n options= ['Nastavi K', 'Nastavi lastne vrednosti'],\n value= 'Nastavi K',\n description='',\n disabled=False\n)\n\n# Define the number of complex eigenvalues for the observer\nselc = widgets.Dropdown(\n options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti'],\n value= 'brez kompleksnih lastnih vrednosti',\n description='Lastne vrednosti:',\n disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n options=['impulzna funkcija', 'koračna funkcija', 'sinusoidna funkcija', 'kvadratni val'],\n value='impulzna funkcija',\n description='Vhod:',\n disabled=False,\n style = {'description_width': 'initial','button_width':'180px'}\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n value=1,\n min=0,\n max=20.0,\n step=0.1,\n description='Referenca:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n value=0.5,\n min=0.01,\n max=4,\n step=0.01,\n description='Perioda: ',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.2f',\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(selc):\n if selc == 'brez kompleksnih lastnih vrednosti':\n eig1c.children[0].children[0].disabled = False\n eig2c.children[1].children[0].disabled = True\n eigc = 0\n if selc == 'dve kompleksni lastni vrednosti':\n eig1c.children[0].children[0].disabled = True\n eig2c.children[1].children[0].disabled = False\n eigc = 2\n return eigc\n\ndef method_choice(selm):\n if selm == 'Nastavi K':\n method = 1\n selc.disabled = True\n if selm == 'Nastavi lastne vrednosti':\n method = 2\n selc.disabled = False\n return method\n```\n\n\n```python\ndef main_callback(Aw, Bw, Brw, X0w, K, eig1c, eig2c, eig3c, u, period, selm, selc, selu, DW):\n A, B, Br = Aw, Bw, Brw \n sols = numpy.linalg.eig(A)\n eigc = eigen_choice(selc)\n method = method_choice(selm)\n \n if method == 1:\n sol = numpy.linalg.eig(A-B*K)\n if method == 2:\n if eigc == 0:\n K = control.acker(A, B, [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n Kw.setM(K) \n if eigc == 2:\n K = control.acker(A, B, [eig1c[0,0], \n numpy.complex(eig2c[0,0],eig2c[1,0]), \n numpy.complex(eig2c[0,0],-eig2c[1,0])])\n Kw.setM(K)\n sol = numpy.linalg.eig(A-B*K)\n print('Lastne vrednosti sistema so:',round(sols[0][0],4),',',round(sols[0][1],4),'in',round(sols[0][2],4))\n print('Lastne vrednosti krmiljenega sistema so:',round(sol[0][0],4),',',round(sol[0][1],4),'in',round(sol[0][2],4))\n \n sys = sss(A-B*K,Br,C,0)\n T = numpy.linspace(0, 6, 1000)\n \n if selu == 'impulzna funkcija': #selu\n U = [0 for t in range(0,len(T))]\n U[0] = u\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n if selu == 'koračna funkcija':\n U = [u for t in range(0,len(T))]\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n if selu == 'sinusoidna funkcija':\n U = u*numpy.sin(2*numpy.pi/period*T)\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n if selu == 'kvadratni val':\n U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n \n fig = plt.figure(num='Simulacija', figsize=(16,10))\n \n fig.add_subplot(211)\n plt.title('Odziv prve spremenljivke stanj')\n plt.ylabel('$X_1$ vs ref')\n plt.plot(T,xout[0],T,U,'r--')\n plt.xlabel('$t$ [s]')\n plt.legend(['$x_1$','Referenca'])\n plt.axvline(x=0,color='black',linewidth=0.8)\n plt.axhline(y=0,color='black',linewidth=0.8)\n plt.grid()\n \n fig.add_subplot(212)\n poles, zeros = control.pzmap(sys,Plot=False)\n plt.title('Diagram polov in ničel')\n plt.ylabel('Im')\n plt.plot(numpy.real(poles),numpy.imag(poles),'rx',numpy.real(zeros),numpy.imag(zeros),'bo')\n plt.xlabel('Re')\n plt.axvline(x=0,color='black',linewidth=0.8)\n plt.axhline(y=0,color='black',linewidth=0.8)\n plt.grid()\n \nalltogether = widgets.VBox([widgets.HBox([selm, \n selc, \n selu]),\n widgets.Label(' ',border=3),\n widgets.HBox([widgets.Label('K:',border=3), Kw, \n widgets.Label(' ',border=3),\n widgets.Label(' ',border=3),\n widgets.Label('Lastne vrednosti:',border=3), \n eig1c, \n eig2c, \n eig3c,\n widgets.Label(' ',border=3),\n widgets.Label(' ',border=3),\n widgets.Label('X0:',border=3), X0w]),\n widgets.Label(' ',border=3),\n widgets.HBox([u, \n period, \n START]),\n widgets.Label(' ',border=3),\n widgets.HBox([widgets.Label('Dinamična matrika Aa:',border=3),\n Aw,\n widgets.Label('Vhodna matrika Ba:',border=3),\n Bw,\n widgets.Label('Referenčna matrika Br:',border=3),\n Brw])])\nout = widgets.interactive_output(main_callback, {'Aw':Aw, 'Bw':Bw, 'Brw':Brw, 'X0w':X0w, 'K':Kw, 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, \n 'u':u, 'period':period, 'selm':selm, 'selc':selc, 'selu':selu, 'DW':DW})\nout.layout.height = '640px'\ndisplay(out, alltogether)\n```\n\n\n Output(layout=Layout(height='640px'))\n\n\n\n VBox(children=(HBox(children=(Dropdown(options=('Nastavi K', 'Nastavi lastne vrednosti'), value='Nastavi K'), …\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "45aeac29c77d827def00160b588980967680b7be", "size": 19921, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-31-Krmiljenje_povratne_zveze_stanj_zmogljivost.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_si/examples/04/SS-31-Krmiljenje_povratne_zveze_stanj_zmogljivost.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_si/examples/04/SS-31-Krmiljenje_povratne_zveze_stanj_zmogljivost.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 38.6815533981, "max_line_length": 381, "alphanum_fraction": 0.4848150193, "converted": true, "num_tokens": 4195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.2200070895174993, "lm_q1q2_score": 0.0879613922876462}} {"text": "# Optimización media-varianza\n\n\n\n\nLa **teoría de portafolios** es una de los avances más importantes en las finanzas modernas e inversiones.\n- Apareció por primera vez en un [artículo corto](https://www.math.ust.hk/~maykwok/courses/ma362/07F/markowitz_JF.pdf) llamado \"Portfolio Selection\" en la edición de Marzo de 1952 de \"the Journal of Finance\".\n- Escrito por un desconocido estudiante de la Universidad de Chicago, llamado Harry Markowitz.\n- Escrito corto (sólo 14 páginas), poco texto, fácil de entender, muchas gráficas y unas cuantas referencias.\n- No se le prestó mucha atención hasta los 60s.\n\nFinalmente, este trabajo se convirtió en una de las más grandes ideas en finanzas, y le dió a Markowitz el Premio Noble casi 40 años después.\n- Markowitz estaba incidentalmente interesado en los mercados de acciones e inversiones.\n- Estaba más bien interesado en entender cómo las personas tomaban sus mejores decisiones cuando se enfrentaban con \"trade-offs\".\n- Principio de conservación de la miseria. O, dirían los instructores de gimnasio: \"no pain, no gain\".\n- Si queremos más de algo, tenemos que perder en algún otro lado.\n- El estudio de este fenómeno era el que le atraía a Markowitz.\n\nDe manera que nadie se hace rico poniendo todo su dinero en la cuenta de ahorros. La única manera de esperar altos rendimientos es si se toma bastante riesgo. Sin embargo, riesgo significa también la posibilidad de perder, tanto como ganar.\n\nPero, ¿qué tanto riesgo es necesario?, y ¿hay alguna manera de minimizar el riesgo mientras se maximizan las ganancias?\n- Markowitz básicamente cambió la manera en que los inversionistas pensamos acerca de esas preguntas.\n- Alteró completamente la práctica de la administración de inversiones.\n- Incluso el título de su artículo era innovador. Portafolio: una colección de activos en lugar de tener activos individuales.\n- En ese tiempo, un portafolio se refería a una carpeta de cuero.\n- En el resto de este módulo, no ocuparemos de la parte analítica de la teoría de portafolios, la cual puede ser resumida en dos frases:\n - No pain, no gain.\n - No ponga todo el blanquillo en una sola bolsa.\n \n\n**Objetivos:**\n- ¿Qué es la línea de asignación de capital?\n- ¿Qué es el radio de Sharpe?\n- ¿Cómo deberíamos asignar nuestro capital entre un activo riesgoso y un activo libre de riesgo?\n\n*Referencia:*\n- Notas del curso \"Portfolio Selection and Risk Management\", Rice University, disponible en Coursera.\n___ \n\n## 1. Línea de asignación de capital\n\n### 1.1. Motivación\n\nEl proceso de construcción de un portafolio tiene entonces los siguientes dos pasos:\n1. Escoger un portafolio de activos riesgosos.\n2. Decidir qué tanto de tu riqueza invertirás en el portafolio y qué tanto invertirás en activos libres de riesgo.\n\nAl paso 2 lo llamamos **decisión de asignación de activos**.\n\nPreguntas importantes:\n1. ¿Qué es el portafolio óptimo de activos riesgosos?\n - ¿Cuál es el mejor portafolio de activos riesgosos?\n - Es un portafolio eficiente en media-varianza.\n2. ¿Qué es la distribución óptima de activos?\n - ¿Cómo deberíamos distribuir nuestra riqueza entre el portafolo riesgoso óptimo y el activo libre de riesgo?\n - Concepto de **línea de asignación de capital**.\n - Concepto de **radio de Sharpe**.\n\nDos suposiciones importantes:\n- Funciones de utilidad media-varianza.\n- Inversionista averso al riesgo.\n\nLa idea sorprendente que saldrá de este análisis, es que cualquiera que sea la actitud del inversionista de cara al riesgo, el mejor portafolio de activos riesgosos es idéntico para todos los inversionistas.\n\nLo que nos importará a cada uno de nosotros en particular, es simplemente la desición óptima de asignación de activos.\n___\n\n### 1.2. Línea de asignación de capital\n\nSean:\n- $r_s$ el rendimiento del activo riesgoso,\n- $r_f$ el rendimiento libre de riesgo, y\n- $w$ la fracción invertida en el activo riesgoso.\n\n Realizar deducción de la línea de asignación de capital en el tablero.\n\n**Tres doritos después...**\n\n#### Línea de asignación de capital (LAC):\n$E[r_p]$ se relaciona con $\\sigma_p$ de manera afín. Es decir, mediante la ecuación de una recta:\n\n$$E[r_p]=r_f+\\frac{E[r_s-r_f]}{\\sigma_s}\\sigma_p.$$\n\n- La pendiente de la LAC es el radio de Sharpe $\\frac{E[r_s-r_f]}{\\sigma_s}=\\frac{E[r_s]-r_f}{\\sigma_s}$,\n- el cual nos dice qué tanto rendimiento obtenemos por unidad de riesgo asumido en la tenencia del activo (portafolio) riesgoso.\n\nAhora, la pregunta es, ¿dónde sobre esta línea queremos estar?\n___\n\n### 1.3. Resolviendo para la asignación óptima de capital\n\nRecapitulando de la clase pasada, tenemos las curvas de indiferencia: **queremos estar en la curva de indiferencia más alta posible, que sea tangente a la LAC**.\n\n Ver en el tablero.\n\nAnalíticamente, el problema es\n\n$$\\max_{w} \\quad E[U(r_p)]\\equiv\\max_{w} \\quad E[r_p]-\\frac{1}{2}\\gamma\\sigma_p^2,$$\n\ndonde los puntos $(\\sigma_p,E[r_p])$ se restringen a estar en la LAC, esto es $E[r_p]=r_f+\\frac{E[r_s-r_f]}{\\sigma_s}\\sigma_p$ y $\\sigma_p=w\\sigma_s$. Entonces el problema anterior se puede escribir de la siguiente manera:\n\n$$\\max_{w} \\quad r_f+wE[r_s-r_f]-\\frac{1}{2}\\gamma w^2\\sigma_s^2.$$\n\n Encontrar la $w$ que maximiza la anterior expresión en el tablero.\n\n**Tres doritos después...**\n\nLa solución es entonces:\n\n$$w^\\ast=\\frac{E[r_s-r_f]}{\\gamma\\sigma_s^2}.$$\n\nDe manera intuitiva:\n- $w^\\ast\\propto E[r_s-r_f]$: a más exceso de rendimiento que se obtenga del activo riesgoso, más querremos invertir en él.\n- $w^\\ast\\propto \\frac{1}{\\gamma}$: mientras más averso al riesgo seas, menos querrás invertir en el activo riesgoso.\n- $w^\\ast\\propto \\frac{1}{\\sigma_s^2}$: mientras más riesgoso sea el activo, menos querrás invertir en él.\n___\n\n## 2. Ejemplo de asignación óptima de capital: acciones y billetes de EU\n\nPongamos algunos números con algunos datos, para ilustrar la derivación que acabamos de hacer.\n\nEn este caso, consideraremos:\n- **Portafolio riesgoso**: mercado de acciones de EU (representados en algún índice de mercado como el S&P500).\n- **Activo libre de riesgo**: billetes del departamento de tesorería de EU (T-bills).\n\nTenemos los siguientes datos:\n\n$$E[r_{US}]=11.9\\%,\\quad \\sigma_{US}=19.15\\%, \\quad r_f=1\\%.$$\n\nRecordamos que podemos escribir la expresión de la LAC como:\n\n\\begin{align}\nE[r_p]&=r_f+\\left[\\frac{E[r_{US}-r_f]}{\\sigma_{US}}\\right]\\sigma_p\\\\\n &=0.01+\\text{S.R.}\\sigma_p,\n\\end{align}\n\ndonde $\\text{S.R}=\\frac{0.119-0.01}{0.1915}\\approx0.569$ es el radio de Sharpe (¿qué es lo que es esto?).\n\nGrafiquemos la LAC con estos datos reales:\n\n\n```python\n# Importamos librerías que vamos a utilizar\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\n# Datos\nErus, sus, rf = 0.119, 0.1915, 0.01\n# Radio de Sharpe para este activo\nSR = (Erus-rf)/sus\n# Vector de volatilidades del portafolio\nsp = np.linspace(0, 0.5, 100)\n# LAC\nErp = rf+SR*sp\n```\n\n\n```python\n# Gráfica\nplt.figure(figsize=(10,6))\nplt.plot(sp, Erp, lw='3', label='LAC')\nplt.plot(0, rf, 'o', ms=10, label='Libre de riesgo')\nplt.plot(sus, Erus, 'o', ms=10, label='Portafolio riesgoso')\nplt.axhline(y=Erus, color='gray')\nplt.axvline(x=sus, color='gray')\nplt.axhline(y=0, color='k')\nplt.axvline(x=0, color='k')\nplt.grid()\nplt.xlabel('Volatility $\\sigma_p$')\nplt.ylabel('Expected return $E[r_p]$')\nplt.legend(loc='best')\n```\n\nBueno, y ¿en qué punto de esta línea querríamos estar?\n- Pues ya vimos que depende de tus preferencias.\n- En particular, de tu actitud de cara al riesgo, medido por tu coeficiente de aversión al riesgo.\n\nSolución al problema de asignación óptima de capital:\n\n$$\\max_{w} \\quad E[U(r_p)]$$\n\n$$w^\\ast=\\frac{E[r_s-r_f]}{\\gamma\\sigma_s^2}$$\n\nDado que ya tenemos datos, podemos intentar para varios coeficientes de aversión al riesgo:\n\n\n```python\n# importar pandas\nimport pandas as pd\n```\n\n\n```python\n# Crear un DataFrame con los pesos, rendimiento\n# esperado y volatilidad del portafolio óptimo \n# entre los activos riesgoso y libre de riesgo\n# cuyo índice sean los coeficientes de aversión\n# al riesgo del 1 al 10 (enteros)\ng = np.arange(1, 11)\nwopt = (Erus-rf)/(g*sus**2)\nsp = wopt*sus\nErp = rf+(Erus-rf)/sus*sp\ndata = pd.DataFrame(index=g, columns=['$w_{opt}$', '$E[r_p]$', '$\\sigma_p$'])\ndata.index.name = '$\\gamma$'\ndata['$w_{opt}$'] = wopt\ndata['$E[r_p]$'] = Erp\ndata['$\\sigma_p$'] = sp\ndata\n```\n\n\n\n\n| \n | $w_{opt}$ | \n$E[r_p]$ | \n$\\sigma_p$ | \n
|---|---|---|---|
| $\\gamma$ | \n\n | \n | \n |
| 1 | \n2.972275 | \n0.333978 | \n0.569191 | \n
| 2 | \n1.486137 | \n0.171989 | \n0.284595 | \n
| 3 | \n0.990758 | \n0.117993 | \n0.189730 | \n
| 4 | \n0.743069 | \n0.090994 | \n0.142298 | \n
| 5 | \n0.594455 | \n0.074796 | \n0.113838 | \n
| 6 | \n0.495379 | \n0.063996 | \n0.094865 | \n
| 7 | \n0.424611 | \n0.056283 | \n0.081313 | \n
| 8 | \n0.371534 | \n0.050497 | \n0.071149 | \n
| 9 | \n0.330253 | \n0.045998 | \n0.063243 | \n
| 10 | \n0.297227 | \n0.042398 | \n0.056919 | \n
Bruno Gonçalves
\n www.data4sci.com
\n @bgoncalves, @data4sci
| \n | Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license.(c) Carlos Alberto Alvarez Henao | \n
\n \n
\n\n\n \n
\n\n- Aritmética de punto flotante no es conmutativa o asociativa\n\n\n- Errores de punto flotante compuestos, No asuma que la precisión doble es suficiente\n\n\n- Mezclar precisión es muy peligroso\n\n***EL ORDEN DE LOS FACTORES NO ALTERA EL PRODUCTO???***\n\n$$2 \\times 3 = 3 \\times 2 = 6$$\n\n\n$$ 10^{300} \\times 10^{50} \\times 10^{-60} = 10^{300} \\times 10^{-60} \\times 10^{50} ??$$\n\n\n\n```python\na = 10**300\nb = 10**10\nc = 10**-60\n\n```\n\n\n```python\nd1 = a * b * c\nprint(\"d1: \", d1)\n```\n\n\n```python\nd2 = b * c * a\nprint(\"d2: \", d2)\n\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 1: Aritmética simple\n\nAritmética simple $\\delta < \\epsilon_{\\text{machine}}$\n\n $$(1+\\delta) - 1 = 1 - 1 = 0$$\n\n $$1 - 1 + \\delta = \\delta$$\n\n\n```python\ndelta = 1.0000000001 * eps\n\nvalue = (1 + delta) - 1\nprint(value)\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 2: Cancelación catastrófica\n\nMiremos qué sucede cuando sumamos dos números $x$ y $y$ cuando $x+y \\neq 0$. De hecho, podemos estimar estos límites haciendo un análisis de error. Aquí necesitamos presentar la idea de que cada operación de punto flotante introduce un error tal que\n\n$$\n \\text{fl}(x ~\\text{op}~ y) = (x ~\\text{op}~ y) (1 + \\delta)\n$$\n\ndonde $\\text{fl}(\\cdot)$ es una función que devuelve la representación de punto flotante de la expresión encerrada, $\\text{op}$ es alguna operación (ex. $+, -, \\times, /$), y $\\delta$ es el error de punto flotante debido a $\\text{op}$.\n\nDe vuelta a nuestro problema en cuestión. El error de coma flotante debido a la suma es\n\n$$\\text{fl}(x + y) = (x + y) (1 + \\delta).$$\n\n\nComparando esto con la solución verdadera usando un error relativo tenemos\n\n$$\\begin{aligned}\n \\frac{(x + y) - \\text{fl}(x + y)}{x + y} &= \\frac{(x + y) - (x + y) (1 + \\delta)}{x + y} = \\delta.\n\\end{aligned}$$\n\nentonces si $\\delta = \\mathcal{O}(\\epsilon_{\\text{machine}})$ no estaremos muy preocupados.\n\nQue pasa si consideramos un error de punto flotante en la representación de $x$ y $y$, $x \\neq y$, y decimos que $\\delta_x$ y $\\delta_y$ son la magnitud de los errores en su representación. Asumiremos que esto constituye el error de punto flotante en lugar de estar asociado con la operación en sí.\n\nDado todo esto, tendríamos\n\n$$\\begin{aligned}\n \\text{fl}(x + y) &= x (1 + \\delta_x) + y (1 + \\delta_y) \\\\\n &= x + y + x \\delta_x + y \\delta_y \\\\\n &= (x + y) \\left(1 + \\frac{x \\delta_x + y \\delta_y}{x + y}\\right)\n\\end{aligned}$$\n\nCalculando nuevamente el error relativo, tendremos\n\n$$\\begin{aligned}\n \\frac{x + y - (x + y) \\left(1 + \\frac{x \\delta_x + y \\delta_y}{x + y}\\right)}{x + y} &= 1 - \\left(1 + \\frac{x \\delta_x + y \\delta_y}{x + y}\\right) \\\\\n &= \\frac{x}{x + y} \\delta_x + \\frac{y}{x + y} \\delta_y \\\\\n &= \\frac{1}{x + y} (x \\delta_x + y \\delta_y)\n\\end{aligned}$$\n\nLo importante aquí es que ahora el error depende de los valores de $x$ y $y$, y más importante aún, su suma. De particular preocupación es el tamaño relativo de $x + y$. A medida que se acerca a cero en relación con las magnitudes de $x$ y $y$, el error podría ser arbitrariamente grande. Esto se conoce como ***cancelación catastrófica***.\n\n\n```python\ndx = np.array([10**(-n) for n in range(1, 16)])\nx = 1.0 + dx\ny = -np.ones(x.shape)\nerror = np.abs(x + y - dx) / (dx)\n\nfig = plt.figure()\nfig.set_figwidth(fig.get_figwidth() * 2)\n\naxes = fig.add_subplot(1, 2, 1)\naxes.loglog(dx, x + y, 'o-')\naxes.set_xlabel(\"$\\Delta x$\")\naxes.set_ylabel(\"$x + y$\")\naxes.set_title(\"$\\Delta x$ vs. $x+y$\")\n\naxes = fig.add_subplot(1, 2, 2)\naxes.loglog(dx, error, 'o-')\naxes.set_xlabel(\"$\\Delta x$\")\naxes.set_ylabel(\"$|x + y - \\Delta x| / \\Delta x$\")\naxes.set_title(\"Diferencia entre $x$ y $y$ vs. Error relativo\")\n\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 3: Evaluación de una función\n\nConsidere la función\n\n$$\n f(x) = \\frac{1 - \\cos x}{x^2}\n$$\n\ncon $x\\in[-10^{-4}, 10^{-4}]$. \n\nTomando el límite cuando $x \\rightarrow 0$ podemos ver qué comportamiento esperaríamos ver al evaluar esta función:\n\n$$\n \\lim_{x \\rightarrow 0} \\frac{1 - \\cos x}{x^2} = \\lim_{x \\rightarrow 0} \\frac{\\sin x}{2 x} = \\lim_{x \\rightarrow 0} \\frac{\\cos x}{2} = \\frac{1}{2}.\n$$\n\n¿Qué hace la representación de punto flotante?\n\n\n```python\nf = (1-np.cos(0))/0**2\n```\n\n\n```python\nx = np.linspace(-1e-3, 1e-3, 100, dtype=np.float32)\nerror = (0.5 - (1.0 - np.cos(x)) / x**2) / 0.5\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.plot(x, error, 'o')\naxes.set_xlabel(\"x\")\naxes.set_ylabel(\"Error Relativo\")\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 4: Evaluación de un Polinomio\n\n $$f(x) = x^7 - 7x^6 + 21 x^5 - 35 x^4 + 35x^3-21x^2 + 7x - 1$$\n\n\n```python\nx = np.linspace(0.988, 1.012, 1000, dtype=np.float16)\ny = x**7 - 7.0 * x**6 + 21.0 * x**5 - 35.0 * x**4 + 35.0 * x**3 - 21.0 * x**2 + 7.0 * x - 1.0\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.plot(x, y, 'r')\naxes.set_xlabel(\"x\")\naxes.set_ylabel(\"y\")\naxes.set_ylim((-0.1, 0.1))\naxes.set_xlim((x[0], x[-1]))\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 5: Evaluación de una función racional\n\nCalcule $f(x) = x + 1$ por la función $$F(x) = \\frac{x^2 - 1}{x - 1}$$\n\n¿Cuál comportamiento esperarías encontrar?\n\n\n```python\nx = np.linspace(0.5, 1.5, 101, dtype=np.float16)\nf_hat = (x**2 - 1.0) / (x - 1.0)\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.plot(x, np.abs(f_hat - (x + 1.0)))\naxes.set_xlabel(\"$x$\")\naxes.set_ylabel(\"Error Absoluto\")\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n## Combinación de error\n\nEn general, nos debemos ocupar de la combinación de error de truncamiento con el error de punto flotante.\n\n- Error de Truncamiento: errores que surgen de la aproximación de una función, truncamiento de una serie.\n\n$$\\sin x \\approx x - \\frac{x^3}{3!} + \\frac{x^5}{5!} + O(x^7)$$\n\n\n- Error de punto flotante: errores derivados de la aproximación de números reales con números de precisión finita\n\n$$\\pi \\approx 3.14$$\n\no $\\frac{1}{3} \\approx 0.333333333$ en decimal, los resultados forman un número finito de registros para representar cada número.\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 1:\n\nConsidere la aproximación de diferencias finitas donde $f(x) = e^x$ y estamos evaluando en $x=1$\n\n$$f'(x) \\approx \\frac{f(x + \\Delta x) - f(x)}{\\Delta x}$$\n\nCompare el error entre disminuir $\\Delta x$ y la verdadera solucion $f'(1) = e$\n\n\n```python\ndelta_x = np.linspace(1e-20, 5.0, 100)\ndelta_x = np.array([2.0**(-n) for n in range(1, 60)])\nx = 1.0\nf_hat_1 = (np.exp(x + delta_x) - np.exp(x)) / (delta_x)\nf_hat_2 = (np.exp(x + delta_x) - np.exp(x - delta_x)) / (2.0 * delta_x)\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.loglog(delta_x, np.abs(f_hat_1 - np.exp(1)), 'o-', label=\"Unilateral\")\naxes.loglog(delta_x, np.abs(f_hat_2 - np.exp(1)), 's-', label=\"Centrado\")\naxes.legend(loc=3)\naxes.set_xlabel(\"$\\Delta x$\")\naxes.set_ylabel(\"Error Absoluto\")\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 2:\n\nEvalúe $e^x$ con la serie de *Taylor*\n\n$$e^x = \\sum^\\infty_{n=0} \\frac{x^n}{n!}$$\n\npodemos elegir $n< \\infty$ que puede aproximarse $e^x$ en un rango dado $x \\in [a,b]$ tal que el error relativo $E$ satisfaga $E<8 \\cdot \\varepsilon_{\\text{machine}}$?\n\n¿Cuál podría ser una mejor manera de simplemente evaluar el polinomio de Taylor directamente por varios $N$?\n\n\n```python\ndef my_exp(x, N=10):\n value = 0.0\n for n in range(N + 1):\n value += x**n / scipy.special.factorial(n)\n \n return value\n\nx = np.linspace(-2, 2, 100, dtype=np.float32)\nfor N in range(1, 50):\n error = np.abs((np.exp(x) - my_exp(x, N=N)) / np.exp(x))\n if np.all(error < 8.0 * np.finfo(float).eps):\n break\n\nprint(N)\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.plot(x, error)\naxes.set_xlabel(\"x\")\naxes.set_ylabel(\"Error Relativo\")\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 3: Error relativo\n\nDigamos que queremos calcular el error relativo de dos valores $x$ y $y$ usando $x$ como valor de normalización\n\n$$\n E = \\frac{x - y}{x}\n$$\ny\n$$\n E = 1 - \\frac{y}{x}\n$$\n\nson equivalentes. En precisión finita, ¿qué forma pidría esperarse que sea más precisa y por qué?\n\nEjemplo tomado de [blog](https://nickhigham.wordpress.com/2017/08/14/how-and-how-not-to-compute-a-relative-error/) posteado por Nick Higham*\n\nUsando este modelo, la definición original contiene dos operaciones de punto flotante de manera que\n\n$$\\begin{aligned}\n E_1 = \\text{fl}\\left(\\frac{x - y}{x}\\right) &= \\text{fl}(\\text{fl}(x - y) / x) \\\\\n &= \\left[ \\frac{(x - y) (1 + \\delta_+)}{x} \\right ] (1 + \\delta_/) \\\\\n &= \\frac{x - y}{x} (1 + \\delta_+) (1 + \\delta_/)\n\\end{aligned}$$\n\nPara la otra formulación tenemos\n\n$$\\begin{aligned}\n E_2 = \\text{fl}\\left( 1 - \\frac{y}{x} \\right ) &= \\text{fl}\\left(1 - \\text{fl}\\left(\\frac{y}{x}\\right) \\right) \\\\\n &= \\left(1 - \\frac{y}{x} (1 + \\delta_/) \\right) (1 + \\delta_-)\n\\end{aligned}$$\n\nSi suponemos que todos las $\\text{op}$s tienen magnitudes de error similares, entonces podemos simplificar las cosas dejando que \n\n$$\n |\\delta_\\ast| \\le \\epsilon.\n$$\n\nPara comparar las dos formulaciones, nuevamente usamos el error relativo entre el error relativo verdadero $e_i$ y nuestras versiones calculadas $E_i$\n\nDefinición original\n\n$$\\begin{aligned}\n \\frac{e - E_1}{e} &= \\frac{\\frac{x - y}{x} - \\frac{x - y}{x} (1 + \\delta_+) (1 + \\delta_/)}{\\frac{x - y}{x}} \\\\\n &\\le 1 - (1 + \\epsilon) (1 + \\epsilon) = 2 \\epsilon + \\epsilon^2\n\\end{aligned}$$\n\nDefinición manipulada:\n\n$$\\begin{aligned}\n \\frac{e - E_2}{e} &= \\frac{e - \\left[1 - \\frac{y}{x}(1 + \\delta_/) \\right] (1 + \\delta_-)}{e} \\\\\n &= \\frac{e - \\left[e - \\frac{y}{x} \\delta_/) \\right] (1 + \\delta_-)}{e} \\\\\n &= \\frac{e - \\left[e + e\\delta_- - \\frac{y}{x} \\delta_/ - \\frac{y}{x} \\delta_/ \\delta_-)) \\right] }{e} \\\\\n &= - \\delta_- + \\frac{1}{e} \\frac{y}{x} \\left(\\delta_/ + \\delta_/ \\delta_- \\right) \\\\\n &= - \\delta_- + \\frac{1 -e}{e} \\left(\\delta_/ + \\delta_/ \\delta_- \\right) \\\\\n &\\le \\epsilon + \\left |\\frac{1 - e}{e}\\right | (\\epsilon + \\epsilon^2)\n\\end{aligned}$$\n\nVemos entonces que nuestro error de punto flotante dependerá de la magnitud relativa de $e$\n\n\n```python\n# Based on the code by Nick Higham\n# https://gist.github.com/higham/6f2ce1cdde0aae83697bca8577d22a6e\n# Compares relative error formulations using single precision and compared to double precision\n\nN = 501 # Note: Use 501 instead of 500 to avoid the zero value\nd = numpy.finfo(numpy.float32).eps * 1e4\na = 3.0\nx = a * numpy.ones(N, dtype=numpy.float32)\ny = [x[i] + numpy.multiply((i - numpy.divide(N, 2.0, dtype=numpy.float32)), d, dtype=numpy.float32) for i in range(N)]\n\n# Compute errors and \"true\" error\nrelative_error = numpy.empty((2, N), dtype=numpy.float32)\nrelative_error[0, :] = numpy.abs(x - y) / x\nrelative_error[1, :] = numpy.abs(1.0 - y / x)\nexact = numpy.abs( (numpy.float64(x) - numpy.float64(y)) / numpy.float64(x))\n\n# Compute differences between error calculations\nerror = numpy.empty((2, N))\nfor i in range(2):\n error[i, :] = numpy.abs((relative_error[i, :] - exact) / numpy.abs(exact))\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.semilogy(y, error[0, :], '.', markersize=10, label=\"$|x-y|/|x|$\")\naxes.semilogy(y, error[1, :], '.', markersize=10, label=\"$|1-y/x|$\")\n\naxes.grid(True)\naxes.set_xlabel(\"y\")\naxes.set_ylabel(\"Error Relativo\")\naxes.set_xlim((numpy.min(y), numpy.max(y)))\naxes.set_ylim((5e-9, numpy.max(error[1, :])))\naxes.set_title(\"Comparasión Error Relativo\")\naxes.legend()\nplt.show()\n```\n\nAlgunos enlaces de utilidad con respecto al punto flotante IEEE:\n\n- [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)\n\n\n- [IEEE 754 Floating Point Calculator](http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html)\n\n\n- [Numerical Computing with IEEE Floating Point Arithmetic](http://epubs.siam.org/doi/book/10.1137/1.9780898718072)\n\n[Volver a la Tabla de Contenido](#TOC)\n\n## Operaciones de conteo\n\n- ***Error de truncamiento:*** *¿Por qué no usar más términos en la serie de Taylor?*\n\n\n- ***Error de punto flotante:*** *¿Por qué no utilizar la mayor precisión posible?*\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 1: Multiplicación matriz - vector\n\nSea $A, B \\in \\mathbb{R}^{N \\times N}$ y $x \\in \\mathbb{R}^N$.\n\n1. Cuenta el número aproximado de operaciones que tomará para calcular $Ax$\n\n2. Hacer lo mismo para $AB$\n\n***Producto Matriz-vector:*** Definiendo $[A]_i$ como la $i$-ésima fila de $A$ y $A_{ij}$ como la $i$,$j$-ésima entrada entonces\n\n$$\n A x = \\sum^N_{i=1} [A]_i \\cdot x = \\sum^N_{i=1} \\sum^N_{j=1} A_{ij} x_j\n$$\n\nTomando un caso en particular, siendo $N=3$, entonces la operación de conteo es\n\n$$\n A x = [A]_1 \\cdot v + [A]_2 \\cdot v + [A]_3 \\cdot v = \\begin{bmatrix}\n A_{11} \\times v_1 + A_{12} \\times v_2 + A_{13} \\times v_3 \\\\\n A_{21} \\times v_1 + A_{22} \\times v_2 + A_{23} \\times v_3 \\\\\n A_{31} \\times v_1 + A_{32} \\times v_2 + A_{33} \\times v_3\n \\end{bmatrix}\n$$\n\nEsto son 15 operaciones (6 sumas y 9 multiplicaciones)\n\nTomando otro caso, siendo $N=4$, entonces el conteo de operaciones es:\n\n$$\n A x = [A]_1 \\cdot v + [A]_2 \\cdot v + [A]_3 \\cdot v = \\begin{bmatrix}\n A_{11} \\times v_1 + A_{12} \\times v_2 + A_{13} \\times v_3 + A_{14} \\times v_4 \\\\\n A_{21} \\times v_1 + A_{22} \\times v_2 + A_{23} \\times v_3 + A_{24} \\times v_4 \\\\\n A_{31} \\times v_1 + A_{32} \\times v_2 + A_{33} \\times v_3 + A_{34} \\times v_4 \\\\\n A_{41} \\times v_1 + A_{42} \\times v_2 + A_{43} \\times v_3 + A_{44} \\times v_4 \\\\\n \\end{bmatrix}\n$$\n\nEsto lleva a 28 operaciones (12 sumas y 16 multiplicaciones).\n\nGeneralizando, hay $N^2$ mutiplicaciones y $N(N-1)$ sumas para un total de \n\n$$\n \\text{operaciones} = N (N - 1) + N^2 = \\mathcal{O}(N^2).\n$$\n\n***Producto Matriz-Matriz ($AB$):*** Definiendo $[B]_j$ como la $j$-ésima columna de $B$ entonces\n\n$$\n (A B)_{ij} = \\sum^N_{i=1} \\sum^N_{j=1} [A]_i \\cdot [B]_j\n$$\n\nEl producto interno de dos vectores es representado por \n\n$$\n a \\cdot b = \\sum^N_{i=1} a_i b_i\n$$\n\nconduce a $\\mathcal{O}(3N)$ operaciones. Como hay $N^2$ entradas en la matriz resultante, tendríamos $\\mathcal{O}(N^3)$ operaciones\n\nExisten métodos para realizar la multiplicación matriz - matriz más rápido. En la siguiente figura vemos una colección de algoritmos a lo largo del tiempo que han podido limitar el número de operaciones en ciertas circunstancias\n$$\n \\mathcal{O}(N^\\omega)\n$$\n\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Ejemplo 2: Método de Horner para evaluar polinomios\n\nDado\n\n$$P_N(x) = a_0 + a_1 x + a_2 x^2 + \\ldots + a_N x^N$$ \n\no\n\n\n$$P_N(x) = p_1 x^N + p_2 x^{N-1} + p_3 x^{N-2} + \\ldots + p_{N+1}$$\n\nqueremos encontrar la mejor vía para evaluar $P_N(x)$\n\nPrimero considere dos vías para escribir $P_3$\n\n$$ P_3(x) = p_1 x^3 + p_2 x^2 + p_3 x + p_4$$\n\ny usando multiplicación anidada\n\n$$ P_3(x) = ((p_1 x + p_2) x + p_3) x + p_4$$\n\nConsidere cuántas operaciones se necesitan para cada...\n\n$$ P_3(x) = p_1 x^3 + p_2 x^2 + p_3 x + p_4$$\n\n$$P_3(x) = \\overbrace{p_1 \\cdot x \\cdot x \\cdot x}^3 + \\overbrace{p_2 \\cdot x \\cdot x}^2 + \\overbrace{p_3 \\cdot x}^1 + p_4$$\n\nSumando todas las operaciones, en general podemos pensar en esto como una pirámide\n\n\n\npodemos estimar de esta manera que el algoritmo escrito de esta manera tomará aproximadamente $\\mathcal{O}(N^2/2)$ operaciones para completar.\n\nMirando nuetros otros medios de evaluación\n\n$$ P_3(x) = ((p_1 x + p_2) x + p_3) x + p_4$$\n\nAquí encontramos que el método es $\\mathcal{O}(N)$ (el 2 generalmente se ignora en estos casos). Lo importante es que la primera evaluación es $\\mathcal{O}(N^2)$ y la segunda $\\mathcal{O}(N)$!\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Algoritmo\n\nComplete la función e implemente el método de *Horner*\n\n```python\ndef eval_poly(p, x):\n \"\"\"Evaluates polynomial given coefficients p at x\n \n Function to evaluate a polynomial in order N operations. The polynomial is defined as\n \n P(x) = p[0] x**n + p[1] x**(n-1) + ... + p[n-1] x + p[n]\n \n The value x should be a float.\n \"\"\"\n pass\n```\n\n\n```python\ndef eval_poly(p, x):\n \"\"\"Evaluates polynomial given coefficients p at x\n \n Function to evaluate a polynomial in order N operations. The polynomial is defined as\n \n P(x) = p[0] x**n + p[1] x**(n-1) + ... + p[n-1] x + p[n]\n \n The value x should be a float.\n \"\"\"\n ### ADD CODE HERE\n pass\n```\n\n\n```python\n# Scalar version\ndef eval_poly(p, x):\n \"\"\"Evaluates polynomial given coefficients p at x\n \n Function to evaluate a polynomial in order N operations. The polynomial is defined as\n \n P(x) = p[0] x**n + p[1] x**(n-1) + ... + p[n-1] x + p[n]\n \n The value x should be a float.\n \"\"\"\n \n y = p[0]\n for coefficient in p[1:]:\n y = y * x + coefficient\n \n return y\n\n# Vectorized version\ndef eval_poly(p, x):\n \"\"\"Evaluates polynomial given coefficients p at x\n \n Function to evaluate a polynomial in order N operations. The polynomial is defined as\n \n P(x) = p[0] x**n + p[1] x**(n-1) + ... + p[n-1] x + p[n]\n \n The value x can by a NumPy ndarray.\n \"\"\"\n \n y = numpy.ones(x.shape) * p[0]\n for coefficient in p[1:]:\n y = y * x + coefficient\n \n return y\n\np = [1, -3, 10, 4, 5, 5]\nx = numpy.linspace(-10, 10, 100)\nplt.plot(x, eval_poly(p, x))\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open('./nb_style.css', 'r').read()\n return HTML(styles)\ncss_styling()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ce03d631c4df06573f64bec7e27cb7cb115ea0f8", "size": 163327, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Cap01_Error.ipynb", "max_stars_repo_name": "carlosalvarezh/Analisis_Numerico", "max_stars_repo_head_hexsha": "4a6aed7cf18832e81e731352ed279bd381cfd7a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-24T17:53:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-24T17:53:50.000Z", "max_issues_repo_path": "Cap01_Error.ipynb", "max_issues_repo_name": "carlosalvarezh/Analisis_Numerico", "max_issues_repo_head_hexsha": "4a6aed7cf18832e81e731352ed279bd381cfd7a6", "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": "Cap01_Error.ipynb", "max_forks_repo_name": "carlosalvarezh/Analisis_Numerico", "max_forks_repo_head_hexsha": "4a6aed7cf18832e81e731352ed279bd381cfd7a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-28T21:22:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T17:53:02.000Z", "avg_line_length": 66.8550961932, "max_line_length": 26748, "alphanum_fraction": 0.7665052318, "converted": true, "num_tokens": 15925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.08570741160836133}} {"text": "```python\nfrom IPython.display import display, Image\n\n```\n\n# Introduction to Gradient Boosting Methods (GBMs)\n\nWe note that the following content mainly builds upon [Introduction to Boosted Trees](https://xgboost.readthedocs.io/en/stable/tutorials/model.html).\n\nThe technique of gradient boosting which has attracted significantly increasing attention in recent years due to its superior for solving\ntabular data problems. The term **Gradient Boosting** originates from the paper *Greedy Function Approximation: A Gradient Boosting Machine*, by Friedman. This tutorial aims to provide a clear explanation on typical gradient boosting methods, such as gradient boosting decision trees (GBDT), in a self-contained and principled way using the elements of supervised learning.\n\n## 1 Elements of Supervised Learning\n\nFirst, we introduce the notations used throughout this tutorial as follows:\n\nGiven the training data $X=\\{\\mathbf{x}_i\\}_{i=1}^{n}$, and the target $Y=\\{y_i\\}_{i=1}^{n}$, where $\\mathbf{x}_i$ denotes the feature vector with respect to the $i$-th data instance, which can be either continuous or categorical features. $\\mathbf{x}_{ij}$ denotes the $j$-th feature of $\\mathbf{x}_i$.\n\n### 1.1 Model and Parameters\nThe **model** in supervised learning usually refers to the mathematical structure by which the prediction $\\hat{y}_{i}$ is made given the input $\\mathbf{x}_i$. A common example is a **linear model**, where the prediction is given as $\\hat{y}_i = \\sum_j \\theta_j \\mathbf{x}_{ij}$, namely a linear combination of weighted input features. The prediction value can have different interpretations, depending on the task, i.e., regression or classification. For example, it can be logistic transformed to get the probability of positive class in logistic regression, and it can also be used as a ranking score when we want to rank the outputs.\n\nThe **parameters** are the undetermined part that we need to learn from data. In linear regression problems, the parameters are the coefficients $\\theta$. Usually we will use $\\theta$ to denote the parameters.\n\n### 1.2 Objective Function: Training Loss + Regularization\nWith judicious choices for $y_i$, we may express a variety of tasks, such as regression, classification, and ranking.\nThe task of **training** the model amounts to finding the best parameters $\\theta$ that best fit the training data $\\mathbf{x}_i$ and labels $y_i$. In order to train the model, we need to define the **objective function**\nto measure how well the model fit the training data.\n\nA salient characteristic of objective functions is that they consist two parts: **training loss** and **regularization term**:\n\n\\begin{equation}\n\\text{obj}(\\theta) = L(\\theta) + \\Omega(\\theta)\n\\end{equation}\n\nwhere $L$ is the training loss function, and $\\Omega$ is\nthe **regularization term**. The training loss measures how *predictive* our model is with respect to the training data. A common choice of $L$ is the *mean squared error*, which is given by\n\n$L(\\theta) = \\sum_i (y_i-\\hat{y}_i)^2$\n\nAnother commonly used loss function is logistic loss, to be used for logistic regression:\n\n$$L(\\theta) = \\sum_i[ y_i\\ln (1+e^{-\\hat{y}_i}) + (1-y_i)\\ln (1+e^{\\hat{y}_i})]$$\n\nThe **regularization term** is what people usually forget to add. The regularization term controls the complexity of the model, which helps us to avoid overfitting.\n\n### 1.3 Why introduce the general principle?\nThe elements introduced above form the basic elements of supervised learning, and they are natural building blocks of machine learning toolkits. For example, you should be able to describe the differences and commonalities between gradient boosted trees and random forests. Understanding the process in a formalized way also helps us to understand the objective that we are learning and the reason behind the heuristics such as pruning and smoothing.\n\n## 2 Gradient Boosting Decision Trees (GBDT)\n\n### 2.1 Tree Ensembles\nNow that we have introduced the elements of supervised learning, let us get started with real trees. The tree ensemble model consists of a set of classification and regression trees (CART). Here's a simple example of a CART that classifies whether someone will like a hypothetical computer game X.\n\nFig. A toy example for CART\n\n\nWe classify the members of a family into different leaves, and assign them the score on the corresponding leaf.\nA CART is a bit different from decision trees, in which the leaf only contains decision values. In CART, a real score\nis associated with each of the leaves, which gives us richer interpretations that go beyond classification.\nThis also allows for a principled, unified approach to optimization, as we will see in a later part of this tutorial.\n\nUsually, a single tree is not strong enough to be used in practice. What is actually used is the ensemble model,\nwhich sums the prediction of multiple trees together.\n\nFig. A toy example for tree ensemble, consisting of two CARTs\n\n\nHere is an example of a tree ensemble of two trees. The prediction scores of each individual tree are summed up to get the final score.\nIf you look at the example, an important fact is that the two trees try to **complement** each other.\nMathematically, we can write our model in the form\n\n$$\\hat{y}_i = \\sum_{k=1}^K f_k(x_i), f_k \\in \\mathcal{F}$$\n\nwhere $K$ is the number of trees, $f$ is a function in the functional space $\\mathcal{F}$, and $\\mathcal{F}$ is the set of all possible CARTs. The objective function to be optimized is given by\n\n$$\\text{obj}(\\theta) = \\sum_i^n l(y_i, \\hat{y}_i) + \\sum_{k=1}^K \\Omega(f_k)$$\n\nNow here comes a trick question: what is the **model** used in random forests? Tree ensembles! So random forests and boosted trees are really the same models; the difference arises from how we train them. This means that, if you write a predictive service for tree ensembles, you only need to write one and it should work for both random forests and gradient boosted trees. (See [Treelite](https://treelite.readthedocs.io/en/latest/index.html) for an actual example.) One example of why elements of supervised learning rock.\n\n### 2.2 Tree Boosting\n\nNow that we introduced the model, let us turn to training: How should we learn the trees?\nThe answer is, as is always for all supervised learning models: **define an objective function and optimize it**!\n\nLet the following be the objective function (remember it always needs to contain training loss and regularization):\n\n$$\\text{obj} = \\sum_{i=1}^n l(y_i, \\hat{y}_i^{(t)}) + \\sum_{i=1}^t\\Omega(f_i)$$\n\nIn particular, $t$ denotes the training step, each step also corresponds to a member function $f$, i.e., a tree.\n\n### 2.3 Additive Training\n\nThe first question we want to ask: what are the **parameters** of trees? You can find that what we need to learn are those functions $f_i$, **each containing the structure of the tree and the leaf scores**. Learning tree structure is much harder than traditional optimization problem where you can simply take the gradient. **It is intractable to learn all the trees at once**.\nInstead, we use an **additive strategy: fix what we have learned, and add one new tree at a time**. In other words, the functions $f_1$ ... $f_{t-1}$ would be viewed as learned functions when we learn $f_t$. We write the prediction value at **step** $t$ as $\\hat{y}_i^{(t)}$. Then we have\n\n\\begin{equation}\n\\begin{split}\n\\hat{y}_i^{(0)} &= 0\\\\\n \\hat{y}_i^{(1)} &= f_1(x_i) = \\hat{y}_i^{(0)} + f_1(x_i)\\\\\n \\hat{y}_i^{(2)} &= f_1(x_i) + f_2(x_i)= \\hat{y}_i^{(1)} + f_2(x_i)\\\\\n &\\dots\\\\\n \\hat{y}_i^{(t)} &= \\sum_{k=1}^t f_k(x_i)= \\hat{y}_i^{(t-1)} + f_t(x_i)\n\\end{split}\n\\end{equation}\n\nIt remains to ask: which tree do we want at each step? A natural thing is to add the one that optimizes our objective.\n\n\\begin{equation}\n\\begin{split}\n \\text{obj}^{(t)} & = \\sum_{i=1}^n l(y_i, \\hat{y}_i^{(t)}) + \\sum_{i=1}^t\\Omega(f_i) \\\\\n & = \\sum_{i=1}^n l(y_i, \\hat{y}_i^{(t-1)} + f_t(x_i)) + \\Omega(f_t) + \\mathrm{constant}\n\\end{split}\n\\end{equation}\n\nIf we consider using mean squared error (MSE) as our loss function, the objective becomes\n\n\\begin{equation}\n\\begin{split}\n \\text{obj}^{(t)} & = \\sum_{i=1}^n (y_i - (\\hat{y}_i^{(t-1)} + f_t(x_i)))^2 + \\sum_{i=1}^t\\Omega(f_i) \\\\\n & = \\sum_{i=1}^n [2(\\hat{y}_i^{(t-1)} - y_i)f_t(x_i) + f_t(x_i)^2] + \\Omega(f_t) + \\mathrm{constant}\n\\end{split}\n\\end{equation}\n\nwhere the terms without $f_t$ are aggregated as a constant since the functions $f_1$ ... $f_{t-1}$ are learned functions in previous steps.\n\n> In calculus, Taylor's theorem gives an approximation of a k-times\ndifferentiable function around a given point by a polynomial of degree\nk, called the kth-order Taylor polynomial. For a smooth function,\nthe Taylor polynomial is the truncation at the order k of the Taylor\nseries of the function.\n>\n> \\begin{equation}\nf(x)=\\sum_{n=0}^{\\infty}\\frac{f^{(n)}(x_{0})}{n!}(x-x_{0})^{n}\n\\end{equation}\n>\n> The first-order Taylor polynomial is the linear approximation of the\nfunction,\n>\n> $f(x)\\approx f(x_{0})+f^{'}(x_{0})(x-x_{0})$\n>\n>The second-order Taylor polynomial is often referred to as the quadratic\napproximation,\n>\n>$f(x)\\approx f(x_{0})+f^{'}(x_{0})(x-x_{0})+f^{''}(x_{0})\\frac{(x-x_{0})^{2}}{2}$\n\nThe form of MSE is friendly, with a first order term (usually called the residual) and a quadratic term.\nFor other losses of interest (for example, logistic loss), it is not so easy to get such a nice form.\nSo in the general case, we take the **Taylor expansion of the loss function up to the second order**:\n\n\\begin{equation}\n\\begin{split}\n \\text{obj}^{(t)} = \\sum_{i=1}^n [l(y_i, \\hat{y}_i^{(t-1)}) + g_i f_t(x_i) + \\frac{1}{2} h_i f_t^2(x_i)] + \\Omega(f_t) + \\mathrm{constant}\n\\end{split}\n\\end{equation}\n\nwhere the $g_i$ and $h_i$ are defined as\n\n\\begin{equation}\n\\begin{split}\n g_i &= \\partial_{\\hat{y}_i^{(t-1)}} l(y_i, \\hat{y}_i^{(t-1)})\\\\\n h_i &= \\partial_{\\hat{y}_i^{(t-1)}}^2 l(y_i, \\hat{y}_i^{(t-1)})\n\\end{split}\n\\end{equation}\n\n> We note that the $f$ in the description on Taylor's theorem is different from $f_{t}$ in the loss function. Put another way, $g_i$ corresponds to $f^{'}(x_{0})$, $h_i$ corresponds to $f^{''}(x_{0})$, $f_t(x_i)$ corresponds to $x-x_{0}$, $\\sum_{i=1}^n l(y_i, \\hat{y}_i^{(t-1)})$ corresponds to $f(x_{0})$.\n\nAfter we remove all the constants, the specific objective at step $t$ becomes\n\n\\begin{equation}\n\\begin{split}\n \\sum_{i=1}^n [g_i f_t(x_i) + \\frac{1}{2} h_i f_t^2(x_i)] + \\Omega(f_t)\n\\end{split}\n\\end{equation}\n\n**This becomes our optimization goal for the new tree**. One important advantage of this definition is that\nthe value of the objective function only depends on $g_i$ and $h_i$. This is how the popular packages, such as **XGBoost** and **LightGBM**, support custom loss functions.\n**We can optimize every loss function, including logistic regression and pairwise ranking, using exactly the same solver that takes $g_i$ and $h_i$ as input**!\n\n### 2.4 Model Complexity\nWe have introduced the training step, but wait, there is one important thing, the **regularization term**!\nWe need to define the complexity of the tree $\\Omega(f)$. In order to do so, let us first refine the definition of the tree $f(x)$ as\n\n\\begin{equation}\n\\begin{split}\n f_t(x) = w_{q(x)}, w \\in R^T, q:R^d\\rightarrow \\{1,2,\\cdots,T\\} .\n\\end{split}\n\\end{equation}\n\nHere $w$ is the vector of scores on leaves, $q$ is a function assigning each data point to the corresponding leaf, and $T$ is the number of leaves.\nIn XGBoost, the complexity is defined as\n\n\\begin{equation}\n\\begin{split}\n \\Omega(f) = \\gamma T + \\frac{1}{2}\\lambda \\sum_{j=1}^T w_j^2\n\\end{split}\n\\end{equation}\n\nOf course, there is more than one way to define the complexity, but this one works well in practice. The regularization is one part most tree packages treat\nless carefully, or simply ignore. This was because the traditional treatment of tree learning only emphasized improving impurity, while the complexity control was left to heuristics.\nBy defining it formally, we can get a better idea of what we are learning and obtain models that perform well in the wild.\n\n### 2.5 The Structure Score\nHere is the magical part of the derivation. After re-formulating the tree model, we can write the objective value with the $t$-th tree as:\n\n\\begin{equation}\n\\begin{split}\n \\text{obj}^{(t)} &\\approx \\sum_{i=1}^n [g_i w_{q(x_i)} + \\frac{1}{2} h_i w_{q(x_i)}^2] + \\gamma T + \\frac{1}{2}\\lambda \\sum_{j=1}^T w_j^2\\\\\n &= \\sum^T_{j=1} [(\\sum_{i\\in I_j} g_i) w_j + \\frac{1}{2} (\\sum_{i\\in I_j} h_i + \\lambda) w_j^2 ] + \\gamma T\n\\end{split}\n\\end{equation}\n\nwhere $I_j = \\{i|q(x_i)=j\\}$ is the set of indices of data points assigned to the $j$-th leaf.\nNotice that in the second line we have changed the index of the summation because all the data points on the same leaf get the same score.\nWe could further compress the expression by defining $G_j = \\sum_{i\\in I_j} g_i$ and $H_j = \\sum_{i\\in I_j} h_i$:\n\n\\begin{equation}\n\\begin{split}\n \\text{obj}^{(t)} = \\sum^T_{j=1} [G_jw_j + \\frac{1}{2} (H_j+\\lambda) w_j^2] +\\gamma T\n\\end{split}\n\\end{equation}\n\nIn this equation, $w_j$ are independent with respect to each other, the form $G_jw_j+\\frac{1}{2}(H_j+\\lambda)w_j^2$ is quadratic and the best $w_j$ for a given structure $q(x)$ and the best objective reduction we can get is:\n\n\\begin{equation}\n\\begin{split}\n w_j^\\ast &= -\\frac{G_j}{H_j+\\lambda}\\\\\n \\text{obj}^\\ast &= -\\frac{1}{2} \\sum_{j=1}^T \\frac{G_j^2}{H_j+\\lambda} + \\gamma T\n\\end{split}\n\\end{equation}\n\nThe last equation measures *how good* a tree structure $q(x)$ is.\n\nFig. An illustration of structure score (fitness)\n\n\n\nIf all this sounds a bit complicated, let's take a look at the picture, and see how the scores can be calculated.\nBasically, for a given tree structure, we push the statistics $g_i$ and $h_i$ to the leaves they belong to,\nsum the statistics together, and use the formula to calculate how good the tree is.\nThis score is like the impurity measure in a decision tree, except that it also takes the model complexity into account.\n\n### 2.6 Learn the tree structure\nNow that we have a way to measure how good a tree is, ideally we would enumerate all possible trees and pick the best one.\nIn practice this is intractable, so we will try to optimize one level of the tree at a time.\nSpecifically we try to split a leaf into two leaves, and the score it gains is\n\n\\begin{equation}\n\\begin{split}\n Gain = \\frac{1}{2} \\left[\\frac{G_L^2}{H_L+\\lambda}+\\frac{G_R^2}{H_R+\\lambda}-\\frac{(G_L+G_R)^2}{H_L+H_R+\\lambda}\\right] - \\gamma\n\\end{split}\n\\end{equation}\n\nThis formula can be decomposed as: 1) the score on the new left leaf, 2) the score on the new right leaf, 3) the score on the original leaf, 4) regularization on the additional leaf.\nWe can see an important fact here: if the gain is smaller than $\\gamma$, we would do better not to add that branch. This is exactly the **pruning** techniques in tree based models! By using the principles of supervised learning, we can naturally come up with the reason these techniques work :)\n\n### 2.7 Approximate Split Finding Using Feature Histograms\n\nIt is vital to find the optimal split of a tree node efficiently, as enumerating every possible split in a brute-force manner is impractical. Current works generally adopt a histogram-based algorithm for\nfast and accurate split finding, like the following picture.\n\n\n```python\npath_img_his = \"../img/histogram_split.png\"\nimg_ltr_perqdata = Image(path_img_his, width = 800, height = 100)\ndisplay(img_ltr_perqdata)\n```\n\nSpecifically, the algorithm considers only $k$ values (i.e., number of bins) for each feature as candidate splits rather than all possible splits (e.g., all feature values). The most common approach to propose the candidates is using the **quantile sketch** to approximate the feature distribution. After candidate splits are prepared, we enumerate\nall instances on a tree node and accumulate their gradient statistics into two histograms, first- and second-order gradients, respectively. The histogram consists of $k$ bins, each of which sums the first- or second-order gradients of instances whose $j$-th feature values fall into that bin. In this way, each feature is summarized by two histograms. We find the best split of $j$-th feature upon the histograms that achieve the maximum gain value and the global best split is the best split over all features.\n\nAnother advantage of the histogram-based algorithm is that we can accelerate the algorithm by a histogram subtraction technique. The instances on two children nodes are **non-overlapping and mutual exclusive**, since **an instance will be classified onto either left or right child node when the parent node gets split** (since the bins or histograms are naturally ordered). Considering the basic operation of histogram is adding gradients, therefore, for a specific feature, the element-wise sum of first or second-order histograms of children nodes equals to that of parent.\n\n- Example case: using local bins\n\n Motivated by this, we can significantly accelerate training by first constructing the histograms of the one child node with fewer instances, and then getting those of the sibling node via histogram subtraction (histograms of parent node are persist in memory). By doing so, we can skip at least one half of the instances. Since histogram construction usually dominates the computation cost, such subtraction technique can speed up the training process considerably.\n\n> Limitation of additive tree learning\n\n Since it is intractable to enumerate all possible tree structures, we add one split at a time. This approach works well most of the time, but there are some edge cases that fail due to this approach. For those edge cases, training results in a degenerate model because we consider only one feature dimension at a time. See [Can Gradient Boosting Learn Simple Arithmetic?](\n\n# Getting Started with Python and Jupyter Notebooks\n\n## Summary\n\nThe purpose of this [Jupyter Notebook](http://jupyter.org/) is to get you started using Python and Jupyter Notebooks for routine chemical engineering calculations. This introduction assumes this is your first exposure to Python or Jupyter notebooks.\n\n## Step 0: Gain Executable Access to Jupyter Notebooks\n\nJupyter notebooks are documents that can be viewed and executed inside any modern web browser. Since you're reading this notebook, you already know how to view a Jupyter notebook. The next step is to learn how to execute computations that may be embedded in a Jupyter notebook.\n\nTo execute Python code in a notebook you will need access to a Python kernal. A kernal is simply a program that runs in the background, maintains workspace memory for variables and functions, and executes Python code. The kernal can be located on the same laptop as your web browser or located in an on-line cloud service. \n\n**Important Note Regarding Versions** There are two versions of Python in widespread use. Version 2.7 released in 2010, which was the last release of the 2.x series. Version 3.5 is the most recent release of the 3.x series which represents the future direction of language. It has taken years for the major scientific libraries to complete the transition from 2.x to 3.x, but it is now safe to recommend Python 3.x for widespread use. So for this course be sure to use latest verstion, currently 3.6, of the Python language.\n\n### Using Jupyter/Python in the Cloud\n\nThe easiest way to use Jupyter notebooks is to sign up for a free or paid account on a cloud-based service such as [Wakari.io](https://www.wakari.io/) or [SageMathCloud](https://cloud.sagemath.com/). You will need continuous internet connectivity to access your work, but the advantages are there is no software to install or maintain. All you need is a modern web browser on your laptop, Chromebook, tablet or other device. Note that the free services are generally heavily oversubscribed, so you should consider a paid account to assure access during prime hours.\n\nThere are also demonstration sites in the cloud, such as [tmpnb.org](https://tmpnb.org/). These start an interactive session where you can upload an existing notebook or create a new one from scratch. Though convenient, these sites are intended mainly for demonstration and generally quite overloaded. More significantly, there is no way to retain your work between sessions, and some python functionality is removed for security reasons.\n\n### Installing Jupyter/Python on your Laptop\n\nFor regular off-line use you should consider installing a Jupyter Notebook/Python environment directly on your laptop. This will provide you with reliable off-line access to a computational environment. This will also allow you to install additional code libraries to meet particular needs. \n\nChoosing this option will require an initial software installation and routine updates. For this course the recommended package is [Anaconda](https://store.continuum.io/cshop/anaconda/) available from [Continuum Analytics](http://continuum.io/). Downloading and installing the software is well documented and easy to follow. Allow about 10-30 minutes for the installation depending on your connection speed. \n\nAfter installing be sure to check for updates before proceeding further. With the Anaconda package this is done by executing the following two commands in a terminal window:\n\n > conda update conda\n > conda update anaconda\n\nAnaconda includes an 'Anaconda Navigator' application that simplifies startup of the notebook environment and manage the update process.\n\n## Step 1: Start a Jupyter Notebook Session\n\nIf you are using a cloud-based service a Jupyter session will be started when you log on. \n\nIf you have installed a Jupyter/Python distribution on your laptop then you can open a Jupyter session in one of two different ways:\n\n* Use the Anaconda Navigator App, or \n* open a terminal window on your laptop and execute the following statement at the command line:\n\n > jupyter notebook\n\nEither way, once you have opened a session you should see a browser window like this:\n\n\n\nAt this point the browser displays a list of directories and files. You can navigate amoung the directories in the usual way by clicking on directory names or on the 'breadcrumbs' located just about the listing. \n\nJupyter notebooks are simply files in a directory with a `.ipynb` suffix. They can be stored in any directory including Dropbox or Google Drive. Upload and create new Jupyter notebooks in the displayed directory using the appropriate buttons. Use the checkboxes to select items for other actions, such as to duplicate, to rename, or to delete notebooks and directories.\n\n* select one of your existing notebooks to work on,\n* start a new notebook by clicking on the `New Notebook` button, or \n* import a notebook from another directory by dragging it onto the list of notebooks.\n\nAn IPython notebook consists of cells that hold headings, text, or python code. The user interface is relatively self-explanatory. Take a few minutes now to open, rename, and save a new notebook. \n\nHere's a quick video overview of Jupyter notebooks.\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo(\"HW29067qVWk\",560,315,rel=0)\n```\n\n\n\n\n\n\n\n\n\n\n## Step 2: Simple Calculations with Python\n\nPython is an elegant and modern language for programming and problem solving that has found increasing use by engineers and scientists. In the next few cells we'll demonstrate some basic Python functionality.\n\n### Basic Arithmetic Operations\n\nBasic arithmetic operations are built into the Python langauge. Here are some examples. In particular, note that exponentiation is done with the \\*\\* operator.\n\n\n```python\na = 12\nb = 2\n\nprint(a + b)\nprint(a**b)\nprint(a/b)\n```\n\n 14\n 144\n 6.0\n\n\n### Python Libraries\n\nThe Python language has only very basic operations. Most math functions are in various math libraries. The `numpy` library is convenient library. This next cell shows how to import `numpy` with the prefix `np`, then use it to call a common mathematical functions.\n\n\n```python\nimport numpy as np\n\n# mathematical constants\nprint(np.pi)\nprint(np.e)\n\n# trignometric functions\nangle = np.pi/4\nprint(np.sin(angle))\nprint(np.cos(angle))\nprint(np.tan(angle))\n```\n\n 3.141592653589793\n 2.718281828459045\n 0.707106781187\n 0.707106781187\n 1.0\n\n\n### Working with Lists\n\nLists are a versatile way of organizing your data in Python. Here are some examples, more can be found on [this Khan Academy video](http://youtu.be/zEyEC34MY1A).\n\n\n```python\nxList = [1, 2, 3, 4]\nxList\n```\n\n\n\n\n [1, 2, 3, 4]\n\n\n\nConcatentation is the operation of joining one list to another. \n\n\n```python\n# Concatenation\nx = [1, 2, 3, 4];\ny = [5, 6, 7, 8];\n\nx + y\n```\n\n\n\n\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n\n\nSum a list of numbers\n\n\n```python\nnp.sum(x)\n```\n\n\n\n\n 10\n\n\n\nAn element-by-element operation between two lists may be performed with \n\n\n```python\nprint(np.add(x,y))\nprint(np.dot(x,y))\n```\n\n [ 6 8 10 12]\n 70\n\n\nA for loop is a means for iterating over the elements of a list. The colon marks the start of code that will be executed for each element of a list. Indenting has meaning in Python. In this case, everything in the indented block will be executed on each iteration of the for loop. This example also demonstrates string formatting.\n\n\n```python\nfor x in xList:\n print(\"sin({0}) = {1:8.5f}\".format(x,np.sin(x)))\n```\n\n sin(1) = 0.84147\n sin(2) = 0.90930\n sin(3) = 0.14112\n sin(4) = -0.75680\n\n\n### Working with Dictionaries\n\nDictionaries are useful for storing and retrieving data as key-value pairs. For example, here is a short dictionary of molar masses. The keys are molecular formulas, and the values are the corresponding molar masses.\n\n\n```python\nmw = {'CH4': 16.04, 'H2O': 18.02, 'O2':32.00, 'CO2': 44.01}\nmw\n```\n\n\n\n\n {'CH4': 16.04, 'CO2': 44.01, 'H2O': 18.02, 'O2': 32.0}\n\n\n\nWe can a value to an existing dictionary.\n\n\n```python\nmw['C8H18'] = 114.23\nmw\n```\n\n\n\n\n {'C8H18': 114.23, 'CH4': 16.04, 'CO2': 44.01, 'H2O': 18.02, 'O2': 32.0}\n\n\n\nWe can retrieve a value from a dictionary.\n\n\n```python\nmw['CH4']\n```\n\n\n\n\n 16.04\n\n\n\nA for loop is a useful means of interating over all key-value pairs of a dictionary.\n\n\n```python\nfor species in mw.keys():\n print(\"The molar mass of {:7.2f}\".format(species, mw[species]))\n```\n\n C8H18 114.23\n CH4 16.04\n CO2 44.01\n H2O 18.02\n O2 32.00\n\n\n\n```python\nfor species in sorted(mw, key = mw.get):\n print(\" {:<8s} {:>7.2f}\".format(species, mw[species]))\n```\n\n CH4 16.04\n H2O 18.02\n O2 32.00\n CO2 44.01\n C8H18 114.23\n\n\n### Plotting with Matplotlib\n\nImporting the `matplotlib.pyplot` library gives IPython notebooks plotting functionality very similar to Matlab's. Here are some examples using functions from the \n\n\n```python\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(0,10)\ny = np.sin(x)\nz = np.cos(x)\n\nplt.plot(x,y,'b',x,z,'r')\nplt.xlabel('Radians');\nplt.ylabel('Value');\nplt.title('Plotting Demonstration')\nplt.legend(['Sin','Cos'])\nplt.grid()\n```\n\n\n```python\nplt.plot(y,z)\nplt.axis('equal')\n```\n\n\n```python\nplt.subplot(2,1,1)\nplt.plot(x,y)\nplt.title('Sin(x)')\n\nplt.subplot(2,1,2)\nplt.plot(x,z)\nplt.title('Cos(x)')\n```\n\n### Solve Equations using Sympy Library\n\nOne of the best features of Python is the ability to extend it's functionality by importing special purpose libraries of functions. Here we demonstrate the use of a symbolic algebra package [`Sympy`](http://sympy.org/en/index.html) for routine problem solving.\n\n\n```python\nimport sympy as sym\n\nsym.var('P V n R T');\n\n# Gas constant\nR = 8.314 # J/K/gmol\nR = R * 1000 # J/K/kgmol\n\n# Moles of air\nmAir = 1 # kg\nmwAir = 28.97 # kg/kg-mol\nn = mAir/mwAir # kg-mol\n\n# Temperature\nT = 298\n\n# Equation\neqn = sym.Eq(P*V,n*R*T)\n\n# Solve for P \nf = sym.solve(eqn,P)\nprint(f[0])\n\n# Use the sympy plot function to plot\nsym.plot(f[0],(V,1,10),xlabel='Volume m**3',ylabel='Pressure Pa')\n```\n\n## Step 3: Where to Learn More\n\nPython offers a full range of programming language features, and there is a seemingly endless range of packages for scientific and engineering computations. Here are some suggestions on places you can go for more information on programming for engineering applications in Python.\n\n### Introduction to Python for Science\n\nThis excellent introduction to python is aimed at undergraduates in science with no programming experience. It is free and available at the following link.\n\n* [Introduction to Python for Science](https://github.com/djpine/pyman)\n\n### Tutorial Introduction to Python for Science and Engineering\n\nThe following text is licensed by the Hesburgh Library for use by Notre Dame students and faculty only. Please refer to the library's [acceptable use policy](http://library.nd.edu/eresources/access/acceptable_use.shtml). Others can find it at [Springer](http://www.springer.com/us/book/9783642549588) or [Amazon](http://www.amazon.com/Scientific-Programming-Computational-Science-Engineering/dp/3642549586/ref=dp_ob_title_bk). Resources for this book are available on [github](http://hplgit.github.io/scipro-primer/).\n\n* [A Primer on Scientific Programming with Python (Fourth Edition)](http://link.springer.com.proxy.library.nd.edu/book/10.1007/978-3-642-54959-5) by Hans Petter Langtangen. Resources for this book are available on [github](http://hplgit.github.io/scipro-primer/).\n\npycse is a package of python functions, examples, and document prepared by John Kitchin at Carnegie Mellon University. It is a recommended for its coverage of topics relevant to chemical engineers, including a chapter on typical chemical engineering computations. \n\n* [pycse - Python Computations in Science and Engineering](https://github.com/jkitchin/pycse/blob/master/pycse.pdf) by John Kitchin at Carnegie Mellon. This is a link into the the [github repository for pycse](https://github.com/jkitchin/pycse), click on the `Raw` button to download the `.pdf` file.\n\n### Interative learning and on-line tutorials\n\n* [Code Academy on Python](http://www.codecademy.com/tracks/python)\n* [Khan Academy Videos on Python Programming](https://www.khanacademy.org/science/computer-science-subject/computer-science)\n* [Python Tutorial](http://docs.python.org/2/tutorial/)\n* [Think Python: How to Think Like a Computer Scientist](http://www.greenteapress.com/thinkpython/html/index.html)\n* [Engineering with Python](http://www.engineeringwithpython.com/)\n\n### Official documentation, examples, and galleries\n\n* [Notebook Examples](https://github.com/ipython/ipython/tree/master/examples/notebooks)\n* [Notebook Gallery](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks)\n* [Official Notebook Documentation](http://ipython.org/ipython-doc/stable/interactive/notebook.html)\n* [Matplotlib](http://matplotlib.org/index.html) \n\n\n```python\n\n```\n\n\n< [Getting Started](http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/01.00-Getting-Started.ipynb) | [Contents](toc.ipynb) | [Python Basics](http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/01.02-Python-Basics.ipynb) >
\n", "meta": {"hexsha": "4fc38c854550b6e4eb4761121718694800573ac9", "size": 139296, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Mathematical Modeling/01.01-Getting-Started-with-Python-and-Jupyter-Notebooks.ipynb", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "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": "Mathematics/Mathematical Modeling/01.01-Getting-Started-with-Python-and-Jupyter-Notebooks.ipynb", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "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": "Mathematics/Mathematical Modeling/01.01-Getting-Started-with-Python-and-Jupyter-Notebooks.ipynb", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T15:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:47:40.000Z", "avg_line_length": 166.2243436754, "max_line_length": 30874, "alphanum_fraction": 0.8902911785, "converted": true, "num_tokens": 3884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082131381216084, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.0843252617377243}} {"text": "## GeostatsPy: Univariate Spatial Trend Modeling for Subsurface Data Analytics in Python \n\n\n### Michael Pyrcz, Associate Professor, University of Texas at Austin \n\n#### [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1)\n\n\n### PGE 383 Exercise: Univariate Spatial Trends Modeling for Subsurface Data Analytics in Python \n\nHere's a simple workflow with basic univariate spatial trend modeling for subsurface modeling workflows. This should help you get started with building subsurface models that include deterministic and stochastic components. \n\n#### Trend Modeling\n\nTrend modeling is the modeling of local features, based on data and interpretation, that are deemed certain (known). The trend is substracted from the data, leaving a residual that is modeled stochastically with uncertainty (treated as unknown).\n\n* geostatistical spatial estimation methods will make an assumption concerning stationarity\n * in the presence of significant nonstationarity we can not rely on spatial estimates based on data + spatial continuity model\n* if we observe a trend, we should model the trend.\n * then model the residuals stochastically\n\nSteps: \n\n1. model trend consistent with data and intepretation at all locations within the area of itnerest, integrate all available information and expertise.\n\n\\begin{equation}\nm(\\bf{u}_\\beta), \\, \\forall \\, \\beta \\in \\, AOI\n\\end{equation}\n\n2. substract trend from data at the $n$ data locations to formulate a residual at the data locations.\n\n\\begin{equation}\ny(\\bf{u}_{\\alpha}) = z(\\bf{u}_{\\alpha}) - m(\\bf{u}_{\\alpha}), \\, \\forall \\, \\alpha = 1, \\ldots, n\n\\end{equation}\n\n3. characterize the statistical behavoir of the residual $y(\\bf{u}_{\\alpha})$ integrating any information sources and interpretations. For example the global cumulative distribution function and a measure of spatial continuity shown here.\n\n\\begin{equation}\nF_y(y) \\quad \\gamma_y(\\bf{h})\n\\end{equation}\n\n4. model the residual at all locations with $L$ multiple realizations.\n\n\\begin{equation}\nY^\\ell(\\bf{u}_\\beta), \\, \\forall \\, \\beta \\, \\in \\, AOI; \\, \\ell = 1, \\ldots, L\n\\end{equation}\n\n5. add the trend back in to the stochastic residual realizations to calculate the multiple realizations, $L$, of the property of interest based on the composite model of known deterministic trend, $m(\\bf{u}_\\alpha)$ and unknown stochastic residual, $y(\\bf{u}_\\alpha)$ \n\n\\begin{equation}\nZ^\\ell(\\bf{u}_\\beta) = Y^\\ell(\\bf{u}_\\beta) + m(\\bf{u}_\\beta), \\, \\forall \\, \\beta \\in \\, AOI; \\, \\ell = 1, \\ldots, L\n\\end{equation}\n\n6. check the model, including quantification of the proportion of variance treated as known (trend) and unknown (residual).\n\n\\begin{equation}\n\\sigma^2_{Z} = \\sigma^2_{Y} + \\sigma^2_{m} + 2 \\cdot C_{Y,m}\n\\end{equation}\n\ngiven $C_{Y,m} \\to 0$:\n\n\\begin{equation}\n\\sigma^2_{Z} = \\sigma^2_{Y} + \\sigma^2_{m}\n\\end{equation}\n\nI can now describe the proportion of variance allocated to known and unknown components as follows:\n\n\\begin{equation}\nProp_{Known} = \\frac{\\sigma^2_{m}}{\\sigma^2_{Y} + \\sigma^2_{m}} \\quad Prop_{Unknown} = \\frac{\\sigma^2_{Y}}{\\sigma^2_{Y} + \\sigma^2_{m}}\n\\end{equation}\n\nI provide some practical, data-driven methods for trend model, but I should indicate that:\n\n1. trend modeling is very important in reservoir modeling as it has large impact on local model accuracy and on the undertainty model\n2. trend modeling is used in almost every subsurface model, unless the data is dense enough to impose local trends\n3. trend modeling includes a high degree of expert judgement combined with the integration of various information sources\n\nWe limit ourselves to simple data-driven methods, but acknowledge much more is needed. In fact, trend modeling requires a high degree of knowledge concerning local geoscience and engineering data and knowledge. \n\n#### Objective \n\nIn the PGE 383: Stochastic Subsurface Modeling class I want to provide hands-on experience with building subsurface modeling workflows. Python provides an excellent vehicle to accomplish this. I have coded a package called GeostatsPy with GSLIB: Geostatistical Library (Deutsch and Journel, 1998) functionality that provides basic building blocks for building subsurface modeling workflows. \n\nThe objective is to remove the hurdles of subsurface modeling workflow construction by providing building blocks and sufficient examples. This is not a coding class per se, but we need the ability to 'script' workflows working with numerical methods. \n\n#### Getting Started\n\nHere's the steps to get setup in Python with the GeostatsPy package:\n\n1. Install Anaconda 3 on your machine (https://www.anaconda.com/download/). \n2. From Anaconda Navigator (within Anaconda3 group), go to the environment tab, click on base (root) green arrow and open a terminal. \n3. In the terminal type: pip install geostatspy. \n4. Open Jupyter and in the top block get started by copy and pasting the code block below from this Jupyter Notebook to start using the geostatspy functionality. \n\nYou will need to copy the data file to your working directory. They are available here:\n\n* Tabular data - sample_data_biased.csv at https://git.io/fh0CW\n\nThere are exampled below with these functions. You can go here to see a list of the available functions, https://git.io/fh4eX, other example workflows and source code. \n\n\n```python\nimport geostatspy.GSLIB as GSLIB # GSLIB utilies, visualization and wrapper\nimport geostatspy.geostats as geostats # GSLIB methods convert to Python \n```\n\nWe will also need some standard packages. These should have been installed with Anaconda 3.\n\n\n```python\nimport numpy as np # ndarrys for gridded data\nimport pandas as pd # DataFrames for tabular data\nimport os # set working directory, run executables\nimport matplotlib.pyplot as plt # for plotting\nfrom scipy import stats # summary statistics\nimport math # trig etc.\nimport scipy.signal as signal # kernel for moving window calculation\n```\n\n#### Set the working directory\n\nI always like to do this so I don't lose files and to simplify subsequent read and writes (avoid including the full address each time). \n\n\n```python\nos.chdir(\"c:/PGE383\") # set the working directory\n```\n\n#### Loading Tabular Data\n\nHere's the command to load our comma delimited data file in to a Pandas' DataFrame object. \n\n\n```python\ndf = pd.read_csv('sample_data_biased.csv') # load our data table (wrong name!)\n```\n\nIt worked, we loaded our file into our DataFrame called 'df'. But how do you really know that it worked? Visualizing the DataFrame would be useful and we already leard about these methods in this demo (https://git.io/fNgRW). \n\nWe can preview the DataFrame by printing a slice or by utilizing the 'head' DataFrame member function (with a nice and clean format, see below). With the slice we could look at any subset of the data table and with the head command, add parameter 'n=13' to see the first 13 rows of the dataset. \n\n\n```python\nprint(df.iloc[0:5,:]) # display first 4 samples in the table as a preview\ndf.head(n=13) # we could also use this command for a table preview\n```\n\n X Y Facies Porosity Perm\n 0 100 900 1 0.115359 5.736104\n 1 100 800 1 0.136425 17.211462\n 2 100 600 1 0.135810 43.724752\n 3 100 500 0 0.094414 1.609942\n 4 100 100 0 0.113049 10.886001\n\n\n\n\n\n
| \n | X | \nY | \nFacies | \nPorosity | \nPerm | \n
|---|---|---|---|---|---|
| 0 | \n100 | \n900 | \n1 | \n0.115359 | \n5.736104 | \n
| 1 | \n100 | \n800 | \n1 | \n0.136425 | \n17.211462 | \n
| 2 | \n100 | \n600 | \n1 | \n0.135810 | \n43.724752 | \n
| 3 | \n100 | \n500 | \n0 | \n0.094414 | \n1.609942 | \n
| 4 | \n100 | \n100 | \n0 | \n0.113049 | \n10.886001 | \n
| 5 | \n200 | \n800 | \n1 | \n0.154648 | \n106.491795 | \n
| 6 | \n200 | \n700 | \n1 | \n0.153113 | \n140.976324 | \n
| 7 | \n200 | \n500 | \n1 | \n0.126167 | \n12.548074 | \n
| 8 | \n200 | \n400 | \n0 | \n0.094750 | \n1.208561 | \n
| 9 | \n200 | \n100 | \n1 | \n0.150961 | \n44.687430 | \n
| 10 | \n300 | \n800 | \n1 | \n0.199227 | \n1079.709291 | \n
| 11 | \n300 | \n700 | \n1 | \n0.154220 | \n179.491695 | \n
| 12 | \n300 | \n500 | \n1 | \n0.137502 | \n38.164911 | \n
| \n | count | \nmean | \nstd | \nmin | \n25% | \n50% | \n75% | \nmax | \n
|---|---|---|---|---|---|---|---|---|
| X | \n289.0 | \n475.813149 | \n254.277530 | \n0.000000 | \n300.000000 | \n430.000000 | \n670.000000 | \n990.000000 | \n
| Y | \n289.0 | \n529.692042 | \n300.895374 | \n9.000000 | \n269.000000 | \n549.000000 | \n819.000000 | \n999.000000 | \n
| Facies | \n289.0 | \n0.813149 | \n0.390468 | \n0.000000 | \n1.000000 | \n1.000000 | \n1.000000 | \n1.000000 | \n
| Porosity | \n289.0 | \n0.134744 | \n0.037745 | \n0.058548 | \n0.106318 | \n0.126167 | \n0.154220 | \n0.228790 | \n
| Perm | \n289.0 | \n207.832368 | \n559.359350 | \n0.075819 | \n3.634086 | \n14.908970 | \n71.454424 | \n5308.842566 | \n
| \n | X | \nY | \nFacies | \nPorosity | \nPerm | \nWts | \n
|---|---|---|---|---|---|---|
| 0 | \n100 | \n900 | \n1 | \n0.115359 | \n5.736104 | \n3.064286 | \n
| 1 | \n100 | \n800 | \n1 | \n0.136425 | \n17.211462 | \n1.076608 | \n
| 2 | \n100 | \n600 | \n1 | \n0.135810 | \n43.724752 | \n0.997239 | \n
| 3 | \n100 | \n500 | \n0 | \n0.094414 | \n1.609942 | \n1.165119 | \n
| 4 | \n100 | \n100 | \n0 | \n0.113049 | \n10.886001 | \n1.224164 | \n
| \n | X | \nY | \nFacies | \nPorosity | \nPerm | \nWts | \nPor_Trend | \nPor_Res | \n
|---|---|---|---|---|---|---|---|---|
| 0 | \n100 | \n900 | \n1 | \n0.115359 | \n5.736104 | \n3.064286 | \n0.117365 | \n-0.002006 | \n
| 1 | \n100 | \n800 | \n1 | \n0.136425 | \n17.211462 | \n1.076608 | \n0.123938 | \n0.012487 | \n
| 2 | \n100 | \n600 | \n1 | \n0.135810 | \n43.724752 | \n0.997239 | \n0.128435 | \n0.007375 | \n
| 3 | \n100 | \n500 | \n0 | \n0.094414 | \n1.609942 | \n1.165119 | \n0.112399 | \n-0.017985 | \n
| 4 | \n100 | \n100 | \n0 | \n0.113049 | \n10.886001 | \n1.224164 | \n0.102791 | \n0.010258 | \n
| $n_{x}^{2}+n_{y}^{2}$ | $n_{x}$ | $n_{y}$ | $N_{\\uparrow \\downarrow }$ | $N_{\\uparrow \\uparrow }$ |
|---|---|---|---|---|
| 0 | 0 | 0 | 2 | 1 |
| 1 | -1 | 0 | ||
| 1 | 0 | |||
| 0 | -1 | |||
| 0 | 1 | 10 | 5 | |
| 2 | -1 | -1 | ||
| -1 | 1 | |||
| 1 | -1 | |||
| 1 | 1 | 18 | 9 | |
| 4 | -2 | 0 | ||
| 2 | 0 | |||
| 0 | -2 | |||
| 0 | 2 | 26 | 13 | |
| 5 | -2 | -1 | ||
| 2 | -1 | |||
| -2 | 1 | |||
| 2 | 1 | |||
| -1 | -2 | |||
| -1 | 2 | |||
| 1 | -2 | |||
| 1 | 2 | 42 | 21 |
| $n_{x}^{2}+n_{y}^{2}+n_{z}^{2}$ | $n_{x}$ | $n_{y}$ | $n_{z}$ | $N_{\\uparrow \\downarrow }$ |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 2 |
| 1 | -1 | 0 | 0 | |
| 1 | 1 | 0 | 0 | |
| 1 | 0 | -1 | 0 | |
| 1 | 0 | 1 | 0 | |
| 1 | 0 | 0 | -1 | |
| 1 | 0 | 0 | 1 | 14 |
| 2 | -1 | -1 | 0 | |
| 2 | -1 | 1 | 0 | |
| 2 | 1 | -1 | 0 | |
| 2 | 1 | 1 | 0 | |
| 2 | -1 | 0 | -1 | |
| 2 | -1 | 0 | 1 | |
| 2 | 1 | 0 | -1 | |
| 2 | 1 | 0 | 1 | |
| 2 | 0 | -1 | -1 | |
| 2 | 0 | -1 | 1 | |
| 2 | 0 | 1 | -1 | |
| 2 | 0 | 1 | 1 | 38 |
| 3 | -1 | -1 | -1 | |
| 3 | -1 | -1 | 1 | |
| 3 | -1 | 1 | -1 | |
| 3 | -1 | 1 | 1 | |
| 3 | 1 | -1 | -1 | |
| 3 | 1 | -1 | 1 | |
| 3 | 1 | 1 | -1 | |
| 3 | 1 | 1 | 1 | 54 |
Diagrams which enter the definition of the ground-state shift energy $\\Delta E_0$. Diagram (i) is first order in the interaction $\\hat{v}$, while diagrams (ii) and (iii) are examples of contributions to second and third order, respectively.
\n\n\n\n\n\nUsing the standard diagram rules (see the discussion on coupled-cluster theory and many-body perturbation theory), the various\ndiagrams contained in the above figure can be readily calculated (in an uncoupled scheme)\n\n\n\n\n$$\n\\begin{equation}\n (i)=\\frac{(-)^{n_h+n_l}}{2^{n_{ep}}}\\sum_{ij\\leq k_F}\n \\langle ij\\vert\\hat{v}\\vert ij\\rangle_{AS},\n\\label{_auto24} \\tag{47}\n\\end{equation}\n$$\n\nwith $n_h=n_l=2$ and $n_{ep}=1$. As discussed in connection with the diagram rules in the many-body perturbation theory chapter, $n_h$\ndenotes the number of hole lines, $n_l$ the number of closed\nfermion loops and $n_{ep}$ is the number of so-called\nequivalent pairs.\nThe factor $1/2^{n_{ep}}$ is needed since we want to count a pair \nof particles only once. We will carry this factor $1/2$ with us\nin the equations below. \nThe subscript $AS$ denotes the antisymmetrized and normalized matrix element\n\n\n\n\n$$\n\\begin{equation}\n \\langle ij\\vert\\hat{v}\\vert ij\\rangle_{AS}=\\langle ij \\vert\\hat{v}\\vert ij\\rangle-\n \\langle ji \\vert\\hat{v}\\vert ij\\rangle.\n\\label{_auto25} \\tag{48}\n\\end{equation}\n$$\n\nSimilarly, diagrams (ii) and (iii) read\n\n\n\n\n$$\n\\begin{equation}\n (ii)=\\frac{(-)^{2+2}}{2^2}\\sum_{ij\\leq k_F}\\sum_{ab>k_F}\n \\frac{\\langle ij\\vert\\hat{v}\\vert ab\\rangle_{AS}\n \\langle ab\\vert\\hat{v}\\vert ij\\rangle_{AS}}\n {\\varepsilon_i+\\varepsilon_j-\\varepsilon_a-\\varepsilon_b},\n\\label{_auto26} \\tag{49}\n\\end{equation}\n$$\n\nand\n\n\n\n\n$$\n\\begin{equation}\n (iii)=\\frac{(-)^{2+2}}{2^3}\\sum_{k_i,k_j\\leq k_F}\\sum_{abcdk_F}\n \\frac{\\langle ij\\vert\\hat{v}\\vert ab\\rangle_{AS}\n \\langle ab\\vert\\hat{v}\\vert cd\\rangle_{AS}\n \\langle cd\\vert\\hat{v}\\vert ij\\rangle_{AS}}\n {(\\varepsilon_i+\\varepsilon_j-\\varepsilon_a-\\varepsilon_b)\n (\\varepsilon_i+\\varepsilon_j-\\varepsilon_c-\\varepsilon_d)}.\n\\label{_auto27} \\tag{50}\n\\end{equation}\n$$\n\nIn the above, $\\varepsilon$ denotes the sp energies defined by\n$H_0$.\nThe steps leading to the above expressions for the various\ndiagrams are rather straightforward. Though, if we wish to compute the\nmatrix elements for the interaction $v$, a serious problem\narises. Typically, the matrix elements will contain a term\n(see the next section for the formal details) $V(|{\\mathbf r}|)$, which\nrepresents the interaction potential $V$ between two nucleons, where\n${\\mathbf r}$ is the internucleon distance.\nAll modern models\nfor $V$ have a strong short-range repulsive core. Hence,\nmatrix elements involving $V(|{\\mathbf r}|)$, will result in large\n(or infinitely large for a potential with a hard core)\nand repulsive contributions to the ground-state energy. Thus, the\ndiagrammatic expansion for the ground-state energy in terms of the\npotential $V(|{\\mathbf r}|)$ becomes meaningless.\n\nOne possible solution to this problem is provided by the well-known\nBrueckner theory or the Brueckner $G$-matrix, or just the\n$G$-matrix. In fact, the $G$-matrix is an almost indispensable\ntool in almost every microscopic nuclear structure\ncalculation. Its main idea may be paraphrased as follows.\nSuppose we want to calculate the function $f(x)=x/(1+x)$. If\n$x$ is small, we may expand the function $f(x)$ as a power series\n$x+x^2+x^3+\\dots$ and it may be adequate to just calculate the first\nfew terms. In other words, $f(x)$ may be calculated using a low-order\nperturbation method. But if $x$ is large\n(or infinitely large), the above\npower series is obviously meaningless.\nHowever, the exact function\n$x/(1+x)$ is still well defined in the limit\nof $x$ becoming very large.\n\nThese arguments suggest that one should sum up the diagrams\n(i), (ii), (iii) in fig. [fig:goldstone](#fig:goldstone) and the similar ones\nto all orders, instead of computing them one by one. Denoting this\nall-order sum as $1/2\\tilde{G}_{ijij}$, where we have\nintroduced the shorthand notation\n$\\tilde{G}_{ijij}=\\langle k_ik_j\\vert \\tilde{G}\\vert k_ik_j\\rangle_{AS}$\n(and similarly for $\\tilde{v}$),\nwe have that\n\n$$\n\\frac{1}{2}\\tilde{G}_{ijij}=\\frac{1}{2}\\hat{v}_{ijij}\n +\\sum_{ab>k_F}\\frac{1}{2}\\hat{v}_{ijab}\\frac{1}{\\varepsilon_i+\\varepsilon_j-\\varepsilon_a-\\varepsilon_b}\n \\nonumber\n$$\n\n\n\n\n$$\n\\begin{equation} \n \\times\\left[\\frac{1}{2}\\hat{v}_{abij}+\\sum_{cd>k_F}\n \\frac{1}{2}\\hat{v}_{abcd}\\frac{1}\n {\\varepsilon_i+\\varepsilon_j-\\varepsilon_c-\\varepsilon_d}\n \\frac{1}{2}V_{cdij}+\\dots \\right].\n\\label{_auto28} \\tag{51}\n\\end{equation}\n$$\n\nThe factor $1/2$ is the same as that discussed above, namely we want \nto count a pair of particles only once.\nThe quantity inside the brackets is just\n$1/2\\tilde{G}_{mnij}$ and the above equation can be\nrewritten as an integral equation\n\n\n\n\n$$\n\\begin{equation}\n \\tilde{G}_{ijij}=\\tilde{V}_{ijij}\n +\\sum_{ab>F}\\frac{1}{2}\\hat{v}_{ijab}\\frac{1}{\\varepsilon_i+\\varepsilon_j-\\varepsilon_a-\\varepsilon_b}\n \\tilde{G}_{abij}.\n\\label{_auto29} \\tag{52}\n\\end{equation}\n$$\n\nNote that $\\tilde{G}$ is the antisymmetrized $G$-matrix since\nthe potential $\\tilde{v}$ is also antisymmetrized. This means that\n$\\tilde{G}$ obeys\n\n\n\n\n$$\n\\begin{equation}\n \\tilde{G}_{ijij}=-\\tilde{G}_{jiij}=-\\tilde{G}_{ijji}.\n\\label{_auto30} \\tag{53}\n\\end{equation}\n$$\n\nThe $\\tilde{G}$-matrix is defined as\n\n\n\n\n$$\n\\begin{equation}\n \\tilde{G}_{ijij}=G_{ijij}-G_{jiij},\n\\label{_auto31} \\tag{54}\n\\end{equation}\n$$\n\nand the equation for $G$ is\n\n\n\n\n$$\n\\begin{equation}\n G_{ijij}=V_{ijij}\n +\\sum_{ab>k_F}V_{ijab}\\frac{1}\n {\\varepsilon_i+\\varepsilon_j-\\varepsilon_a-\\varepsilon_b}\n G_{abij},\n\\label{eq:ggeneral} \\tag{55}\n\\end{equation}\n$$\n\nwhich is the familiar $G$-matrix equation. The above\nmatrix is specifically designed to treat a class of diagrams\ncontained in $\\Delta E_0$, of which typical contributions\nwere shown in fig. [fig:goldstone](#fig:goldstone). In fact the sum of the diagrams\nin fig. [fig:goldstone](#fig:goldstone) is equal to $1/2(G_{ijij}-G_{jiij})$.\n\nLet us now define a more general $G$-matrix as\n\n\n\n\n$$\n\\begin{equation}\n G_{ijij}=V_{ijij}\n +\\sum_{mn>0}V_{ijmn}\\frac{Q(mn)}\n {\\omega -\\varepsilon_m-\\varepsilon_n}\n G_{mnij},\n\\label{eq:gwithq} \\tag{56}\n\\end{equation}\n$$\n\nwhich is an extension of Eq. ([eq:ggeneral](#eq:ggeneral)). Note that \nEq. ([eq:ggeneral](#eq:ggeneral)) has\n$\\varepsilon_i+\\varepsilon_j$ in the energy denominator, whereas\nin the latter equation we have a general energy variable $\\omega$\nin the denominator. Furthermore, in Eq. ([eq:ggeneral](#eq:ggeneral))\nwe have a restricted\nsum over $mn$, while in Eq. ([eq:gwithq](#eq:gwithq))\nwe sum over all $ab$ and we have\nintroduced a weighting factor $Q(ab)$. In Eq. ([eq:gwithq](#eq:gwithq)) $Q(ab)$\ncorresponds to the choice\n\n\n\n\n$$\n\\begin{equation}\n Q(a , b ) =\n \\left\\{\\begin{array}{cc}1,&min(a ,b ) > k_F\\\\\n 0,&\\mathrm{else}.\\end{array}\\right. ,\n\\label{_auto32} \\tag{57}\n\\end{equation}\n$$\n\nwhere $Q(ab)$ is usually referred to as the $G$-matrix Pauli\nexclusion operator. The role of $Q$ is to enforce a selection\nof the intermediate states allowed in the $G$-matrix equation. The above\n$Q$ requires that the intermediate particles $a$ and $b$\nmust be both above the Fermi surface defined by $F$. We may enforce\na different requirement by using a summation over intermediate states\ndifferent from that in Eq. ([eq:gwithq](#eq:gwithq)).\nAn example is the Pauli operator\nfor the model-space Brueckner-Hartree-Fock method discussed below.\n\n\nBefore ending this section, let us rewrite the $G$-matrix equation\nin a more compact form.\nThe sp energies $\\varepsilon$ and wave functions are defined\nby the unperturbed hamiltonian $H_0$ as\n\n\n\n\n$$\n\\begin{equation}\n H_0\\vert \\psi_a\\psi_b=(\\varepsilon_a+\\varepsilon_b)\n \\vert \\psi_a\\psi_b.\n\\label{_auto33} \\tag{58}\n\\end{equation}\n$$\n\nThe $G$-matrix equation can then be rewritten in the following\ncompact form\n\n\n\n\n$$\n\\begin{equation}\n G(\\omega )=V+V\\frac{\\hat{Q}}{\\omega -H_0}G(\\omega ),\n\\label{_auto34} \\tag{59}\n\\end{equation}\n$$\n\nwith\n$\\hat{Q}=\\sum_{ab}\\vert \\psi_a\\psi_b\\langle\\langle \\psi_a\\psi_b\\vert$.\nIn terms of diagrams, $G$ corresponds to an all-order sum of the\n\"ladder-type\" interactions between two particles with the\nintermediate states restricted by $Q$.\n\nThe $G$-matrix equation has a very simple form. But its\ncalculation is rather complicated, particularly for finite\nnuclear systems such as the nucleus $^{18}$O. There are a\nnumber of complexities. To mention a few, the Pauli operator\n$Q$ may not commute with the unperturbed hamiltonian\n$H_0$ and we have to make the replacement\n\n$$\n\\frac{Q}{\\omega -H_0}\\rightarrow Q\\frac{1}{\\omega -QH_0Q}Q.\n$$\n\nThe determination of the starting energy $\\omega$ is also another\nproblem. \n\n\nIn a medium such as nuclear \nmatter we must account\nfor the fact that certain states are not available as intermediate\nstates in the calculation of the $G$-matrix.\nFollowing the discussion above\nthis is achieved by introducing the medium\ndependent Pauli operator $Q$. Further, the\nenergy $\\omega$ of the incoming particles, given by a pure kinetic\nterm in a scattering problem between two unbound particles (for example two colliding protons), must be modified so as to allow\nfor medium corrections.\nHow to evaluate the Pauli operator for\nnuclear matter is, however, not straightforward.\nBefore discussing how to evaluate the Pauli operator for nuclear matter,\nwe note that the $G$-matrix\nis conventionally given in terms of partial waves and\nthe coordinates of the relative and center-of-mass motion.\nIf we assume that the $G$-matrix is diagonal in $\\alpha$ ($\\alpha$ is a shorthand\nnotation for $J$, $S$, $L$ and $T$), we write the equation for the $G$-matrix as a \ncoupled-channels equation in the relative and center-of-mass system\n\n\n\n\n$$\n\\begin{equation}\n G_{ll'}^{\\alpha}(kk'K\\omega )=V_{ll'}^{\\alpha}(kk')\n +\\sum_{l''}\\int \\frac{d^3 q}{(2\\pi )^3}V_{ll''}^{\\alpha}(kq)\n \\frac{Q(q,K)}{\\omega -H_0}\n G_{l''l'}^{\\alpha}(qk'K\\omega).\n\\label{eq:gnonrel} \\tag{60}\n\\end{equation}\n$$\n\nThis equation is similar in structure to the scattering\nequations discussed in connection with nuclear forces (see the chapter on models for nuclear forces), except that we now have\nintroduced the Pauli operator $Q$ and a medium dependent two-particle\nenergy $\\omega$. The notations in this equation follow those of the chapter on nuclear forces\nwhere we discuss the solution of the scattering\nmatrix $T$.\nThe numerical details on how to solve the above $G$-matrix\nequation through matrix inversion techniques are discussed below\nNote however that the $G$-matrix may not be diagonal in $\\alpha$.\nThis is due to the fact that the\nPauli operator $Q$ is not diagonal\nin the above representation in the relative and center-of-mass\nsystem. The Pauli operator depends on the\nangle between the relative momentum and the center of mass momentum.\nThis angle dependence causes $Q$ to couple states with different\nrelative angular\nmomentua ${\\cal J}$, rendering a partial wave decomposition of the $G$-matrix equation \nrather difficult.\nThe angle dependence of the Pauli operator\ncan be eliminated by introducing the angle-average\nPauli operator, where one replaces the exact Pauli operator $Q$\nby its average $\\bar{Q}$ over all angles for fixed relative and center-of-mass\nmomenta.\nThe choice of Pauli operator is decisive to the determination of the\nsp\nspectrum. Basically, to first order in the reaction matrix $G$,\nthere are three commonly used sp spectra, all\ndefined by the solution of the following equations\n\n\n\n\n$$\n\\begin{equation}\n \\varepsilon_{m} = \\varepsilon (k_{m})= t_{m} + u_{m}=\\frac{k_{m}^2}{2M_N}+u_{m},\n\\label{eq:spnrel} \\tag{61}\n\\end{equation}\n$$\n\nand\n\n\n\n\n$$\n\\begin{equation}\n u_{m} = {\\displaystyle \\sum_{h \\leq k_F}}\\left\\langle m h \\right| G(\\omega = \\varepsilon_{m} + \\varepsilon_h )\n \\left| m h \\right\\rangle_{AS} \\hspace{3mm}k_m \\leq k_M, \n\\label{_auto35} \\tag{62}\n\\end{equation}\n$$\n\n\n\n\n$$\n\\begin{equation} \n\\label{_auto36} \\tag{63}\n\\end{equation}\n$$\n\n\n\n\n$$\n\\begin{equation} \n u_m=0, k_m > k_M.\n\\label{eq:selfcon} \\tag{64}\n\\end{equation}\n$$\n\nFor notational economy, we set $|{\\bf k}_m|=k_m$.\nHere we employ antisymmetrized matrix elements (AS), and $k_M$ is a cutoff\non the momentum. Further, $t_m$ is the sp kinetic\nenergy and similarly $u_m$\nis the\nsp potential.\nThe choice of cutoff $k_M$ is actually what determines the three\ncommonly used sp spectra.\nIn the conventional BHF approach one employs $k_M = k_F$,\nwhich leads\nto a Pauli operator $Q_{\\mathrm{BHF}}$ (in the laboratory system) given by\n\n\n\n\n$$\n\\begin{equation}\n Q_{\\mathrm{BHF}}(k_m , k_n ) =\n \\left\\{\\begin{array}{cc}1,&min(k_m ,k_n ) > k_F\\\\\n 0,&\\mathrm{else}.\\end{array}\\right.\n\\label{eq:bhf} \\tag{65},\n\\end{equation}\n$$\n\nor, since we will define an\nangle-average Pauli operator in the relative and center-of-mass\nsystem, we have\n\n\n\n\n$$\n\\begin{equation}\n \\bar{Q}_{\\mathrm{BHF}}(k,K)=\\left\\{\\begin{array}{cc}\n 0,&k\\leq \\sqrt{k_{F}^{2}-K^2/4}\\\\\n 1,&k\\geq k_F + K/2\\\\\n\t\\frac{K^2/4+k^2 -k_{F}^2}{kK}&\\mathrm{else},\\end{array}\\right.\n\\label{eq:qbhf} \\tag{66}\n\\end{equation}\n$$\n\nwith $k_F$ the momentum at the Fermi surface.\n\nThe BHF choice sets $u_k = 0$ for $k > k_F$, which leads\nto an unphysical, large gap at the Fermi surface, typically\nof the order of $50-60$ MeV. \nTo overcome the gap\nproblem, Mahaux and collaborators \nintroduced a continuous sp spectrum\nfor all values of $k$. The divergencies\nwhich then may occur in Eq. ([eq:gnonrel](#eq:gnonrel)) are taken care of by\nintroducing\na principal value integration in Eq. ([eq:gnonrel](#eq:gnonrel)),\nto retain only the\nreal part contribution to the $G$-matrix.\n\n\nTo define the energy denominators we will also make use of the\nangle-average approximation.\nThe angle dependence is handled by the\nso-called effective mass approximation. The single-particle energies\nin nuclear matter are assumed to have the simple quadratic form\n\n\n\n\n$$\n\\begin{equation}\n \\begin{array}{ccc}\n \\varepsilon (k_m)=&\n {\\displaystyle\\frac{\\hbar^{2}k_m^2}\n {2M_{N}^{*}}}+\\Delta ,&\\hspace{3mm}k_m\\leq k_F\\\\\n &&\\\\\n =&{\\displaystyle\\frac{\\hbar^{2}\n k_m^2}{2M_{N}}},&\\hspace{3mm}k_m> k_F ,\\\\\n \\end{array}\n\\label{eq:spen} \\tag{67}\n\\end{equation}\n$$\n\nwhere $M_{N}^{*}$ is the effective mass of the nucleon and $M_{N}$ is the\nbare nucleon mass. For particle states above the Fermi sea we choose\na pure kinetic energy term, whereas for hole states,\nthe terms $M_{N}^{*}$ and $\\Delta$, the latter being \nan effective single-particle\npotential related to the $G$-matrix, are obtained through the\nself-consistent Brueckner-Hartree-Fock procedure.\nThe sp potential is obtained through the same angle-average approximation\n\n\n\n\n$$\n\\begin{equation}\n\\label{eq:Uav} \\tag{68}\n U(k_m) =\\sum_{l\\alpha} (2T+1)(2J+1)\n \\left \\{ \\frac{8}{\\pi}\\int_{0}^{(k_F-k_m)/2}\n k^2dk G_{ll}^{\\alpha}(k,\\bar{K}_1) \\right. \n\\end{equation}\n$$\n\n$$\n\\left.\n + \\frac{1}{\\pi k_m}\\int_{(k_F-k_m)/2}^{(k_F+k_m)/2}\n kdk (k_F ^2-(k_m-2k)^2)\n G_{ll}^{\\alpha}(k,\\bar{K}_2) \\right \\} \\nonumber,\n$$\n\nwhere we have defined\n\n\n\n\n$$\n\\begin{equation}\n \\bar{K}_1^2=4(k_m^2+k^2),\n\\label{_auto37} \\tag{69}\n\\end{equation}\n$$\n\nand\n\n\n\n\n$$\n\\begin{equation}\n \\bar{K}_2^2=4(k_m^2+k^2)-(2k+k_m-k_F)(2k+k_1+k_F).\n\\label{_auto38} \\tag{70}\n\\end{equation}\n$$\n\nThis\nself-consistency scheme consists in choosing adequate initial values of the\neffective mass and $\\Delta$. The obtained $G$-matrix is in turn used to\nobtain new values for $M_{N}^{*}$ and $\\Delta$. This procedure\ncontinues until these parameters vary little.\n\n\n\n\n\n\n## Exercise 5: Quantum numbers for infinite matter, neutron matter and/or the electron gas in 3d\n\n\n**a)**\nSet up the quantum numbers for infinite nuclear matter and neutron matter or the electron gas in 3d using a given value \nof $n_{\\mathrm{max}}$.\n\n\n\n**Solution.**\nThe following python code sets up the quantum numbers for both infinite nuclear matter and neutron matter meploying a cutoff in the value of $n$.\n\n\n```\nfrom numpy import *\n\nnmax =2\nnshell = 3*nmax*nmax\ncount = 1\ntzmin = 1\n\nprint (\"Symmetric nuclear matter:\")\nprint (\"a, nx, ny, nz, sz, tz, nx^2 + ny^2 + nz^2\")\nfor n in range(nshell): \n for nx in range(-nmax,nmax+1):\n for ny in range(-nmax,nmax+1):\n for nz in range(-nmax, nmax+1): \n for sz in range(-1,1+1):\n tz = 1\n for tz in range(-tzmin,tzmin+1):\n e = nx*nx + ny*ny + nz*nz\n if e == n:\n if sz != 0: \n if tz != 0: \n print count, \" \",nx,\" \",ny, \" \",nz,\" \",sz,\" \",tz,\" \",e\n count += 1\n \n \nnmax =1\nnshell = 3*nmax*nmax\ncount = 1\ntzmin = 1\nprint (\"------------------------------------\")\nprint (\"Neutron matter or the electron gas:\") \nprint (\"a, nx, ny, nz, sz, nx^2 + ny^2 + nz^2\")\nfor n in range(nshell): \n for nx in range(-nmax,nmax+1):\n for ny in range(-nmax,nmax+1):\n for nz in range(-nmax, nmax+1): \n for sz in range(-1,1+1):\n e = nx*nx + ny*ny + nz*nz\n if e == n:\n if sz != 0: \n print count, \" \",nx,\" \",ny, \" \",sz,\" \",tz,\" \",e\n count += 1\n```\n\n\n\n\n", "meta": {"hexsha": "1dc46e01c9e2e136b6323cb7d7f5a02ba9788716", "size": 152772, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/inf/ipynb/inf.ipynb", "max_stars_repo_name": "NuclearTalent/ManyBody2018", "max_stars_repo_head_hexsha": "2339ed834777fa10f6156344f17494b9a7c0bf91", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-07-17T01:09:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T02:34:02.000Z", "max_issues_repo_path": "doc/pub/inf/ipynb/inf.ipynb", "max_issues_repo_name": "NuclearTalent/ManyBody2018", "max_issues_repo_head_hexsha": "2339ed834777fa10f6156344f17494b9a7c0bf91", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/pub/inf/ipynb/inf.ipynb", "max_forks_repo_name": "NuclearTalent/ManyBody2018", "max_forks_repo_head_hexsha": "2339ed834777fa10f6156344f17494b9a7c0bf91", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-07-16T06:31:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-01T07:53:38.000Z", "avg_line_length": 34.8237975838, "max_line_length": 609, "alphanum_fraction": 0.5103160265, "converted": true, "num_tokens": 32725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.19930799314806233, "lm_q1q2_score": 0.08344964074097808}} {"text": "```python\n%%HTML\n\n```\n\n\n\n\n\n\n# Metody Numeryczne\n\n## Elementy analizy numerycznej\n\n### dr hab. inż. Jerzy Baranowski, Prof. AGH.\n\n\n## Informacje ogólne\n- Katedra Automatyki i Robotyki, C3, p. 214\n- Konsultacje \n - Czwartki 11:00-12:00\n (o ile nie ma Kolegium Wydziałowego lub seminarium)\n- jb@agh.edu.pl\n- wykłady dostępne tutaj: https://github.com/KAIR-ISZ/public_lectures\n\n# Reprezentacja liczb\n\n\n\n## Kod binarny\n\n- Zapis liczby z wykorzystaniem dwóch symboli **1** i **0**\n- Podstawa współczesnego sposobu reprezentacji informacji\n\n\n## Zamierzchła historia\n\n- Pingala, Chandaḥśāstra i Prozodia\n - Ok. 4 wiek pne\n - Wykorzystanie zapisu w formie zer i jedynek do opisu metrum\n- Chiny, hexagramy, Shao Yong, I-Ching\n- Leibniz\n\n## Algebra Boole'a\n\n$$\n\\begin{align}\nx \\land y & = xy & \\mathsf{Koniunkcja}\\\\\nx \\lor y & = x+y-xy & \\mathsf{Alternatywa}\\\\\n\\neg x & =1-x & \\mathsf{Negacja}\\\\\nx \\rightarrow y & = (\\neg x\\lor y) & \\mathsf{Implikacja}\\\\\nx \\oplus y & = (x \\lor y)\\land\\neg(x\\land y) & \\mathsf{EXOR}\\\\\nx = y & = \\neg(x\\oplus y) & \\mathsf{Równoważność}\\\\\n\\end{align}\n$$\n\n## Nieco mniej zamierzchła historia\n- 1937 Shannon – przekaźnikowa realizacja operacji binarnych i algebry Boole’a\n- 1937 Stibitz – Pierwszy komputer przekaźnikowy (dodawanie)\n\n## Kod binarny\n| **0** | **0** | **1** | **0** | **1** | **0** | **1** | **1** |\n|---------|---------|---------|---------|---------|---------|---------|---------|\n| $2^{7}$ | $2^{6}$ | $2^{5}$ | $2^{4}$ | $2^{3}$ | $2^{2}$ | $2^{1}$ | $2^{0}$ |\n\nCo daje $ =2^5+2^3+2^1+2^0=32+8+2+1=43$\n\n## Liczby naturalne\n- Ogólnie zakres od 0 do 2n-1\n- 8 bit – zakres od 0 do 255\n- 16 bit – zakres od 0 do 65,535 (short, int)\n- 32 bit – zakres od 0 do 4,294,967,295 (long)\n\nW Pythonie i matlabie za bardzo nie przejmujemy się typami, chyba że je wymusimy\n\n## Operacje na liczbach binarnych\n\n- Dodawanie\n - 0+0=0\n - 0+1=1\n - 1+0=1\n - 1+1=0, przenieś 1\n- Jak w dodawaniu pisemnym\n\n`` 1 1 1 1 1 ``(cyfry przenoszone) \n`` 0 1 1 0 1 ``(1310) \n``+ 1 0 1 1 1 ``(2310) \n``------------ `` \n``=1 0 0 1 0 0 `` (3610)\n\n## Operacje na liczbach binarnych\n\n- Odejmowanie\n - 0-0=0\n - 0-1=1, pożyczka 1\n - 1-0=1\n - 1-1=0,\n- Analogicznie\n\n`` * * * * ``(pożyczki) \n`` 1 1 0 1 1 1 0``(11010) \n``- 1 0 1 1 1``(2310) \n``--------------- `` \n``= 1 0 1 0 1 1 1`` (8710)\n\n## Co z liczbami ujemnymi?\n\nUzupełniamy zapis o tzw. bit znaku\n\n| **1** | **0** | **1** | **0** | **1** | **0** | **1** | **1** |\n|---------|---------|---------|---------|---------|---------|---------|---------|\n| S | $2^{6}$ | $2^{5}$ | $2^{4}$ | $2^{3}$ | $2^{2}$ | $2^{1}$ | $2^{0}$ |\n\nCo daje $ =(-1)^1(2^3+2^1+2^0)=-(8+2+1)=-11$\n\nZmieniają się zakresy:\n- 8 bit (-128 do 127)\n- 16 bit (−32,768 do 32,767)\n- itd\n\n## Problemy\n\n- Niepraktyczny zapis\n- Trzeba przekodowywać wyniki operacji\n- Potencjalnie podatniejsze na błędy\n\n## Kod uzupełnienia do 2 (U2)\n| **1** | **1** | **1** | **1** | **1** | **0** | **1** | **1** |\n|---------|---------|---------|---------|---------|---------|---------|---------|\n| $-2^{7}$| $2^{6}$ | $2^{5}$ | $2^{4}$ | $2^{3}$ | $2^{2}$ | $2^{1}$ | $2^{0}$ |\n\nCo daje $ =-2^7+2^6+2^5+2^4+2^3+2^1+2^0$\n\n$=-128+64+32+16+8+2+1=-5$\n\n## Bardzo łatwa konwersja\n- Liczby dodatnie są takie same jak były\n- Aby zamienić liczbę na jej przeciwną wystarczy zanegować wszystkie bity i do wyniku dodać 1 (*w obie strony*)\n\n| **0** | **0** | **0** | **0** | **0** | **1** | **0** | **1** | 510 | oryginał |\n|----------|---------|---------|---------|---------|---------|---------|---------|-----------------|-----------|\n| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | | negacja |\n| **1** | **1** | **1** | **1** | **1** | **0** | **1** | **1** | -510 | dodanie 1 |\n| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | | negacja |\n| **0** | **0** | **0** | **0** | **0** | **1** | **0** | **1** | 510 | dodanie 1 |\n| -$2^{7}$ | $2^{6}$ | $2^{5}$ | $2^{4}$ | $2^{3}$ | $2^{2}$ | $2^{1}$ | $2^{0}$ | | |\n\n## Jaka z tego korzyść?\n- Odejmowanie staje się dodawaniem (prawie)\n$$ A - B = A + \\neg B + 1$$\n- Przykład 13 – 7 (na 8 bitach)\n\n`` 1 1 1 1 1 ``(cyfry przenoszone) \n`` 0 0 0 0 1 1 0 1``(1310) \n`` 1 1 1 1 1 0 0 0``(zanegowane 710) \n``+ 1``(jedynka) \n``-----------------`` \n``= 0 0 0 0 0 1 1 0`` (610) \n\n## Operacje na liczbach binarnych\nMnożenie również przypomina mnożenie pisemne\n\n`` 1 0 1 1`` 1110 \n`` * 1 0 1 0`` 1010 \n`` -----------`` \n`` 0 0 0 0`` \n`` + 1 0 1 1 `` \n`` + 0 0 0 0`` \n`` + 1 0 1 1`` \n`` ---------------`` \n`` = 1 1 0 1 1 1 0`` 11010\n\n\n# Metody Numeryczne\n\n## Reprezentacja liczb wymiernych\n\n### dr hab. inż. Jerzy Baranowski, Prof. AGH.\n\n## A co z ułamkami?\nSą dwa sposoby zapisu liczb niecałkowitych\n- Stałoprzecinkowy (stałopozycyjny)\n- Zmiennoprzecinkowy (zmiennopozycyjny)\n\n## Zapis stałoprzecinkowy\n| **1** | **0** | **1** | **1** | **1** | **0** | **0** | **0** |\n|---------|---------|---------|---------|---------|---------|---------|---------|\n| $2^{1}$ | $2^{0}$ | $2^{-1}$ | $2^{-2}$ | $2^{-3}$ | $2^{-4}$ | $2^{-5}$ | $2^{-6}$ |\n\n$$\n2^1+2^{-1}+2^{-2}+2^{-3}=2+\\frac{1}{2}+\\frac{1}{4}+\\frac{1}{8}=2.875\n$$\n\n\n\n## Zalety zapisu stałoprzecinkowego\n- Nie ma różnicy w kodowaniu\n- Mamy stale określoną dokładność, którą możemy w miarę dokładnie kształtować\n- Stosunkowa prostota\n- Małe wymagania sprzętowe\n\n## Wady zapisu stałoprzecinkowego\nProblemy z dokładnością, np. nie da się dokładnie przedstawić liczby 0.1\n- Na 3 bitach części ułamkowej różnica wynosi 0.025\n- Na 7 bitach części ułamkowej różnica wynosi ok. 0.001 \n\n\n## Jak wykonujemy działania?\n- Działania wykonujemy traktując zapis liczby stałoprzecinkowej jako normalną binarną\n- Kod U2 dalej działa\n- Należy pamiętać, że wtedy liczba jest pomnożona przez 2n gdzie n to ilość bitów części ułamkowej \n- W liczbach poddanych działaniu liczba bitów części całkowitej i ułamkowej musi być równa\n\n## Działania stałoprzecinkowe\n- Dodawanie wykonujemy identycznie\n- W przypadku mnożenia wynik musimy podzielić przez 2n \n- Mnożenie liczb stałoprzecinkowych przez potęgę 2 polega tylko na przesuwaniu bitów (bardzo proste w realizacji)\n\n| 1 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | |\n|---------------|---------------|-----|-----|-----|-----|-----|-----|---|\n| 0 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | Podzielenie przez $2^{2}$ |\n| $2^{1}$ | $2^{0}$ | $2^{-1}$ | $2^{-2}$ | $2^{-3}$ | $2^{-4}$ | $2^{-5}$ | $2^{-6}$ ||\n\n## Format zmiennoprzecinkowy\n- Bardziej zaawansowany sposób przedstawiania liczb\n- Ustandaryzowany normą IEEE\n- Dający pod pewnymi względami większą dokładność\n\n## Format zmiennoprzecinkowy\n\nReprezentacja liczby\n\n$$\nx=S\\cdot M\\cdot B^E\n$$\n\n- S – znak (*sign*)\n- M – mantysa (*mantissa*, także *fraction*)\n- B – podstawa (*base*, zazwyczaj 2, rzadziej 10)\n- E - wykładnik (*exponent*)\n\n## Mantysa\n- Liczba odpowiadająca za ułamkową część zapisu\n- Format stałoprzecinkowy, zazwyczaj liczba z przedziału [1,2)\n\n## Podstawa i wykładnik\n\n- Pozwalają na określenie szerokiego zakresu\n- Ze względu na kodowanie, zazwyczaj podstawa to 2\n- Wykładnik może być ujemny lub dodatni.\n- Wykładnik koduje się w U2, lub też wprowadza się przesunięcie\n\n## Działania na liczbach zmiennoprzecinkowych\nDodawanie i odejmowanie\n\n$$\nx_1\\pm x_2=\\left(M_1\\pm M_2\\cdot B^{E_2-E_1}\\right)\\cdot B^{E_1}\n$$\n\nMnożenie i dzielenie\n\n$$\nx_1\\cdot x_2=(S_1\\cdot S_2)\\cdot (M_1\\cdot M_2)\\cdot B^{E_1+E_2}\n$$\n\n$$\nx_1 / x_2=(S_1\\cdot S_2)\\cdot (M_1/ M_2)\\cdot B^{E_1-E_2}\n$$\n\n\n\n## Dzielenie\n- Mając możliwość zapisu liczby ulamkowej można sformułować operację dzielenia.\n- Istnieje wiele algorytmów np.\n - *restoring division*\n - *non-restoring division*\n - SRT\n - algorytm Newtona-Raphsona\n - algorytm Goldschmidta\n- Są one już zaimplementowane, jedno dzielenie zazwyczaj wymaga przeprowadzenia 3-4 mnożeń\n\n\n## Ważne formaty – IEEE Single precision\n\n- 8 bitów wykładnika, wykładnik przesunięty o 127 (zamiana z -126 do 127 na 1 do 244)\n- 24 bity mantysy, ale zawsze koduje się tylko 23 po kropce, przed kropką jest 1 \n- Specjalne zapisy nieskończoności i błędów\n- w NumPy - ``float32``\n\n## Ważne formaty – IEEE Double precision\n\n- 11 bitów wykładnika, wykładnik przesunięty o 1023 (zamiana z -1022 do 1023 na 1 do 2046)\n- 53 bity mantysy, ale zawsz koduje się tylko 52 po kropce, przed kropką jest 1 \n- Specjalne zapisy nieskończoności i błędów\n- w NumPy - ``float64``, ale w zasadzie każda liczba w Pythonie i Matlabie to double, chyba że wymusimy inaczej\n\n## Wyświetlanie liczb\n- Normalnie \n- Notacja inżynierska\n - $3700=3.7\\cdot10^3$, $0.12=120\\cdot10^{-3}$\n- Notacja naukowa\n - ``3700=3.7E3``, ``0.12=1.2E-1``\n\n# Metody Numeryczne\n\n## Błedy numeryczne\n\n### dr hab. inż. Jerzy Baranowski, Prof. AGH.\n\n## Podstawowe definicje\nWartość dokładna\n$$y=\\tilde{y}+\\varepsilon$$\n- $\\tilde{y}$ - wartość przybliżona\n- $\\varepsilon$ - błąd\n\n## Błąd bezwzględny\nWartość bezwzględna różnicy między rozwiązaniem dokładnym i przybliżonym\n$$ \\varepsilon=|y-\\tilde{y}|$$\n\n## Błąd względny\nStosunek błędu bezwzględnego do wartości bezwzględnej rozwiązania\n$$\\eta=\\frac{|y-\\tilde{y}|}{|y|}=\\left|\\frac{y-\\tilde{y}}{y}\\right|=\\left|1-\\frac{\\tilde{y}}{y}\\right|$$\nCzasami błąd względny wyrażamy w procentach\n\n## Przykłady\nPierwiastek kwadratowy ze 122\n\n$$\n\\begin{align}\ny{}&=\\sqrt{122}\\approx 11.04536\\\\\n\\tilde{y}{}&=11\\\\\n\\varepsilon{}&=|y-\\tilde{y}|=0.04536\\\\\n\\eta{}&=\\frac{|y-\\tilde{y}|}{|y|}=0.00411\n\\end{align}\n$$\n\n## Przykłady\nLiczba obywateli Polski (stan na ostatni spis powszechny z 2011)\n\n$$\n\\begin{align}\ny{}&=38\\ 538\\ 447\\\\\n\\tilde{y}{}&=38\\ 500\\ 000\\\\\n\\varepsilon{}&=|y-\\tilde{y}|=38\\ 447\\\\\n\\eta{}&=\\frac{|y-\\tilde{y}|}{|y|}=9.97627\\cdot10^{-4}\\approx 0.001\n\\end{align}\n$$\n\n## Przykłady\nObliczanie stałej grawitacji\n$$\n\\begin{align}\ny{}&=6.673841\\cdot10^{-11}\\\\\n\\tilde{y}{}&=6.7\\cdot10^{-11}\\\\\n\\varepsilon{}&=|y-\\tilde{y}|=2.6159\\cdot10^{-13}\\\\\n\\eta{}&=\\frac{|y-\\tilde{y}|}{|y|}=0.00391\n\\end{align}\n$$\n\n## Źródła błędów\nBłędy powstające przy formułowaniu zagadnienia\n- Błędy pomiaru\n- Błędy wynikające z przyjęcia określonych przybliżeń opisu zjawisk fizycznych\n\nBłędy powstające przy obliczeniach\n- Błędy grube (pomyłki)\n- Błędy metody (obcięcia)\n- Błędy zaokrągleń\n\n## Błędy grube\n- Błąd przy wpisywaniu wzoru do komputera\nnp. ``x=A/b`` zamiast ``x=A\\b``\n- Zła implementacja algorytmu\n- Niewłaściwa kolejność wykonywania działań\n\n## Błędy metody (obcięcia)\n- Błędy obcięcia są nieodłącznym elementem obliczeń numerycznych.\n- Błąd obcięcia jest to błąd wynikający z tego, że do uzyskania dokładnego rozwiązania potrzebujemy wykonać nieskończenie wiele obliczeń\n\n## Przykłady błędów metody\nMożna wykazać, że\n$$\n\\begin{align}\n\\sin x={}&x-\\frac{x^3}{3!}+\\frac{x^5}{5!}-\\frac{x^7}{7!}+\\ldots=\\\\\n={}&\\sum\\limits_{n=0}^\\infty(-1)^n\\frac{x^{2n+1}}{(2n+1)!}\n\\end{align}\n$$\nBłędem odcięcia będzie \n$$\n\\sin x\\approx x-\\frac{x^3}{3!}+\\frac{x^5}{5!}\n$$\n\n## Przykłady błędów metody\n\nMetoda bisekcji\n\n\n```python\ndef bisection(f,a,b,N): \n a_n = a\n b_n = b\n for n in range(1,N+1):\n m_n = (a_n + b_n)/2\n f_m_n = f(m_n)\n if f(a_n)*f_m_n < 0:\n a_n = a_n\n b_n = m_n\n elif f(b_n)*f_m_n < 0:\n a_n = m_n\n b_n = b_n\n return (a_n + b_n)/2\n```\n\nSzukamy pierwiastka wielomianu $x^2-2$, w przedziale $[1,2]$. Rozwiązanie to $\\sqrt{2}$.\n\n\n```python\nf = lambda x: x**2 - 2 # definicja funkcji\nbisection(f,1,2,5) # 5 kroków\n```\n\n\n\n\n 1.421875\n\n\n\n\n```python\nbisection(f,1,2,10) # 10 kroków\n```\n\n\n\n\n 1.41455078125\n\n\n\n\n```python\nbisection(f,1,2,15) # 15 kroków\n```\n\n\n\n\n 1.4141998291015625\n\n\n\n\n```python\nimport numpy as np\nnp.sqrt(2) \n```\n\n\n\n\n 1.4142135623730951\n\n\n\n## Błąd metody - podsumowanie\n- Praktycznie wszystkie metody numeryczne mają jakiś błąd metody\n- Dobre algorytmy podają jednak jego oszacowanie, w ten sposób wiemy jak daleko jesteśmy od rozwiązania nawet jak przerwiemy obliczenia\n\n# Metody Numeryczne\n\n## Błędy zaokrągleń\n\n### dr hab. inż. Jerzy Baranowski, Prof. AGH.\n\n## Błędy zaokrągleń\nKolejne nieusuwalne w pełni źródło błędów, nad którym mamy mniejszą kontrolę niż nad błędem metody\n\n## Zaokrąglenie i cyfry znaczące\nLiczba $\\tilde{y}=\\mathrm{rd}(y)$ jest poprawnie zaokrąglona do *d* miejsc po przecinku, jeżeli \n\n$$\n\\varepsilon=|y-\\tilde{y}|\\leq\\frac{1}{2}\\cdot10^{-d}\n$$\n*k*-tą cyfrę dziesiętną liczby $\\tilde{y}$ nazwiemy znaczącą gdy\n$$|y-\\tilde{y}|\\leq\\frac{1}{2}\\cdot10^{-k}$$\noraz \n$$|\\tilde{y}|\\geq10^{-k}\n$$\n\n## Rzeczywiste obliczenia zmiennoprzecinkowe\n$$\n\\begin{align}\n\\mathrm{fl}(x+y)={}&\\mathrm{rd}(x+y)\\\\\n\\mathrm{fl}(x-y)={}&\\mathrm{rd}(x-y)\\\\\n\\mathrm{fl}(x\\cdot y)={}&\\mathrm{rd}(x\\cdot y)\\\\\n\\mathrm{fl}(x/y)={}&\\mathrm{rd}(x/y)\\\\\n\\end{align}\n$$\n\n## Liczby maszynowe\n- Liczba maszynowa, to taka liczba jaką można przedstawić w komputerze. Zbiór tych liczb oznaczamy A\n- Dokładność maszynową (epsilon maszynowy) – eps, $\\varepsilon_m$, definiujemy:\n$$\n\\mathrm{eps}=\\min\\{x\\in{A}\\colon \\mathrm{fl}(1+x)>1,\\ x>0\\}\n$$\nInnymi słowy, jest to najmniejsza liczba, którą możemy dodać do 1, aby uzyskać coś większego od 1. \n\n## Epsilon maszynowy w różnych formatach\n\nZależy on od liczby bitów na część ułamkową\n- Single precision $\\varepsilon_m=2^{-24}\\approx 5.96\\cdot10^{-8}$\n- Double precision $\\varepsilon_m=2^{-52}\\approx 1.11\\cdot10^{-16}$\n\n### Przykład\n\n\n```python\na=10**(-15)\nb=10**(-17)\n1+a>1,1+b>1\n```\n\n\n\n\n (True, False)\n\n\n\n## Maksymalny błąd reprezentacji\nDla każdej liczby rzeczywistej $x$ istnieje taka liczba $\\varepsilon$, taka że $|\\varepsilon|<\\varepsilon_m$, że\n$\\mathrm{fl}(x)=x(1+\\varepsilon)$\n\nOznacza to, że **błąd względny między liczbą rzeczywistą, a jej najbliższą reprezentacją zmiennoprzecinkową jest zawsze mniejszy od $\\varepsilon_m$**\n\n## Lemat Wilkinsona\nBłedy zaokrągleń powstałe podczas wykonywania działań zmiennoprzecinkowych są równoważne zastępczemu zaburzeniu liczb, na których wykonujemy działania \n\n$$\n\\begin{align}\n\\mathrm{fl}(x+y)={}&(x+y)(1+\\varepsilon_1)\\\\\n\\mathrm{fl}(x-y)={}&(x-y)(1+\\varepsilon_2)\\\\\n\\mathrm{fl}(x\\cdot y)={}&(x\\cdot y)(1+\\varepsilon_3)\\\\\n\\mathrm{fl}(x/y)={}&(x/y)(1+\\varepsilon_4)\\\\\n|\\varepsilon_i|<{}&\\varepsilon_m\n\\end{align}\n$$\n(dla każdej pary liczb $x,\\ y$ zaburzenia zastępcze $\\varepsilon_i$ są inne)\n\n## Konsekwencja lematu Wilkinsona\nPrawa łączności i rozdzielności operacji matematycznych są ogólnie nieprawdziwe dla obliczeń zmiennoprzecinkowych\n\n### Przykład\n\n\n```python\na=np.float32(0.23371258*10**(-4))\nb=np.float32(0.33678429*10**(2))\nc=np.float32(-0.33677811*10**(2))\nprint([a,b,c])\n```\n\n [2.3371258e-05, 33.67843, -33.67781]\n\n\nChcemy obliczyć ``a+b+c``\n\n## Obliczenia\n\n\n```python\n## Podejście 1\nd=b+c\nwynik_1=a+d\nprint(wynik_1)\n```\n\n 0.0006413522\n\n\n\n```python\n## Podejście 2\ne=a+b\nwynik_2=e+c\nprint(wynik_2)\n```\n\n 0.00064086914\n\n\n## Co tu się porobiło?\n\n\n## Konsekwencje obliczen zmiennoprzecinkowych\n\n\n```python\nm_a, e_a = np.frexp(a)\nprint(m_a,e_a)\nm_b,e_b = np.frexp(b)\nprint(m_b,e_b)\nm_c,e_c = np.frexp(c)\nprint(m_c,e_c)\n```\n\n 0.7658294 -15\n 0.52622545 6\n -0.5262158 6\n\n\nWykładnik ``a`` od wykładników ``b`` i ``c`` różni się o 21. Oznacza to, że z 23 bitów mantysy liczby ``a`` po sprowadzeniu do wspólnego wykładnika z ``b`` zostaną nam tylko 2 najbardziej znaczące. \n\n## Konsekwencje cd..\nJeżeli dodajemy małą liczbę do dużej, zawsze musimy się liczyć z zaokrągleniem i to normalne. W tym przypadku jednak dwie duże liczby ``b`` i ``c`` są przeciwnych znaków i bliskie co do wartości bezwzględnej. Wynik tego działania:\n\n\n```python\nm_d,e_d = np.frexp(d)\nprint(m_d,e_d)\nprint(wynik_2)\n```\n\n 0.6328125 -10\n 0.00064086914\n\n\nW konsekwencji dodając ``a`` do ``d`` na zaokrągleniu stracimy jedynie 5 bitów mantysy ``a``.\n\n## O ile się pomyliliśmy (w stosunku do dokładniejszych obliczeń)\n\n\n```python\na_dbl=(0.23371258*10**(-4))\nb_dbl=(0.33678429*10**(2))\nc_dbl=(-0.33677811*10**(2))\nd_dbl=b_dbl+c_dbl\nwynik_dbl=a_dbl+d_dbl\nepsilon_1=np.abs((wynik_1)-wynik_dbl)\neta_1=epsilon_1/np.abs(wynik_dbl)\nprint(\"Metoda 1: Błąd bezwzględny %10.2e, Błąd względny %10.2e\"%(epsilon_1,eta_1))\nepsilon_2=np.abs((wynik_2)-wynik_dbl)\neta_2=epsilon_2/np.abs(wynik_dbl)\nprint(\"Metoda 2: Błąd bezwzględny %10.2e, Błąd względny %10.2e\"%(epsilon_2,eta_2))\n\n\n```\n\n Metoda 1: Błąd bezwzględny 1.91e-08, Błąd względny 2.97e-05\n Metoda 2: Błąd bezwzględny 5.02e-07, Błąd względny 7.83e-04\n\n\n# Przenoszenie się błędów zaokrągleń\nKorzystając z rachunku różniczkowego (różniczkowa analiza błędów) możemy podać wzór na przenoszenie się błędów.\n\nNiech $y=\\varphi(x_1,\\ x_2,,\\ldots\\ x_n)$ będzie wielkością, którą chcemy obliczyć a $x_i$ są zaokrąglone z błędem $\\varepsilon_{x_i}$. Błąd względny wyliczania $y$ wynosi w przybliżeniu:\n\n$$\n\\varepsilon_y = \\sum_{i=0}^n \\frac{x_i}{\\varphi(\\mathbf{x})}\n\\cdot \\frac{\\partial\\varphi(\\mathbf{x})}{\\partial x_i}\\cdot\\varepsilon_{x_i}\n$$\n\n\n\n# Nieunikniony błąd obliczeń\nZe względu na zaokrąglenia pewnych błędów nigdy nie unikniemy. Nieunikniony błąd wartości składa się z błędu wyliczenia wartości (przeniesienia błędów) oraz samego błędu zaokrąglenia:\n\n$$\n\\frac{\\Delta y}{y} = \\epsilon_y + \\mathrm{eps}\n$$\n\n## Przykład\nWyliczanie pierwiastka równania kwadratowego $y^2+2py-q=0$ o mniejszej wartości bezwzględnej:\n$$ y=-p+\\sqrt{p^2+q} $$\nmożna policzyć, że \n$$\n\\varepsilon_y=-\\frac{p}{\\sqrt{p^2-q}}\\varepsilon_p+\\frac{p+\\sqrt{p^2-q}}{2\\sqrt{p^2-q}}\\varepsilon_q\n$$\n\n## Analiza błędu nieuniknionego\nPonieważ dla $q>0$ mamy\n\n$$\n\\left|\\frac{p}{\\sqrt{p^2-q}}\\right|\\leq1,\\quad \\left|\\frac{p+\\sqrt{p^2-q}}{2\\sqrt{p^2-q}}\\right|\\leq1\n$$\nto wtedy mamy (przyjmując, że nie zachodzi $p^2\\approx q$)\n$$\n\\mathrm{eps}\\leq\\left|\\frac{\\Delta y}{y}\\right| = |\\epsilon_y + \\mathrm{eps}|\\leq 3 \\mathrm{eps}\n$$\n\n## Porównanie algorytmów\nRozpartrzmy dwa sposoby wyliczania $y$ dla $p$ i $q$ mniejszych od zera\n\n$$\n\\begin{aligned}\ns:={}&p^2\\\\\nt:={}&s+q\\\\\nu:={}&\\sqrt{t}\\\\\ny:={}&-p+q\n\\end{aligned}\n\\quad \\quad \\quad \\quad\n\\begin{aligned}\ns:={}&p^2\\\\\nt:={}&s+q\\\\\nu:={}&\\sqrt{t}\\\\\nv:={}&p+u\\\\\ny:={}&q/v\n\\end{aligned}\n$$\n\n\n## Algorytm 1\nPodstawowym źródłem błędu będzie wzmocnienie błędu zaokrąglenia wyliczania pierwiastka z $t$ poprzez odejmowanie dwóch liczb przy wyliczaniu $y$\n$$\\varepsilon_y=\\frac{p\\sqrt{p^2+q}+p^2+q}{q}\\varepsilon=\\kappa\\varepsilon$$\n$\\kappa$ można oszacować z dołu, przez \n$$\n\\kappa>\\frac{2 p^2}{q} >0\n$$\nco oznacza, że dla małych $q$ błąd obliczeń będzie dużo większy niż błąd nieunikniony.\n\n\n## Algorytm 2\nW tym algorytmie zakokrąglenie przez odejmowanie nie wystąpi\n\n$$\n\\varepsilon_y = -\\frac{\\sqrt{p^2+q}}{p+\\sqrt{p^2+q}}\\varepsilon = \\kappa\\varepsilon\n$$\nw tym przypadku zawsze $|\\kappa|<1$.\n\n\n```python\ndef algorytm_1(p,q):\n s=p**2\n t=s+q\n u=np.sqrt(t)\n return u-p\n\ndef algorytm_2(p,q):\n s=p**2\n t=s+q\n u=np.sqrt(t)\n v=p+u\n return q/v\n```\n\n# Porównanie obliczeń\n\n\n```python\np=1000\nq=0.018000000081\nexact_sol=np.max(np.roots([1,2*p,-q]))\n```\n\n\n```python\nepsilon_1=np.abs((algorytm_1(p,q))-exact_sol)\neta_1=epsilon_1/np.abs(exact_sol)\nepsilon_2=np.abs((algorytm_2(p,q))-exact_sol)\neta_2=epsilon_2/np.abs(exact_sol)\n```\n\n\n```python\nprint('Algorytm 1')\nprint(algorytm_1(p,q))\nprint('Algorytm 2')\nprint(algorytm_2(p,q))\nprint('Rozwiązanie dokładne')\nprint(exact_sol)\nprint(\"Algorytm 1: Błąd bezwzględny %10.2e, Błąd względny %10.2e\"%(epsilon_1,eta_1))\nprint(\"Algorytm 2: Błąd bezwzględny %10.2e, Błąd względny %10.2e\"%(epsilon_2,eta_2))\n```\n\n Algorytm 1\n 8.999999977277184e-06\n Algorytm 2\n 9e-06\n Rozwiązanie dokładne\n 9e-06\n Algorytm 1: Błąd bezwzględny 2.27e-14, Błąd względny 2.52e-09\n Algorytm 2: Błąd bezwzględny 0.00e+00, Błąd względny 0.00e+00\n\n\n# Metody Numeryczne\n\n## Ocena algorytmów numerycznych\n\n### dr hab. inż. Jerzy Baranowski, Prof. AGH.\n\n## Notacja O duże\n- Mówimy, że dla wielkości zależnej od parametru np. $F(n)$ zachodzi\n$$ \nF(n)=O(G(n))\n$$\njeżeli istnieje taka stała $C$, że przy $n$ zmierzającym do nieskończoności (odpowiednio dużym), mamy\n$$F(n)≤C G(n)$$\n- Jeżeli interesuje nas $O(c)$, gdzie $c$ jest stałą, zależność ta ma zachodzić niezależnie od wielkości parametru.\n- Mówimy potocznie, gdy błąd jest równy $O(n^2)$, że błąd jest rzędu $n^2$\n \n\n## Ocena algorytmu\n- Naszym celem jest obliczenie pewnej wielkości $f(x)$, zależnej od danych wejściowych $x$\n- W przypadku obliczeń komputerowych zawsze mamy do czynienia z obliczaniem przybliżonym stąd algorytm obliczania $f(x)$ będziemy oznaczać jako $f^*(x)$\n- Dane w komputerze również są reprezentowane w sposób zaokrąglony, więc będziemy je oznaczać jako $x^*$\n\n## Uwarunkowanie problemu\n\n- Mówimy, że problem $f(x)$ jest dobrze uwarunkowany, jeżeli mała zmiana $x$ powoduje małą zmianę w $f(x)$\n- Problem jest źle uwarunkowany, jeżeli mała zmiana $x$ powoduje dużą zmianę w $f(x)$\n- Miarą uwarunkowania jest stała $\\kappa$ (kappa), która (nieformalnie) określa największy iloraz zaburzeń $f(x)$ wywołanych przez najmniejsze zaburzenia $x$.\n- Stałą $\\kappa$ można wyliczyć tylko w niektórych probemach\n\n## Dokładność algorytmu\n- Algorytm jest dokładny, jeżeli\n$$\n\\frac{\\Vert f^*(x)-f(x) \\Vert}{\\Vert f(x)\\Vert}=O(\\varepsilon_m)\n$$\n- Zagwarantowanie, że algorytm jest dokładny wg tej definicji jest niezwykle trudne, zwłaszcza dla źle uwarunkowanych problemów\n\n## Stabilność algorytmu\n\nMówimy, że algorytm jest stabilny, gdy dla każdego $x$, zachodzi\n$$\n\\frac{\\Vert f^*(x)-f(x^*) \\Vert}{\\Vert f(x^*)\\Vert}=O(\\varepsilon_m)\n$$\ndla takich $x^*$, że\n$$\\frac{\\Vert x-x^* \\Vert}{\\Vert x\\Vert}=O(\\varepsilon_m)$$\nInnymi słowy\n**Stabilny algorytm daje prawie dobrą odpowiedź na prawie dobre pytanie**\n\n## Stabilność wsteczna algorytmu\nAlgorytm jest stabilny wstecznie, jeżeli dla każdego $x$, zachodzi\n$$f^*(x)=f(x^*)$$\ndla takich $x^*$, że\n$$\\frac{\\Vert x-x^* \\Vert}{\\Vert x\\Vert}=O(\\varepsilon_m)$$\nInnymi słowy\n**Stabilny wstecznie algorytm daje prawidłową odpowiedź na prawie dobre pytanie**\n\n\n\n\n\n## Dokładność algorytmów stabilnych wstecznie przy złym uwarunkowaniu\nJeśli algorytm jest stabilny wstecznie, to jego błąd względny pogarsza się proporcjonalnie do stałej uwarunkowania tj. $O(\\kappa\\varepsilon_m)$\n\n# Metody Numeryczne\n\n## Problemy techniczne\n\n### dr hab. inż. Jerzy Baranowski, Prof. AGH.\n", "meta": {"hexsha": "0cae0325b4d14c6106edf131487b06ff7ca7c38e", "size": 43817, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Metody Numeryczne 2019/Lecture 1 (errors and stuff)/Lecture 1.ipynb", "max_stars_repo_name": "Piotrek12332121/Piotr-Polak-MN2", "max_stars_repo_head_hexsha": "2d5113981171a53716130cac8005835fbd7e0b76", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Metody Numeryczne 2019/Lecture 1 (errors and stuff)/Lecture 1.ipynb", "max_issues_repo_name": "Piotrek12332121/Piotr-Polak-MN2", "max_issues_repo_head_hexsha": "2d5113981171a53716130cac8005835fbd7e0b76", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Metody Numeryczne 2019/Lecture 1 (errors and stuff)/Lecture 1.ipynb", "max_forks_repo_name": "Piotrek12332121/Piotr-Polak-MN2", "max_forks_repo_head_hexsha": "2d5113981171a53716130cac8005835fbd7e0b76", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6578503095, "max_line_length": 236, "alphanum_fraction": 0.4919551772, "converted": true, "num_tokens": 9915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.08335759915822619}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\n#environment setup with watermark\n%load_ext watermark\n%watermark -a 'Gopala KR' -u -d -v -p watermark,numpy,pandas,matplotlib,nltk,sklearn,tensorflow,theano,mxnet,chainer\n```\n\n WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n\n\n Gopala KR \n last updated: 2018-01-30 \n \n CPython 3.6.3\n IPython 6.2.1\n \n watermark 1.6.0\n numpy 1.13.1\n pandas 0.20.3\n matplotlib 2.0.2\n nltk 3.2.5\n sklearn 0.19.0\n tensorflow 1.3.0\n theano 1.0.1\n mxnet 1.0.0\n chainer 3.3.0\n\n\n\n# The Johnson-Lindenstrauss bound for embedding with random projections\n\n\n\nThe `Johnson-Lindenstrauss lemma`_ states that any high dimensional\ndataset can be randomly projected into a lower dimensional Euclidean\nspace while controlling the distortion in the pairwise distances.\n\n\n\nTheoretical bounds\n==================\n\nThe distortion introduced by a random projection `p` is asserted by\nthe fact that `p` is defining an eps-embedding with good probability\nas defined by:\n\n\\begin{align}(1 - eps) \\|u - v\\|^2 < \\|p(u) - p(v)\\|^2 < (1 + eps) \\|u - v\\|^2\\end{align}\n\nWhere u and v are any rows taken from a dataset of shape [n_samples,\nn_features] and p is a projection by a random Gaussian N(0, 1) matrix\nwith shape [n_components, n_features] (or a sparse Achlioptas matrix).\n\nThe minimum number of components to guarantees the eps-embedding is\ngiven by:\n\n\\begin{align}n\\_components >= 4 log(n\\_samples) / (eps^2 / 2 - eps^3 / 3)\\end{align}\n\n\nThe first plot shows that with an increasing number of samples ``n_samples``,\nthe minimal number of dimensions ``n_components`` increased logarithmically\nin order to guarantee an ``eps``-embedding.\n\nThe second plot shows that an increase of the admissible\ndistortion ``eps`` allows to reduce drastically the minimal number of\ndimensions ``n_components`` for a given number of samples ``n_samples``\n\n\nEmpirical validation\n====================\n\nWe validate the above bounds on the digits dataset or on the 20 newsgroups\ntext document (TF-IDF word frequencies) dataset:\n\n- for the digits dataset, some 8x8 gray level pixels data for 500\n handwritten digits pictures are randomly projected to spaces for various\n larger number of dimensions ``n_components``.\n\n- for the 20 newsgroups dataset some 500 documents with 100k\n features in total are projected using a sparse random matrix to smaller\n euclidean spaces with various values for the target number of dimensions\n ``n_components``.\n\nThe default dataset is the digits dataset. To run the example on the twenty\nnewsgroups dataset, pass the --twenty-newsgroups command line argument to this\nscript.\n\nFor each value of ``n_components``, we plot:\n\n- 2D distribution of sample pairs with pairwise distances in original\n and projected spaces as x and y axis respectively.\n\n- 1D histogram of the ratio of those distances (projected / original).\n\nWe can see that for low values of ``n_components`` the distribution is wide\nwith many distorted pairs and a skewed distribution (due to the hard\nlimit of zero ratio on the left as distances are always positives)\nwhile for larger values of n_components the distortion is controlled\nand the distances are well preserved by the random projection.\n\n\nRemarks\n=======\n\nAccording to the JL lemma, projecting 500 samples without too much distortion\nwill require at least several thousands dimensions, irrespective of the\nnumber of features of the original dataset.\n\nHence using random projections on the digits dataset which only has 64 features\nin the input space does not make sense: it does not allow for dimensionality\nreduction in this case.\n\nOn the twenty newsgroups on the other hand the dimensionality can be decreased\nfrom 56436 down to 10000 while reasonably preserving pairwise distances.\n\n\n\n\n\n```python\nprint(__doc__)\n\nimport sys\nfrom time import time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.random_projection import johnson_lindenstrauss_min_dim\nfrom sklearn.random_projection import SparseRandomProjection\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import load_digits\nfrom sklearn.metrics.pairwise import euclidean_distances\n\n# Part 1: plot the theoretical dependency between n_components_min and\n# n_samples\n\n# range of admissible distortions\neps_range = np.linspace(0.1, 0.99, 5)\ncolors = plt.cm.Blues(np.linspace(0.3, 1.0, len(eps_range)))\n\n# range of number of samples (observation) to embed\nn_samples_range = np.logspace(1, 9, 9)\n\nplt.figure()\nfor eps, color in zip(eps_range, colors):\n min_n_components = johnson_lindenstrauss_min_dim(n_samples_range, eps=eps)\n plt.loglog(n_samples_range, min_n_components, color=color)\n\nplt.legend([\"eps = %0.1f\" % eps for eps in eps_range], loc=\"lower right\")\nplt.xlabel(\"Number of observations to eps-embed\")\nplt.ylabel(\"Minimum number of dimensions\")\nplt.title(\"Johnson-Lindenstrauss bounds:\\nn_samples vs n_components\")\n\n# range of admissible distortions\neps_range = np.linspace(0.01, 0.99, 100)\n\n# range of number of samples (observation) to embed\nn_samples_range = np.logspace(2, 6, 5)\ncolors = plt.cm.Blues(np.linspace(0.3, 1.0, len(n_samples_range)))\n\nplt.figure()\nfor n_samples, color in zip(n_samples_range, colors):\n min_n_components = johnson_lindenstrauss_min_dim(n_samples, eps=eps_range)\n plt.semilogy(eps_range, min_n_components, color=color)\n\nplt.legend([\"n_samples = %d\" % n for n in n_samples_range], loc=\"upper right\")\nplt.xlabel(\"Distortion eps\")\nplt.ylabel(\"Minimum number of dimensions\")\nplt.title(\"Johnson-Lindenstrauss bounds:\\nn_components vs eps\")\n\n# Part 2: perform sparse random projection of some digits images which are\n# quite low dimensional and dense or documents of the 20 newsgroups dataset\n# which is both high dimensional and sparse\n\nif '--twenty-newsgroups' in sys.argv:\n # Need an internet connection hence not enabled by default\n data = fetch_20newsgroups_vectorized().data[:500]\nelse:\n data = load_digits().data[:500]\n\nn_samples, n_features = data.shape\nprint(\"Embedding %d samples with dim %d using various random projections\"\n % (n_samples, n_features))\n\nn_components_range = np.array([300, 1000, 10000])\ndists = euclidean_distances(data, squared=True).ravel()\n\n# select only non-identical samples pairs\nnonzero = dists != 0\ndists = dists[nonzero]\n\nfor n_components in n_components_range:\n t0 = time()\n rp = SparseRandomProjection(n_components=n_components)\n projected_data = rp.fit_transform(data)\n print(\"Projected %d samples from %d to %d in %0.3fs\"\n % (n_samples, n_features, n_components, time() - t0))\n if hasattr(rp, 'components_'):\n n_bytes = rp.components_.data.nbytes\n n_bytes += rp.components_.indices.nbytes\n print(\"Random matrix with size: %0.3fMB\" % (n_bytes / 1e6))\n\n projected_dists = euclidean_distances(\n projected_data, squared=True).ravel()[nonzero]\n\n plt.figure()\n plt.hexbin(dists, projected_dists, gridsize=100, cmap=plt.cm.PuBu)\n plt.xlabel(\"Pairwise squared distances in original space\")\n plt.ylabel(\"Pairwise squared distances in projected space\")\n plt.title(\"Pairwise distances distribution for n_components=%d\" %\n n_components)\n cb = plt.colorbar()\n cb.set_label('Sample pairs counts')\n\n rates = projected_dists / dists\n print(\"Mean distances rate: %0.2f (%0.2f)\"\n % (np.mean(rates), np.std(rates)))\n\n plt.figure()\n plt.hist(rates, bins=50, normed=True, range=(0., 2.), edgecolor='k')\n plt.xlabel(\"Squared distances rate: projected / original\")\n plt.ylabel(\"Distribution of samples pairs\")\n plt.title(\"Histogram of pairwise distance rates for n_components=%d\" %\n n_components)\n\n # TODO: compute the expected value of eps and add them to the previous plot\n # as vertical lines / region\n\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\ntest complete; Gopal\n```\n", "meta": {"hexsha": "0155afa65542fcd58fdf684a33295a2b40f695c3", "size": 232006, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tests/scikit-learn/plot_johnson_lindenstrauss_bound.ipynb", "max_stars_repo_name": "gopala-kr/ds-notebooks", "max_stars_repo_head_hexsha": "bc35430ecdd851f2ceab8f2437eec4d77cb59423", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-10T09:16:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T09:16:23.000Z", "max_issues_repo_path": "tests/scikit-learn/plot_johnson_lindenstrauss_bound.ipynb", "max_issues_repo_name": "gopala-kr/ds-notebooks", "max_issues_repo_head_hexsha": "bc35430ecdd851f2ceab8f2437eec4d77cb59423", "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": "tests/scikit-learn/plot_johnson_lindenstrauss_bound.ipynb", "max_forks_repo_name": "gopala-kr/ds-notebooks", "max_forks_repo_head_hexsha": "bc35430ecdd851f2ceab8f2437eec4d77cb59423", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-14T07:30:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T07:30:18.000Z", "avg_line_length": 526.0907029478, "max_line_length": 37944, "alphanum_fraction": 0.9409541133, "converted": true, "num_tokens": 1990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.184767510648, "lm_q1q2_score": 0.08303315837360026}} {"text": "# Machine learning compilation of quantum circuits\n> Optimal compiling of unitaries reaching the theoretical lower bound\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [machine learning, compilation, qiskit, paper review]\n- image: images/grovercirc.png\n\n# Introduction\n\nI am going to review a recent [preprint](http://arxiv.org/abs/2106.05649) by Liam Madden and\nAndrea Simonetto that uses techniques from machine learning to tackle the problem of quantum circuits compilation. I find the approach suggested in the paper very interesting and the preliminary results quite promising.\n\n## What is compilation?\n> Note that a variety of terms are floating around the literature and used more or less interchangibly. Among those are **synthesis**, **compilation**, **transpilation** and **decomposition** of quantum circuits. I will not make a distinction and try to stick to **compilation**.\n\nBut first things first, what is a compilation of a quantum circuit? The best motivation and illustration for the problem is the following. Say you need to run a textbook quantum circuit on a real hardware. The real hardware usually allows only for a few basic one and two qubit gates. In contrast, your typical textbook quantum circuit may feature (1) complex many-qubit gates, for example multi-controlled gates and (2) one and two qubit gates which are not supported by the hardware. As a simple example take this 3-qubit Grover's circuit (from [qiskit textbook](https://qiskit.org/textbook/ch-algorithms/grover.html)):\n\n\n```python\n# collapse\n#initialization\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# importing Qiskit\nfrom qiskit import IBMQ, Aer, assemble, transpile\nfrom qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister\nfrom qiskit.providers.ibmq import least_busy\n\n# import basic plot tools\nfrom qiskit.visualization import plot_histogram\n\ndef initialize_s(qc, qubits):\n \"\"\"Apply a H-gate to 'qubits' in qc\"\"\"\n for q in qubits:\n qc.h(q)\n return qc\n\ndef diffuser(nqubits):\n qc = QuantumCircuit(nqubits)\n # Apply transformation |s> -> |00..0> (H-gates)\n for qubit in range(nqubits):\n qc.h(qubit)\n # Apply transformation |00..0> -> |11..1> (X-gates)\n for qubit in range(nqubits):\n qc.x(qubit)\n # Do multi-controlled-Z gate\n qc.h(nqubits-1)\n qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli\n qc.h(nqubits-1)\n # Apply transformation |11..1> -> |00..0>\n for qubit in range(nqubits):\n qc.x(qubit)\n # Apply transformation |00..0> -> |s>\n for qubit in range(nqubits):\n qc.h(qubit)\n # We will return the diffuser as a gate\n U_s = qc.to_gate()\n U_s.name = \"U$_s$\"\n return U_s\n\nqc = QuantumCircuit(3)\nqc.cz(0, 2)\nqc.cz(1, 2)\noracle_ex3 = qc.to_gate()\noracle_ex3.name = \"U$_\\omega$\"\n\nn = 3\ngrover_circuit = QuantumCircuit(n)\ngrover_circuit = initialize_s(grover_circuit, [0,1,2])\ngrover_circuit.append(oracle_ex3, [0,1,2])\ngrover_circuit.append(diffuser(n), [0,1,2])\ngrover_circuit = grover_circuit.decompose()\ngrover_circuit.draw(output='mpl')\n```\n\nThe three qubit gates like Toffoli are not generally available on a hardware and one and two qubit gates my be different from those in the textbook algorithm. For example ion quantum computers are good with [Mølmer–Sørensen gates](https://en.wikipedia.org/wiki/M%C3%B8lmer%E2%80%93S%C3%B8rensen_gate) and may need several native one qubit gates to implement the Hadamard gate.\n\nAdditional important problem is to take into account qubit connectivity. Usually textbook algorithms assume full connectivity, meaning that two-qubit gates can act on any pair of qubits. On most hardware platforms however a qubit can only interact with its neighbors. Assuming that one and two qubits gates available on the hardware can implement a SWAP gate between adjacent qubits, to solve the connectivity problem one can insert as many SWAPs as necessary to connect topologically disjoint qubits. Using SWAPs however leads to a huge overhead in the number of total gates in the compiled circuit, and it is of much importance use them as economically as possible. In fact, the problem of optimal SWAPping alone in generic situation is [NP-complete](https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=on+the+complexity+of+quantum+circuit+compilation&btnG=).\n\n## Simplified problem\nWhen compiling a quantum circuit one has to decide which resulting circuits are considered to be efficient. Ideally, one should optimize for the total fidelity of the circuit. Let us imagine running the algorithm on a real device. Probably my theorist's image of a real device is still way too platonic, but I will try my best. Many details need to be taken into account. For example, gates acting on different qubits or pairs of qubits may have different fidelities. Decoherence of qubits with time can make circuits where many operations can be executed in parallel more favorable. Cross-talk (unwanted interactions) between neighboring qubits may lead to exotic patterns for optimal circuits. A simple proxy for the resulting fidelity that is often adopted is the number of two-qubit gates (which are generically much less accurate than a single-qubit gates). So the problem that is often studied, and that is addressed in the preprint we are going to discuss, is the problem of optimal compilation into a gate set consisting of arbitrary single-qubit gates and CNOTs, the only two qubits gate. The compiled circuit must \n\n1. Respect hardware connectivity.\n1. Have as few CNOTs as possible.\n1. Exceed a given fidelity threshold.\n\nLast item here means that we also allow for an approximate compilation. By increasing the number of CNOTs one can always achieve an exact compilation, but since in reality each additional CNOT comes with its own fidelity cost this might not be a good trade-off. Note also that a specific choice for two-qubit gate is made, a CNOT gate. Any two-qubit gate can be decomposed into at most 3 CNOTs [see e.g. here](https://arxiv.org/pdf/quant-ph/0308006.pdf), so in terms of computational complexity this is of course inconsequential. However in the following discussion we will care a lot about constant factors and may wish to revisit this choice at the end.\n\n## Existing results \n\nSince finding the exact optimal solution to the compilation problem is intractable, as with many things in life one needs to resort to heuristic methods. A combination of many heuristic methods, in fact. As an example one can check out the [transpilation workflow](https://qiskit.org/documentation/apidoc/transpiler.html) in `qiskit`. Among others, there is a step that compiles >2 qubit gates into one and two qubit gates; the one that tries to find a good initial placement of the logical qubits onto physical hardware; the one that 'routes' the desired circuit to match a given topology being as greedy on SWAPs as possible. Each of these steps can use several different heuristic optimization algorithms, which are continuously refined and extended (for example this [recent preprint](https://arxiv.org/abs/2106.06446) improves on the default rounting procedure in `qiskit`). In my opinion it would be waay better to have one unified heuristic for all steps of the process, especially taking into account that they are not completely independent. Although this might be too much to ask for, some advances are definitely possible and machine learning tools might prove very useful. The paper we are going to discuss is an excellent demonstration.\n\n## Theoretical lower bound and quantum Shannon decomposition\nThere is a couple of very nice theoretical results about the compilation problem that I need to mention. But first, let us agree that we will compile unitaries, not circuits. What is the difference? Of course, any quantum circuit (without measurements and neglecting losses) corresponds to a unitary matrix. However, to compute that unitary matrix for a large quantum circuit explicitly is generally an intractable problem, precisely for the same reasons that quantum computation is assumed to be more powerful than classical. Still, taking as the input a unitary matrix (which is in general hard to compute from the circuit) is very useful both theoretically and practically. I will discuss pros and cons of this approach later on.\n\nOK, now the fun fact. Generically, one needs at least this many CNOTs\n\n\\begin{align}\n L:=\\# \\text{CNOTs} \\geq \\frac14\\left(4^n-3n-1\\right) \\label{TLB}\n\\end{align}\n\nto exactly compile an $n$-qubit unitary. 'Generically' means that the set of $n$-qubit unitaries that can be compiled exactly with smaller amount of CNOTs has measure zero. Keep in mind though, that there are important unitaries in this class like multi-controlled gates or qubit permutations. We will discuss compilation of some gates from the 'measure-zero' later on. \n\nThe authors of the preprint (I hope you and me still remember that there is some actual results to discuss, not just my overly long introduction to read) refer to \\eqref{TLB} as the theoretical lower bound or TLB for short. The proof of this [fact](https://dl.acm.org/doi/10.5555/968879.969163) is actually rather simple and I will sketch it. A general $d\\times d$ unitary has $d^2$ real parameters. For $n$ qubits $d=2^n$. Single one-qubit gate has 3 real parameters. Any sequence of one-qubit gates applied to the same qubit can be reduced to a single one-qubit gate and hence can have no more than 3 parameters. That means, that without CNOTs we can only have 3n parameters in our circuit, 3 for each one-qubit gate. This is definitely not enough to describe an arbitrary unitary on $n$ qubits which has $d^2=4^n$ parameters.\n\nNow, adding a single CNOT allows to insert two more 1-qubit unitaries after it, like that\n\n\n```python\n#collapse\nfrom qiskit.circuit import Parameter\n\na1, a2, a3 = [Parameter(a) for a in ['a1', 'a2', 'a3']]\nb1, b2, b3 = [Parameter(b) for b in ['b1', 'b2', 'b3']]\n\nqc = QuantumCircuit(2)\nqc.cx(0, 1)\nqc.u(a1, a2, a3, 0) \nqc.u(b1, b2, b3, 1)\n \nqc.draw(output='mpl')\n```\n\nAt the first glance this allows to add 6 more parameters. However, each single-qubit unitary can be represented via the Euler angles as a product of only $R_z$ and $R_x$ rotations either as $U=R_z R_x R_z$ or $U=R_x R_y R_z$ (I do not specify angles). Now, CNOT can be represented as $CNOT=|0\\rangle\\langle 0|\\otimes I+|1\\rangle\\langle 1|\\otimes X$. It follows that $R_z$ commutes with the control of CNOT and $R_x$ commutes with the target of CNOT, hence they can be dragged to the left and joined with preceding one-qubit gates. So in fact each new CNOT gate allows to add only 4 real parameters:\n\n\n```python\n#collapse\na1, a2 = [Parameter(a) for a in ['a1', 'a2']]\nb1, b2 = [Parameter(b) for b in ['b1', 'b2']]\n\nqc = QuantumCircuit(2)\nqc.cx(0, 1)\nqc.rx(a1, 0) \nqc.rz(a2, 0)\nqc.rz(b1, 1)\nqc.rx(b2, 1)\n \nqc.draw(output='mpl')\n```\n\n That's it, there are no more caveats. Thus, the total number of parameters we can get with $L$ CNOTs is $3n+4L$ and we need to describe a $d\\times d$ unitary which has $4^n$ parameters. In fact, the global phase of the unitary is irrelevant so we only need $3n+4L \\geq 4^n-1$. Solving for $L$ gives the TLB \\eqref{TLB}. That's pretty cool, isn't it?\n\nNow there is an algorithm, called *quantum Shannon decomposition* (see [ref](https://arxiv.org/abs/quant-ph/0406176)), which gives an exact compilation of any unitary with the number of CNOTs twice as much as the TLB requires. In complexity-theoretic terms an overall factor of two is of course inessential, but for current NISQ devices we want to get as efficient as possible. Moreover, to my understanding the quantum Shannon decomposition is not easily extendable to restricted topology while inefficient generalizations lead to a much bigger overhead (roughly an order of magnitude).\n\n# What's in the preprint?\n## Templates\nI've already wrote an introduction way longer than intended so from now on I will try to be brief and to the point. The authors of the preprint propose two templates inspired by the quantum Shannon decomposition. The building block for each template is a 'CNOT unit'\n\n\n```python\n#collapse\na1, a2 = [Parameter(a) for a in ['a1', 'a2']]\nb1, b2 = [Parameter(b) for b in ['b1', 'b2']]\n\nqc = QuantumCircuit(2)\nqc.cx(0, 1)\nqc.ry(a1, 0) \nqc.rz(a2, 0)\nqc.ry(b1, 1)\nqc.rx(b2, 1)\n \nqc.draw(output='mpl')\n```\n\nFirst template is called **sequ** in the paper and is obtained as follows. There are $n(n-1)/2$ different CNOTs on $n$-qubit gates. We enumerate them somehow and simply stack sequentially. Here is a 3-qubut example with two layers (I use `qiskit` gates `cz` instead of our 'CNOT units' for the ease of graphical representation)\n\n\n```python\n#collapse\nqc = QuantumCircuit(3)\nfor _ in range(2):\n qc.cz(0, 1)\n qc.cz(0, 2)\n qc.cz(1, 2)\n qc.barrier()\nqc.draw(output='mpl')\n```\n\nThe second template is called **spin** and for 4 qubits looks as follows\n\n\n```python\n#collapse\nqc = QuantumCircuit(4)\nfor _ in range(2):\n qc.cz(0, 1)\n qc.cz(1, 2)\n qc.cz(2, 3)\n qc.barrier()\nqc.draw(output='mpl')\n```\n\nI'm sure you get the idea. That's it! The templates fix the pattern of CNOTs while angles of single-qubit gates are adjustable parameters which are collectively denoted by $\\theta$. \n\nThe idea now is simple. Try to optimize these parameters to achieve the highest possible fidelity for a given target unitary to compile. I am not at all an expert on the optimization methods, so I might miss many subtleties, but on the surface the problem looks rather straightforward. You can choose your favorite flavor of the gradient descent and hope for convergence. The problem appears to be non-convex but the gradient descent seems to work well in practice. One technical point that I do not fully understand is that the authors choose to work with fidelity defined by the Frobenius norm $||U-V||_F^2$ which is sensitive to the global phase of each unitary. To my understanding they often find that local minima of this fidelity coincides with the global minimum up to a global phase. OK, so in the rest of the post I refer to the 'gradient descent' as the magic numerical method which does good job of finding physically sound minimums.\n\n## Results\n### Compiling random unitaries\nOK, finally, for the surprising results. The authors find experimentally that both **sequ** and **spin** perform surprisingly well on random unitaries always coming very close to the TLB \\eqref{TLB} with good fidelity. More precisely, the tests proceed as follows. First, one generates a random unitary. Next, for each number $L$ of CNOTs below the TLB one runs the gradient descent to see how much fidelity can be achieved with this amount of CNOTs. Finally, one plots the fidelity as a function of $L$. Impressively, on the sample of hundred unitaries the fidelity always approaches 100% when the number of CNOTs reaches the TLB. For the $n=3$ qubits TLB is $L=14$, for $n=5$ $L=252$ (these are the two cases studied). So, in all cases studied, the gradient descent lead by the provided templates seems to always find the optimal compilation circuit! Recall that this is two times better than quantum Shannon decomposition. Please see the original paper for nice plots that I do not reproduce here.\n\n\n### Compiling on restricted topology\nThese tests were performed on the fully connected circuits. The next remarkable discovery is that restricting the connectivity does not to seem to harm the performance of the compilation! More precisely, the authors considered two restricted topologies in the paper, 'star' where all qubits are connected to single central one and 'line' where well, they are connected by links on a line. The **spin** template can not be applied to star topology, but it can be applied to line topology. The **sequ** template can be generalized to any topology by simply omitting CNOTs that are not allowed. Again, as examining a hundred of random unitaries on $n=3$ and $n=5$ qubits shows, the fidelity nearing 100% can be achieved right at the TLB in all cases, which hints that topology restriction may not be a problem in this approach at all! To appreciate the achievement, imagine decomposing each unitary via the quantum Shannon decomposition and then routing on restricted topology with swarms of SWAPs, a terrifying picture indeed. It would be interesting to compare the results against the performance of `qiskit` transpiler which is unfortunately not done in the paper to my understanding.\n\n### Compiling specific 'measure zero' gates\nSome important multi-qubit gates fall into the 'measure zero' set which can be compiled with a smaller amount of CNOTs than is implied by the TLB \\eqref{TLB}. For example, 4-qubit Toffoli gate can be compiled with 14 CNOTs while the TLB requires 61 gates. Numerical tests show that the plain version of the algorithm presented above does not generically obtain the optimal compilation for special gates. However, with some tweaking and increasing the amount of attempts the authors were able to find optimal decompositions for a number of known gates such as 3- and 4-qubit Toffoli, 3-qubit Fredkin and 1-bit full adder on 4 qubits. The tweaking included randomly changing the orientation of some CNOTs (note that in both **sequ** and **spin** the control qubit is always at the top) and running many optimization cycles with random initial conditions. The best performing method appeared to be **sequ** with random flips of CNOTs. The whole strategy might look a bit fishy, but I would argue that it is not. My argument is simple: you only need to find a good compilation of the 4-qubit Toffoli *once*. After that you pat yourself on the back and use the result in all your algorithms. So it does not really matter how hard it was to find the compilation as long as you did not forget to write it down.\n\n### Compressing the quantum Shannon decomposition\nFinally, as a new twist on the plot the authors propose a method to compress the standard quantum Shannon decomposition (which is twice the TLB, remember?). The idea seems simple and works surprisingly well. The algorithm works as follows.\n1. Compile a unitary exactly using the quantum Shannon decomposition.\n1. Promote parameters in single-qubit gates variables (they have fixed values in quantum Shannon decomposition).\n2. Add [LASSO](https://en.wikipedia.org/wiki/Lasso_(statistics)-type regularization term, which forces one-qubit gates to have small parameters, ideally zero (which makes the corresponding gates into identities).\n3. Run a gradient descent on the regularized cost function (fidelity+LASSO term). Some one-qubit gates will become identity after that (one might need to tune the regularization parameter here).\n4. After eliminating identity one-qubit gates one can end up in the situation where there is a bunch of CNOTs with no single-qubit gates in between. There are efficient algorithms for reducing the amount of CNOTs in this case. \n5. Recall that the fidelity was compromised by adding regularization terms. Run the gradient descent once more, this time without regularization, to squeeze out these last percents of fidelity.\n\nFrom the description of this algorithm it does not appear obvious that the required cancellations (elimination of single-qubit gates and cancellations in resulting CNOT clusters) is bound to happen, but the experimental tests show that they do. Again, from a bunch of random unitaries it seems that the $\\times 2$ reduction to the TLB is almost sure to happen! Please see the preprint for plots.\n\n## Weak spots\nAlthough I find results of the paper largely impressive, a couple of weak spots deserve a mention.\n### Limited scope of experiments\nThe numerical experiments were only carried out for $n=3$ and $n=5$ qubits which of course is not much. To see if the method keeps working as the number of qubits is scaled is sure very important. There may be two promblems. First, the templates can fail to be expressive enough for larger circuits. The authors hope to attack this problem from the theoretical side and show that the templates do fill the space of unitaries. Well, best of luck with that! Another potential problem is that although the templates work fine for higher $n$, the learning part might become way more challenging. Well, I guess we should wait and see. \n### Unitary as the input\nAs I discussed somewhere way above, for a realistic quantum computation we can not know the unitary matrix that we need to compile. If we did, there would no need in the quantum computer in the first place. I can make two objects here. First, we are still in the NISQ era and pushing the existing quantum computers to their edge is a very important task. Even if an algorithm can be simulated classically, running it on a real device might be invaluable. Second, even quantum circuits on 1000 qubits do not usually feature 100-qubit unitaries. So it could be possible to separate a realistic quantum circuit into pieces, each containing only a few qubits, and compile them separately.\n\n# Final remarks\nTo me, the algorithms presented in the preprint seem to be refreshingly efficient and universal. At some level it appears to be irrelevant which exact template do we use. Near the theoretical lower bound they all perform similarly well, even on restricted topology. This might be a justification for choosing CNOT as the two-qubit gate, as this probably does not matter in the end! I'm really cheering for a universal algorithm like that to win the compilation challenge over a complicated web of isolated heuristics, which are currently state of the art.\n", "meta": {"hexsha": "5f5e02022c847441ac3bb7161e200337baac58a0", "size": 71814, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2021-07-22-Machine learning compilation of quantum circuits.ipynb", "max_stars_repo_name": "idnm/blog", "max_stars_repo_head_hexsha": "a9e976ea45fe077b7b13a5fa3680fab1affc2c48", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_notebooks/2021-07-22-Machine learning compilation of quantum circuits.ipynb", "max_issues_repo_name": "idnm/blog", "max_issues_repo_head_hexsha": "a9e976ea45fe077b7b13a5fa3680fab1affc2c48", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_notebooks/2021-07-22-Machine learning compilation of quantum circuits.ipynb", "max_forks_repo_name": "idnm/blog", "max_forks_repo_head_hexsha": "a9e976ea45fe077b7b13a5fa3680fab1affc2c48", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 166.2361111111, "max_line_length": 10804, "alphanum_fraction": 0.8604868132, "converted": true, "num_tokens": 5216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.1710611959045317, "lm_q1q2_score": 0.08285863648875881}} {"text": "\n# Data Analysis and Machine Learning: \n\n \n**Christian Forssén**, Department of Physics, Chalmers University of Technology, Sweden \n\n **Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n\nDate: **Dec 23, 2020**\n\nCopyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n# Elements of Bayesian theory and Bayesian Neural Networks\n\n\n## Why Bayesian Statistics?\n\nWe have already made ourselves familiar with elements of a statistical\ndata analysis via quantities like the bias-variance tradeoff as well\nas some central distribution functions such as the Normal\ndistribution, the binomial distribution and other probability\ndistribution functions. \n\nIn essentially all the Machine Learning algorithms we have studied,\nour focus has been on a so-called **frequentist approach**, where\nknowledge of an underlying likelihood function has not been\nemphasized. Our data, whether we had a classification or a regression\nproblem, have been our central points of departure.\n\nHere we wish to merge this approach with the derivation of a\nlikelihood function which can be used to make prediction on how our\nsystem under study evolves. We will venture into the realm of what is\ncalled Bayesian Neural Networks. To get an overarching view on what\nthis entails, the following figure conveys the essential differences\nbetween a standard Neural network that we have met earlier and a\nBayesian Neural Network. In order to get there, we need to present\nsome of the basic elements of Bayesian statistics, starting with the\nproduct rule and Bayes' theorem.\n\n\n\n\n## Inference\nInference:\n : \n \"the act of passing from one proposition, statement or judgment considered as true to another whose truth is believed to follow from that of the former\" (Webster) \n Do premises $A, B, \\ldots \\to$ hypothesis, $H$? \n\nDeductive inference:\n : \n Premises allow definite determination of truth/falsity of H (syllogisms, symbolic logic, Boolean algebra) \n $B(H|A,B,...) = 0$ or $1$\n\nInductive inference:\n : \n Premises bear on truth/falsity of H, but don’t allow its definite determination (weak syllogisms, analogies)\n $A, B, C, D$ share properties $x, y, z$; $E$ has properties $x, y$\n $\\to$ $E$ probably has property $z$.\n\n\n\n\n## Statistical Inference\n* Quantify the strength of inductive inferences from facts, in the form of data ($D$), and other premises, e.g. models, to hypotheses about the phenomena producing the data.\n\n* Quantify via probabilities, or averages calculated using probabilities. Frequentists ($\\mathcal{F}$) and Bayesians ($\\mathcal{B}$) use probabilities very differently for this.\n\n* To the pioneers such as Bernoulli, Bayes and Laplace, a probability represented a *degree-of-belief* or plausability: how much they thought that something as true based on the evidence at hand. This is the Bayesian approach.\n\n* To the 19th century scholars, this seemed too vague and subjective. They redefined probability as the *long run relative frequency* with which an event occurred, given (infinitely) many repeated (experimental) trials.\n\n\n\n\n## Some history\nAdapted from D.S. Sivia[^Sivia]:\n\n[^Sivia]: Sivia, Devinderjit, and John Skilling. Data Analysis : A Bayesian Tutorial, OUP Oxford, 2006\n\n> Although the frequency definition appears to be more objective, its range of validity is also far more limited. For example, Laplace used (his) probability theory to estimate the mass of Saturn, given orbital data that were available to him from various astronomical observatories. In essence, he computed the posterior pdf for the mass M , given the data and all the relevant background information I (such as a knowledge of the laws of classical mechanics): prob(M|{data},I); this is shown schematically in the figure [Fig. 1.2].\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n> To Laplace, the (shaded) area under the posterior pdf curve between $m_1$ and $m_2$ was a measure of how much he believed that the mass of Saturn lay in the range $m_1 \\le M \\le m_2$. As such, the position of the maximum of the posterior pdf represents a best estimate of the mass; its width, or spread, about this optimal value gives an indication of the uncertainty in the estimate. Laplace stated that: ‘ . . . it is a bet of 11,000 to 1 that the error of this result is not 1/100th of its value.’ He would have won the bet, as another 150 years’ accumulation of data has changed the estimate by only 0.63%!\n\n\n\n\n\n\n> According to the frequency definition, however, we are not permitted to use probability theory to tackle this problem. This is because the mass of Saturn is a constant and not a random variable; therefore, it has no frequency distribution and so probability theory cannot be used.\n> \n> If the pdf [of Fig. 1.2] had to be interpreted in terms of the frequency definition, we would have to imagine a large ensemble of universes in which everything remains constant apart from the mass of Saturn.\n\n\n\n\n\n\n> As this scenario appears quite far-fetched, we might be inclined to think of [Fig. 1.2] in terms of the distribution of the measurements of the mass in many repetitions of the experiment. Although we are at liberty to think about a problem in any way that facilitates its solution, or our understanding of it, having to seek a frequency interpretation for every data analysis problem seems rather perverse.\n> For example, what do we mean by the ‘measurement of the mass’ when the data consist of orbital periods? Besides, why should we have to think about many repetitions of an experiment that never happened? What we really want to do is to make the best inference of the mass given the (few) data that we actually have; this is precisely the Bayes and Laplace view of probability.\n\n\n\n\n\n\n> Faced with the realization that the frequency definition of probability theory did not permit most real-life scientific problems to be addressed, a new subject was invented — statistics! To estimate the mass of Saturn, for example, one has to relate the mass to the data through some function called the statistic; since the data are subject to ‘random’ noise, the statistic becomes the random variable to which the rules of probability the- ory can be applied. But now the question arises: How should we choose the statistic? The frequentist approach does not yield a natural way of doing this and has, therefore, led to the development of several alternative schools of orthodox or conventional statis- tics. The masters, such as Fisher, Neyman and Pearson, provided a variety of different principles, which has merely resulted in a plethora of tests and procedures without any clear underlying rationale. This lack of unifying principles is, perhaps, at the heart of the shortcomings of the cook-book approach to statistics that students are often taught even today.\n\n\n\n\n\n\n## The Bayesian recipe\nAssess hypotheses by calculating their probabilities $p(H_i | \\ldots)$ conditional on known and/or presumed information using the rules of probability theory.\n\n\nProbability Theory Axioms:\nProduct (AND) rule :\n : \n $p(A, B | I) = p(A|I) p(B|A, I) = p(B|I)p(A|B,I)$\n Should read $p(A,B|I)$ as the probability for propositions $A$ AND $B$ being true given that $I$ is true.\n\nSum (OR) rule:\n : \n $p(A + B | I) = p(A | I) + p(B | I) - p(A, B | I)$\n $p(A+B|I)$ is the probability that proposition $A$ OR $B$ is true given that $I$ is true.\n\nNormalization:\n : \n $p(A|I) + p(\\bar{A}|I) = 1$\n $\\bar{A}$ denotes the proposition that $A$ is false.\n\n\n\n\n## Bayes' theorem\nBayes' theorem follows directly from the product rule\n\n$$\n$$\np(A|B,I) = \\frac{p(B|A,I) p(A|I)}{p(B|I)}.\n$$\n$$\n\nThe importance of this property to data analysis becomes apparent if we replace $A$ and $B$ by hypothesis($H$) and data($D$):\n\n\n\n\n$$\n\\begin{equation}\np(H|D,I) = \\frac{p(D|H,I) p(H|I)}{p(D|I)}.\n\\label{eq:bayes} \\tag{1}\n\\end{equation}\n$$\n\nThe power of Bayes’ theorem lies in the fact that it relates the quantity of interest, the probability that the hypothesis is true given the data, to the term we have a better chance of being able to assign, the probability that we would have observed the measured data if the hypothesis was true.\n\n\n\n\nThe various terms in Bayes’ theorem have formal names. \n* The quantity on the far right, $p(H|I)$, is called the *prior* probability; it represents our state of knowledge (or ignorance) about the truth of the hypothesis before we have analysed the current data. \n\n* This is modified by the experimental measurements through $p(D|H,I)$, the *likelihood* function, \n\n* The denominator $p(D|I)$ is called the *evidence*. It does not depend on the hypothesis and can be regarded as a normalization constant.\n\n* Together, these yield the *posterior* probability, $p(H|D, I )$, representing our state of knowledge about the truth of the hypothesis in the light of the data. \n\nIn a sense, Bayes’ theorem encapsulates the process of learning.\n\n\n\n\n## The friends of Bayes' theorem\nNormalization:\n : \n $\\sum_i p(H_i|\\ldots) = 1$.\n\nMarginalization:\n : \n $\\sum_i p(A,H_i|I) = \\sum_i p(H_i|A,I) p(A|I) = p(A|I)$.\n\nMarginalization (continuum limit):\n : \n $\\int dx p(A,H(x)|I) = p(A|I)$.\n\nIn the above, $H_i$ is an exclusive and exhaustive list of hypotheses. For example,let’s imagine that there are five candidates in a presidential election; then $H_1$ could be the proposition that the first candidate will win, and so on. The probability that $A$ is true, for example that unemployment will be lower in a year’s time (given all relevant information $I$, but irrespective of whoever becomes president) is then given by $\\sum_i p(A,H_i|I)$.\n\nIn the continuum limit of propositions we must understand $p(\\ldots)$ as a pdf (probability density function).\n\nMarginalization is a very powerful device in data analysis because it enables us to deal with nuisance parameters; that is, quantities which necessarily enter the analysis but are of no intrinsic interest. The unwanted background signal present in many experimental measurements are examples of nuisance parameters.\n\n\n\n\n## Inference With Parametric Models\nInductive inference with parametric models is a very important tool in the natural sciences.\n* Consider $N$ different models $M_i$ ($i = 1, \\ldots, N$), each with parameters $\\boldsymbol{\\alpha}_i$. Each of them implies a sampling distribution (conditional predictive distribution for possible data)\n\n$$\n$$\np(D|\\boldsymbol{\\alpha}_i, M_i)\n$$\n$$\n\n* The $\\boldsymbol{\\alpha}_i$ dependence when we fix attention on the actual, observed data ($D_\\mathrm{obs}$) is the likelihood function:\n\n$$\n$$\n\\mathcal{L}_i (\\boldsymbol{\\alpha}_i) \\equiv p(D_\\mathrm{obs}|\\boldsymbol{\\alpha}_i, M_i)\n$$\n$$\n\n* We may be uncertain about $i$ (model uncertainty),\n\n* or uncertain about $\\boldsymbol{\\alpha}_i$ (parameter uncertainty).\n\n\n\n\nParameter Estimation:\n : \n Premise = choice of model (pick specific $i$)\n $\\Rightarrow$ What can we say about $\\boldsymbol{\\alpha}_i$?\n\nModel comparison:\n : \n Premise = $\\{M_i\\}$\n $\\Rightarrow$ What can we say about $i$?\n\nModel adequacy:\n : \n Premise = $M_1$\n $\\Rightarrow$ Is $M_1$ adequate?\n\nHybrid Uncertainty:\n : \n Models share some common params: $\\boldsymbol{\\alpha}_1 = \\{ \\boldsymbol{\\varphi}, \\boldsymbol{\\eta}_i\\}$\n $\\Rightarrow$ What can we say about $\\boldsymbol{\\varphi}$? (Systematic error is an example)\n\n\n\n\n## Illustrative examples with python code\n* Is this a fair coin? (analytical)\n\n* Flux from a star (single parameter, MCMC)\n\n* The lighthouse problem (two parameters, MCMC)\n\n* Linear fit with outliers (nuisance parameters)\n\n* ...\n\n\n\n\n## Example: Is this a fair coin?\nLet us begin with the analysis of data from a simple coin-tossing experiment. \nGiven that we had observed 6 heads in 8 flips, would you think it was a fair coin? By fair, we mean that we would be prepared to lay an even 1 : 1 bet on the outcome of a flip being a head or a tail. If we decide that the coin was fair, the question which follows naturally is how sure are we that this was so; if it was not fair, how unfair do we think it was? Furthermore, if we were to continue collecting data for this particular coin, observing the outcomes of additional flips, how would we update our belief on the fairness of the coin?\n\nA sensible way of formulating this problem is to consider a large number of hypotheses about the range in which the bias-weighting of the coin might lie. If we denote the bias-weighting by $H$, then $H = 0$ and $H = 1$ can represent a coin which produces a tail or a head on every flip, respectively. There is a continuum of possibilities for the value of H between these limits, with $H = 0.5$ indicating a fair coin. Our state of knowledge about the fairness, or the degree of unfairness, of the coin is then completely summarized by specifying how much we believe these various propositions to be true. \n\nLet us perform a computer simulation of a coin-tossing experiment. This provides the data that we will be analysing.\n\n0\n \n<\n<\n<\n!\n!\nC\nO\nD\nE\n_\nB\nL\nO\nC\nK\n \n \np\ny\nc\no\nd\n\n\n```\nnp.random.seed(999) # for reproducibility\na=0.6 # biased coin\nflips=np.random.rand(2**12) # simulates 4096 coin flips\nheads=flips\n\n\n$$\n\\begin{equation}\n\\int_0^1 p(H|D,I) dH = 1.\n\\label{eq:coin_posterior_norm} \\tag{2}\n\\end{equation}\n$$\n\nThe prior pdf, $p(H|I)$, represents what we know about the coin given only the information $I$ that we are dealing with a ‘strange coin’. We could keep a very open mind about the nature of the coin; a simple probability assignment which reflects this is a uniform, or flat, prior\n\n\n\n\n$$\n\\begin{equation}\np(H|I) = \\left\\{ \\begin{array}{ll}\n1 & 0 \\le H \\le 1, \\\\\n0 & \\mathrm{otherwise}.\n\\end{array} \\right.\n\\label{eq:coin_prior_uniform} \\tag{3}\n\\end{equation}\n$$\n\nWe will get back later to the choice of prior and its effect on the analysis.\n\nThis prior state of knowledge, or ignorance, is modified by the data through the likelihood function $p(D|H,I)$. It is a measure of the chance that we would have obtained the data that we actually observed, if the value of the bias-weighting was given (as known). If, in the conditioning information $I$, we assume that the flips of the coin were independent events, so that the outcome of one did not influence that of another, then the probability of obtaining the data `R heads in N tosses' is given by the binomial distribution (we leave a formal definition of this to a statistics textbook)\n\n\n\n\n$$\n\\begin{equation}\np(D|H,I) \\propto H^R (1-H)^{N-R}.\n\\label{_auto1} \\tag{4}\n\\end{equation}\n$$\n\nIt seems reasonable because $H$ is the chance of obtaining a head on any flip, and there were $R$ of them, and $1-H$ is the corresponding probability for a tail, of which there were $N-R$. We note that this binomial distribution also contains a normalization factor, but we will ignore it since it does not depend explicitly on $H$, the quantity of interest. It will be absorbed by the normalization condition ([2](#eq:coin_posterior_norm)).\n\nWe perform the setup of this Bayesian framework on the computer.\n\n\n```\ndef prior(H):\n p=np.zeros_like(H)\n p[(0<=x)&(x<=1)]=1 # allowed range: 0<=H<=1\n return p # uniform prior\ndef likelihood(H,data):\n N = len(data)\n no_of_heads = sum(data)\n no_of_tails = N - no_of_heads\n return H**no_of_heads * (1-H)**no_of_tails\ndef posterior(H,data):\n p=prior(H)*likelihood(H,data)\n norm=np.trapz(p,H)\n return p/norm\n```\n\nThe next step is to confront this setup with the simulated data. To get a feel for the result, it is instructive to see how the posterior pdf evolves as we obtain more and more data pertaining to the coin. The results of such an analyses is shown in Fig. [fig:coinflipping](#fig:coinflipping).\n\n\n```\nx=np.linspace(0,1,100)\nfig, axs = plt.subplots(nrows=4,ncols=3,sharex=True,sharey='row')\naxs_vec=np.reshape(axs,-1)\naxs_vec[0].plot(x,prior(x))\nfor ndouble in range(11):\n ax=axs_vec[1+ndouble]\n ax.plot(x,posterior(x,heads[:2**ndouble]))\n ax.text(0.1, 0.8, '$N={0}$'.format(2**ndouble), transform=ax.transAxes)\nfor row in range(4): axs[row,0].set_ylabel('$p(H|D_\\mathrm{obs},I)$')\nfor col in range(3): axs[-1,col].set_xlabel('$H$')\n```\n\n\n\n\n\nThe evolution of the posterior pdf for the bias-weighting of a coin, as the number of data available increases. The figure on the top left-hand corner of each panel shows the number of data included in the analysis.
\n\n\n\n\n\nThe panel in the top left-hand corner shows the posterior pdf for $H$ given no data, i.e., it is the same as the prior pdf of Eq. ([3](#eq:coin_prior_uniform)). It indicates that we have no more reason to believe that the coin is fair than we have to think that it is double-headed, double-tailed, or of any other intermediate bias-weighting.\n\nThe first flip is obviously tails. At this point we have no evidence that the coin has a side with heads, as indicated by the pdf going to zero as $H \\to 1$. The second flip is obviously heads and we have now excluded both extreme options $H=0$ (double-tailed) and $H=1$ (double-headed). We can note that the posterior at this point has the simple form $p(H|D,I) = H(1-H)$ for $0 \\le H \\le 1$.\n\nThe remainder of Fig. [fig:coinflipping](#fig:coinflipping) shows how the posterior pdf evolves as the number of data analysed becomes larger and larger. We see that the position of the maximum moves around, but that the amount by which it does so decreases with the increasing number of observations. The width of the posterior pdf also becomes narrower with more data, indicating that we are becoming increasingly confident in our estimate of the bias-weighting. For the coin in this example, the best estimate of $H$ eventually converges to 0.6, which, of course, was the value chosen to simulate the flips.\n\n\n## A few words on different priors\n* uniform\n\n* Gaussian\n\n* Jeffrey's prior\n\nRepeat the coin flipping experiment with other priors.\n\n\n## Bayesian parameter estimation (single parameter)\nWe will now consider the very important task of model parameter estimation using statistical inference. \n[CF 1: maybe stress that model parameters are not random variables, and the meaning of parameter estimation is therefore very different between frequentist and bayesian approaches.]\n\nThroughout this section we will consider a specific example that involves a model with a single parameter: \"Measured flux from a star\".\n\n\n\n\n### Example: Measured flux from a star\n\nAdapted from the blog [Pythonic Perambulations](http://jakevdp.github.io) by Jake VanderPlas.\n\nImagine that we point our telescope to the sky, and observe the light coming from a single star. For the time being, we'll assume that the star's true flux is constant with time, i.e. that is it has a fixed value $F_\\mathrm{true}$ (we'll also ignore effects like sky noise and other sources of systematic error). We'll assume that we perform a series of $N$ measurements with our telescope, where the ith measurement reports the observed photon flux $F_i$ and error $e_i$[^errors].\nThe question is, given this set of measurements $D = \\{F_i, e_i\\}$, what is our best estimate of the true flux $F_\\mathrm{true}$?\n\n[^errors]: We'll make the reasonable assumption that errors are Gaussian. In a Frequentist perspective, $e_i$ is the standard deviation of the results of a single measurement event in the limit of repetitions of *that event*. In the Bayesian perspective, $e_i$ is the standard deviation of the (Gaussian) probability distribution describing our knowledge of that particular measurement given its observed value.\n\nBecause the measurements are number counts, a Poisson distribution is a good approximation to the measurement process:\n\n\n```\nnp.random.seed(1) # for repeatability\nF_true = 1000 # true flux, say number of photons measured in 1 second\nN = 50 # number of measurements\nF = stats.poisson(F_true).rvs(N)\n # N measurements of the flux\ne = np.sqrt(F) # errors on Poisson counts estimated via square root\n```\n\nNow let's make a simple visualization of the \"observed\" data, see Fig. [fig:flux](#fig:flux).\n\n\n```\nfig, ax = plt.subplots()\nax.errorbar(F, np.arange(N), xerr=e, fmt='ok', ecolor='gray', alpha=0.5)\nax.vlines([F_true], 0, N, linewidth=5, alpha=0.2)\nax.set_xlabel(\"Flux\");ax.set_ylabel(\"measurement number\");\n```\n\n\n\n\n\nSingle photon counts (flux measurements).
\n\n\n\n\n\nThese measurements each have a different error $e_i$ which is estimated from Poisson statistics using the standard square-root rule. In this toy example we already know the true flux $F_\\mathrm{true}$, but the question is this: given our measurements and errors, what is our best estimate of the true flux?\n\nLet's take a look at the frequentist and Bayesian approaches to solving this.\n\n### Simple Photon Counts: Frequentist Approach\n\nWe'll start with the classical frequentist maximum likelihood approach. Given a single observation $D_i = (F_i, e_i)$, we can compute the probability distribution of the measurement given the true flux Ftrue given our assumption of Gaussian errors\n\n\n\n\n$$\n\\begin{equation}\np(D_i | F_\\mathrm{true}, I) = \\frac{1}{\\sqrt{2\\pi e_i^2}} \\exp \\left( \\frac{-(F_i-F_\\mathrm{true})^2}{2e_i^2} \\right).\n\\label{_auto2} \\tag{5}\n\\end{equation}\n$$\n\nThis should be read \"the probability of $D_i$ given $F_\\mathrm{true}$\nequals ...\". You should recognize this as a normal distribution with mean $F_\\mathrm{true}$ and standard deviation $e_i$.\n\nWe construct the *likelihood function* by computing the product of the probabilities for each data point\n\n\n\n\n$$\n\\begin{equation}\n\\mathcal{L}(D | F_\\mathrm{true}, I) = \\prod_{i=1}^N p(D_i | F_\\mathrm{true}, I),\n\\label{_auto3} \\tag{6}\n\\end{equation}\n$$\n\nhere $D = \\{D_i\\}$ represents the entire set of measurements. Because the value of the likelihood can become very small, it is often more convenient to instead compute the log-likelihood. Combining the previous two equations and computing the log, we have\n\n\n\n\n$$\n\\begin{equation}\n\\log\\mathcal{L} = -\\frac{1}{2} \\sum_{i=1}^N \\left[ \\log(2\\pi e_i^2) + \\frac{(F_i-F_\\mathrm{true})^2}{e_i^2} \\right].\n\\label{_auto4} \\tag{7}\n\\end{equation}\n$$\n\nWhat we'd like to do is determine $F_\\mathrm{true}$ such that the likelihood is maximized. For this simple problem, the maximization can be computed analytically (i.e. by setting $d\\log\\mathcal{L}/d F_\\mathrm{true} = 0$). This results in the following observed estimate of $F_\\mathrm{true}$\n\n\n\n\n$$\n\\begin{equation}\nF_\\mathrm{est} = \\sum_{i=1}^N w_i F_i; \\quad w_i = 1/e_i^2.\n\\label{_auto5} \\tag{8}\n\\end{equation}\n$$\n\nNotice that in the special case of all errors $e_i$ being equal, this reduces to\n\n\n\n\n$$\n\\begin{equation}\nF_\\mathrm{est} = \\frac{1}{N} \\sum_{i=1} F_i.\n\\label{_auto6} \\tag{9}\n\\end{equation}\n$$\n\nThat is, in agreement with intuition, $F_\\mathrm{est}$ is simply the mean of the observed data when errors are equal.\n\nWe can go further and ask what the error of our estimate is. In the frequentist approach, this can be accomplished by fitting a Gaussian approximation to the likelihood curve at maximum; in this simple case this can also be solved analytically (the sum of Gaussians is also a Gaussian). It can be shown that the standard deviation of this Gaussian approximation is\n\n\n\n\n$$\n\\begin{equation}\n\\sigma_\\mathrm{est} = \\sum_{i=1}^N w_i.\n\\label{_auto7} \\tag{10}\n\\end{equation}\n$$\n\nThese results are fairly simple calculations; let's evaluate them for our toy dataset:\n\n\n```\nw=1./e**2\nprint(\"\"\"\nF_true = {0}\nF_est = {1:.0f} +/- {2:.0f} (based on {3} measurements) \"\"\"\\\n .format(F_true, (w * F).sum() / w.sum(), w.sum() ** -0.5, N))\n```\n\n`F_true = 1000` \n`F_est = 998 +/- 4 (based on 50 measurements)` \n\nWe find that for 50 measurements of the flux, our estimate has an error of about 0.4% and is consistent with the input value.\n\n\n### Simple Photon Counts: Bayesian Approach\n\nThe Bayesian approach, as you might expect, begins and ends with probabilities. Our hypothesis is that the star has a constant flux $F_\\mathrm{true}$. It recognizes that what we fundamentally want to compute is our knowledge of the parameters in question given the data and other information (such as our knowledge of uncertainties for the observed values), i.e. in this case, $p(F_\\mathrm{true} | D,I)$.\nNote that this formulation of the problem is fundamentally contrary to the frequentist philosophy, which says that probabilities have no meaning for model parameters like $F_\\mathrm{true}$. Nevertheless, within the Bayesian philosophy this is perfectly acceptable.\n\nTo compute this result, Bayesians next apply Bayes' Theorem ([1](#eq:bayes)).\nIf we set the prior $p(F_\\mathrm{true}|I) \\propto 1$ (a flat prior), we find\n$p(F_\\mathrm{true}|D,I) \\propto p(D | F_\\mathrm{true},I) \\equiv \\mathcal{L}(D | F_\\mathrm{true},I)$\nand the Bayesian probability is maximized at precisely the same value as the frequentist result! So despite the philosophical differences, we see that (for this simple problem at least) the Bayesian and frequentist point estimates are equivalent.\n\n### A note about priors\n\nThe prior allows inclusion of other information into the computation, which becomes very useful in cases where multiple measurement strategies are being combined to constrain a single model. The necessity to specify a prior, however, is one of the more controversial pieces of Bayesian analysis.\nA frequentist will point out that the prior is problematic when no true prior information is available. Though it might seem straightforward to use a noninformative prior like the flat prior mentioned above, there are some [surprisingly subtleties](http://normaldeviate.wordpress.com/2013/07/13/lost-causes-in-statistics-ii-noninformative- priors/comment-page-1/) involved. It turns out that in many situations, a truly noninformative prior does not exist! Frequentists point out that the subjective choice of a prior which necessarily biases your result has no place in statistical data analysis.\nA Bayesian would counter that frequentism doesn't solve this problem, but simply skirts the question. Frequentism can often be viewed as simply a special case of the Bayesian approach for some (implicit) choice of the prior: a Bayesian would say that it's better to make this implicit choice explicit, even if the choice might include some subjectivity.\n\n### Simple Photon Counts: Bayesian approach in practice\n\nLeaving these philosophical debates aside for the time being, let's address how Bayesian results are generally computed in practice. For a one parameter problem like the one considered here, it's as simple as computing the posterior probability $p(F_\\mathrm{true} | D,I)$ as a function of $F_\\mathrm{true}$: this is the distribution reflecting our knowledge of the parameter $F_\\mathrm{true}$.\nBut as the dimension of the model grows, this direct approach becomes increasingly intractable. For this reason, Bayesian calculations often depend on sampling methods such as Markov Chain Monte Carlo (MCMC). For this practical example, let us apply an MCMC approach using Dan Foreman-Mackey's [emcee](http://dan.iel.fm/emcee/current/) package. Keep in mind here that the goal is to generate a set of points drawn from the posterior probability distribution, and to use those points to determine the answer we seek.\nTo perform this MCMC, we start by defining Python functions for the prior $p(F_\\mathrm{true} | I)$, the likelihood $p(D | F_\\mathrm{true},I)$, and the posterior $p(F_\\mathrm{true} | D,I)$, noting that none of these need be properly normalized. Our model here is one-dimensional, but to handle multi-dimensional models we'll define the model in terms of an array of parameters $\\boldsymbol{\\alpha}$, which in this case is $\\boldsymbol{\\alpha} = [F_\\mathrm{true}]$\n\n\n```\ndef log_prior(alpha):\n return 0 # flat prior\n\ndef log_likelihood(alpha, F, e):\n return -0.5 * np.sum(np.log(2 * np.pi * e ** 2) \\\n + (F - alpha[0]) ** 2 / e ** 2)\n \ndef log_posterior(alpha, F, e):\n return log_prior(alpha) + log_likelihood(alpha, F, e)\n```\n\nNow we set up the problem, including generating some random starting guesses for the multiple chains of points.\n\n\n```\nndim = 1 # number of parameters in the model\nnwalkers = 50 # number of MCMC walkers\nnburn = 1000 # \"burn-in\" period to let chains stabilize\nnsteps = 2000 # number of MCMC steps to take\n# we'll start at random locations between 0 and 2000\nstarting_guesses = 2000 * np.random.rand(nwalkers, ndim)\nsampler = emcee.EnsembleSampler(nwalkers, ndim, log_posterior, args=[F,e])\nsampler.run_mcmc(starting_guesses, nsteps)\n# Shape of sampler.chain = (nwalkers, nsteps, ndim)\n# Flatten the sampler chain and discard burn-in points:\nsamples = sampler.chain[:, nburn:, :].reshape((-1, ndim))\n```\n\nIf this all worked correctly, the array sample should contain a series of 50,000 points drawn from the posterior. Let's plot them and check. See results in Fig. [fig:flux-bayesian](#fig:flux-bayesian).\n\n\n```\nfig, ax = plt.subplots()\nax.hist(samples, bins=50, histtype=\"stepfilled\", alpha=0.3, normed=True)\nax.set_xlabel(r'$F_\\mathrm{est}$')\nax.set_ylabel(r'$p(F_\\mathrm{est}|D,I)$')\n```\n\n\n\n\n\nBayesian posterior pdf (represented by a histogram of MCMC samples) from flux measurements.
\n\n\n\n\n\n### Best estimates and confidence intervals\n\nThe posterior distribution from our Bayesian data analysis is the key quantity that encodes our inference about the values of the model parameters, given the data and the relevant background information. Often, however, we wish to summarize this result with just a few numbers: the best estimate and a measure of its reliability. \n\nThere are a few different options for this. The choice of the most appropriate one depends mainly on the shape of the posterior distribution:\n\n*Symmetric posterior pdfs*: Since the probability (density) associated with any particular value of the parameter is a measure of how much we believe that it lies in the neighbourhood of that point, our best estimate is given by the maximum of the posterior pdf. If we denote the quantity of interest by $X$, with a posterior pdf $P =p(X|D,I)$, then the best estimate of its value $X_0$ is given by the condition $dP/dX|_{X=X_0}=0$. Strictly speaking, we should also check the sign of the second derivative to ensure that $X_0$ represents a maximum.\n\nTo obtain a measure of the reliability of this best estimate, we need to look at the width or spread of the posterior pdf about $X_0$. When considering the behaviour of any function in the neighbourhood of a particular point, it is often helpful to carry out a Taylor series expansion; this is simply a standard tool for (locally) approximating a complicated function by a low-order polynomial. The linear term is zero at the maximum and the quadratic term is often the dominating one determining the width of the posterior pdf. Ignoring all the higher-order terms we arrive at the Gaussian approximation\n\n\n\n\n$$\n\\begin{equation}\np(X|D,I) \\approx \\frac{1}{\\sigma\\sqrt{2\\pi}} \\exp \\left[ -\\frac{(x-\\mu)^2}{2\\sigma^2} \\right],\n\\label{_auto8} \\tag{11}\n\\end{equation}\n$$\n\nwhere the mean $\\mu = X_0$ and the variance $\\sigma = \\left( - \\left. \\frac{d^2L}{dX^2} \\right|_{X_0} \\right)^{-1/2}$, where $L$ is the logarithm of the posterior $P$. Our inference about the quantity of interest is conveyed very concisely, therefore, by the statement $X = X_0 \\pm \\sigma$, and\n\n$$\n$$\np(X_0-\\sigma < X < X_0+\\sigma | D,I) = \\int_{X_0-\\sigma}^{X_0+\\sigma} p(X|D,I) dX \\approx 0.67.\n$$\n$$\n\n*Asymmetric posterior pdfs*: While the maximum of the posterior ($X_0$) can still be regarded as giving the best estimate, the true value is now more likely to be on one side of this rather than the other. Alternatively one can compute the mean value, $\\langle X \\rangle = \\int X p(X|D,I) dX$, although this tends to overemphasise very long tails. The best option is probably a compromise that can be employed when having access to a large sample from the posterior (as provided by an MCMC), namely to give the median of this ensamble.\n\nFurthermore, the concept of an error-bar does not seem appropriate in this case, as it implicitly entails the idea of symmetry. A good way of expressing the reliability with which a parameter can be inferred, for an asymmetric posterior pdf, is rather through a *confidence interval*. Since the area under the posterior pdf between $X_1$ and $X_2$ is proportional to how much we believe that $X$ lies in that range, the shortest interval that encloses 67% of the area represents a sensible measure of the uncertainty of the estimate. Obviously we can choose to provide some other degree-of-belief that we think is relevant for the case at hand. Assuming that the posterior pdf has been normalized, to have unit area, we need to find $X_1$ and $X_2$ such that:\n\n$$\n$$\np(X_1 < X < X_2 | D,I) = \\int_{X_1}^{X_2} p(X|D,I) dX \\approx 0.67, \n$$\n$$\n\nwhere the difference $X_2 - X_1$ is as small as possible. The region $X_1 < X < X_2$ is then called the shortest 67% confidence interval. \n\n*Multimodal posterior pdfs*: We can sometimes obtain posteriors which are multimodal; i.e. contains several disconnected regions with large probabilities. There is no difficulty when one of the maxima is very much larger than the others: we can simply ignore the subsidiary solutions, to a good approximation, and concentrate on the global maximum. The problem arises when there are several maxima of comparable magnitude. What do we now mean by a best estimate, and how should we quantify its reliability? The idea of a best estimate and an error-bar, or even a confidence interval, is merely an attempt to summarize the posterior with just two or three numbers; sometimes this just can’t be done, and so these concepts are not valid. For the bimodal case we might be able to characterize the posterior in terms of a few numbers: two best estimates and their associated error-bars, or disjoint confidence intervals. For a general multimodal pdf, the most honest thing we can do is just display the posterior itself.\n\n### Simple Photon Counts: Best estimates and confidence intervals\n\nTo compute these numbers for our example, you would run:\n\n\n```\nsampper=np.percentile(samples, [2.5, 16.5, 50, 83.5, 97.5],axis=0).flatten()\nprint(\"\"\"\nF_true = {0}\nBased on {1} measurements the posterior point estimates are:\n...F_est = {2:.0f} +/- {3:.0f}\nor using credible intervals:\n...F_est = {4:.0f} (posterior median) \n...F_est in [{5:.0f}, {6:.0f}] (67% credible interval) \n...F_est in [{7:.0f}, {8:.0f}] (95% credible interval) \"\"\"\\\n .format(F_true, N, np.mean(samples), np.std(samples), \\\n sampper[2], sampper[1], sampper[3], sampper[0], sampper[4]))\n```\n\n`F_true = 1000` \n`Based on 50 measurements the posterior point estimates are:` \n`...F_est = 998 +/- 4` \n`or using credible intervals:` \n`...F_est = 998 (posterior median)` \n`...F_est in [993, 1002] (67% credible interval)` \n`...F_est in [989, 1006] (95% credible interval)` \n\nIn this particular example, the posterior pdf is actually a Gaussian (since it is constructed as a product of Gaussians), and the mean and variance from the quadratic approximation will agree exactly with the frequentist approach.\n\nFrom this final result you might come away with the impression that the Bayesian method is unnecessarily complicated, and in this case it certainly is. Using an MCMC sampler to characterize a one-dimensional normal distribution is a bit like using the Death Star to destroy a beach ball, but we did this here because it demonstrates an approach that can scale to complicated posteriors in many, many dimensions, and can provide nice results in more complicated situations where an analytic likelihood approach is not possible.\n\nFurthermore, as data and models grow in complexity, the two approaches can diverge greatly. \n\n\n## Bayesian parameter estimation (multiple parameters, covariance)\n* multidimensional posterior pdf:s\n\n* nuisance parameters (e.g. background subtraction?)\n\n* corner plots, covariance, correlations\n\n* best example?\n\n\n\n\n\n## Bayesian model selection\n* Bayesian evidence\n\n* Occam's razor\n\n* Best example? How many spectral lines are there?\n", "meta": {"hexsha": "200cdd664f2eca40e56c0122716150ee3600d4bf", "size": 50062, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/src/LectureNotes/chapter11.ipynb", "max_stars_repo_name": "anacost/MachineLearning", "max_stars_repo_head_hexsha": "89e1c3637fe302c2b15b96bf89c8a01d2d693f29", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/src/LectureNotes/chapter11.ipynb", "max_issues_repo_name": "anacost/MachineLearning", "max_issues_repo_head_hexsha": "89e1c3637fe302c2b15b96bf89c8a01d2d693f29", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/src/LectureNotes/chapter11.ipynb", "max_forks_repo_name": "anacost/MachineLearning", "max_forks_repo_head_hexsha": "89e1c3637fe302c2b15b96bf89c8a01d2d693f29", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-04T16:21:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T16:21:16.000Z", "avg_line_length": 48.5567410281, "max_line_length": 1080, "alphanum_fraction": 0.6357716432, "converted": true, "num_tokens": 9795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.20434190478229486, "lm_q1q2_score": 0.08246561666761613}} {"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n import openmdao.api as om\nexcept ImportError:\n if 'google.colab' in str(get_ipython()):\n !python -m pip install openmdao[notebooks]\n else:\n missing_packages.append('openmdao')\ntry:\n import dymos as dm\nexcept ImportError:\n if 'google.colab' in str(get_ipython()):\n !python -m pip install dymos\n else:\n missing_packages.append('dymos')\ntry:\n import pyoptsparse\nexcept ImportError:\n if 'google.colab' in str(get_ipython()):\n !pip install -q condacolab\n import condacolab\n condacolab.install_miniconda()\n !conda install -c conda-forge pyoptsparse\n else:\n missing_packages.append('pyoptsparse')\nif missing_packages:\n raise EnvironmentError('This notebook requires the following packages '\n 'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n# The Length-Constrained Brachistochrone\n\n```{admonition} Things you'll learn through this example\n- How to connect the outputs from a trajectory to a downstream system.\n```\n\nThis is a modified take on the brachistochrone problem.\nIn this instance, we assume that the quantity of wire available is limited.\nNow, we seek to find the minimum time brachistochrone trajectory subject to a upper-limit on the arclength of the wire.\n\nThe most efficient way to approach this problem would be to treat the arc-length $S$ as an integrated state variable.\nIn this case, as is often the case in real-world MDO analyses, the implementation of our arc-length function is not integrated into our pseudospectral approach.\nRather than rewrite an analysis tool to accommodate the pseudospectral approach, the arc-length analysis simply takes the result of the trajectory in its entirety and computes the arc-length constraint via the trapezoidal rule:\\\n\n\\begin{align}\n S &= \\frac{1}{2} \\left( \\sum_{i=1}^{N-1} \\sqrt{1 + \\frac{1}{\\tan{\\theta_{i-1}}}} + \\sqrt{1 + \\frac{1}{\\tan{\\theta_{i}}}} \\right) \\left(x_{i-1} - x_i \\right)\n\\end{align}\n\nThe OpenMDAO component used to compute the arclength is defined as follows:\n\n\n```python\nfrom __future__ import print_function, division, absolute_import\n\nimport numpy as np\n\nfrom openmdao.api import ExplicitComponent\n\n\nclass ArcLengthComp(ExplicitComponent):\n\n def initialize(self):\n\n self.options.declare('num_nodes', types=(int,))\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_input('x', val=np.ones(nn), units='m', desc='x at points along the trajectory')\n self.add_input('theta', val=np.ones(nn), units='rad',\n desc='wire angle with vertical along the trajectory')\n\n self.add_output('S', val=1.0, units='m', desc='arclength of wire')\n\n self.declare_partials(of='S', wrt='*', method='cs')\n\n def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None):\n\n x = inputs['x']\n theta = inputs['theta']\n\n dy_dx = -1.0 / np.tan(theta)\n dx = np.diff(x)\n f = np.sqrt(1 + dy_dx**2)\n\n # trapezoidal rule\n fxm1 = f[:-1]\n fx = f[1:]\n outputs['S'] = 0.5 * np.dot(fxm1 + fx, dx)\n```\n\n```{Note}\nIn this example, the number of nodes used to compute the arclength is needed when building the problem.\nThe transcription object is initialized and its attribute `grid_data.num_nodes` is used to provide the number of total nodes (the number of points in the timeseries) to the downstream arc length calculation.\n```\n\n\n```python\nom.display_source(\"dymos.examples.brachistochrone.brachistochrone_ode\")\n```\n\n\n```python\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\nfrom dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE\n\nMAX_ARCLENGTH = 11.9\nOPTIMIZER = 'SLSQP'\n\np = om.Problem(model=om.Group())\np.add_recorder(om.SqliteRecorder('length_constrained_brach_sol.db'))\n\nif OPTIMIZER == 'SNOPT':\n p.driver = om.pyOptSparseDriver()\n p.driver.options['optimizer'] = OPTIMIZER\n p.driver.opt_settings['Major iterations limit'] = 1000\n p.driver.opt_settings['Major feasibility tolerance'] = 1.0E-6\n p.driver.opt_settings['Major optimality tolerance'] = 1.0E-5\n p.driver.opt_settings['iSumm'] = 6\n p.driver.opt_settings['Verify level'] = 3\nelse:\n p.driver = om.ScipyOptimizeDriver()\n\np.driver.declare_coloring()\n\n# Create the transcription so we can get the number of nodes for the downstream analysis\ntx = dm.Radau(num_segments=20, order=3, compressed=False)\n\ntraj = dm.Trajectory()\nphase = dm.Phase(transcription=tx, ode_class=BrachistochroneODE)\ntraj.add_phase('phase0', phase)\n\np.model.add_subsystem('traj', traj)\n\nphase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n\nphase.add_state('x', units='m', rate_source='xdot', fix_initial=True, fix_final=True)\nphase.add_state('y', units='m', rate_source='ydot', fix_initial=True, fix_final=True)\nphase.add_state('v', units='m/s', rate_source='vdot', fix_initial=True, fix_final=False)\n\nphase.add_control('theta', units='deg', lower=0.01, upper=179.9,\n continuity=True, rate_continuity=True)\n\nphase.add_parameter('g', units='m/s**2', opt=False, val=9.80665)\n\n# Minimize time at the end of the phase\nphase.add_objective('time', loc='final', scaler=1)\n\n# p.model.options['assembled_jac_type'] = top_level_jacobian.lower()\n# p.model.linear_solver = DirectSolver(assemble_jac=True)\n\n# Add the arc length component\np.model.add_subsystem('arc_length_comp',\n subsys=ArcLengthComp(num_nodes=tx.grid_data.num_nodes))\n\np.model.connect('traj.phase0.timeseries.controls:theta', 'arc_length_comp.theta')\np.model.connect('traj.phase0.timeseries.states:x', 'arc_length_comp.x')\n\np.model.add_constraint('arc_length_comp.S', upper=MAX_ARCLENGTH, ref=1)\n\np.setup(check=True)\n\np.set_val('traj.phase0.t_initial', 0.0)\np.set_val('traj.phase0.t_duration', 2.0)\n\np.set_val('traj.phase0.states:x', phase.interp('x', [0, 10]))\np.set_val('traj.phase0.states:y', phase.interp('y', [10, 5]))\np.set_val('traj.phase0.states:v', phase.interp('v', [0, 9.9]))\np.set_val('traj.phase0.controls:theta', phase.interp('theta', [5, 100]))\np.set_val('traj.phase0.parameters:g', 9.80665)\n\np.run_driver()\n\np.record(case_name='final')\n\n\n# Generate the explicitly simulated trajectory\nexp_out = traj.simulate()\n\n# Extract the timeseries from the implicit solution and the explicit simulation\nx = p.get_val('traj.phase0.timeseries.states:x')\ny = p.get_val('traj.phase0.timeseries.states:y')\nt = p.get_val('traj.phase0.timeseries.time')\ntheta = p.get_val('traj.phase0.timeseries.controls:theta')\n\nx_exp = exp_out.get_val('traj.phase0.timeseries.states:x')\ny_exp = exp_out.get_val('traj.phase0.timeseries.states:y')\nt_exp = exp_out.get_val('traj.phase0.timeseries.time')\ntheta_exp = exp_out.get_val('traj.phase0.timeseries.controls:theta')\n\nfig, axes = plt.subplots(nrows=2, ncols=1)\n\naxes[0].plot(x, y, 'o')\naxes[0].plot(x_exp, y_exp, '-')\naxes[0].set_xlabel('x (m)')\naxes[0].set_ylabel('y (m)')\n\naxes[1].plot(t, theta, 'o')\naxes[1].plot(t_exp, theta_exp, '-')\naxes[1].set_xlabel('time (s)')\naxes[1].set_ylabel(r'$\\theta$ (deg)')\n\nplt.show()\n```\n", "meta": {"hexsha": "e623806bb4e83c3c1ad4242233dd7ff0bc6a9f9d", "size": 10337, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/examples/length_constrained_brachistochrone/length_constrained_brachistochrone.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/examples/length_constrained_brachistochrone/length_constrained_brachistochrone.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/examples/length_constrained_brachistochrone/length_constrained_brachistochrone.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6560283688, "max_line_length": 238, "alphanum_fraction": 0.5824707362, "converted": true, "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1755380693103044, "lm_q1q2_score": 0.08229060150873861}} {"text": " **Chapter 2: [Diffraction](CH2_00-Diffraction.ipynb)** \n\n| \n | Picture 1 | \nPicture 2 | \nPicture 3 | \nSky | \nTree | \n
|---|---|---|---|---|---|
| Picture 1 | \n0 | \n0 | \n0 | \n1 | \n1 | \n
| Picture 2 | \n0 | \n0 | \n0 | \n1 | \n0 | \n
| Picture 3 | \n0 | \n0 | \n0 | \n1 | \n1 | \n
| Sky | \n1 | \n1 | \n1 | \n0 | \n0 | \n
| Tree | \n1 | \n0 | \n1 | \n0 | \n0 | \n
| \n | Picture 1 | \nPicture 2 | \nPicture 3 | \nSky | \nTree | \n
|---|---|---|---|---|---|
| Picture 1 | \n0.0 | \n0 | \n0.0 | \n0.333333 | \n0.5 | \n
| Picture 2 | \n0.0 | \n0 | \n0.0 | \n0.333333 | \n0.0 | \n
| Picture 3 | \n0.0 | \n0 | \n0.0 | \n0.333333 | \n0.5 | \n
| Sky | \n0.5 | \n1 | \n0.5 | \n0.000000 | \n0.0 | \n
| Tree | \n0.5 | \n0 | \n0.5 | \n0.000000 | \n0.0 | \n
| \n | e_0 | \n
|---|---|
| Picture 1 | \n1 | \n
| Picture 2 | \n0 | \n
| Picture 3 | \n0 | \n
| Sky | \n0 | \n
| Tree | \n0 | \n
| \n | 0 | \n1 | \n2 | \n3 | \n4 | \n5 | \n6 | \n7 | \n8 | \n9 | \n... | \n41 | \n42 | \n43 | \n44 | \n45 | \n46 | \n47 | \n48 | \n49 | \n50 | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Picture 1 | \n1 | \n0.2 | \n0.466667 | \n0.253333 | \n0.418311 | \n0.286329 | \n0.391308 | \n0.307325 | \n0.374446 | \n0.320749 | \n... | \n0.344591 | \n0.344625 | \n0.344598 | \n0.344620 | \n0.344603 | \n0.344616 | \n0.344605 | \n0.344614 | \n0.344607 | \n0.344613 | \n
| Picture 2 | \n0 | \n0.0 | \n0.106667 | \n0.021333 | \n0.100978 | \n0.037262 | \n0.089448 | \n0.047699 | \n0.081228 | \n0.054405 | \n... | \n0.066326 | \n0.066343 | \n0.066329 | \n0.066340 | \n0.066331 | \n0.066338 | \n0.066333 | \n0.066337 | \n0.066333 | \n0.066336 | \n
| Picture 3 | \n0 | \n0.0 | \n0.266667 | \n0.053333 | \n0.218311 | \n0.086329 | \n0.191308 | \n0.107325 | \n0.174446 | \n0.120749 | \n... | \n0.144591 | \n0.144625 | \n0.144598 | \n0.144620 | \n0.144603 | \n0.144616 | \n0.144605 | \n0.144614 | \n0.144607 | \n0.144613 | \n
| Sky | \n0 | \n0.4 | \n0.080000 | \n0.378667 | \n0.139733 | \n0.335431 | \n0.178873 | \n0.304605 | \n0.204019 | \n0.284540 | \n... | \n0.248785 | \n0.248734 | \n0.248774 | \n0.248742 | \n0.248768 | \n0.248747 | \n0.248764 | \n0.248750 | \n0.248761 | \n0.248752 | \n
| Tree | \n0 | \n0.4 | \n0.080000 | \n0.293333 | \n0.122667 | \n0.254649 | \n0.149063 | \n0.233046 | \n0.165860 | \n0.219557 | \n... | \n0.195707 | \n0.195673 | \n0.195700 | \n0.195679 | \n0.195696 | \n0.195682 | \n0.195693 | \n0.195684 | \n0.195691 | \n0.195686 | \n
5 rows × 51 columns
\n| \n | name | \nkeyword | \ns | \nbetx | \nalfx | \nmux | \nbety | \nalfy | \nmuy | \nx | \n... | \nsig54 | \nsig55 | \nsig56 | \nsig61 | \nsig62 | \nsig63 | \nsig64 | \nsig65 | \nsig66 | \nn1 | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| #s | \nmycell$start:1 | \nmarker | \n0.0 | \n463.623288 | \n-1.156109 | \n0.000000 | \n369.779162 | \n0.929316 | \n0.000000 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
| quadrupole1 | \nquadrupole1:1 | \nquadrupole | \n5.0 | \n463.623288 | \n1.156109 | \n0.001709 | \n369.779162 | \n-0.929316 | \n0.002161 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
| drift_0[0] | \ndrift_0:0 | \ndrift | \n25.0 | \n419.394867 | \n1.055312 | \n0.008930 | \n408.967742 | \n-1.030113 | \n0.010350 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
| marker1 | \nmarker1:1 | \nmarker | \n25.0 | \n419.394867 | \n1.055312 | \n0.008930 | \n408.967742 | \n-1.030113 | \n0.010350 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
| drift_1[0] | \ndrift_1:0 | \ndrift | \n50.0 | \n369.779162 | \n0.929316 | \n0.019041 | \n463.623288 | \n-1.156109 | \n0.019493 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
| quadrupole2 | \nquadrupole2:1 | \nquadrupole | \n55.0 | \n369.779162 | \n-0.929316 | \n0.021202 | \n463.623288 | \n1.156109 | \n0.021202 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
| drift_2[0] | \ndrift_2:0 | \ndrift | \n100.0 | \n463.623288 | \n-1.156109 | \n0.038533 | \n369.779162 | \n0.929316 | \n0.038533 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
| #e | \nmycell$end:1 | \nmarker | \n100.0 | \n463.623288 | \n-1.156109 | \n0.038533 | \n369.779162 | \n0.929316 | \n0.038533 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
8 rows × 256 columns
\n| \n | name | \ns | \nbetx | \nbety | \nalfx | \nalfy | \n
|---|---|---|---|---|---|---|
| #s | \nmycell$start:1 | \n0.0 | \n463.623288 | \n369.779162 | \n-1.156109 | \n0.929316 | \n
| quadrupole1 | \nquadrupole1:1 | \n5.0 | \n463.623288 | \n369.779162 | \n1.156109 | \n-0.929316 | \n
| drift_0[0] | \ndrift_0:0 | \n25.0 | \n419.394867 | \n408.967742 | \n1.055312 | \n-1.030113 | \n
| marker1 | \nmarker1:1 | \n25.0 | \n419.394867 | \n408.967742 | \n1.055312 | \n-1.030113 | \n
| drift_1[0] | \ndrift_1:0 | \n50.0 | \n369.779162 | \n463.623288 | \n0.929316 | \n-1.156109 | \n
| quadrupole2 | \nquadrupole2:1 | \n55.0 | \n369.779162 | \n463.623288 | \n-0.929316 | \n1.156109 | \n
| drift_2[0] | \ndrift_2:0 | \n100.0 | \n463.623288 | \n369.779162 | \n-1.156109 | \n0.929316 | \n
| #e | \nmycell$end:1 | \n100.0 | \n463.623288 | \n369.779162 | \n-1.156109 | \n0.929316 | \n
| \n | length | \norbit5 | \nalfa | \ngammatr | \nq1 | \ndq1 | \nbetxmax | \ndxmax | \ndxrms | \nxcomax | \n... | \nycorms | \ndeltap | \nsynch_1 | \nsynch_2 | \nsynch_3 | \nsynch_4 | \nsynch_5 | \nsynch_6 | \nsynch_8 | \nnflips | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| #e | \n100.0 | \n-0.0 | \n0.0 | \n0.0 | \n0.038533 | \n-0.043847 | \n463.623288 | \n0.0 | \n0.0 | \n0.0 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n
1 rows × 27 columns
\n| \n | sm | \nd1 | \nd2 | \npd1 | \npd2 | \np | \n
|---|---|---|---|---|---|---|
| (1, 1) | \n2 | \n1 | \n1 | \nNaN | \nNaN | \nNaN | \n
| (1, 2) | \n3 | \n1 | \n2 | \nNaN | \nNaN | \nNaN | \n
| (1, 3) | \n4 | \n1 | \n3 | \nNaN | \nNaN | \nNaN | \n
| (1, 4) | \n5 | \n1 | \n4 | \nNaN | \nNaN | \nNaN | \n
| (1, 5) | \n6 | \n1 | \n5 | \nNaN | \nNaN | \nNaN | \n
| \n | sm | \nd1 | \nd2 | \npd1 | \npd2 | \np | \n
|---|---|---|---|---|---|---|
| (1, 1) | \n2 | \n1 | \n1 | \n0.111111 | \n0.166667 | \nNaN | \n
| (1, 2) | \n3 | \n1 | \n2 | \n0.111111 | \n0.166667 | \nNaN | \n
| (1, 3) | \n4 | \n1 | \n3 | \n0.111111 | \n0.166667 | \nNaN | \n
| (1, 4) | \n5 | \n1 | \n4 | \n0.111111 | \n0.166667 | \nNaN | \n
| (1, 5) | \n6 | \n1 | \n5 | \n0.111111 | \n0.166667 | \nNaN | \n
| (1, 6) | \n7 | \n1 | \n6 | \n0.111111 | \n0.166667 | \nNaN | \n
| (2, 1) | \n3 | \n2 | \n1 | \n0.111111 | \n0.166667 | \nNaN | \n
| (2, 2) | \n4 | \n2 | \n2 | \n0.111111 | \n0.166667 | \nNaN | \n
| (2, 3) | \n5 | \n2 | \n3 | \n0.111111 | \n0.166667 | \nNaN | \n
| (2, 4) | \n6 | \n2 | \n4 | \n0.111111 | \n0.166667 | \nNaN | \n
| \n | sm | \nd1 | \nd2 | \npd1 | \npd2 | \np | \n
|---|---|---|---|---|---|---|
| (1, 1) | \n2 | \n1 | \n1 | \n0.111111 | \n0.166667 | \n0.0185185 | \n
| (1, 2) | \n3 | \n1 | \n2 | \n0.111111 | \n0.166667 | \n0.0185185 | \n
| (1, 3) | \n4 | \n1 | \n3 | \n0.111111 | \n0.166667 | \n0.0185185 | \n
| (1, 4) | \n5 | \n1 | \n4 | \n0.111111 | \n0.166667 | \n0.0185185 | \n
| (1, 5) | \n6 | \n1 | \n5 | \n0.111111 | \n0.166667 | \n0.0185185 | \n
| \n View on TensorFlow.org\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
| \n | log_radon | \nfloor | \ncounty | \nlog_uranium_ppm | \n
|---|---|---|---|---|
| 0 | \n0.788457 | \n1 | \n0 | \n-0.689048 | \n
| 1 | \n0.788457 | \n0 | \n0 | \n-0.689048 | \n
| 2 | \n1.064711 | \n0 | \n0 | \n-0.689048 | \n
| 3 | \n0.000000 | \n0 | \n0 | \n-0.689048 | \n
| 4 | \n1.131402 | \n0 | \n1 | \n-0.847313 | \n
| \n | animal_id | \nname | \ndatetime | \nmonthyear | \ndate_of_birth | \noutcome_type | \noutcome_subtype | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \nA775354 | \nCharley | \n2019-11-12T13:29:00.000 | \n2019-11-12T13:29:00.000 | \n2013-06-28T00:00:00.000 | \nAdoption | \nNaN | \nDog | \nNeutered Male | \n6 years | \nCocker Spaniel Mix | \nBlack/White | \n
| 1 | \nA775130 | \n*Slinky | \n2019-11-12T13:17:00.000 | \n2019-11-12T13:17:00.000 | \n2016-06-25T00:00:00.000 | \nAdoption | \nFoster | \nDog | \nSpayed Female | \n3 years | \nPit Bull Mix | \nBlue/White | \n
| 2 | \nA808385 | \nNaN | \n2019-11-12T13:16:00.000 | \n2019-11-12T13:16:00.000 | \n2018-11-08T00:00:00.000 | \nTransfer | \nPartner | \nDog | \nNeutered Male | \n1 year | \nPug/Chihuahua Shorthair | \nWhite/Brown | \n
| 3 | \nA799709 | \n*Deeogee | \n2019-11-12T13:15:00.000 | \n2019-11-12T13:15:00.000 | \n2018-07-11T00:00:00.000 | \nAdoption | \nFoster | \nDog | \nNeutered Male | \n1 year | \nBeagle Mix | \nBrown Brindle | \n
| 4 | \nA713661 | \nCoco | \n2019-11-12T12:46:00.000 | \n2019-11-12T12:46:00.000 | \n2013-10-10T00:00:00.000 | \nReturn to Owner | \nNaN | \nDog | \nSpayed Female | \n6 years | \nLabrador Retriever Mix | \nBlack/White | \n
| \n | animal_id | \nname | \ndatetime | \nmonthyear | \ndate_of_birth | \noutcome_subtype | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \nA775354 | \nCharley | \n2019-11-12T13:29:00.000 | \n2019-11-12T13:29:00.000 | \n2013-06-28T00:00:00.000 | \nNaN | \nDog | \nNeutered Male | \n6 years | \nCocker Spaniel Mix | \nBlack/White | \nAdopted | \n
| 1 | \nA775130 | \n*Slinky | \n2019-11-12T13:17:00.000 | \n2019-11-12T13:17:00.000 | \n2016-06-25T00:00:00.000 | \nFoster | \nDog | \nSpayed Female | \n3 years | \nPit Bull Mix | \nBlue/White | \nAdopted | \n
| 2 | \nA808385 | \nNaN | \n2019-11-12T13:16:00.000 | \n2019-11-12T13:16:00.000 | \n2018-11-08T00:00:00.000 | \nPartner | \nDog | \nNeutered Male | \n1 year | \nPug/Chihuahua Shorthair | \nWhite/Brown | \nNot adopted | \n
| 3 | \nA799709 | \n*Deeogee | \n2019-11-12T13:15:00.000 | \n2019-11-12T13:15:00.000 | \n2018-07-11T00:00:00.000 | \nFoster | \nDog | \nNeutered Male | \n1 year | \nBeagle Mix | \nBrown Brindle | \nAdopted | \n
| 5 | \nA808367 | \nDaily | \n2019-11-12T12:38:00.000 | \n2019-11-12T12:38:00.000 | \n2016-11-07T00:00:00.000 | \nPartner | \nDog | \nIntact Female | \n3 years | \nAustralian Cattle Dog/Labrador Retriever | \nCream | \nNot adopted | \n
| ... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n... | \n
| 99995 | \nA679740 | \nNaN | \n2014-05-26T16:55:00.000 | \n2014-05-26T16:55:00.000 | \n2014-03-25T00:00:00.000 | \nPartner | \nDog | \nIntact Male | \n2 months | \nCatahoula Mix | \nBrown Brindle/White | \nNot adopted | \n
| 99996 | \nA679715 | \nNaN | \n2014-05-26T16:54:00.000 | \n2014-05-26T16:54:00.000 | \n2014-03-25T00:00:00.000 | \nPartner | \nDog | \nIntact Female | \n2 months | \nCatahoula Mix | \nTan/White | \nNot adopted | \n
| 99997 | \nA677532 | \n*Taco | \n2014-05-26T16:52:00.000 | \n2014-05-26T16:52:00.000 | \n2014-03-15T00:00:00.000 | \nNaN | \nCat | \nNeutered Male | \n2 months | \nDomestic Shorthair Mix | \nWhite | \nAdopted | \n
| 99998 | \nA677530 | \n*Chimichanga | \n2014-05-26T16:51:00.000 | \n2014-05-26T16:51:00.000 | \n2014-03-15T00:00:00.000 | \nNaN | \nCat | \nNeutered Male | \n2 months | \nDomestic Shorthair Mix | \nBlack | \nAdopted | \n
| 99999 | \nA679225 | \nPhoebe | \n2014-05-26T16:40:00.000 | \n2014-05-26T16:40:00.000 | \n2011-05-17T00:00:00.000 | \nNaN | \nDog | \nSpayed Female | \n3 years | \nMaltese/Miniature Poodle | \nApricot | \nAdopted | \n
80618 rows × 12 columns
\n| \n | animal_id | \nname | \ndatetime | \nmonthyear | \ndate_of_birth | \noutcome_type | \noutcome_subtype | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2565 | \nA803963 | \nLittle Bit | \n2019-09-27 17:59:00 | \n2019-09-27T17:59:00.000 | \n2017-09-09T00:00:00.000 | \nNaN | \nNaN | \nDog | \nIntact Male | \nNaN | \nMiniature Schnauzer | \nGray/Black | \nAdopted | \n
| 53725 | \nA737705 | \n*Heddy | \n2016-11-19 16:35:00 | \n2016-11-19T16:35:00.000 | \n2013-11-02T00:00:00.000 | \nNaN | \nNaN | \nDog | \nNaN | \nNaN | \nLabrador Retriever Mix | \nBlack/White | \nAdopted | \n
| 94975 | \nA686025 | \nNaN | \n2014-08-16 08:35:00 | \n2014-08-16T08:35:00.000 | \n2013-08-15T00:00:00.000 | \nNaN | \nNaN | \nOther | \nUnknown | \n1 year | \nBat Mix | \nBrown | \nAdopted | \n
Expected experimental information on the calcium isotopes that can be obtained at FRIB. The limits for detailed spectroscopic information are around $A\\sim 60$.
\n\n\n\n\n\n\n\n\n## Motivation and aims\n\nThe aim of the first part of this course is to present some of the\nexperimental data which can be used to extract information about\ncorrelations in nuclear systems. In particular, we will start with a\ntheoretical analysis of a quantity called the separation energy for\nneutrons or protons. This quantity, to be discussed below, is defined\nas the difference between two binding energies (masses) of neighboring\nnuclei. As we will see from various figures below and exercises as\nwell, the separation energies display a varying behavior as function\nof the number of neutrons or protons. These variations from one\nnucleus to another one, laid the foundation for the introduction of\nso-called magic numbers and a mean-field picture in order to describe\nnuclei theoretically.\n\n\n\n\n\n\n## Mean-field picture\n\nWith a mean- or average-field picture we mean that a given nucleon (either a proton or a neutron) moves in an average potential field which is set up by all other nucleons in the system. Consider for example a nucleus like ${}^{17}\\mbox{O}$ with nine neutrons and eight protons. Many properties of this nucleus can be interpreted in terms of a picture where we can view it as\none neutron on top of ${}^{16}\\mbox{O}$. We infer from data and our theoretical interpretations that this additional neutron behaves almost as an individual neutron which *sees* an average interaction set up by the remaining 16 nucleons in ${}^{16}\\mbox{O}$. A nucleus like ${}^{16}\\mbox{O}$ is an example of what we in this course will denote as a good closed-shell nucleus. We will come back to what this means later.\n\n\n\n\n\n## Mean-field picture, which potential do we opt for?\n\n\nA simple potential model which enjoys quite some popularity in nuclear\nphysics, is the **three-dimensional harmonic oscillator**. This potential\nmodel captures some of the physics of deeply bound single-particle\nstates but fails in reproducing the less bound single-particle\nstates. \n\nA parametrized, and more realistic, potential model which is\nwidely used in nuclear physics, is the so-called **Woods-Saxon**\npotential. Both the harmonic oscillator and the Woods-Saxon potential\nmodels define computational problems that can easily be solved (see\nbelow), resulting (with the appropriate parameters) in a rather good\nreproduction of experiment for nuclei which can be approximated as one\nnucleon on top (or one nucleon removed) of a so-called closed-shell\nsystem.\n\n\n\n\n\n\n## Too simple?\n\nTo be able to interpret a nucleus in such a way requires at least that\nwe are capable of parametrizing the abovementioned interactions in\norder to reproduce say the excitation spectrum of a nucleus like\n${}^{17}\\mbox{O}$.\n\nWith such a parametrized interaction we are able to solve\nSchroedinger's equation for the motion of one nucleon in a given\nfield. A nucleus is however a true and complicated many-nucleon\nsystem, with extremely many degrees of freedom and complicated\ncorrelations, rendering the ideal solution of the many-nucleon\nSchroedinger equation an impossible enterprise. It is much easier to\nsolve a single-particle problem with say a Woods-Saxon\npotential.\n\n\n\n## Motivation, better mean-fields\n\nAn improvement to these simpler single-nucleon potentials is given by\nthe Hartree-Fock method, where the variational principle is used to\ndefine a mean-field which the nucleons move in. There are many\ndifferent classes of mean-field methods. An important difference\nbetween these methods and the simpler parametrized mean-field\npotentials like the harmonic oscillator and the Woods-Saxon\npotentials, is that the resulting equations contain information about\nthe nuclear forces present in our models for solving Schroedinger's\nequation. Hartree-Fock and other mean-field methods like density\nfunctional theory form core topics in later lectures.\n\n\n\n\n\n\n## Aims here\n\nThe aim here is to present some of the experimental data we\nwill confront theory with. In particular, we will focus on separation\nand shell-gap energies and use these to build a picture of nuclei in\nterms of (from a philosophical stand we would call this a reductionist\napproach) a single-particle picture. The harmonic oscillator will\nserve as an excellent starting point in building nuclei from the\nbottom and up. Here we will neglect nuclear forces, these are\nintroduced in the next section when we discuss the Hartree-Fock\nmethod.\n\nThe aim of this course is to develop our physics intuition of nuclear systems using a theoretical approach where we describe data in terms of \nthe motion of individual nucleons and their mutual interactions. \n\n**How our theoretical pictures and models can be used to interpret data is in essence what this course is about**. Our narrative will lead us along a path where we start with single-particle models and end with the theory of the nuclear shell-model. The latter will be used to understand and analyze excitation spectra and decay patterns of nuclei, linking our theoretical understanding with interpretations of experiment. The way we build up our theoretical descriptions and interpretations follows what we may call a standard reductionistic approach, that is we start with what we believe are our effective degrees of freedom (nucleons in our case) and interactions amongst these and solve thereafter the underlying equations of motions. This defines the nuclear many-body problem, and mean-field approaches like Hartree-Fock theory and the nuclear shell-model represent different approaches to our solutions of Schroedinger's equation.\n\n\n\n\n\n## Aims of this course\n\n\n\nThe aims of this course are to develop our physics intuition of nuclear\nsystems using a theoretical approach where we describe data in terms\nof the motion of individual nucleons and their mutual interactions.\n\n**How our theoretical pictures and models can be used to interpret data is in essence what this course is about**. Our narrative will lead us\nalong a path where we start with single-particle models and end with\nthe theory of the nuclear shell-model. The latter will be used to\nunderstand and analyze excitation spectra and decay patterns of\nnuclei, linking our theoretical understanding with interpretations of\nexperiment. The way we build up our theoretical descriptions and\ninterpretations follows what we may call a standard reductionistic\napproach, that is we start with what we believe are our effective\ndegrees of freedom (nucleons in our case) and interactions amongst\nthese and solve thereafter the underlying equations of motions. This\ndefines the nuclear many-body problem, and mean-field approaches like\nHartree-Fock theory and the nuclear shell-model represent different\napproaches to our solutions of Schroedinger's equation.\n\n\n\n\n\n\n\n\n## Back to the stability of matter questions\n**Do we understand the physics of dripline systems?**\n\n\nWe start our tour of experimental data and our interpretations by\nconsidering the chain of oxygen isotopes. In the exercises below you\nwill be asked to perform similar analyses for other chains of\nisotopes.\n\nThe oxygen isotopes are the heaviest isotopes for which the drip line\nis well established. The drip line is defined as the point where\nadding one more nucleon leads to an unbound nucleus. Below we will see\nthat we can define the dripline by studying the separation\nenergy. Where the neutron (proton) separation energy changes sign as a\nfunction of the number of neutrons (protons) defines the neutron\n(proton) drip line.\n\n\n\n\n\n## Back to the stability of matter questions\n**Do we understand the physics of dripline systems?**\n\n\n\nThe oxygen isotopes are simple enough to be described by some few\nselected single-particle degrees of freedom.\n\n* Two out of four stable even-even isotopes exhibit a doubly magic nature, namely ${}^{22}\\mbox{O}$ ($Z=8$, $N=14$) and ${}^{24}\\mbox{O}$ ($Z=8$, $N=16$).\n\n* The structure of ${}^{22}\\mbox{O}$ and ${}^{24}\\mbox{O}$ is assumed to be governed by the evolution of the $1s_{1/2}$ and $0d_{5/2}$ one-quasiparticle states.\n\n* The isotopes ${}^{25}\\mbox{O}$, ${}^{26}\\mbox{O}$, ${}^{27}\\mbox{O}$ and ${}^{28}\\mbox{O}$ are outside the drip line, since the $0d_{3/2}$ orbit is not bound.\n\n\n\n\n\n\n\n## Recent articles on Oxygen isotopes\n**Many experiments and theoretical calculations worldwide!**\n\n\n* ${}^{24}\\mbox{O}$ and lighter: C. R. Hoffman *et al.*, Phys. Lett. B **672**, 17 (2009); R. Kanungo *et al*., Phys. Rev. Lett.~**102**, 152501 (2009); C. R. Hoffman *et al*., Phys. Rev. C **83**, 031303(R) (2011); Stanoiu *et al*., Phys. Rev. C **69**, 034312 (2004)\n\n* ${}^{25}\\mbox{O}$: C. R. Hoffman *et al*., Phys. Rev. Lett. **102**,152501 (2009). \n\n* ${}^{26}\\mbox{O}$: E. Lunderberg *et al*., Phys. Rev. Lett. **108**, 142503 (2012). \n\n* ${}^{26}\\mbox{O}$: Z. Kohley *et al*., Study of two-neutron radioactivity in the decay of 26O, Phys. Rev. Lett., **110**, 152501 (2013). \n\n* Theory: Oxygen isotopes with three-body forces, Otsuka *et al*., Phys. Rev. Lett. **105**, 032501 (2010). Hagen *et al.*, Phys. Rev. Lett., **108**, 242501 (2012).\n\n\n\n\n\n## Do we understand the physics of dripline systems?\nOur first approach in analyzing data theoretically, is to see if we can use experimental information to \n\n* Extract information about a *so-called* single-particle behavior\n\n* And interpret such a behavior in terms of the underlying forces and microscopic physics\n\nThe next step is to see if we could use these interpretations to say something about shell closures and magic numbers. Since we focus on single-particle properties, a quantity we can extract from experiment is the separation energy for protons and neutrons. Before we proceed, we need to define quantities like masses and binding energies. Two excellent reviews on \nrecent trends in the determination of nuclear masses can be found in the articles of [Lunney and co-workers](http://journals.aps.org/rmp/abstract/10.1103/RevModPhys.75.1021) and [Blaum and co-workers](http://iopscience.iop.org/1402-4896/2013/T152/014017/)\n\n\n\n\n\n## Masses and Binding energies\nA basic quantity which can be measured for the ground states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with atomic mass number $A$ and charge $Z$. The number of neutrons is $N$.\n\nAtomic masses are usually tabulated in terms of the mass excess defined by\n\n$$\n\\Delta M(N, Z) = M(N, Z) - uA,\n$$\n\nwhere $u$ is the Atomic Mass Unit\n\n$$\nu = M(^{12}\\mathrm{C})/12 = 931.49386 \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n$$\n\nIn this course we will mainly use \ndata from the 2003 compilation of [Audi, Wapstra and Thibault](http://www.sciencedirect.com/science/journal/03759474/729/1).\n\n\n\n\n## Masses and Binding energies\nThe nucleon masses are\n\n$$\nm_p = 938.27203(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.00727646688(13)u,\n$$\n\nand\n\n$$\nm_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n$$\n\nIn the 2003 mass evaluation there are 2127 nuclei measured with an accuracy of 0.2\nMeV or better, and 101 nuclei measured with an accuracy of greater than 0.2 MeV. For\nheavy nuclei one observes several chains of nuclei with a constant $N-Z$ value whose masses are obtained from the energy released in $\\alpha$-decay.\n\n\n\n\n\n## Masses and Binding energies\nThe nuclear binding energy is defined as the energy required to break up a given nucleus\ninto its constituent parts of $N$ neutrons and $Z$ protons. In terms of the atomic masses $M(N, Z)$ the binding energy is defined by\n\n$$\nBE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n$$\n\nwhere $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\nIn terms of the mass excess the binding energy is given by\n\n$$\nBE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n$$\n\nwhere $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n\n\n\n\n## Masses and Binding energies\nThe following python program reads in the experimental data on binding energies and, stored in the file bindingenergies.dat, plots them as function of the mass number $A$. One notices clearly a saturation of the binding energy per nucleon at $A\\approx 56$.\n\n\n```\n%matplotlib inline\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/bindingenergies.dat\")\n# Make arrays containing x-axis and binding energies as function of A\nx = data[:,2]\nbexpt = data[:,3]\nplt.plot(x, bexpt ,'ro')\nplt.axis([0,270,-1, 10.0])\nplt.xlabel(r'$A$')\nplt.ylabel(r'Binding energies in [MeV]')\nplt.legend(('Experiment'), loc='upper right')\nplt.title(r'Binding energies from experiment')\nplt.savefig('expbindingenergies.pdf')\nplt.savefig('expbindingenergies.png')\nplt.show()\n```\n\n## Liquid drop model as a simple parametrization of binding energies\n\nA popular and physically intuitive model which can be used to parametrize \nthe experimental binding energies as function of $A$, is the so-called \nthe liquid drop model. The ansatz is based on the following expression\n\n$$\nBE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n$$\n\nwhere $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \nto the experimental data.\n\n\n\n\n## Liquid drop model as a simple parametrization of binding energies\nTo arrive at the above expression we have assumed that we can make the following assumptions:\n\n * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n\n * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.\n\n\n\n## Liquid drop model as a simple parametrization of binding energies, continues\n\n * There is a Coulomb energy term $a_3\\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. \n\n * There is an asymmetry term $a_4\\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflectd the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.\n\nWe could also add a so-called pairing term, which is a correction term that\narises from the tendency of proton pairs and neutron pairs to\noccur. An even number of particles is more stable than an odd number. \nPerforming a least-square fit to data, we obtain the following numerical values for the various constants\n* $a_1=15.49$ MeV\n\n* $a_2=17.23$ MeV\n\n* $a_3=0.697$ MeV\n\n* $a_4=22.6$ MeV\n\n\n\n\n\n\n## Masses and Binding energies\nThe following python program reads now in the experimental data on binding energies as well as the results from the above liquid drop model and plots these energies as function of the mass number $A$. One sees that for larger values of $A$, there is a better agreement with data.\n\n\n```\nimport numpy as np\nfrom matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/bindingenergies.dat\")\n# Make arrays containing x-axis and binding energies as function of\nx = data[:,2]\nbexpt = data[:,3]\nliquiddrop = data[:,4]\nplt.plot(x, bexpt ,'b-o', x, liquiddrop, 'r-o')\nplt.axis([0,270,-1, 10.0])\nplt.xlabel(r'$A$')\nplt.ylabel(r'Binding energies in [MeV]')\nplt.legend(('Experiment','Liquid Drop'), loc='upper right')\nplt.title(r'Binding energies from experiment and liquid drop')\nplt.savefig('bindingenergies.pdf')\nplt.savefig('bindingenergies.png')\nplt.show()\n```\n\n\n## Masses and Binding energies\nThe python program on the next slide reads now in the experimental data on binding energies and performs a nonlinear least square fitting of the data. In the example here we use only the parameters $a_1$ and $a_2$, leaving it as an exercise to the reader to perform the fit for all four paramters. The results are plotted and compared with the experimental values. To read more about non-linear least square methods, see for example the text of M.J. Box, D. Davies and W.H. Swann, Non-Linear optimisation Techniques, Oliver & Boyd, 1969.\n\n\n\n\n\n## Masses and Binding energies, the code\n\n\n```\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/bindingenergies.dat\")\n# Make arrays containing A on x-axis and binding energies\nA = data[:,2]\nbexpt = data[:,3]\n# The function we want to fit to, only two terms here\ndef func(A,a1, a2):\n return a1*A-a2*(A**(2.0/3.0))\n# function to perform nonlinear least square with guess for a1 and a2\npopt, pcov = curve_fit(func, A, bexpt, p0 = (16.0, 18.0))\na1 = popt[0]\na2 = popt[1]\nliquiddrop = a1*A-a2*(A**(2.0/3.0))\n\nplt.plot(A, bexpt ,'bo', A, liquiddrop, 'ro')\nplt.axis([0,270,-1, 10.0])\nplt.xlabel(r'$A$')\nplt.ylabel(r'Binding energies in [MeV]')\nplt.legend(('Experiment','Liquid Drop'), loc='upper right')\nplt.title(r'Binding energies from experiment and liquid drop')\nplt.savefig('bindingenergies.pdf')\nplt.savefig('bindingenergies.png')\nplt.show()\n```\n\n\n## $Q$-values and separation energies\nWe are now interested in interpreting experimental binding energies in terms of a single-particle picture.\nIn order to do so, we consider first energy conservation for nuclear transformations that include, for\nexample, the fusion of two nuclei $a$ and $b$ into the combined system $c$\n\n$$\n{^{N_a+Z_a}}a+ {^{N_b+Z_b}}b\\rightarrow {^{N_c+Z_c}}c\n$$\n\nor the decay of nucleus $c$ into two other nuclei $a$ and $b$\n\n$$\n^{N_c+Z_c}c \\rightarrow ^{N_a+Z_a}a+ ^{N_b+Z_b}b\n$$\n\n\n## $Q$-values and separation energies\nIn general we have the reactions\n\n$$\n\\sum_i {^{N_i+Z_i}}i \\rightarrow \\sum_f {^{N_f+Z_f}}f\n$$\n\nWe require also that the number of protons and neutrons (the total number of nucleons) is conserved in the initial stage and final stage, unless we have processes which violate baryon conservation,\n\n$$\n\\sum_iN_i = \\sum_f N_f \\hspace{0.2cm}\\mathrm{and} \\hspace{0.2cm}\\sum_iZ_i = \\sum_f Z_f.\n$$\n\n\n## Motivation\n**Do we understand the physics of dripline systems?**\n\nArtist's rendition of the emission of one proton from various oxygen isotopes. Protons are in red while neutrons are in blue. These processes could be interpreted as the decay\nnucleus $c$ into two other nuclei $a$ and $b$\n\n$$\n^{N_c+Z_c}c \\rightarrow ^{N_a+Z_a}a+ ^{N_b+Z_b}b .\n$$\n\n\n\n\nArtist's rendition of the emission of one proton from various oxygen isotopes.
\n\n\n\n\n\n\n\n\n## $Q$-values and separation energies\nThe above processes can be characterized by an energy difference called the $Q$ value, defined as\n\n$$\nQ=\\sum_i M(N_i, Z_i)c^2-\\sum_f M(N_f, Z_f)c^2=\\sum_i BE(N_f, Z_f)-\\sum_i BE(N_i, Z_i)\n$$\n\nSpontaneous decay involves a single initial nuclear state and is allowed if $Q > 0$. In the decay, energy is released in the form of the kinetic energy of the final products. Reactions involving two initial nuclei are called endothermic (a net loss of energy) if $Q < 0$. The reactions are exothermic (a net release of energy) if $Q > 0$.\n\n\n\n\n\n## $Q$-values and separation energies\nLet us study the Q values associated with the removal of one or two nucleons from\na nucleus. These are conventionally defined in terms of the one-nucleon and two-nucleon\nseparation energies. The neutron separation energy is defined as\n\n$$\nS_n= -Q_n= BE(N,Z)-BE(N-1,Z),\n$$\n\nand the proton separation energy reads\n\n$$\nS_p= -Q_p= BE(N,Z)-BE(N,Z-1).\n$$\n\nThe two-neutron separation energy is defined as\n\n$$\nS_{2n}= -Q_{2n}= BE(N,Z)-BE(N-2,Z),\n$$\n\nand the two-proton separation energy is given by\n\n$$\nS_{2p}= -Q_{2p}= BE(N,Z)-BE(N,Z-2).\n$$\n\n\n## Separation energies and energy gaps\nUsing say the neutron separation energies (alternatively the proton separation energies)\n\n$$\nS_n= -Q_n= BE(N,Z)-BE(N-1,Z),\n$$\n\nwe can define the so-called energy gap for neutrons (or protons) as\n\n$$\n\\Delta S_n= BE(N,Z)-BE(N-1,Z)-\\left(BE(N+1,Z)-BE(N,Z)\\right),\n$$\n\nor\n\n$$\n\\Delta S_n= 2BE(N,Z)-BE(N-1,Z)-BE(N+1,Z).\n$$\n\nThis quantity can in turn be used to determine which nuclei are magic or not. \nFor protons we would have\n\n$$\n\\Delta S_p= 2BE(N,Z)-BE(N,Z-1)-BE(N,Z+1).\n$$\n\nWe leave it as an exercise to the reader to define and interpret the two-neutron or two-proton gaps.\n\n\n\n\n\n## Separation energies for oxygen isotopes\nThe following python programs can now be used to plot the separation energies and the energy gaps for the oxygen isotopes. The following python code reads the separation energies from file for all oxygen isotopes from $A=13$ to $A=25$, The data are taken from the file *snox.dat*. This files contains the separation energies and the shell gap energies.\n\n\n```\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/snox.dat\")\n# Make arrays containing x-axis and binding energies as function of\nx = data[:,1]\ny = data[:,2]\n\nplt.plot(x, y,'b-+',markersize=6)\nplt.axis([4,18,-1, 25.0])\nplt.xlabel(r'Number of neutrons $N$',fontsize=20)\nplt.ylabel(r'$S_n$ [MeV]',fontsize=20)\nplt.legend(('Separation energies for oxygen isotpes'), loc='upper right')\nplt.title(r'Separation energy for the oxygen isotopes')\nplt.savefig('snoxygen.pdf')\nplt.savefig('snoxygen.png')\nplt.show()\n```\n\n\n## Energy gaps for oxygen isotopes\nHere we display the python program for plotting the corresponding results for shell gaps for the oxygen isotopes.\n\n\n```\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/snox.dat\")\n# Make arrays containing x-axis and binding energies as function of\nx = data[:,1]\ny = data[:,3]\n\nplt.plot(x, y,'b-+',markersize=6)\nplt.axis([4,18,-7, 12.0])\nplt.xlabel(r'Number of neutrons $N$',fontsize=20)\nplt.ylabel(r'$\\Delta S_n$ [MeV]',fontsize=20)\nplt.legend(('Shell gap energies for oxygen isotpes'), loc='upper right')\nplt.title(r'Shell gap energies for the oxygen isotopes')\nplt.savefig('gapoxygen.pdf')\nplt.savefig('gapoxygen.png')\nplt.show()\n```\n\n## Features to be noted\nSince we will focus in the beginning on single-particle degrees of freedom and mean-field approaches before we\nstart with nuclear forces and many-body approaches like the nuclear shell-model, there are some features to be noted\n\n* In the discussion of the liquid drop model and binding energies, we note that the total binding energy is not that different from the sum of the individual neutron and proton masses. \n\nOne may thus infer that intrinsic properties of nucleons in a nucleus are close to those of free nucleons.\n* In the discussion of the neutron separation energies for the oxygen isotopes, we note a clear staggering effect between odd and even isotopes with the even ones being more bound (larger separation energies). We will later link this to strong pairing correlations in nuclei.\n\n \n\n\n## Features to be noted, continues\n* The neutron separation energy becomes negative at ${}^{25}\\mbox{O}$, making this nucleus unstable with respect to the emission of one neutron. A nucleus like ${}^{24}\\mbox{O}$ is thus the last stable oxygen isotopes which has been observed. Oxygen-26 has been \"found\":\"journals.aps.org/prl/abstract/10.1103/PhysRevLett.108.142503\" to be unbound with respect to ${}^{24}\\mbox{O}$.\n\n* We note also that there are large shell-gaps for some nuclei, meaning that more energy is needed to remove one nucleon. These gaps are used to define so-called magic numbers. For the oxygen isotopes we see a clear gap for ${}^{16}\\mbox{O}$. We will interpret this gap as one of several experimental properties that define so-called magic numbers. In our discussion below we will make a first interpretation using single-particle states from the harmonic oscillator and the Woods-Saxon potential. \n\nIn the exercises below you will be asked to perform a similar analysis for other chains of isotopes and interpret the results.\n\n \n\n\n\n## Radii\nThe root-mean-square (rms) charge radius has been measured for the ground states of many\nnuclei. For a spherical charge density, $\\rho(\\boldsymbol{r})$, the mean-square radius is defined by\n\n$$\n\\langle r^2\\rangle = \\frac{ \\int d \\boldsymbol{r} \\rho(\\boldsymbol{r}) r^2}{ \\int d \\boldsymbol{r} \\rho(\\boldsymbol{r})},\n$$\n\nand the rms radius is the square root of this quantity denoted by\n\n$$\nR =\\sqrt{ \\langle r^2\\rangle}.\n$$\n\n## Radii\nRadii for most stable\nnuclei have been deduced from electron scattering form\nfactors and/or from the x-ray transition energies of muonic atoms. \nThe relative radii for a\nseries of isotopes can be extracted from the isotope shifts of atomic x-ray transitions.\nThe rms radius for the nuclear point-proton density, $R_p$ is obtained from the rms charge radius by:\n\n$$\nR_p = \\sqrt{R^2_{\\mathrm{ch}}- R^2_{\\mathrm{corr}}},\n$$\n\nwhere\n\n$$\nR^2_{\\mathrm{corr}}= R^2_{\\mathrm{op}}+(N/Z)R^2_{\\mathrm{on}}+R^2_{\\mathrm{rel}},\n$$\n\nwhere\n\n$$\nR_{\\mathrm{op}}= 0.875(7) \\mathrm{fm}.\n$$\n\nis the rms radius of the proton, $R^2_{\\mathrm{on}} = 0.116(2)$ $\\mbox{fm}^{2}$ is the\nmean-square radius of the neutron and $R^2_{\\mathrm{rel}} = 0.033$ $\\mbox{fm}^{2}$ is the relativistic Darwin-Foldy correction. There are additional smaller nucleus-dependent corrections.\n\n\n\n\n\n\n\n\n\n\n## Definitions\nWe will now introduce the potential models we have discussex above, namely the harmonic oscillator and the Woods-Saxon potentials. In order to proceed, we need some definitions.\n\nWe define an operator as $\\hat{O}$ throughout. Unless otherwise specified the total number of nucleons is\nalways $A$ and $d$ is the dimension of the system. In nuclear physics\nwe normally define the total number of particles to be $A=N+Z$, where\n$N$ is total number of neutrons and $Z$ the total number of\nprotons. In case of other baryons such as isobars $\\Delta$ or various\nhyperons such as $\\Lambda$ or $\\Sigma$, one needs to add their\ndefinitions. When we refer to a single neutron we will use the label $n$ and when we refer to a single proton we will use the label $p$. Unless otherwise specified, we will simply call these particles for nucleons.\n\n\n\n## Definitions\nThe quantum numbers of a single-particle state in coordinate space are\ndefined by the variables\n\n$$\nx=(\\boldsymbol{r},\\sigma),\n$$\n\nwhere\n\n$$\n\\boldsymbol{r}\\in {\\mathbb{R}}^{d},\n$$\n\nwith $d=1,2,3$ represents the spatial coordinates and $\\sigma$ is the eigenspin of the particle. For fermions with eigenspin $1/2$ this means that\n\n$$\nx\\in {\\mathbb{R}}^{d}\\oplus (\\frac{1}{2}),\n$$\n\nand the integral\n\n$$\n\\int dx = \\sum_{\\sigma}\\int d^dr = \\sum_{\\sigma}\\int d\\boldsymbol{r}.\n$$\n\nSince we are dealing with protons and neutrons we need to add isospin as a new degree of freedom.\n\n\n\n\n## Definitions\nIncluding isospin $\\tau$ we have\n\n$$\nx=(\\boldsymbol{r},\\sigma,\\tau),\n$$\n\nwhere\n\n$$\n\\boldsymbol{r}\\in {\\mathbb{R}}^{3},\n$$\n\nFor nucleons, which are fermions with eigenspin $1/2$ and isospin $1/2$ this means that\n\n$$\nx\\in {\\mathbb{R}}^{d}\\oplus (\\frac{1}{2})\\oplus (\\frac{1}{2}),\n$$\n\nand the integral\n\n$$\n\\int dx = \\sum_{\\sigma\\tau}\\int d\\boldsymbol{r},\n$$\n\nand\n\n$$\n\\int d^Ax= \\int dx_1\\int dx_2\\dots\\int dx_A.\n$$\n\nWe will use the standard nuclear physics definition of isospin, resulting in $\\tau_z=-1/2$ for protons and $\\tau_z=1/2$ for neutrons.\n\n\n\n\n\n\n## Definitions\nThe quantum mechanical wave function of a given state with quantum numbers $\\lambda$ (encompassing all quantum numbers needed to specify the system), ignoring time, is\n\n$$\n\\Psi_{\\lambda}=\\Psi_{\\lambda}(x_1,x_2,\\dots,x_A),\n$$\n\nwith $x_i=(\\boldsymbol{r}_i,\\sigma_i,\\tau_i)$ and the projections of $\\sigma_i$ and $\\tau_i$ take the values\n$\\{-1/2,+1/2\\}$. \nWe will hereafter always refer to $\\Psi_{\\lambda}$ as the exact wave function, and if the ground state is not degenerate we label it as\n\n$$\n\\Psi_0=\\Psi_0(x_1,x_2,\\dots,x_A).\n$$\n\n## Definitions\nSince the solution $\\Psi_{\\lambda}$ seldomly can be found in closed form, approximations are sought. In this text we define an approximative wave function or an ansatz to the exact wave function as\n\n$$\n\\Phi_{\\lambda}=\\Phi_{\\lambda}(x_1,x_2,\\dots,x_A),\n$$\n\nwith\n\n$$\n\\Phi_{0}=\\Phi_{0}(x_{1},x_{2},\\dots,x_{A}),\n$$\n\nbeing the ansatz for the ground state.\n\n\n\n\n## Definitions\nThe wave function $\\Psi_{\\lambda}$ is sought in the Hilbert space of either symmetric or anti-symmetric $N$-body functions, namely\n\n$$\n\\Psi_{\\lambda}\\in {\\cal H}_A:= {\\cal H}_1\\oplus{\\cal H}_1\\oplus\\dots\\oplus{\\cal H}_1,\n$$\n\nwhere the single-particle Hilbert space $\\hat{H}_1$ is the space of square integrable functions over $\\in {\\mathbb{R}}^{d}\\oplus (\\sigma)\\oplus (\\tau)$ resulting in\n\n$$\n{\\cal H}_1:= L^2(\\mathbb{R}^{d}\\oplus (\\sigma)\\oplus (\\tau)).\n$$\n\n## Definitions\nOur Hamiltonian is invariant under the permutation (interchange) of two particles.\nSince we deal with fermions however, the total wave function is antisymmetric.\nLet $\\hat{P}$ be an operator which interchanges two particles.\nDue to the symmetries we have ascribed to our Hamiltonian, this operator commutes with the total Hamiltonian,\n\n$$\n[\\hat{H},\\hat{P}] = 0,\n$$\n\nmeaning that $\\Psi_{\\lambda}(x_1, x_2, \\dots , x_A)$ is an eigenfunction of \n$\\hat{P}$ as well, that is\n\n$$\n\\hat{P}_{ij}\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_A)=\n\\beta\\Psi_{\\lambda}(x_1, x_2, \\dots,x_j,\\dots,x_i,\\dots,x_A),\n$$\n\nwhere $\\beta$ is the eigenvalue of $\\hat{P}$. We have introduced the suffix $ij$ in order to indicate that we permute particles $i$ and $j$.\nThe Pauli principle tells us that the total wave function for a system of fermions\nhas to be antisymmetric, resulting in the eigenvalue $\\beta = -1$.\n\n\n\n\n## Definitions and notations\nThe Schrodinger equation reads\n\n\n\n\n$$\n\\begin{equation}\n\\hat{H}(x_1, x_2, \\dots , x_A) \\Psi_{\\lambda}(x_1, x_2, \\dots , x_A) = \nE_\\lambda \\Psi_\\lambda(x_1, x_2, \\dots , x_A), \\label{eq:basicSE1} \\tag{1}\n\\end{equation}\n$$\n\nwhere the vector $x_i$ represents the coordinates (spatial, spin and isospin) of particle $i$, $\\lambda$ stands for all the quantum\nnumbers needed to classify a given $A$-particle state and $\\Psi_{\\lambda}$ is the pertaining eigenfunction. Throughout this course,\n$\\Psi$ refers to the exact eigenfunction, unless otherwise stated.\n\n\n\n## Definitions and notations\nWe write the Hamilton operator, or Hamiltonian, in a generic way\n\n$$\n\\hat{H} = \\hat{T} + \\hat{V}\n$$\n\nwhere $\\hat{T}$ represents the kinetic energy of the system\n\n$$\n\\hat{T} = \\sum_{i=1}^A \\frac{\\mathbf{p}_i^2}{2m_i} = \\sum_{i=1}^A \\left( -\\frac{\\hbar^2}{2m_i} \\mathbf{\\nabla_i}^2 \\right) =\n\t\t\\sum_{i=1}^A t(x_i)\n$$\n\nwhile the operator $\\hat{V}$ for the potential energy is given by\n\n\n\n\n$$\n\\begin{equation}\n\t\\hat{V} = \\sum_{i=1}^A \\hat{u}_{\\mathrm{ext}}(x_i) + \\sum_{ji=1}^A v(x_i,x_j)+\\sum_{ijk=1}^Av(x_i,x_j,x_k)+\\dots\n\\label{eq:firstv} \\tag{2}\n\\end{equation}\n$$\n\nHereafter we use natural units, viz. $\\hbar=c=e=1$, with $e$ the elementary charge and $c$ the speed of light. This means that momenta and masses\nhave dimension energy.\n\n\n\n\n\n## Definitions and notations\nThe potential energy part includes also an external potential $\\hat{u}_{\\mathrm{ext}}(x_i)$.\n\nIn a non-relativistic approach to atomic physics, this external potential is given by the attraction an electron feels from the atomic nucleus. The latter being much heavier than the involved electrons, is often used to define a natural center of mass. In nuclear physics there is no such external potential. It is the nuclear force which results in binding in nuclear systems. In a non-relativistic framework, the nuclear force contains two-body, three-body and more complicated degrees of freedom. The potential energy reads then\n\n$$\n\\hat{V} = \\sum_{ij}^A v(x_i,x_j)+\\sum_{ijk}^Av(x_i,x_j,x_k)+\\dots\n$$\n\n## Definitions and notations, more complicated forces\nThree-body and more complicated forces arise since we are dealing with protons and neutrons as effective degrees of freedom. We will come back to this topic later. Furthermore, in large parts of these lectures we will assume that the potential energy can be approximated by a two-body interaction only. Our Hamiltonian reads then\n\n\n\n\n$$\n\\begin{equation}\n\t\\hat{H} = \\sum_{i=1}^A \\frac{\\mathbf{p}_i^2}{2m_i}+\\sum_{ij}^A v(x_i,x_j).\n\\label{eq:firstH} \\tag{3}\n\\end{equation}\n$$\n\n## A modified Hamiltonian\nIt is however, from a computational point of view, convenient to introduce an external potential $\\hat{u}_{\\mathrm{ext}}(x_i)$ by adding and substracting it to the original Hamiltonian. \nThis means that our Hamiltonian can be rewritten as\n\n$$\n\\hat{H} = \\hat{H}_0 + \\hat{H}_I \n = \\sum_{i=1}^A \\hat{h}_0(x_i) + \\sum_{i < j=1}^A \\hat{v}(x_{ij})-\\sum_{i=1}^A\\hat{u}_{\\mathrm{ext}}(x_i),\n$$\n\nwith\n\n$$\n\\hat{H}_0=\\sum_{i=1}^A \\hat{h}_0(x_i) = \\sum_{i=1}^A\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right).\n$$\n\nThe interaction (or potential energy term) reads now\n\n$$\n\\hat{H}_I= \\sum_{i < j=1}^A \\hat{v}(x_{ij})-\\sum_{i=1}^A\\hat{u}_{\\mathrm{ext}}(x_i).\n$$\n\nIn nuclear physics the one-body part $u_{\\mathrm{ext}}(x_i)$ is often approximated by a harmonic oscillator potential or a\nWoods-Saxon potential. However, this is not fully correct, because as we have discussed, nuclei are self-bound systems and there is no external confining potential. As we will see later, *the $\\hat{H}_0$ part of the hamiltonian cannot be used to compute the binding energy of a nucleus since it is not based on a model for the nuclear forces*. That is, the binding energy is not the sum of the individual single-particle energies.\n\n\n\n\n## A modified Hamiltonian\nWhy do we introduce the Hamiltonian in the form\n\n$$\n\\hat{H} = \\hat{H}_0 + \\hat{H}_I?\n$$\n\nThere are many reasons for this. Let us look at some of them, using the harmonic oscillator in three dimensions as our starting point. For the harmonic oscillator we know that\n\n$$\n\\hat{h}_0(x_i)\\psi_{\\alpha}(x_i)=\\varepsilon_{\\alpha}\\psi_{\\alpha}(x_i),\n$$\n\nwhere the eigenvalues are $\\varepsilon_{\\alpha}$ and the eigenfunctions are $\\psi_{\\alpha}(x_i)$. The subscript $\\alpha$ represents quantum numbers like the orbital angular momentum $l_{\\alpha}$, its projection $m_{l_{\\alpha}}$ and the \nprincipal quantum number $n_{\\alpha}=0,1,2,\\dots$. \n\nThe eigenvalues are\n\n$$\n\\varepsilon_{\\alpha} = \\hbar\\omega \\left(2n_{\\alpha}+l_{\\alpha}+\\frac{3}{2}\\right).\n$$\n\n## A modified Hamiltonian\nThe following mathematical properties of the harmonic oscillator are handy. \n * First of all we have a complete basis of orthogonal eigenvectors. These have well-know expressions and can be easily be encoded. \n\n * With a complete basis $\\psi_{\\alpha}(x_i)$, we can construct a new basis $\\phi_{\\tau}(x_i)$ by expanding in terms of a harmonic oscillator basis, that is\n\n$$\n\\phi_{\\tau}(x_i)=\\sum_{\\alpha} C_{\\tau\\alpha}\\psi_{\\alpha}(x_i),\n$$\n\nwhere $C_{\\tau\\alpha}$ represents the overlap between the two basis sets. \n * As we will see later, the harmonic oscillator basis allows us to compute in an expedient way matrix elements of the interactions between two nucleons. Using the above expansion we can in turn represent nuclear forces in terms of new basis, for example the Woods-Saxon basis to be discussed later here.\n\n\n\n\n## A modified Hamiltonian\nThe harmonic oscillator (a shifted one by a negative constant) provides also a very good approximation to most bound single-particle states. Furthermore, it serves as a starting point in building up our picture of nuclei, in particular how we define magic numbers and systems with one nucleon added to (or removed from) a closed-shell core nucleus. The figure here shows \nthe various harmonic oscillator states, with those obtained with a Woods-Saxon potential as well, including a spin-orbit splitting (to be discussed below).\n\n\n\n\n\n## A modified Hamiltonian, harmonic oscillator spectrum\n\n\n\nSingle-particle spectrum and quantum numbers for a harmonic oscillator potential and a Woods-Saxon potential with and without a spin-orbit force.
\n\n\n\n\n\n\n\n\n\n\n\n\n## The harmonic oscillator Hamiltonian\nIn nuclear physics the one-body part $u_{\\mathrm{ext}}(x_i)$ is often \napproximated by a harmonic oscillator potential. However, as we also noted with the Woods-Saxon potential there is no \nexternal confining potential in nuclei. \n\nWhat many people do then, is to add and subtract a harmonic oscillator potential,\nwith\n\n$$\n\\hat{u}_{\\mathrm{ext}}(x_i)=\\hat{u}_{\\mathrm{ho}}(x_i)= \\frac{1}{2}m\\omega^2 r_i^2,\n$$\n\nwhere $\\omega$ is the oscillator frequency. This leads to\n\n$$\n\\hat{H} = \\hat{H_0} + \\hat{H_I} \n = \\sum_{i=1}^A \\hat{h}_0(x_i) + \\sum_{i < j=1}^A \\hat{v}(x_{ij})-\\sum_{i=1}^A\\hat{u}_{\\mathrm{ho}}(x_i),\n$$\n\nwith\n\n$$\nH_0=\\sum_{i=1}^A \\hat{h}_0(x_i) = \\sum_{i=1}^A\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ho}}(x_i)\\right).\n$$\n\nMany practitioners use this as the standard Hamiltonian when doing nuclear structure calculations. \nThis is ok if the number of nucleons is large, but still with this Hamiltonian, we do not obey translational invariance. How can we cure this?\n\n\n\n## Translationally Invariant Hamiltonian\n In setting up a translationally invariant Hamiltonian \n the following expressions are helpful.\n The center-of-mass (CoM) momentum is\n\n$$\nP=\\sum_{i=1}^A\\boldsymbol{p}_i,\n$$\n\nand we have that\n\n$$\n\\sum_{i=1}^A\\boldsymbol{p}_i^2 =\n \\frac{1}{A}\\left[\\boldsymbol{P}^2+\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2\\right]\n$$\n\nmeaning that\n\n$$\n\\left[\\sum_{i=1}^A\\frac{\\boldsymbol{p}_i^2}{2m} -\\frac{\\boldsymbol{P}^2}{2mA}\\right]\n =\\frac{1}{2mA}\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2.\n$$\n\n## The harmonic oscillator Hamiltonian\n In a similar fashion we can define the CoM coordinate\n\n$$\n\\boldsymbol{R}=\\frac{1}{A}\\sum_{i=1}^{A}\\boldsymbol{r}_i,\n$$\n\nwhich yields\n\n$$\n\\sum_{i=1}^A\\boldsymbol{r}_i^2 =\n \\frac{1}{A}\\left[A^2\\boldsymbol{R}^2+\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2\\right].\n$$\n\n## The harmonic oscillator Hamiltonian\n If we then introduce the harmonic oscillator one-body Hamiltonian\n\n$$\nH_0= \\sum_{i=1}^A\\left(\\frac{\\boldsymbol{p}_i^2}{2m}+\n\t \\frac{1}{2}m\\omega^2\\boldsymbol{r}_i^2\\right),\n$$\n\nwith $\\omega$ the oscillator frequency,\n we can rewrite the latter as\n\n\n\n\n$$\nH_{\\mathrm{HO}}= \\frac{\\boldsymbol{P}^2}{2mA}+\\frac{mA\\omega^2\\boldsymbol{R}^2}{2}\n\t +\\frac{1}{2mA}\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2\n\t +\\frac{m\\omega^2}{2A}\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2.\n\\label{eq:obho} \\tag{4}\n$$\n\n## The harmonic oscillator Hamiltonian\nAlternatively, we could write it as\n\n$$\nH_{\\mathrm{HO}}= H_{\\mathrm{CoM}}+\\frac{1}{2mA}\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2\n\t +\\frac{m\\omega^2}{2A}\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2,\n$$\n\nThe center-of-mass term is defined as\n\n$$\nH_{\\mathrm{CoM}}= \\frac{\\boldsymbol{P}^2}{2mA}+\\frac{mA\\omega^2\\boldsymbol{R}^2}{2}.\n$$\n\n## Translationally Invariant Hamiltonian\n The translationally invariant one- and two-body Hamiltonian reads for an A-nucleon system,\n\n\n\n\n$$\n\\label{eq:ham} \\tag{5}\n\\hat{H}=\\left[\\sum_{i=1}^A\\frac{\\boldsymbol{p}_i^2}{2m} -\\frac{\\boldsymbol{P}^2}{2mA}\\right] +\\sum_{i < j}^A V_{ij} \\; ,\n$$\n\nwhere $V_{ij}$ is the nucleon-nucleon interaction. Adding zero as here\n\n$$\n\\sum_{i=1}^A\\frac{1}{2}m\\omega^2\\boldsymbol{r}_i^2-\n \\frac{m\\omega^2}{2A}\\left[\\boldsymbol{R}^2+\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2\\right]=0.\n$$\n\nwe can then rewrite the Hamiltonian as\n\n$$\n\\hat{H}=\\sum_{i=1}^A \\left[ \\frac{\\boldsymbol{p}_i^2}{2m}\n +\\frac{1}{2}m\\omega^2 \\boldsymbol{r}^2_i\n \\right] + \\sum_{i < j}^A \\left[ V_{ij}-\\frac{m\\omega^2}{2A}\n (\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2\n \\right]-H_{\\mathrm{CoM}}.\n$$\n\n## The Woods-Saxon potential\nThe Woods-Saxon potential is a mean field potential for the nucleons (protons and neutrons) \ninside an atomic nucleus. It represent an average potential that a given nucleon feels from the forces applied on each nucleon. \nThe parametrization is\n\n$$\n\\hat{u}_{\\mathrm{ext}}(r)=-\\frac{V_0}{1+\\exp{(r-R)/a}},\n$$\n\nwith $V_0\\approx 50$ MeV representing the potential well depth, $a\\approx 0.5$ fm \nlength representing the \"surface thickness\" of the nucleus and $R=r_0A^{1/3}$, with $r_0=1.25$ fm and $A$ the number of nucleons.\nThe value for $r_0$ can be extracted from a fit to data, see for example [M. Kirson's article](http://www.sciencedirect.com/science/article/pii/S037594740600769X).\n\n\n\n\n## The Woods-Saxon potential\nThe following python code produces a plot of the Woods-Saxon potential with the above parameters.\n\n\n```\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import rc, rcParams\nimport matplotlib.units as units\nimport matplotlib.ticker as ticker\nrc('text',usetex=True)\nrc('font',**{'family':'serif','serif':['Woods-Saxon potential']})\nfont = {'family' : 'serif',\n 'color' : 'darkred',\n 'weight' : 'normal',\n 'size' : 16,\n }\nv0 = 50\nA = 100\na = 0.5\nr0 = 1.25\nR = r0*A**(0.3333)\nx = np.linspace(0.0, 10.0)\ny = -v0/(1+np.exp((x-R)/a))\n\nplt.plot(x, y, 'b-')\nplt.title(r'{\\bf Woods-Saxon potential}', fontsize=20) \nplt.text(3, -40, r'Parameters: $A=20$, $V_0=50$ [MeV]', fontdict=font)\nplt.text(3, -44, r'$a=0.5$ [fm], $r_0=1.25$ [fm]', fontdict=font)\nplt.xlabel(r'$r$ [fm]',fontsize=20)\nplt.ylabel(r'$V(r)$ [MeV]',fontsize=20)\n\n# Tweak spacing to prevent clipping of ylabel\nplt.subplots_adjust(left=0.15)\nplt.savefig('woodsaxon.pdf', format='pdf')\n```\n\nFrom the plot we notice that the potential\n* rapidly approaches zero as $r$ goes to infinity, reflecting the short-distance nature of the strong nuclear force.\n\n* For large $A$, it is approximately flat in the center.\n\n* Nucleons near the surface of the nucleus experience a large force towards the center.\n\n\n\n\n\n\n## Single-particle Hamiltonians and spin-orbit force\nWe have introduced a single-particle Hamiltonian\n\n$$\nH_0=\\sum_{i=1}^A \\hat{h}_0(x_i) = \\sum_{i=1}^A\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right),\n$$\n\nwith an external and central symmetric potential $u_{\\mathrm{ext}}(x_i)$, which is often \napproximated by a harmonic oscillator potential or a Woods-Saxon potential. Being central symmetric leads to a degeneracy \nin energy which is not observed experimentally. We see this from for example our discussion of separation energies and magic numbers. There are, in addition to the assumed magic numbers from a harmonic oscillator basis of $2,8,20,40,70\\dots$ magic numbers like $28$, $50$, $82$ and $126$. \n\nTo produce these additional numbers, we need to add a phenomenological spin-orbit force which lifts the degeneracy, that is\n\n$$\n\\hat{h}(x_i) = \\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i) +\\xi(\\boldsymbol{r})\\boldsymbol{ls}=\\hat{h}_0(x_i)+\\xi(\\boldsymbol{r})\\boldsymbol{ls}.\n$$\n\n## Single-particle Hamiltonians and spin-orbit force\nWe have introduced a modified single-particle Hamiltonian\n\n$$\n\\hat{h}(x_i) = \\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i) +\\xi(\\boldsymbol{r})\\boldsymbol{ls}=\\hat{h}_0(x_i)+\\xi(\\boldsymbol{r})\\boldsymbol{ls}.\n$$\n\nWe can calculate the expectation value of the latter using the fact that\n\n$$\n\\xi(\\boldsymbol{r})\\boldsymbol{ls}=\\frac{1}{2}\\xi(\\boldsymbol{r})\\left(\\boldsymbol{j}^2-\\boldsymbol{l}^2-\\boldsymbol{s}^2\\right).\n$$\n\nFor a single-particle state with quantum numbers $nlj$ (we suppress $s$ and $m_j$), with $s=1/2$, we obtain the single-particle energies\n\n$$\n\\varepsilon_{nlj} = \\varepsilon_{nlj}^{(0)}+\\Delta\\varepsilon_{nlj},\n$$\n\nwith $\\varepsilon_{nlj}^{(0)}$ being the single-particle energy obtained with $\\hat{h}_0(x)$ and\n\n$$\n\\Delta\\varepsilon_{nlj}=\\frac{C}{2}\\left(j(j+1)-l(l+1)-\\frac{3}{4}\\right).\n$$\n\n## Single-particle Hamiltonians and spin-orbit force\nThe spin-orbit force gives thus an additional contribution to the energy\n\n$$\n\\Delta\\varepsilon_{nlj}=\\frac{C}{2}\\left(j(j+1)-l(l+1)-\\frac{3}{4}\\right),\n$$\n\nwhich lifts the degeneracy we have seen before in the harmonic oscillator or Woods-Saxon potentials. The value $C$ is the radial\nintegral involving $\\xi(\\boldsymbol{r})$. Depending on the value of $j=l\\pm 1/2$, we obtain\n\n$$\n\\Delta\\varepsilon_{nlj=l-1/2}=\\frac{C}{2}l,\n$$\n\nor\n\n$$\n\\Delta\\varepsilon_{nlj=l+1/2}=-\\frac{C}{2}(l+1),\n$$\n\nclearly lifting the degeneracy. Note well that till now we have simply postulated the spin-orbit force in *ad hoc* way.\nLater, we will see how this term arises from the two-nucleon force in a natural way.\n\n\n\n## Single-particle Hamiltonians and spin-orbit force\nWith the spin-orbit force, we can modify our Woods-Saxon potential to\n\n$$\n\\hat{u}_{\\mathrm{ext}}(r)=-\\frac{V_0}{1+\\exp{(r-R)/a}}+V_{so}(r)\\boldsymbol{ls},\n$$\n\nwith\n\n$$\nV_{so}(r) = V_{so}\\frac{1}{r}\\frac{d f_{so}(r)}{dr},\n$$\n\nwhere we have\n\n$$\nf_{so}(r) = \\frac{1}{1+\\exp{(r-R_{so})/a_{so}}}.\n$$\n\n\nWe can also add, in case of proton, a Coulomb potential. The\nWoods-Saxon potential has been widely used in parametrizations of\neffective single-particle potentials. \n\n**However, as was the case with\nthe harmonic oscillator, none of these potentials are linked directly\nto the nuclear forces**. \n\nOur next step is to build a mean field based\non the nucleon-nucleon interaction. This will lead us to our first\nand simplest many-body theory, Hartree-Fock theory.\n\n\n\n\n\n\n## Single-particle Hamiltonians and spin-orbit force\nThe Woods-Saxon potential does not give us closed-form or analytical solutions of the eigenvalue problem\n\n$$\n\\hat{h}_0(x_i)\\psi_{\\alpha}(x_i)=\\varepsilon_{\\alpha}\\psi_{\\alpha}(x_i).\n$$\n\nFor the harmonic oscillator in three dimensions we have closed-form expressions for the energies and analytical solutions for the eigenstates,\nwith the latter given by either Hermite polynomials (cartesian coordinates) or Laguerre polynomials (spherical coordinates).\n\nTo solve the above equation is however rather straightforward numerically.\n\n\n\n## Numerical solution of the single-particle Schroedinger equation\nWe will illustrate the numerical solution of Schroedinger's equation by solving it for the harmonic oscillator in three dimensions.\nIt is straightforward to change the harmonic oscillator potential with a Woods-Saxon potential, or any other type of potentials. \n\nWe are interested in the solution of the radial part of Schroedinger's equation for one nucleon. \nThe angular momentum part is given by the so-called Spherical harmonics. \n\nThe radial equation reads\n\n$$\n-\\frac{\\hbar^2}{2 m} \\left ( \\frac{1}{r^2} \\frac{d}{dr} r^2\n \\frac{d}{dr} - \\frac{l (l + 1)}{r^2} \\right )R(r) \n + V(r) R(r) = E R(r).\n$$\n\n## Numerical solution of the single-particle Schroedinger equation\nIn our case $V(r)$ is the harmonic oscillator potential $(1/2)kr^2$ with\n$k=m\\omega^2$ and $E$ is\nthe energy of the harmonic oscillator in three dimensions.\nThe oscillator frequency is $\\omega$ and the energies are\n\n$$\nE_{nl}= \\hbar \\omega \\left(2n+l+\\frac{3}{2}\\right),\n$$\n\nwith $n=0,1,2,\\dots$ and $l=0,1,2,\\dots$.\n\n\n\n\n\n## Numerical solution of the single-particle Schroedinger equation\nSince we have made a transformation to spherical coordinates it means that \n$r\\in [0,\\infty)$. \nThe quantum number\n$l$ is the orbital momentum of the nucleon. Then we substitute $R(r) = (1/r) u(r)$ and obtain\n\n$$\n-\\frac{\\hbar^2}{2 m} \\frac{d^2}{dr^2} u(r) \n + \\left ( V(r) + \\frac{l (l + 1)}{r^2}\\frac{\\hbar^2}{2 m}\n \\right ) u(r) = E u(r) .\n$$\n\nThe boundary conditions are $u(0)=0$ and $u(\\infty)=0$.\n\n\n\n\n## Numerical solution of the single-particle Schroedinger equation\nWe introduce a dimensionless variable $\\rho = (1/\\alpha) r$\nwhere $\\alpha$ is a constant with dimension length and get\n\n$$\n-\\frac{\\hbar^2}{2 m \\alpha^2} \\frac{d^2}{d\\rho^2} u(\\rho) \n + \\left ( V(\\rho) + \\frac{l (l + 1)}{\\rho^2}\n \\frac{\\hbar^2}{2 m\\alpha^2} \\right ) u(\\rho) = E u(\\rho) .\n$$\n\nLet us specialize to $l=0$. \nInserting $V(\\rho) = (1/2) k \\alpha^2\\rho^2$ we end up with\n\n$$\n-\\frac{\\hbar^2}{2 m \\alpha^2} \\frac{d^2}{d\\rho^2} u(\\rho) \n + \\frac{k}{2} \\alpha^2\\rho^2u(\\rho) = E u(\\rho) .\n$$\n\nWe multiply thereafter with $2m\\alpha^2/\\hbar^2$ on both sides and obtain\n\n$$\n-\\frac{d^2}{d\\rho^2} u(\\rho) \n + \\frac{mk}{\\hbar^2} \\alpha^4\\rho^2u(\\rho) = \\frac{2m\\alpha^2}{\\hbar^2}E u(\\rho) .\n$$\n\n## Numerical solution of the single-particle Schroedinger equation\nWe have thus\n\n$$\n-\\frac{d^2}{d\\rho^2} u(\\rho) \n + \\frac{mk}{\\hbar^2} \\alpha^4\\rho^2u(\\rho) = \\frac{2m\\alpha^2}{\\hbar^2}E u(\\rho) .\n$$\n\nThe constant $\\alpha$ can now be fixed\nso that\n\n$$\n\\frac{mk}{\\hbar^2} \\alpha^4 = 1,\n$$\n\nor\n\n$$\n\\alpha = \\left(\\frac{\\hbar^2}{mk}\\right)^{1/4}.\n$$\n\n## Numerical solution of the single-particle Schroedinger equation\nDefining\n\n$$\n\\lambda = \\frac{2m\\alpha^2}{\\hbar^2}E,\n$$\n\nwe can rewrite Schroedinger's equation as\n\n$$\n-\\frac{d^2}{d\\rho^2} u(\\rho) + \\rho^2u(\\rho) = \\lambda u(\\rho) .\n$$\n\nThis is the first equation to solve numerically. In three dimensions \nthe eigenvalues for $l=0$ are \n$\\lambda_0=3,\\lambda_1=7,\\lambda_2=11,\\dots .$\n\n\n\n\n\n## Numerical solution of the single-particle Schroedinger equation\nWe use the standard\nexpression for the second derivative of a function $u$\n\n\n\n\n$$\n\\begin{equation}\n u''=\\frac{u(\\rho+h) -2u(\\rho) +u(\\rho-h)}{h^2} +O(h^2),\n\\label{eq:diffoperation} \\tag{6}\n\\end{equation}\n$$\n\nwhere $h$ is our step.\nNext we define minimum and maximum values for the variable $\\rho$,\n$\\rho_{\\mathrm{min}}=0$ and $\\rho_{\\mathrm{max}}$, respectively.\nYou need to check your results for the energies against different values\n$\\rho_{\\mathrm{max}}$, since we cannot set\n$\\rho_{\\mathrm{max}}=\\infty$.\n\n\n\n\n## Numerical solution of the single-particle Schroedinger equation\nWith a given number of steps, $n_{\\mathrm{step}}$, we then \ndefine the step $h$ as\n\n$$\nh=\\frac{\\rho_{\\mathrm{max}}-\\rho_{\\mathrm{min}} }{n_{\\mathrm{step}}}.\n$$\n\nDefine an arbitrary value of $\\rho$ as\n\n$$\n\\rho_i= \\rho_{\\mathrm{min}} + ih \\hspace{1cm} i=0,1,2,\\dots , n_{\\mathrm{step}}\n$$\n\nwe can rewrite the Schroedinger equation for $\\rho_i$ as\n\n$$\n-\\frac{u(\\rho_i+h) -2u(\\rho_i) +u(\\rho_i-h)}{h^2}+\\rho_i^2u(\\rho_i) = \\lambda u(\\rho_i),\n$$\n\nor in a more compact way\n\n$$\n-\\frac{u_{i+1} -2u_i +u_{i-1}}{h^2}+\\rho_i^2u_i=-\\frac{u_{i+1} -2u_i +u_{i-1} }{h^2}+V_iu_i = \\lambda u_i.\n$$\n\n## Numerical solution of the single-particle Schroedinger equation\nDefine first the diagonal matrix element\n\n$$\nd_i=\\frac{2}{h^2}+V_i,\n$$\n\nand the non-diagonal matrix element\n\n$$\ne_i=-\\frac{1}{h^2}.\n$$\n\nIn this case the non-diagonal matrix elements are given by a mere constant. *All non-diagonal matrix elements are equal*.\n\n\n\n\n## Numerical solution of the single-particle Schroedinger equation\nWith these definitions the Schroedinger equation takes the following form\n\n$$\nd_iu_i+e_{i-1}u_{i-1}+e_{i+1}u_{i+1} = \\lambda u_i,\n$$\n\nwhere $u_i$ is unknown. We can write the \nlatter equation as a matrix eigenvalue problem\n\n\n\n\n$$\n\\begin{equation}\n \\left( \\begin{array}{ccccccc} d_1 & e_1 & 0 & 0 & \\dots &0 & 0 \\\\\n e_1 & d_2 & e_2 & 0 & \\dots &0 &0 \\\\\n 0 & e_2 & d_3 & e_3 &0 &\\dots & 0\\\\\n \\dots & \\dots & \\dots & \\dots &\\dots &\\dots & \\dots\\\\\n 0 & \\dots & \\dots & \\dots &\\dots &d_{n_{\\mathrm{step}}-2} & e_{n_{\\mathrm{step}}-1}\\\\\n 0 & \\dots & \\dots & \\dots &\\dots &e_{n_{\\mathrm{step}}-1} & d_{n_{\\mathrm{step}}-1}\n \\end{array} \\right) \\left( \\begin{array}{c} u_{1} \\\\\n u_{2} \\\\\n \\dots\\\\ \\dots\\\\ \\dots\\\\\n u_{n_{\\mathrm{step}}-1}\n \\end{array} \\right)=\\lambda \\left( \\begin{array}{c} u_{1} \\\\\n u_{2} \\\\\n \\dots\\\\ \\dots\\\\ \\dots\\\\\n u_{n_{\\mathrm{step}}-1}\n \\end{array} \\right) \n\\label{eq:sematrix} \\tag{7}\n\\end{equation}\n$$\n\n## Numerical solution of the single-particle Schroedinger equation\n\nTo be more detailed we have\n\n\n\n\n$$\n\\begin{equation}\n \\left( \\begin{array}{ccccccc} \\frac{2}{h^2}+V_1 & -\\frac{1}{h^2} & 0 & 0 & \\dots &0 & 0 \\\\\n -\\frac{1}{h^2} & \\frac{2}{h^2}+V_2 & -\\frac{1}{h^2} & 0 & \\dots &0 &0 \\\\\n 0 & -\\frac{1}{h^2} & \\frac{2}{h^2}+V_3 & -\\frac{1}{h^2} &0 &\\dots & 0\\\\\n \\dots & \\dots & \\dots & \\dots &\\dots &\\dots & \\dots\\\\\n 0 & \\dots & \\dots & \\dots &\\dots &\\frac{2}{h^2}+V_{n_{\\mathrm{step}}-2} & -\\frac{1}{h^2}\\\\\n 0 & \\dots & \\dots & \\dots &\\dots &-\\frac{1}{h^2} & \\frac{2}{h^2}+V_{n_{\\mathrm{step}}-1}\n \\end{array} \\right) \n\\label{eq:matrixse} \\tag{8} \n\\end{equation}\n$$\n\nRecall that the solutions are known via the boundary conditions at\n$i=n_{\\mathrm{step}}$ and at the other end point, that is for $\\rho_0$.\nThe solution is zero in both cases.\n\n\n\n\n\n## Program to solve Schroedinger's equation\nThe following python program is an example of how one can obtain the eigenvalues for a single-nucleon moving in a harmonic oscillator potential. It is rather easy to change the onebody-potential with ones like a Woods-Saxon potential. \n\n\n* The c++ and Fortran versions of this program can be found atSchematic plot of the possible single-particle levels with double degeneracy. The filled circles indicate occupied particle states. The spacing between each level $p$ is constant in this picture. We show some possible two-particle states.
\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6fb963e51df714e9ec5291ec4076515638c15c91", "size": 104182, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/spdata/ipynb/spdata.ipynb", "max_stars_repo_name": "NuclearTalent/NuclearStructure", "max_stars_repo_head_hexsha": "7d18ed926172abeea358e95f4e95415e7b0a3498", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-07-04T16:21:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-24T18:10:11.000Z", "max_issues_repo_path": "doc/pub/spdata/ipynb/spdata.ipynb", "max_issues_repo_name": "NuclearTalent/NuclearStructure", "max_issues_repo_head_hexsha": "7d18ed926172abeea358e95f4e95415e7b0a3498", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/pub/spdata/ipynb/spdata.ipynb", "max_forks_repo_name": "NuclearTalent/NuclearStructure", "max_forks_repo_head_hexsha": "7d18ed926172abeea358e95f4e95415e7b0a3498", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-06-30T16:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-01T07:54:49.000Z", "avg_line_length": 33.2318979266, "max_line_length": 947, "alphanum_fraction": 0.5723349523, "converted": true, "num_tokens": 19902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.24508500761839527, "lm_q1q2_score": 0.07946523522940015}} {"text": "```python\n%matplotlib inline\nimport pandas as pd\n\nimport numpy as np\nfrom __future__ import division\nimport itertools\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.rcParams['axes.grid'] = False\nplt.rcParams['figure.figsize'] = (10,16)\n\nimport logging\nlogger = logging.getLogger()\n```\n\n7 Clustering\n=======\n\n**Goal**: points in the same cluster have a small distance from one other, while points in different clusters are at a large distance from one another.\n\n### 7.1 Introduction to Clustering Techniques\n#### 7.1.1 Points, Spaces, Distances\nA dataset suitable for clustering is a collection of points, which are objects belonging to some space.\n\ndistance measure: \n1. nonnegative. \n2. symmetric. \n3. obey the triangle inequality. \n\n#### 7.1.2 Clustering Strategies\ntwo groups: \n1. Hierarchinal or agglomerative algorithms. \n Combine, bottom-to-top.\n \n2. Point assignment. \n iteration\n \n \nA key distinction: \nEuclidean space can summarize a collection of points by their *centroid*.\n\n### 7.1.3 The Curse of Dimensionality\nIt refers that a number of unintuitive properties of high-dimensional Euclidean space.\n\n1. Almost all pairs of points are equally far away from one another.\n\n2. Almost any two vectors are almost orthogomal.\n\n`%todo: Proof`\n\n#### 7.1.4 Exercises for Section 7.1\n##### 7.1.1\n\\begin{align}\nE[d(x,y)] &= \\int_{y=0}^1 \\int_{x=0}^1 |x - y| \\, \\mathrm{d}x \\, \\mathrm{d}y \\\\\n &= \\int_{y=0}^1 \\int_{x=0}^{y} (y-x) \\, \\mathrm{d}x + \\int_{x=y}^{1} (x-y) \\, \\mathrm{d}x \\, \\mathrm{d}y \\\\\n &= \\int_{y=0}^1 \\frac{1}{2} y^2 + \\frac{1}{2} (1-y)^2 \\, \\mathrm{d}y \\\\\n &= \\frac{1}{3}\n\\end{align}\n\n#### 7.1.2 \nBecause: $$\\sqrt{\\frac{{|x_1|}^2+{|x_2|}^2}{2}} \\geq \\frac{|x_1|+|x_2|}{2}$$\nWe have:\n$$\\sqrt{\\frac{{|x_1 - x_2|}^2+{|y_1 - y_2|}^2}{2}} \\geq \\frac{|x_1 - x_2|+|y_1 - y_2|}{2}$$\nSo:\n$$E[d(\\mathbf{x}, \\mathbf{y})] \\geq \\frac{\\sqrt{2}}{3}$$\n\nWhile:\n$$\\sqrt{{|x_1 - x_2|}^2+{|y_1 - y_2|}^2} \\leq |x_1 - x_2|+|y_1 - y_2|$$\nSo:\n$$E[d(\\mathbf{x}, \\mathbf{y})] \\leq \\frac{2}{3}$$\n\nAbove all:\n$$\\frac{\\sqrt{2}}{3} \\leq E[d(\\mathbf{x}, \\mathbf{y})] \\leq \\frac{2}{3}$$\n\n#### 7.1.3\nfor $x_i y_i$ of numerator, there are four cases: $1=1\\times1, 1=-1\\times-1$ and $-1=1\\times-1, -1=-1\\times1$. So both 1 and -1 are $\\frac{1}{2}$ probility. So the expected value of their sum is 0.\n\nHence, the expected value of cosine is 0, as $d$ grows large. \n\n### 7.2 Hierarchinal Clustering\nThis algorithm can only be used for relatively small datasets.\n\nprocedure: \nWe begin with every point in its own cluster. As time goes on, larger clusters will be constructed by combining two smaller clusters. \nHence we have to decide in advance: \n\n1. How to represent cluster? \n + For Euclidean space, use centriod. \n + For Non-Euclidean space, use clustroid. \n **clustroid**: \n - the point is close to all the points of the cluster. \n - minimizes the sum of the distance to the other points. \n - minimizes the maximum distance to another point. \n - minimizes the sum of the squares of the distances to the other points. \n\n2. How to choose clusters to merge? \n + shortest distance between clusters. \n + the minimum of the distance between any two points. \n + the average distance of all pairs of points. \n + Combine the two clusters whose resulting cluster has the lowerst radius(the maximum distance between all the points and the centriod). \n modification: \n - lowest average distance between a point and the centriod. \n - the sum of the squares of the distances between the points and the centriod. \n + Cobine the two clusters whose resulting cluster has the smallest diameter(the maximum distance between any two points of the cluster). \n The radius and diameter are not related directly, but there is a tendecy for them to be proportional.\n\n3. When to stop? \n + how many clusters expected? \n + When at some point the best combination of existing clusters produces a cluster that is inadequate. \n - threshold of average distance of points to its centriod. \n - threshold of the diameter of the new cluster. \n - threshold of the density of the new cluster. \n - track the average diameter of all the current clusters. stop if take a sudden jump.\n + reach one cluster. $\\to$ tree. \n eg. genome $\\to$ common ancestor. \n \nThere is no substantial change in the option for stopping citeria and combining citeria when we move from Euclidean to Non-Euclidean spaces.\n\n\n```python\n# Example 7.2\nlogger.setLevel('WARN')\n\npoints = np.array([\n [4, 10],\n [7, 10],\n [4, 8],\n [6, 8],\n [3, 4],\n [10, 5],\n [12, 6],\n [11, 4],\n [2, 2],\n [5, 2],\n [9, 3],\n [12, 3]\n ],\n dtype=np.float\n)\n\nx, y = points[:,0], points[:,1]\ncluster = range(len(x))\n#cluster_colors = plt.get_cmap('hsv')(np.linspace(0, 1.0, len(cluster)))\ncluster_colors = sns.color_palette(\"hls\", len(cluster))\nplt.scatter(x, y, c=map(lambda x: cluster_colors[x], cluster))\n\ndf_points = pd.DataFrame({\n 'x': x,\n 'y': y,\n 'cluster': cluster \n }\n)\ndf_points\n```\n\n\n```python\nlogger.setLevel('WARN')\n\nclass Hierarchical_cluster():\n def __init__(self):\n pass\n def clustroid_calc(self, df_points, calc_func=np.mean):\n clustroid = df_points.groupby('cluster').aggregate(calc_func) \n logger.info('\\n clustroid:{}'.format(clustroid))\n \n return clustroid\n \n def candidate_merge(self, clustroid):\n from scipy.spatial.distance import pdist, squareform\n \n clustroid_array = clustroid.loc[:,['x','y']].as_matrix()\n dist = squareform(pdist(clustroid_array, 'euclidean'))\n cluster = clustroid.index\n \n df_dist = pd.DataFrame(dist, index=cluster, columns=cluster)\n df_dist.replace(0, np.nan, inplace=True)\n logger.info('\\n dist:{}'.format(df_dist))\n \n flat_index = np.nanargmin(df_dist.as_matrix())\n candidate_iloc = np.unravel_index(flat_index, df_dist.shape)\n candidate_loc = [cluster[x] for x in candidate_iloc]\n logger.info('candidate cluster:{}'.format(candidate_loc))\n \n new_cluster, old_cluster = candidate_loc\n return new_cluster, old_cluster \n \n def combine(self, df_points, show=False):\n clustroid = self.clustroid_calc(df_points)\n \n new_cluster, old_cluster = self.candidate_merge(clustroid)\n df_points.cluster.replace(old_cluster, new_cluster, inplace=True)\n \n new_order, old_order = df_points.merge_order[[new_cluster, old_cluster]]\n df_points.merge_order[new_cluster] = {'l': new_order, 'r': old_order}\n \n if show:\n plt.figure()\n plt.scatter(df_points.x, df_points.y, c=map(lambda x: cluster_colors[x], df_points.cluster))\n \n return df_points\n \n def cluster(self, df_points, cluster_nums=1, show=False):\n assert cluster_nums > 0, 'The number of cluster should be positive.'\n \n df_points['merge_order'] = [[x] for x in range(len(df_points.x))]\n \n while len(set(df_points.cluster)) > cluster_nums:\n df_points = self.combine(df_points, show)\n```\n\n\n```python\nlogger.setLevel('WARN')\ndf_p = df_points.copy()\n\ntest = Hierarchical_cluster()\ntest.cluster(df_p, 1, show=True)\n```\n\n\n```python\nimport json\nprint json.dumps(df_p.merge_order[0], sort_keys=True, indent=4)\n```\n\n {\n \"l\": {\n \"l\": {\n \"l\": {\n \"l\": {\n \"l\": [\n 0\n ], \n \"r\": [\n 2\n ]\n }, \n \"r\": [\n 3\n ]\n }, \n \"r\": [\n 1\n ]\n }, \n \"r\": {\n \"l\": {\n \"l\": [\n 4\n ], \n \"r\": [\n 8\n ]\n }, \n \"r\": [\n 9\n ]\n }\n }, \n \"r\": {\n \"l\": {\n \"l\": {\n \"l\": {\n \"l\": [\n 5\n ], \n \"r\": [\n 7\n ]\n }, \n \"r\": [\n 6\n ]\n }, \n \"r\": [\n 11\n ]\n }, \n \"r\": [\n 10\n ]\n }\n }\n\n\n#### Efficiency\nThe algorithm is $O(n^3) = \\sum_{i=n}^{2} C_n^2$, since it computes the distances between each pair of clusters in iteration.\n\nOptimize: \n1. At first, computing the distance between all pairs. $O(n^2)$.\n\n2. Save the distances information into a priority queue, in order to get the smallest distance in one step. $O(n^2)$.\n\n3. When merging two clusters, we remove all entries involving them in the priority queue. $O(n \\lg n) = 2n \\times O(\\lg n)$.\n\n4. Compute all the distances between the new cluster and the remaining clusters.\n\n### 7.3 K-means Algorithms\nAssumptions: 1. Euclidean space; 2. $k$ is known in advance.\n\nThe heart of the algortim is the for-loop, in which we consider each point and assign it to the \"closest\" cluster.\n\n\n```python\nplt.figure(figsize=(10,16))\nplt.imshow(plt.imread('./res/fig7_7.png'))\n```\n\n#### 7.3.2 Initializing Clusters for K-Means\nWe want to pick points that have a good chance of lying in different clusters.\n\ntwo approaches:\n\n1. Cluster a sample of the data, and pick a point from the $k$ clusters.\n\n2. Pick points that are as far away from one another as possible.\n\n```\nPick the first point at random;\nWHILE there are fewer than k points DO\n ADD the point whose minimum disance from the selected points is as large as possible;\nEND;\n```\n\n#### 7.3.3 Picking the Right Value of k\nIf we take a measure of appropriateness for clusters, then we can use it to measure the quality of the clustering for various values of $k$ and so the right value of $k$ is guessed.\n\n\n```python\nplt.figure(figsize=(10,16))\nplt.imshow(plt.imread('./res/fig7_9.png'))\n```\n\nWe can use a binary search to find the best values for $k$.\n\n\n```python\nplt.scatter(df_points.x, df_points.y)\n```\n\n\n```python\ndf_points['cluster'] = 0\ndf_points\n```\n\n\n\n\n| \n | cluster | \nx | \ny | \n
|---|---|---|---|
| 0 | \n0 | \n4 | \n10 | \n
| 1 | \n0 | \n7 | \n10 | \n
| 2 | \n0 | \n4 | \n8 | \n
| 3 | \n0 | \n6 | \n8 | \n
| 4 | \n0 | \n3 | \n4 | \n
| 5 | \n0 | \n10 | \n5 | \n
| 6 | \n0 | \n12 | \n6 | \n
| 7 | \n0 | \n11 | \n4 | \n
| 8 | \n0 | \n2 | \n2 | \n
| 9 | \n0 | \n5 | \n2 | \n
| 10 | \n0 | \n9 | \n3 | \n
| 11 | \n0 | \n12 | \n3 | \n
\n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n\n**Result:**\n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n**Now it's your turn to have some Markdown fun.** In the next cell, try out some of the commands. You can just throw in some things, or do something more structured (like a small notebook).\n\n
Now let's see what is this thing called paragraph. Hmmm looks interesting.
\n\nActually I can put new lines and new paragraphs.
Awsome!
Let's see how we can put image to our first try with Markdown.
\n\n\nNow let's try some text formats in a paragraph.
\n Here is my first bold text.
\n Let's try how italic looks like.
\n Now let's buy some milkshnitte dark chocolate.
\n See this is Emphasized text.
\n Now this is Underline text.
\n Aaaaand this is x2.
\n Aaaaaand this is L1.
\n
And some code format:
\n \n```python\n for i in range(1, 10):\n print(i)\n```\n\nAnd some code inline format:
\n\nThis is called anonymous function: `lambda s: s + 1` in python.\n\nLet's see what is a link - Software University
\nSample table example:
\n| Company | \nContact | \nCountry | \n
|---|---|---|
| Alfreds Futterkiste | \nMaria Anders | \nGermany | \n
| Centro comercial Moctezuma | \nFrancisco Chang | \nMexico | \n
| Ernst Handel | \nRoland Mendel | \nAustria | \n
| Island Trading | \nHelen Bennett | \nUK | \n
| Laughing Bacchus Winecellars | \nYoshi Tannamuri | \nCanada | \n
| Magazzini Alimentari Riuniti | \nGiovanni Rovelli | \nItaly | \n
| \n | \n prepared by Abuzer Yakaryilmaz (QLatvia) and Maksim Dimitrijev(QLatvia) \n | \n
| This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. |
@slendrmeans | February 2013\n\n## Introduction (Attention Conservation Notice)\n\nThis notebook contains information that is new and useful. But the parts that are new are not useful, and the parts that are useful are not new. It exists because I wanted to experiment in Cython and in the IPython notebook. The code here is all but useless except for pedagogy. Virtually no one has any rightful business coding up their own linear algebra routines. And the mathematical and algorithmic content is elementary.\n\nWhich is all useful for my purpose: when you try out new tools you want to do it on well-known problems. And the excessive verbiage and formulas give me an excuse to tinker with the notebooks typographical capabilities.\n\nAs such this may be of no use to anyone besides the author. Consider yourself warned.\n\nComments regarding my amateur Cython, or any other topic, are welcome.\n\n## A linear system\n\nOur goal is to understand and, if possible, solve the system of $n$ linear equations\n\n$$\n\\begin{align}\na_{00}\\,x_0 + a_{01}\\,x_1 + \\ldots + a_{0,n-1}\\,x_{n-1} &= b_0 \\\\\\\na_{10}\\,x_0 + a_{11}\\,x_1 + \\ldots + a_{1,n-1}\\,x_{n-1} &= b_1 \\\\\\\n\\vdots & \\\\\\\na_{n-1,0}\\,x_0 + a_{n-1,1}\\,x_1 + \\ldots + a_{n-1,n-1}\\,x_{n-1} &= b_{n-1}\\ .\n\\end{align}\n$$\n\nIn the system, the $a_{ij}$s and $b_i$s are known, while the $x_i$s are the unkown variables we wish to solve for. In other words, solving the system means finding the values for the $x_i$s using the $a_{ij}$s and $b_i$s. \n\nUsing matrix notation, we can write the system as\n\n$$\n\\begin{pmatrix}\na_{00} & a_{01} & \\ldots & a_{0,n-1} \\\\\\\na_{10} & a_{11} & \\ldots & a_{1,n-1} \\\\\\\n\\vdots & & \\ddots & \\vdots \\\\\\\na_{n-1,0} & a_{n-1,1} & \\ldots & a_{n-1,n-1}\n\\end{pmatrix} \\,\n\\begin{pmatrix} x_0 \\\\\\ x_1 \\\\\\ \\vdots \\\\\\ x_{n-1}\\end{pmatrix}\n=\n\\begin{pmatrix} b_0 \\\\\\ b_1 \\\\\\ \\vdots \\\\\\ b_{n-1}\\end{pmatrix}\\ \n$$\n\nor $Ax = b$. In this form, a solution to the system is the vector $x$ that satisfies the equation.
\n\n\n\n\n\n\n----------------\n\n##### Exercise: Matrix multiplication in Cython\n\nTo work with linear systems, we’ll want to be able to multiply matrices with vectors, like in the equation above, but also with other matrices.\n\nTo use Cython in the notebook, we have to load the `cythonmagic` extension. We’ll also want to load numpy and scipy modules form, among other things, benchmarks for our Cython functions.\n\n\n```python\n%load_ext cythonmagic\nimport numpy as np\nimport scipy.linalg as la\n```\n\nUsing `%%cython` cell magic, we can write and compile a Cython module within a notebook cell.\n\nWe want to be able to multiply a matrix $A$ by either a vector $x$, like above, or another matrix $B$. Unlike, say, C++, Cython does not allow use to overload a function by using different arguments. (As far as I know.) For example, we can’t define two versions of a function `matprod` that takes either one 2-D array and one 1-D array, or two 2-D arrays.\n\nBut Cython is flexible, and lets us define functions where not all arguments are typed. So we’ll write a wrapper function `matprod` that has the second argument untyped. Then, based on whether the second argument is a vector or a matrix, dispatches to the appropriate C-like (typed) function.\n\n\n```cython\n%%cython\ncimport cython\nimport numpy as np\ncimport numpy as np\n\ndef matprod(np.ndarray[double, ndim = 2] A, B):\n '''\n Matrix-by-vector or matrix-by-matrix multiplication.\n\n The arguments are dispatched to one of two functions\n depending on whether B is a vector or a matrix.\n '''\n if B.ndim == 1:\n # B is a vector\n return matvecprod(A, B)\n else:\n # B is a matrix\n return matmatprod(A, B)\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ncdef np.ndarray[double, ndim=2] matmatprod(\n np.ndarray[double, ndim=2] A,\n np.ndarray[double, ndim=2] B):\n '''\n Matrix-matrix multiplication.\n '''\n cdef: \n int i, j, k\n int A_n = A.shape[0]\n int A_m = A.shape[1]\n int B_n = B.shape[0]\n int B_m = B.shape[1]\n np.ndarray[double, ndim=2] C\n \n # Are matrices conformable?\n assert A_m == B_n, \\\n 'Non-conformable shapes.'\n \n # Initialize the results matrix.\n C = np.zeros((A_n, B_m))\n for i in xrange(A_n):\n for j in xrange(B_m):\n for k in xrange(A_m):\n C[i, j] += A[i, k] * B[k, j]\n return C\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ncdef np.ndarray[double, ndim=1] matvecprod(\n np.ndarray[double, ndim=2] A,\n np.ndarray[double, ndim=1] b):\n '''\n Matrix-vector multiplication.\n '''\n cdef: \n Py_ssize_t i, j, k\n Py_ssize_t A_n = A.shape[0]\n Py_ssize_t A_m = A.shape[1]\n Py_ssize_t b_n = b.shape[0]\n np.ndarray[double, ndim=1] c\n \n # Are matrices conformable?\n assert A_m == b_n, \\\n 'Non-conformable shapes.'\n \n # Initialize the results matrix.\n c = np.zeros(A_n)\n for i in xrange(A_n):\n for k in xrange(b_n):\n c[i] += A[i, k] * b[k]\n return c\n```\n\n \n\n\nIf the above compiles successfully, nothing should happen. Otherwise an output cell with a compilation error message and traceback will appear.\n\nFor speed comparisons, the following is a pure Python version of matrix-matrix multiplication.\n\n\n```python\ndef pymatmatprod(A, B):\n '''\n Matrix-matrix multiplication\n '''\n A_n, A_m = A.shape\n B_n, B_m = B.shape\n assert A_m == B_n, \"Non-conformable shapes.\"\n C = np.zeros((A_n, B_m))\n for i in xrange(A_n):\n for j in xrange(B_m):\n for k in xrange(A_m):\n C[i, j] += A[i, k] * B[k, j]\n return C\n```\n\nWe create some small sample matrices to test the functions.\n\n\n```python\n# A is 2x3\nA = np.array([[2.0, 0.25, -1.0], \n [3.0, 0.0 , 5.0]])\n# B is 3x2\nB = np.array([[-3.0, 0.5], \n [ 2.0, 1.5], \n [ 4.0, -4.0]])\n# C is 2x2\nC = np.array([[1.0, 1.5], \n [2.5, -1.0]])\n# b is 3x1 (a vector)\nb = np.array([1.0, -2.0, 0.5])\n```\n\nAnd check to see they give the same results.\n\n\n```python\nprint 'Cython:'\nprint '-------'\nprint \"A x B =\\n\", matprod(A, B), \"\\n\"\nprint \"A x b =\\n\", matprod(A, b), \"\\n\"\nprint 'Numpy dot:'\nprint '----------'\nprint \"A x B =\\n\", np.dot(A, B), \"\\n\"\nprint \"A x b =\\n\", np.dot(A, b), \"\\n\"\nprint 'Python loops:'\nprint '-------------'\nprint \"A x B =\\n\", pymatmatprod(A, B), \"\\n\"\n```\n\n Cython:\n -------\n A x B =\n [[ -9.5 5.375]\n [ 11. -18.5 ]] \n \n A x b =\n [ 1. 5.5] \n \n Numpy dot:\n ----------\n A x B =\n [[ -9.5 5.375]\n [ 11. -18.5 ]] \n \n A x b =\n [ 1. 5.5] \n \n Python loops:\n -------------\n A x B =\n [[ -9.5 5.375]\n [ 11. -18.5 ]] \n \n\n\nWe want to make sure the function doesn't try to multiply non-conformable matrices. Without this check, depending on how we code the function, we might not get an error, but instead nonsense.\n\n\n```python\n# Non-comformable matrices\nprint matprod(A, C) \n```\n\nNow that it works correctly, we can check the speed of our Cython function. It appears to be a bit slower than numpy's `dot` function, but much faster than pure Python.\n\n\n```python\n%timeit np.dot(A, B)\n```\n\n 1000000 loops, best of 3: 1.33 µs per loop\n\n\n\n```python\n%timeit matprod(A, B)\n```\n\n 100000 loops, best of 3: 3.53 µs per loop\n\n\n\n```python\n%timeit pymatmatprod(A, B)\n```\n\n 10000 loops, best of 3: 23.3 µs per loop\n\n\n-------------------------\n\n##### Note: Numpy arrays in Cython using buffers or MemoryViews\n\nIn the functions above, we declared a variable to be a numpy array with, for example,\n\n np.ndarray[double, ndim=2] x\n \nThis is an example of creating a Numpy array buffer. There is a newer method [recommended](http://docs.cython.org/src/userguide/memoryviews.html) in the Numpy documentation, using typed MemoryViews. Using this method, we would have instead declared\n\n double[:, :] x\n \nor\n\n double[:, ::1] x\n \nThe `::1` slice indicates that `x` is a C-contiguous array; i.e. its columns are one memory-location apart. This is a much simpler syntax than the array buffer declaration. MemoryViews are also supposed to be faster and more flexible than buffers. In my experience they are when working on larger arrays, but on smaller problems, there seems to be some overhead involved in creating MemoryViews and coercing them back to arrays. \n\nI’ll use the two notations interchangeably throughout.\n\n-----------\n\n## Solution by matrix inversion\n\nThe natural solution to the matrix equation $Ax = b$ is to find the inverse of $A$, denoted $A^{-1}$. $\\ A^{-1}$ is the matrix that has the property $A^{-1}A = I$. Pre-multiplying both sides of the equation will then leave us with the solution $x = A^{-1}b$.\n\nIt turns out, though, that computing $A^{-1}$ is expensive, and that there are more efficient ways of solving the system. As John Cook says, “There is hardly ever a good reason to invert a matrix.” With that advice, we'll not spend effort on writing algorithms for computing matrix inverses.\n\nWhat is useful to know about $A^{-1}$ is that it only exists if the linear system has a unique solution. That is, if there is one and only one $x$ that solves $Ax = b.$ If $A$ has an inverse, it's called nonsingular. \n\nUnder what circumstances would $A$ *not* have an inverse?\nIf one of the columns in $A$ can be calculated as a linear combination of the other columns, then $A$ will not have an inverse. To have an inverse, $\\,A$’s columns must be linearly independent. \n\nFor example, let’s look at the linear system\n\n$$\n\\begin{pmatrix}\n2 & 3 & 1 \\\\\\\n0.5 & 2 & -1 \\\\\\\n-1 & 5 & -7\n\\end{pmatrix}\\,\n\\begin{pmatrix}\nx_0 \\\\\\ x_1 \\\\\\ x_2\n\\end{pmatrix} =\n\\begin{pmatrix}\n10 \\\\\\ -3 \\\\\\ 2\n\\end{pmatrix}\\\n$$\n\nHere the third column, $A_{\\cdot2}$ is equal to $2\\times A_{\\cdot0} - 1\\times A_{\\cdot 1}$, so the columns of this matrix are not linearly independent. This relationship means that $x_2 = 2x_0 - x_1$, so $x_2$ is not an independent variable, and we really only have two variables in three equations. There will be an infinite number of combinations of $x_0$ and $x_1$ that solve the system.\n\nWhen the columns of $A$ are not linearly independent, and $A$ has no inverse, it’s called singular or degenerate.\n\n## The determinant of a matrix\n\nIn the example above, it was easy to see that the columns of the matrix were not linearly independent. For larger matrices, a more reliable method of detecting singular matrices is required.\n\nThe determinant of a matrix—a real number denoted $\\det(A)$—is an attribute of a square matrix that can be used to tell whether a matrix is singular, and therefore whether the linear system has a solution.\n\nThe check is straightforward: when the determinant of a matrix is zero, the matrix is singular, and no solution exists. We can check this with the singular matrix in the example above, using numpy’s `det` function.\n \n\n\n```python\nA = np.array([[ 2, 3, 1],\n [0.5, 2, -1],\n [ -1, 5, -7]])\n\n# A is singular, so it's determinant should be zero.\nprint \"The determinant is\", np.linalg.det(A)\n```\n\n The determinant is 0.0\n\n\n \nCalculating the determinant, though, is not so easy.\n \nLet’s start with a trivial definition. We’ll say that the determinant of a $1\\times1$ matrix $A$ (a scalar), is simply equal to $A$. So, for example, $\\det(4) = 4$.\n\nThe well-known formula for the determinant of a $2x2$ matrix\n\n$$\nA =\n\\begin{pmatrix}\na & b \\\\\\\nc & d \n\\end{pmatrix}\n$$\n\nis $\\det(A) = ad - bc$. We can break this formula down and generalize it to larger matrices.
\n\nFirst, let’s define the $(i, j)$ minor of $A$, denoted $A_{ij}$ as the matrix that results from removing row $i$ and column $j$ from $A$. For example, the (0, 0) minor of the $2\\times2$ matrix above is:\n\n$$\n\\begin{pmatrix}\n\\cdot & \\cdot \\\\\\\n\\cdot & d\n\\end{pmatrix} = d.\n$$\n\nSimilarly the (0, 1) minor is:\n \n$$\n\\begin{pmatrix}\n\\cdot & \\cdot \\\\\\\nc & \\cdot\n\\end{pmatrix} = c.\n$$ \n\nWe can now re-write the formula for the determinant as\n\n$$\n\\det(A) = a_{00}\\det(A_{00}) - a_{01}\\det(A_{01})\\ ,\n$$\n\nsince the the minors $A_{0i}, i = 0, 1$ are scalars so are equal to their determinants by our definition above. Even better, we can take care of the minus sign by noting that
\n\n$$\n\\det(A) = (-1^0)\\;a_{00}\\det(A_{00}) + (-1^1)\\;a_{01}\\det(A_{01})\\ .\n$$\n\nEverything in this formula can now be generalized to the determinant of an arbitrary $n\\times n$ matrix.\n\n$$\n\\det(A) = \\sum_{i=0}^{n-1}(-1^i)\\;a_{0i}\\det(A_{0i})\n$$\n\nOur choice to move across row 0 of the matrix was arbitrary; we could have chosen to go across any row or down any column of the matrix, as long as we obtained the associated minor and computed the correct sign on each term. For example, we could have used column 2, in which case we would have had:\n \n$$\n\\det(A) = \\sum_{i=0}^{n-1}(-1^{i+2})\\;a_{i2}\\det(A_{i2})\n$$\n\nThis flexibility can often come in handy. For example, if a row or column has a lot of zeros in it, we can exploit that to cut down on the number of calculations needed since terms in the sum get zeroed out.\n\nLastly, notice that these definitions are recursive. That is, to find the determinant of an $n\\times n$ matrix $A$, we have to find the determinants of the $(n-1)\\times(n-1)$ minors $A_{0i}$ (of which there are $n$). To find the determinants of *these* matrices, we have to compute the determinants of their $(n-2)\\times(n-2)$ minors (of which there are $n-1$). So we are now computing $n\\times(n-1)$ determinants of $(n-2)\\times(n-2)$ matrices. This continues all the way down until the minor matrices are scalars, at which point we know the determinants by definition.\n\nThe recursive equation gives us a simple and elegant way to express all this computation. Furthermore we can write our code using this recursive equation directly, by writing a `determinant` function that calls itself. But as is often the case this elegance comes at a cost, and we’ll find that this recursive method gets very computationally expensive.\n\n-------------------\n\n##### Exercise: Computing determinants with recursive functions\n\nThe following code implements the recursive algorithm for calculating the determinant. Note the compiler flag after `%%cython`; necessary since we'll use a function from C's `math` library.\n\n\n```cython\n%%cython -lm \n# Note the lm flag, used to import the C math library.\nimport cython\nimport numpy as np\ncimport numpy as np\n# Using C's power function instead of Python, hence the\n# math library link flag above.\nfrom libc.math cimport pow\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ncpdef double determinant(double[:, :] M):\n '''\n Compute the determinant of a square nxn matrix using\n the recursive formula:\n \n det(M) = sum_{i=0}^{n-1} (-1^i)*M[0,i]*det(M_minor(0,i))\n\n where M_minor(0,i) is the (n-1)x(n-1) matrix formed by\n removing row 0 and column i from M.\n '''\n \n assert M.shape[0] == M.shape[1], 'Matrix is not square.'\n \n cdef int i, j\n cdef int n = M.shape[0]\n cdef double det = 0.0\n cdef double coef\n cdef double[:, :] M_minor = np.empty((n-1, n-1))\n \n if n == 1:\n # If M is a scalar (1x1) just return it\n return M[0, 0]\n else:\n # If M is nxn, then get its (n-1)x(n-1) minors\n # (one for each of M's n columns) and compute \n # their determinants and add them to the summation.\n for j in xrange(n):\n coef = pow(-1, j) * M[0, j]\n _get_minor(M, M_minor, 0, j)\n det += coef * determinant(M_minor)\n return det\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ncdef void _get_minor(double[:, :] M, double[:, :] M_minor, \n int row, int col):\n '''\n Return the minor of a matrix, by removing a specified\n row and column\n\n If M is nxn, then _get_minor(M, row, col) will fill in\n the (n-1)x(n-1) matrix M_minor by removing row `row` \n and column `col` from M.\n '''\n cdef:\n int n = M.shape[0]\n int i_to, j_to, i_from, j_from\n \n \n # _from indicates the index of the original\n # matrix M, _to, indicates the index of the\n # result matrix M_minor.\n i_from = 0\n for i_to in xrange(n-1):\n if (i_to == row): \n # This is the row to exclude from the\n # minor, so skip it.\n i_from += 1\n j_from = 0\n for j_to in xrange(n-1):\n if (j_to == col): \n # This is the column to exclude from the\n # minor, so skip it.\n j_from += 1\n \n M_minor[i_to, j_to] = M[i_from, j_from]\n j_from += 1\n \n i_from += 1\n```\n\nTesting the function on a sample matrix, suggests it’s correctly coded.\n\n\n```python\n\n# A is 3x3\nA = np.array([[ 2, -1, 4],\n [-1, 3, 0.5],\n [ 5, -9, 11]])\n\nprint 'Numpy: ', np.linalg.det(A)\nprint 'Cython: ', determinant(A)\n```\n\n Numpy: 37.5\n Cython: 37.5\n\n\nAnd it is even quite fast on a $3\\times3$ matrix.\n\n\n```python\nprint 'Numpy time:'\n%timeit np.linalg.det(A)\nprint 'Recursive Cython time'\n%timeit determinant(A)\n```\n\n Numpy time:\n 10000 loops, best of 3: 62.7 µs per loop\n Recursive Cython time\n 10000 loops, best of 3: 26.1 µs per loop\n\n\nBut—as feared—it is deadly slow on even just a somewhat larger, $10\\times 10$ matrix.\n\n\n```python\n# B is 10x10\nprint 'Numpy time:'\nB = np.random.randn(100).reshape(10, 10)\n%timeit np.linalg.det(B)\nprint 'Recursive Cython time'\n%timeit determinant(B)\n```\n\n Numpy time:\n 10000 loops, best of 3: 65.6 µs per loop\n Recursive Cython time\n 1 loops, best of 3: 16.2 s per loop\n\n\n---------------------------\n\n## Linear systems with triangular matrices\n\nAt this point, the elegance of mathematics has been thwarted by the dirty business of computing. We would like to know whether a linear system is solvable, which we can do by calculating it’s determinant. But the mathematical formula we have derived for it computes terribly. Even if we could compute the determinant and find the system to be solvable, we have been warned against using the algebraically sensible method of matrix inversion to solve it.\n\nLet’s go down a new road. Our system, once more, is:\n\n$$\n\\begin{pmatrix}\na_{00} & a_{01} & \\ldots & a_{0,n-1} \\\\\\\na_{10} & a_{11} & \\ldots & a_{1,n-1} \\\\\\\n\\vdots & & \\ddots & \\vdots \\\\\\\na_{n-1,0} & a_{n-1,1} & \\ldots & a_{n-1,n-1}\n\\end{pmatrix} \\,\n\\begin{pmatrix} x_0 \\\\\\ x_1 \\\\\\ \\vdots \\\\\\ x_{n-1}\\end{pmatrix}\n=\n\\begin{pmatrix} b_0 \\\\\\ b_1 \\\\\\ \\vdots \\\\\\ b_{n-1}\\end{pmatrix}\\ \n$$\n\nBut imagine that our system was of the form:\n \n$$\n\\begin{pmatrix}\nl_{00} & 0 & 0 & \\ldots & 0 \\\\\\\nl_{10} & l_{11} & 0 & \\ldots & 0 \\\\\\\n\\vdots & & & \\ddots & \\vdots\\\\\\\nl_{n-1,0} & l_{n-1,1} & l_{n-1,2} & \\ldots & l_{n-1,n-1}\n\\end{pmatrix}\\,\n\\begin{pmatrix} y_0 \\\\\\ y_1 \\\\\\ \\vdots \\\\\\ y_{n-1}\\end{pmatrix}\n=\n\\begin{pmatrix} c_0 \\\\\\ c_1 \\\\\\ \\vdots \\\\\\ c_{n-1}\\end{pmatrix}\\ \n$$\n\nor $Ly = c$. The matrix $L$ is lower triangular, which means all the elements above its diagonal are zero.
\n\nThis is a simple system to solve. The first row gives us the value of $x_0$; once we have that, substituting it into the second row gives us $x_1$. We can then roll this process down to solve for a new variable in each row until we’ve solve the whole system. This process is called forward substitution. The formula for any $y_i$ in the system above is \n\n$$\ny_i = \\frac{1}{l_{ii}}\\left(c_i - \\sum_{k=0}^{i-1}l_{ik}\\,y_k\\right),\n$$\n\nwhich only depends on the previous values of $y\\,$: $y_{i-1}, y_{i-2}, \\ldots, y_0$.
\n\n\nThe process, of course, is just as simple with an upper triangular matrix:\n \n$$\n\\begin{pmatrix}\nu_{01} & u_{11} & \\ldots & u_{0, n-2} & u_{0,n-1} \\\\\\\n0 & u_{11} & \\ldots & u_{1, n-2}& u_{1,n-1} \\\\\\\n\\vdots & & \\ddots & &\\vdots\\\\\\\n0 & 0 & \\ldots & 0 & u_{n-1,n-1}\n\\end{pmatrix}\\,\n\\begin{pmatrix} y_0 \\\\\\ y_1 \\\\\\ \\vdots \\\\\\ y_{n-1}\\end{pmatrix}\n=\n\\begin{pmatrix} c_0 \\\\\\ c_1 \\\\\\ \\vdots \\\\\\ c_{n-1}\\end{pmatrix}\\ \n$$\n\nor $Uy = c$. Here we would simply move up the rows, substituting and solving for one new variable each time; a process called, unsurprisingly, backwards substitution.
\n\n### Determinants of triangular matrices\n\nAnother convenient property of triangular matrices is that their determinants are just the products of their diagonal entries. This is easy to prove using the recursive determinant formula defined above. For a lower triangular matrix, just take the determinant across the top row. Only the first term is non-zero, so we have\n\n$$\n\\det(L) = l_{00}\\det(L_{00}).\n$$\n\nThe minor $L_{00}$ is just another lower triangular matrix, so its determinant is\n\n$$\n\\det(L_{00}) = l_{11}\\det(L_{00_{00}}),\n$$\n\ngiving us
\n$$\n\\det(L) = l_{00}\\cdot l_{11}\\det(L_{00_{00}}).\n$$\n\nWe can imagine proceding down this route, substituting minors, until all that remains is the product $\\det(L) = l_{00}\\cdot l_{11}\\cdots l_{n-1,n-1}\\,.$\n\nThe process is the same for an upper triangular matrix. If we take the determinant down the first column, we'll find each subsequent minor matrix in the recursion is also an upper triangular matrix, so it’s determinant is also just the product of its diagonals, $u_{00}\\cdot u_{11}\\cdots u_{n-1, n-1}$.\n\nThe implication of this is that a triangular matrix is non-singular or invertible so long as none of its diagonal elements are zero. This makes intuitive sense if you imagine proceeding through each step of forward or backward substitution—a zero on the diagonal would break the chain of sequential subsitutions.\n\n---------------\n\n##### Exercise: Coding forward- and backward-substitution solution methods\n\nThe forward and backward substitution algorithms are straightforward to code. Below are two functions, expecting either a lower or upper triangular matrix, that solve the respective system.\n\n\n```cython\n%%cython -lm\nimport cython\nimport numpy as np\ncimport numpy as np\nfrom libc.math cimport fabs\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\n@cython.cdivision(True)\ncpdef np.ndarray[double, ndim=1] forward_sub_solve( \n np.ndarray[double, ndim=2] L, \n np.ndarray[double, ndim=1] b):\n ''' \n Solve, by forward substition, the system Lx = b, where\n L is a lower triangular matrix.\n \n Note that the code does not check whether L is lower\n triangular. Calling the function with an arbitrary\n '''\n \n assert L.shape[1] == b.shape[0], \\\n 'Matrix and vector are incompatible shapes.'\n assert fabs(L[0, 0]) >= 10e-16, \\\n 'Zero element on diagonal.'\n \n # No. of variables to solve\n cdef int n = b.shape[0]\n \n # Loop indices\n cdef int i, k\n \n # Initialize the solution vector\n cdef np.ndarray[double, ndim=1] y = np.zeros(b.shape[0])\n y[0] = b[0] / L[0,0] \n\n cdef double sum_term = 0.0\n for i in xrange(1, n):\n if fabs(L[i, i]) <= 10e-16:\n raise ValueError('Zero element on diagonal.')\n sum_term = 0.0\n for k in xrange(0, i):\n sum_term += L[i, k] * y[k]\n y[i] = (b[i] - sum_term) / L[i, i]\n \n return y\n\ncpdef np.ndarray[double, ndim=2] backward_sub_solve(\n np.ndarray[double, ndim=2] U,\n np.ndarray[double, ndim=1] b):\n ''' \n Solve, by backward substition, the system Ux = b, where\n U is an upper triangular matrix.\n \n Note that the code does not check whether U is upper\n triangular. Calling the function with an arbitrary\n square matrix will result in nonsense.\n '''\n assert U.shape[1] == b.shape[0], \\\n 'Matrix and vector are incompatible shapes.'\n assert fabs(U[0, 0]) >= 10e-16, \\\n 'Zero element on diagonal.'\n \n # No. of variables to solve\n cdef int n = b.shape[0]\n \n # Loop indices\n cdef int i, k\n \n # Initialize the solution vector\n cdef np.ndarray[double, ndim=1] y = np.zeros(b.shape[0])\n y[n-1] = b[n-1] / U[n-1, n-1] \n\n cdef double sum_term = 0.0\n for i in xrange(n-2, -1, -1):\n if fabs(U[i, i]) <= 10e-16:\n raise ValueError('Zero element on diagonal.')\n sum_term = 0.0\n for k in xrange(i+1, n):\n sum_term += U[i, k] * y[k]\n y[i] = (b[i] - sum_term) / U[i,i]\n \n return y\n```\n\nThe functions give identical results to numpy's `solve` function on some sample triangular matrices.\n\n\n```python\n# L is 3x3 lower-triangular\nL = np.array([[ 2, 0, 0],\n [1.5, -3, 0],\n [ -5, 0.5, 4]])\n\n# U is 3x3 upper-triangular\nU = np.array([[ -1, 3, -5],\n [ 0, -0.5, 2],\n [ 0, 0, 1.5]])\n\nb = np.array([-1., 5., 3.])\n\nprint 'Cython (forward):', forward_sub_solve(L, b)\nprint 'Numpy (forward): ', np.linalg.solve(L, b)\n\nprint 'Cython (backward):', backward_sub_solve(U, b)\nprint 'Numpy (backward): ', np.linalg.solve(U, b)\n\n```\n\n Cython (forward): [-0.5 -1.91666667 0.36458333]\n Numpy (forward): [-0.5 -1.91666667 0.36458333]\n Cython (backward): [-15. -2. 2.]\n Numpy (backward): [-15. -2. 2.]\n\n\nForward and backward substitution are quite fast. Here they're compared to numpy's `solve` function, which isn't quite fair, since the latter is more general. But it gives us a frame of reference.\n\n\n```python\nprint 'Numpy solve:'\n%timeit np.linalg.solve(L, b)\nprint 'Cython forward substitution'\n%timeit forward_sub_solve(L, b)\nprint 'Numpy solve:'\n%timeit np.linalg.solve(U, b)\nprint 'Cython backwards substitution'\n%timeit backward_sub_solve(U, b)\n```\n\n Numpy solve:\n 10000 loops, best of 3: 26.2 µs per loop\n Cython forward substitution\n 100000 loops, best of 3: 4.32 µs per loop\n Numpy solve:\n 10000 loops, best of 3: 26.2 µs per loop\n Cython backwards substitution\n 100000 loops, best of 3: 4.69 µs per loop\n\n\nLet's also time the function on a large, $1000\\times 1000$ matrix, to make sure its performance scales.\n\n\n```python\nL = np.random.randn(1e6).reshape((1e3,1e3))\ncond = np.subtract.outer(np.arange(1e3), np.arange(1e3))\nL[cond < 0] = 0.\nb = np.random.randn(1e3)\n\n%timeit forward_sub_solve(L, b)\n```\n\n 1000 loops, best of 3: 452 µs per loop\n\n\n----------------\n\n## The LU(P) decomposition\n\nWe’ve established that triangular systems are easy to solve and can be implemented in fast code. This is fortunate, becuase it turns out that any square matrix can be represented as the product of a lower and an upper triangular matrix. That is,\n\n$$\nA = LU\\,.\n$$\n\nThis representation is called the LU decomposition of $A$. Using this decomposition, the linear system $Ax = b$ can be represented as\n\n$$\n\\begin{align}\nAx &= b\\\\\\\nLUx &= b\\\\\\\nLy &= b\\,,\n\\end{align}\n$$\n\nwhere $y \\equiv Ux$. We can easily solve for $y$ using forward substitution. Having done that, we have
\n\n$$\nUx = y\\,,\n$$\n\nand we can now solve for $x$ by forward substituion.
\n\nThe algorithm—actually there is more than one—to find $L$ and $U$ is not complicated. It's easiest to see working through an example. Consider the $3\\times 3$ matrix\n$$\nA = \n\\begin{pmatrix}\n2 & -1 & 4 \\\\\\\n-1 & 3 & \\frac{1}{2} \\\\\\\n5 & -9 & 11\n\\end{pmatrix}\\,.\n$$\n\nWe initialize $U = A$, and $L = I$. Then we proceed to set the sub-diagonal element of U to zero using gaussian elimination. In the first step, we'll remove the sub-diagonal entries in the first column of $U$. There is a separate elimination for each row. To eliminate $u_{10}$ we multiply each entry in the first row by $\\frac{u_{10}}{u_{00}} = -\\frac{1}{2}$ and substract it from the second row. That is $u_{1j} \\rightarrow u_{1j} + \\frac{1}{2} u_{0j}$ for $j = 0,\\ldots,2$.\n\nTo eliminate $u_{20}$ we similarly substract the first rows times $\\frac{u_{20}}{u_{00}} = \\frac{5}{2}$ from the third row.\n\nWe represent these elimination steps in $L$ by setting $l_{10}$ to $-\\frac{1}{2}$ and $l_{20}$ to $\\frac{5}{2}$.\n\nThis step leaves us with\n\n$$\nL = \\begin{pmatrix}\n1 & 0 & 0 \\\\\\\n-\\frac{1}{2} & 1 & 0 \\\\\\\n\\frac{5}{2} & 0 & 1 \n\\end{pmatrix}\n$$\nand\n\n$$\nU =\n\\begin{pmatrix}\n2 & -1 & 4 \\\\\\\n0 & \\frac{5}{2} & \\frac{5}{2} \\\\\\\n0 & -\\frac{13}{2} & 1\\end{pmatrix}\\,.\n$$\n\nThe next step repeats the first, but for the second column of $U$. Here we only need to eliminate one sub-diagonal entry, $u_{21}$. We can do this by subtracting the second row times $\\frac{u_{21}}{u_{11}} = -\\frac{13}{5}$. Like before, we set $l_{21}$ to $-\\frac{13}{5}$ to represent the elimination. We now have\n\n\n\n$$\nL = \\begin{pmatrix}\n1 & 0 & 0 \\\\\\\n-\\frac{1}{2} & 1 & 0 \\\\\\\n\\frac{5}{2} & -\\frac{13}{5} & 1 \n\\end{pmatrix}\n$$\nand\n$$\nU =\n\\begin{pmatrix}\n2 & -1 & 4 \\\\\\\n0 & \\frac{5}{2} & \\frac{5}{2} \\\\\\\n0 & 0 & \\frac{15}{2} \n\\end{pmatrix}\\,.\n$$\n\nThis completes the process since $U$ is now upper triangular and $L$ is lower triangular.\n\nLet’s test that our calculations are correct. If we did everything correctly, we should recover $A$ from $LU$.\n\n\n```python\nA = np.array([[2., -1., 4.],\n [-1., 3., 0.5],\n [ 5., -9., 11.]])\n\nL = np.array([[1, 0, 0],\n [-1./2, 1, 0],\n [5/2., -13./5, 1]])\n\nU = np.array([[2, -1, 4],\n [0, 5./2, 5./2],\n [0, 0, 15./2]])\n\nif np.all(np.abs(matprod(L, U) - A) < 10e-14):\n print 'A = LU, OK!'\nelse:\n print 'A != LU, Not OK!'\n```\n\n A = LU, OK!\n\n\n### The LU decompositon with pivoting\n\nIn practice, the LU decomposition algorithm outlined above can sometimes be numerically unstable. At each step, $k$, of the algorithm, we calculate $\\frac{u_{ik}}{u_{kk}}$ for $i > k$. If any of the diagonals, $u_{kk}$ (called the pivots are near zero, this calculation can overflow.\n\nTo avoid this, an extra step, called pivoting is added to the algorithm. At each step $k$, before performing the gaussian elimination, we swap the rows of $U$ to get the largest possible magnitude for $u_{kk}$. This helps avoid the overflow problem.\n\nIn the example above, we start with\n\n$$\nU = \n\\begin{pmatrix}\n2 & -1 & 4 \\\\\\\n-1 & 3 & \\frac{1}{2} \\\\\\\n5 & -9 & 11\n\\end{pmatrix}\\,.\n$$\n\nHere, we would first switch the first row with the third row, since $5 > 2$. So\n\n$$\nU = \n\\begin{pmatrix}\n5 & -9 & 11 \\\\\\\n-1 & 3 & \\frac{1}{2} \\\\\\\n2 & -1 & 4\n\\end{pmatrix}\\,.\n$$\n\nThe gaussian elimination of the first column would then give us\n\n$$\nL = \n\\begin{pmatrix}\n1 & 0 & 0 \\\\\\\n-\\frac{1}{5} & 1 & 0 \\\\\\\n\\frac{2}{5} & 0 & 1\n\\end{pmatrix}\n$$\n\nand\n\n$$\nU = \n\\begin{pmatrix}\n5 & -9 & 11 \\\\\\\n0 & \\frac{6}{5} & \\frac{27}{10} \\\\\\\n0 & \\frac{13}{5} & -\\frac{2}{5}\n\\end{pmatrix}\\,.\n$$\n\nWe would also represent the row swap by adding a permutation matrix, $P$, where\n\n$$\nP = \n\\begin{pmatrix}\n0 & 0 & 1 \\\\\\\n0 & 1 & 0 \\\\\\\n1 & 0 & 0\n\\end{pmatrix}\\,.\n$$\n\nWhen this permuation matrix is multiplied by the original $U$, it swaps $U\\,$'s rows in the desired way. \n\nIn the second step, we’ll have to swap the second and third rows, since $\\frac{13}{5} > \\frac{6}{5}$. We record this permutation in two ways: first by swapping the second and third rows in $P$; second by swapping the second and third rows of the *first column* of $L$. So we have\n\n$$\nP = \n\\begin{pmatrix}\n0 & 0 & 1 \\\\\\\n1 & 0 & 0 \\\\\\\n0 & 1 & 0\n\\end{pmatrix}\\,.\n$$\n\nand\n\n$$\nL = \n\\begin{pmatrix}\n1 & 0 & 0 \\\\\\\n\\frac{2}{5} & 1 & 0 \\\\\\\n-\\frac{1}{5} & \\frac{6}{13} & 1\n\\end{pmatrix}\\,.\n$$\n\nPerforming the gaussian elimination step on (the swapped-row) $U$ gives us\n\n$$\nU = \n\\begin{pmatrix}\n5 & -9 & 11 \\\\\\\n0 & \\frac{13}{5} & -\\frac{2}{5}\\\\\\\n0 & 0 & \\frac{75}{26} \n\\end{pmatrix}\\,.\n$$\n\nWith $U$ upper triangular and $L$ lower triangular, the process is complete. But with the pivoting, we no longer have the decomposition $A = LU$, but instead $PA = LU$. The addition of the permutation adds only a trivial step to solving the system $Ax = b$ using decomposition, and protects us from potential numerical problems.\n\nAs before, we’ll check our calculations to make sure the $L$, $U$, and $P$ matrices we calculated satisfy $PA = LU$.\n\n\n```python\nA = np.array([[2., -1., 4.],\n [-1., 3., 0.5],\n [ 5., -9., 11.]])\n\nL = np.array([[1, 0, 0],\n [2./5, 1, 0],\n [-1/5., 6./13, 1]])\n\nU = np.array([[5, -9, 11],\n [0, 13./5, -2./5],\n [0, 0, 75./26]])\n\nP = np.array([[0., 0., 1.], \n [1., 0., 0.], \n [0., 1., 0.]])\n\nif np.all(np.abs(matprod(L,U) - matprod(P, A)) < 10e-14):\n print 'LU = PA, OK!'\nelse:\n print 'LU != PA, Not OK!'\n\n\n```\n\n LU = PA, OK!\n\n\n--------------------\n\n##### Exercise: The LUP algorithm\n\nGeneralizing from the example above, the code below performs LUP decomposition for an arbitrary square matrix. There are several points to note.\n\n1. To keep the code clear, the pivoting step is assigned to helper functions called within the main function. \n2. The function also keeps track of the number of row swaps performed. This information will come in handy later.\n3. Since we’re working with MemoryViews in this function, they are coerced back to arrays in the `return`. Otherwise the function would return MemoryView objects in the result tuple.\n\n\n```cython\n%%cython -lm\nimport cython\nimport numpy as np\ncimport numpy as np\nfrom libc.math cimport pow\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\n@cython.cdivision(True)\ncpdef lup_decomp(double[:, ::1] A):\n '''\n Perform the LUP decomposition of A:\n PA = LU\n \n Returns a tuple, (L, U, P, nswaps), where\n nswaps is the number of permutations made \n while performing the decomposition.\n '''\n \n assert A.shape[0] == A.shape[1], 'Not a square matrix.'\n \n cdef:\n int n = A.shape[0]\n int i_piv, k, j, h\n int nswaps = 0\n double[:, ::1] U = A.copy()\n double[:, ::1] P = np.eye(n)\n double[:, ::1] L = np.eye(n)\n \n for k in xrange(n-1):\n # Find the pivot row and permute matrices\n i_piv = get_pivot(U, k)\n if i_piv != k:\n nswaps += 1\n swap_rows(U, k, i_piv, k, n)\n swap_rows(P, k, i_piv, 0, n) \n if k > 0:\n swap_rows(L, k, i_piv, 0, k)\n \n # Gaussian eliminate sub-diagonal elements of U.\n for j in xrange(k+1, n):\n L[j, k] = U[j, k] / U[k, k]\n for h in xrange(k, n):\n U[j, h] -= U[k, h] * L[j, k] \n \n return (np.asarray(L), np.asarray(U), np.asarray(P), nswaps)\n \n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef int get_pivot(double[:, ::1] U, int k):\n '''\n Find the pivot row of column k in a matrix.\n The pivot row is the row i (>= k) of U for which \n abs(U[i, k]) is largest.\n '''\n cdef:\n int j\n int n = U.shape[0]\n int i_piv = k\n\n for j in xrange(k + 1, n):\n if abs(U[j, k]) > abs(U[i_piv, k]):\n i_piv = j\n return i_piv\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef void swap_rows(double[:, ::1] M, int row1, int row2, int col_start, int col_end):\n '''\n A helper function to swap segments of rows in a matrix.\n\n M[row1, col_start:col_end] <-> M[row2, col_start:col_end]\n ''' \n cdef:\n double[::1] first = M[row1, col_start:col_end].copy()\n \n M[row1, col_start:col_end] = M[row2, col_start:col_end].copy()\n M[row2, col_start:col_end] = first\n```\n\nAs always, we test its accuracy\n\n\n```python\nA = np.array([[2., -1., 4.],\n [-1., 3., 0.5],\n [ 5., -9., 11.]])\n\nL, U, P, nswaps = lup_decomp(A)\nprint 'L ='\nprint L\nprint 'U ='\nprint U\nprint 'P ='\nprint P\n```\n\n L =\n [[ 1. 0. 0. ]\n [ 0.4 1. 0. ]\n [-0.2 0.46153846 1. ]]\n U =\n [[ 5. -9. 11. ]\n [ 0. 2.6 -0.4 ]\n [ 0. 0. 2.88461538]]\n P =\n [[ 0. 0. 1.]\n [ 1. 0. 0.]\n [ 0. 1. 0.]]\n\n\nScipy has a function `lu` in its `linalg` module that performs LUP decompositions. (Oddly, numpy does not).\n\n\n```python\nP, L, U = la.lu(A)\nprint 'L ='\nprint L\nprint 'U ='\nprint U\nprint 'P ='\nprint P\n```\n\n L =\n [[ 1. 0. 0. ]\n [ 0.4 1. 0. ]\n [-0.2 0.46153846 1. ]]\n U =\n [[ 5. -9. 11. ]\n [ 0. 2.6 -0.4 ]\n [ 0. 0. 2.88461538]]\n P =\n [[ 0. 1. 0.]\n [ 0. 0. 1.]\n [ 1. 0. 0.]]\n\n\nNote that our results match scipy’s except for the $P$ matrix. This is because scipy perform the decomposition $A = LUP$. Therefore what scipy returns as $P$ is actually the inverse of what we’ve defined as $P$. The inverse of a permutation matrix is its transpose (obvious if you think about it), and that's what we see here. So our function appears accurate.\n\nNow, timings.\n\n\n```python\nA = np.random.randn(1e4).reshape((100, 100))\nprint 'Scipy lu'\n%timeit la.lu(A)\nprint 'Cython'\n%timeit lup_decomp(A)\n```\n\n Scipy lu\n 1000 loops, best of 3: 255 µs per loop\n Cython\n 100 loops, best of 3: 2.88 ms per loop\n\n\nOn a $100 \\times 100$ matrix, our Cython function is ten times slower than scipy. Not great news, but perhaps not surprising given that scipy is calling a highly-optimized Fortran function. There are also probably some low-level optimizations we could make to our code. But this is fast enough to be satisfactory.\n\n-----------\n\n### The determinant redux\n\nRecall that above we convinced ourselves that the determinant of a triangular matrix is just the product of its diagonal entries. Since the determinant of the product of two matrices is the product of their determinants, then for an LU decomposition we have\n \n$$\n\\begin{align}\n\\det(A) &= \\det(LU)\\\\\\\n &= \\det(L)\\times\\det(U)\\\\\\\n &= \\prod_{i=0}^{n-1}l_{ii}\\times\\prod_{i=0}^{n-1}u_{ii}\\\\\\\n &= \\prod_{i=0}^{n-1}u_{ii}\\,.\n\\end{align}\n$$\n\nThe last line obtains, becuase $L$ has ones along its diagonal. (There are alternative $LU$ decompositions where this isn’t so. For the LUP decomposition we have\n \n$$\n\\begin{align}\n\\det(A) &= \\det(L)\\times \\det(U) \\times \\det\\left(P^T\\right)\\\\\\\n &= \\det\\left(P^T\\right)\\times\\prod_{i=0}^{n-1}u_{ii}\\,.\n\\end{align} \n$$\n\nIt can be shown (but not so easily) that the determinant of $P^T$ is equal to $(-1)^\\textrm{# swaps}$. So if we swapped two rows during the decomposition, the determinant would be 1, if we swapped three, it would be $-1$. This is why we recorded the number of row swaps in the `lup_decomp` function above.\n \nSo the LUP decomposition not only provides an efficient method for solving a linear system, it also provides an efficient method for computing determinants. \n\n--------------------\n\n##### Exercise: Computing the determinant via LUP decomposition\n\nWith the code for the LUP decomposition already written, writing a determinant function is straightforward. Because each `%%cython` cell in the IPython notebook is an independent module, we have to include all the LUP decomposition code in the cell below. But everything below the `lup_determinant` function is identical to what was coded above.\n\n\n```cython\n%%cython -lm\nimport cython\nimport numpy as np\ncimport numpy as np\nfrom libc.math cimport pow\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncpdef double lup_determinant(double[:, ::1] A):\n assert A.shape[0] == A.shape[1], 'Requires square matrix.'\n cdef:\n int n = A.shape[0]\n double[:, ::1] L\n double[:, ::1] U\n double[:, ::1] P\n int nswaps\n int i\n \n L, U, P, nswaps = lup_decomp(A)\n \n cdef double det = pow(-1, nswaps)\n for i in xrange(n):\n det *= U[i, i]\n return det\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\n@cython.cdivision(True)\ncpdef lup_decomp(double[:, ::1] A):\n '''\n Perform the LUP decomposition of A:\n PA = LU\n \n Returns a tuple, (L, U, P, nswaps), where\n nswaps is the number of permutations made \n while performing the decomposition.\n '''\n \n assert A.shape[0] == A.shape[1], 'Not a square matrix.'\n \n cdef:\n int n = A.shape[0]\n int i_piv, k, j, h\n int nswaps = 0\n double[:, ::1] U = A.copy()\n double[:, ::1] P = np.eye(n)\n double[:, ::1] L = np.eye(n)\n \n for k in xrange(n-1):\n # Find the pivot row and permute matrices\n i_piv = get_pivot(U, k)\n if i_piv != k:\n nswaps += 1\n swap_rows(U, k, i_piv, k, n)\n swap_rows(P, k, i_piv, 0, n) \n if k > 0:\n swap_rows(L, k, i_piv, 0, k)\n \n # Gaussian eliminate sub-diagonal elements of U.\n for j in xrange(k+1, n):\n L[j, k] = U[j, k] / U[k, k]\n for h in xrange(k, n):\n U[j, h] -= U[k, h] * L[j, k] \n \n return (np.asarray(L), np.asarray(U), np.asarray(P), nswaps)\n \n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef int get_pivot(double[:, ::1] U, int k):\n '''\n Find the pivot row of column k in a matrix.\n The pivot row is the row i (>= k) of U for which \n abs(U[i, k]) is largest.\n '''\n cdef:\n int j\n int n = U.shape[0]\n int i_piv = k\n\n for j in xrange(k + 1, n):\n if abs(U[j, k]) > abs(U[i_piv, k]):\n i_piv = j\n return i_piv\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef void swap_rows(double[:, ::1] M, int row1, int row2, int col_start, int col_end):\n '''\n A helper function to swap segments of rows in a matrix.\n\n M[row1, col_start:col_end] <-> M[row2, col_start:col_end]\n ''' \n cdef:\n double[::1] first = M[row1, col_start:col_end].copy()\n \n M[row1, col_start:col_end] = M[row2, col_start:col_end].copy()\n M[row2, col_start:col_end] = first\n```\n\nAs always, we test accuracy and speed.\n\n\n```python\nB = np.random.randn(100).reshape((10, 10))\nprint 'Numpy'\nprint np.linalg.det(B)\nprint 'Cython, LUP determinant'\nprint lup_determinant(B)\n```\n\n Numpy\n 19.8309766936\n Cython, LUP determinant\n 19.8309766936\n\n\n\n```python\nprint 'Numpy'\n%%timeit np.linalg.det(B)\nprint 'Cython, LUP determinant'\n%%timeit lup_determinant(B)\n```\n\n Numpy\n 10000 loops, best of 3: 63.3 µs per loop\n Cython, LUP determinant\n 1000 loops, best of 3: 236 µs per loop\n\n\nOur function is still slower than numpy, but in the ballpark. It is dramatically faster than the ill-fated recursive function.\n\n------------------\n\n## Synthesis: Solving a linear system with LUP decomposition\n\nWith all the puzzle pieces on the table, the code below arranges them into a linear system solver. The function `lup_solve` simply wraps the determinant, decomposition, and backward and forward substition code already written.\n\n\n```cython\n%%cython -lm\nimport cython\nimport numpy as np\ncimport numpy as np\nfrom libc.math cimport pow, fabs\n\ndef lup_solve(double[:, ::1] A, double[::1] b):\n # Perform the LUP decomposition.\n cdef:\n double[:, ::1] L\n double[:, ::1] U\n double[:, ::1] P\n int nswaps\n L, U, P, nswaps = lup_decomp(A)\n \n # Is the determinant non-zero?\n cdef double det\n det = determinant_from_lup(U, nswaps)\n assert fabs(det) > 10e-16, 'Zero determinant'\n \n # Decomposition provides PA = LU therefore\n # Ax = b -> PAx = Pb -> LUx = Pb, which\n # can be solve by backward and forward \n # induction.\n \n # Permute b\n cdef double [::1] b_permute = matvecprod(P, b)\n \n # Solve Ly = Pb, y := Ux\n cdef double[::1] y = forward_sub_solve(L, b_permute)\n \n # Solve Ux = y\n cdef double[::1] x = backward_sub_solve(U, y)\n \n return np.asarray(x)\n \n\n@cython.boundscheck(False)\n@cython.wraparound(False)\n@cython.cdivision(True)\ncpdef lup_decomp(double[:, ::1] A):\n '''\n Perform the LUP decomposition of A:\n PA = LU\n \n Returns a tuple, (L, U, P, nswaps), where\n nswaps is the number of permutations made \n while performing the decomposition.\n '''\n \n assert A.shape[0] == A.shape[1], 'Not a square matrix.'\n \n cdef:\n int n = A.shape[0]\n int i_piv, k, j, h\n int nswaps = 0\n double[:, ::1] U = A.copy()\n double[:, ::1] P = np.eye(n)\n double[:, ::1] L = np.eye(n)\n \n for k in xrange(n-1):\n # Find the pivot row and permute matrices\n i_piv = get_pivot(U, k)\n if i_piv != k:\n nswaps += 1\n swap_rows(U, k, i_piv, k, n)\n swap_rows(P, k, i_piv, 0, n) \n if k > 0:\n swap_rows(L, k, i_piv, 0, k)\n \n # Gaussian eliminate sub-diagonal elements of U.\n for j in xrange(k+1, n):\n L[j, k] = U[j, k] / U[k, k]\n for h in xrange(k, n):\n U[j, h] -= U[k, h] * L[j, k] \n \n return (np.asarray(L), np.asarray(U), np.asarray(P), nswaps)\n \n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef int get_pivot(double[:, ::1] U, int k):\n '''\n Find the pivot row of column k in a matrix.\n The pivot row is the row i (>= k) of U for which \n abs(U[i, k]) is largest.\n '''\n cdef:\n int j\n int n = U.shape[0]\n int i_piv = k\n\n for j in xrange(k + 1, n):\n if abs(U[j, k]) > abs(U[i_piv, k]):\n i_piv = j\n return i_piv\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef void swap_rows(double[:, ::1] M, int row1, int row2, int col_start, int col_end):\n '''\n A helper function to swap segments of rows in a matrix.\n\n M[row1, col_start:col_end] <-> M[row2, col_start:col_end]\n ''' \n cdef:\n double[::1] first = M[row1, col_start:col_end].copy()\n \n M[row1, col_start:col_end] = M[row2, col_start:col_end].copy()\n M[row2, col_start:col_end] = first\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef double determinant_from_lup(double[:, ::1] U, int nswaps):\n '''\n Find the determinant of a matrix from its LUP decomposition\n U is the upper-triangular matrix from the decomposition.\n nswaps is the number of pivot swaps made.\n Both are returned by lup_decomposition; the L and P \n matrices are not needed.\n '''\n cdef double det = pow(-1, nswaps)\n for i in xrange(U.shape[0]):\n det *= U[i, i]\n return det\n\ncimport cython\nimport numpy as np\ncimport numpy as np\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\n@cython.cdivision(True)\ncdef double[::1] forward_sub_solve(double[:, ::1] L, double[::1] b):\n ''' \n Solve, by forward substition, the system Lx = b, where\n L is a lower triangular matrix.\n \n Note that the code does not check whether L is lower\n triangular. Calling the function with an arbitrary\n '''\n \n assert L.shape[1] == b.shape[0], \\\n 'Matrix and vector are incompatible shapes.'\n assert fabs(L[0, 0]) >= 10e-16, \\\n 'Zero element on diagonal.'\n \n # No. of variables to solve\n cdef int n = b.shape[0]\n \n # Loop indices\n cdef int i, k\n \n # Initialize the solution vector\n cdef double[::1] y = np.zeros(b.shape[0])\n y[0] = b[0] / L[0,0] \n\n cdef double sum_term = 0.0\n for i in xrange(1, n):\n if fabs(L[i, i]) <= 10e-16:\n raise ValueError('Zero element on diagonal.')\n sum_term = 0.0\n for k in xrange(0, i):\n sum_term += L[i, k] * y[k]\n y[i] = (b[i] - sum_term) / L[i, i]\n \n return y\n\ncdef double[::1] backward_sub_solve(double[:, ::1] U, double[::1] b):\n ''' \n Solve, by backward substition, the system Ux = b, where\n U is an upper triangular matrix.\n \n Note that the code does not check whether U is upper\n triangular. Calling the function with an arbitrary\n square matrix will result in nonsense.\n '''\n assert U.shape[1] == b.shape[0], \\\n 'Matrix and vector are incompatible shapes.'\n assert fabs(U[0, 0]) >= 10e-16, \\\n 'Zero element on diagonal.'\n \n # No. of variables to solve\n cdef int n = b.shape[0]\n \n # Loop indices\n cdef int i, k\n \n # Initialize the solution vector\n cdef double[::1] y = np.zeros(b.shape[0])\n y[n-1] = b[n-1] / U[n-1, n-1] \n\n cdef double sum_term = 0.0\n for i in xrange(n-2, -1, -1):\n if fabs(U[i, i]) <= 10e-16:\n raise ValueError('Zero element on diagonal.')\n sum_term = 0.0\n for k in xrange(i+1, n):\n sum_term += U[i, k] * y[k]\n y[i] = (b[i] - sum_term) / U[i,i]\n \n return y\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ncdef double[::1] matvecprod(double[:, ::1] A, double[::1] b):\n '''\n Matrix-vector multiplication.\n '''\n cdef: \n Py_ssize_t i, j, k\n Py_ssize_t A_n = A.shape[0]\n Py_ssize_t A_m = A.shape[1]\n Py_ssize_t b_n = b.shape[0]\n double[::1] c\n \n # Are matrices conformable?\n assert A_m == b_n, \\\n 'Non-conformable shapes.'\n \n # Initialize the results matrix.\n c = np.zeros(A_n)\n for i in xrange(A_n):\n for k in xrange(b_n):\n c[i] += A[i, k] * b[k]\n return c\n```\n\nHaving already tested its component functions, the solver ought to be correct. It matches numpy’s solver on a sample $3\\times 3$ system. \n\n\n```python\nA = np.array([[1., -2, 2], [4, 1, 3], [-2, 3, 1]])\nb = np.array([-10, 4., .25])\n\nprint 'Cython:'\nprint lup_solve(A, b)\nprint 'Numpy solve:'\nprint np.linalg.solve(A, b)\n```\n\n Cython:\n [ 2.75 3.03125 -3.34375]\n Numpy solve:\n [ 2.75 3.03125 -3.34375]\n\n\nWhile it is substantially slower than numpy—about 6 times—the absolute speed is acceptable on this small system.\n\n\n```python\nprint 'Cython:'\n%timeit lup_solve(A, b)\nprint 'Numpy solve:'\n%timeit np.linalg.solve(A, b)\n```\n\n Cython:\n 10000 loops, best of 3: 153 µs per loop\n Numpy solve\n 10000 loops, best of 3: 26.4 µs per loop\n\n\nIt solves a much larger, $1000\\times 1000$ matrix in under a second; about 20 times slower than numpy.\n\n\n```python\n# A larger 1000 x 1000 system.\nM = np.random.randn(1e6).reshape((1000, 1000))\nc = np.random.randn(1000).reshape((1000,))\n\n# Timings\nprint 'Cython'\n%timeit lup_solve(M, c)\nprint 'Numpy solve'\n%timeit np.linalg.solve(M, c)\n\n# Check that they are the same to tolerance\nif np.abs(lup_solve(M, c) - np.linalg.solve(M, c)).sum() > 10e-9:\n print 'Cython != Numpy, not OK'\nelse:\n print 'Cython = Numpy, OK'\n```\n\n## Iterative Methods: A whole other route\n\nIterative methods are an altnerative means of solving linear systems. They are not always successful, but when they are, they can be very efficient.\n\nLet $Q$ be some matrix that is easily invertible; some cadidates are mentioned below. Consider the following re-arrangement of the matrix equation:\n\n$$\n\\begin{align}\nAx &= b \\\\\\\n 0 &= b - Ax \\\\\\\nQx &= b - Ax + Qx \\\\\\\nQx &= b + (Q - A)\\,x \\\\\\\nx &= Q^{-1}b + (I-Q^{-1}A)\\,x \\,.\n\\end{align}\n$$\n\nThe last line suggests an iteration on $x$ along the following lines.\n\n$$\n\\begin{align}\nx^{(0)} &\\leftarrow \\tilde{x} \\ \\textrm{(guess)} \\\\\\\nx^{(k+1)} &\\leftarrow Q^{-1}b + (I-Q^{-1}A)\\,x^{(k)}\\\\\\\n\\textrm{until} & \\left|x^{(k-1)} - x^{(k)}\\right| \\le \\varepsilon\n\\end{align}\n$$\n\nThis is the generic form of an iterative solver. Specific methods differ in their choice of $Q$ or implementation details.\n\nThe Gauss-Siedel method is a simple, relatively robust implementation of the iteration where $Q$ is an upper triangular matrix whose entries are the upper-triangular entries of $A$. There is a somewhat simpler method, called the Jacobi method, where $Q$ is taken to be a diagonal matrix comprised of the diagonal elements of $A$. The Gauss-Siedel often has more robust convergence, though that depends on the properties of $A$. \n\nBoth methods converge better when the $A$ is diagonally dominant, when the value of each diagonal element is larger than the sum of entries in the column and row of that element. Or:\n \n$$\n\\left|a_{ii}\\right| > \\sum_{i=1\\,;\\,j\\ne i}^n\\left|a_{ij}\\right| \\;\\;\\; \\forall\\, i\n$$\n\n______________________\n\n##### Exercise: The Gauss-Siedel Algorithm\n\nThe function below implements the Gauss-Siedel method. Note that the matrix $Q$ is never formally referred to in the code. It’s inversion is baked into the iterative formula. Similarities with the forward substitution formulas coded above are not coincidental. \n\n\n```cython\n%%cython -lm\nimport cython\nimport numpy as np\ncimport numpy as np\nfrom libc.math cimport abs\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\n@cython.cdivision(True)\ncpdef gauss_siedel_solve(double[:, ::1] A, double[::1] b,\n double tol = 10e-12, int max_iter = 100):\n '''\n Solve a linear system Ax = b using the Gauss-Siedel iterative\n method.\n '''\n \n assert A.shape[0] == A.shape[1], 'Matrix is not square.'\n assert A.shape[1] == b.shape[0], \\\n 'Non-conformable matrix and vector.'\n cdef:\n int n = A.shape[0]\n double[::1] x = np.ones(n)\n int iter_i = 0\n double tol_i = 10e12 # Large number to start.\n double sum_term = 0.\n double new_x_i\n int i, j\n \n while (tol_i > tol):\n tol_i = 0.\n for i in xrange(n):\n assert abs(A[i, i]) > 10e-16, 'Zero on diagonal detected.'\n sum_term = 0.\n for j in xrange(n):\n if j != i:\n sum_term += A[i, j] * x[j]\n new_x_i = (b[i] - sum_term) / A[i, i]\n tol_i += abs(new_x_i - x[i])\n x[i] = new_x_i\n\n iter_i += 1\n if iter_i > max_iter:\n print 'Max iterations, solution may not have converged.'\n print 'Matrix may not be diagonally dominant.'\n break\n \n return (np.asarray(x), iter_i, tol_i)\n```\n\nOn a randomly generated $5\\times 5$ system, the Gauss-Seidel converges to the solution in 10 to 12 iterations.\nNote how $A$ was agumented to be diagonally dominant. Without that change, the Gauss-Seidel method typically does not converge.\n\n\n```python\n# Randomly generate a 5 x 5 linear system.\nA = np.random.randn(25).reshape((5,5)) + np.eye(5) * 10\nb = np.random.randn(5)\n\nprint 'Numpy Solve'\nprint np.linalg.solve(A, b)\nx, niter, tol = gauss_siedel_solve(A, b)\nprint 'Cython Gauss Siedel'\nprint x, '\\n # Iterations: ', niter\n```\n\n Numpy Solve\n [ 0.05977965 0.00185487 0.00081283 -0.00602107 0.11776965]\n Cython Gauss Siedel\n [ 0.05977965 0.00185487 0.00081283 -0.00602107 0.11776965] \n # Iterations: 11\n\n\nTo time the method, we’ll use a large sparse system. The cell below generates a matrix fully populated on the diagonal, but with mostly zeros elsewhere.\n\n\n```python\n# Randomly generate a 1000 x 1000 sparse linear system\nn = 1000\nn_entries = int(0.1 * n)\nA = np.eye(n) * np.random.randn(n)\noff_diag_entries = np.random.randn(n_entries)\ni = 0\nwhile (i < n_entries):\n fill_row = np.random.random_integers(0, n)\n fill_col = np.random.random_integers(0, n)\n if (fill_row == fill_col):\n continue\n else:\n A[fill_row, fill_col] = off_diag_entries[i]\n i += 1\n \nb = np.random.randn(1000)\n```\n\nFor this system, the Gauss Siedel method is substantially faster, and it converges in only a few iterations. Checking the result shows the solution it converged to is essentially the same as numpy.\n\n\n```python\nprint 'Numpy solve'\n%timeit np.linalg.solve(A, b)\nprint 'Cython Gauss-Siedel'\n%timeit gauss_siedel_solve(A, b)\n```\n\n Numpy solve\n 10 loops, best of 3: 26.1 ms per loop\n Cython Gauss-Siedel\n 100 loops, best of 3: 3.34 ms per loop\n\n\n\n```python\ny_np = np.linalg.solve(A, b)\ny_gs, niter, tol = gauss_siedel_solve(A, b)\nprint 'Gauss Siedel # iterations:', niter\nprint 'Sum abs. difference between numpy and Gauss-Seidel:', np.abs(y_np - y_gs).sum()\n\n```\n\n Gauss Siedel # iterations: 3\n Sum abs. difference: 2.87827053858e-13\n\n", "meta": {"hexsha": "b0460e3e510d3648aba36b41312e4dffedebc945", "size": 90352, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scratch_notebooks/.ipynb_checkpoints/cython_linalg-checkpoint.ipynb", "max_stars_repo_name": "vishalseshagiri/INF552_DataScienceBowl2018", "max_stars_repo_head_hexsha": "656ad5755ba706daa36b39e7ff9239b1b3035b3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-24T00:26:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-24T00:26:29.000Z", "max_issues_repo_path": "scratch_notebooks/cython_linalg.ipynb", "max_issues_repo_name": "vishalseshagiri/INF552_DataScienceBowl2018", "max_issues_repo_head_hexsha": "656ad5755ba706daa36b39e7ff9239b1b3035b3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-25T19:56:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T19:56:40.000Z", "max_forks_repo_path": "scratch_notebooks/cython_linalg.ipynb", "max_forks_repo_name": "vishalseshagiri/INF552_DataScienceBowl2018", "max_forks_repo_head_hexsha": "656ad5755ba706daa36b39e7ff9239b1b3035b3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-25T19:53:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-16T23:47:31.000Z", "avg_line_length": 33.5506869662, "max_line_length": 614, "alphanum_fraction": 0.4991588454, "converted": true, "num_tokens": 18713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.1801066728881779, "lm_q1q2_score": 0.07816295772096804}} {"text": "```python\nimport numpy as np\nimport pandas as pd\nimport linearsolve as ls\nimport matplotlib.pyplot as plt\nplt.style.use('classic')\n%matplotlib inline\n```\n\n# Homework 7\n\n**Instructions:** Complete the notebook below. Download the completed notebook in HTML format. Upload assignment using Canvas.\n\n**Due:** Mar. 5 at **12:30pm.**\n\n## Exercise: The Labor-Leisure Tradeoff\n\n\\begin{align}\n\\frac{\\varphi}{1-L_t} & = \\frac{(1-\\alpha)A_tK_t^{\\alpha}L_t^{-\\alpha}}{C_t} \\tag{1}\n\\end{align}\n\n**Questions** \n\n1. Explain words why the left-hand side of equation (1) represents the marginal cost to the household of working. A complete answer will make use of the term *marginal utility* .\n2. Explain words why the right-hand side of equation (1) represents the marginal benefit to the household of supplying labor (i.e., working). A complete answer will make use of the terms *marginal utility* and *marginal product*.\n3. Holding everything else constant, according to equation (1), what effect will an increase in TFP have on equilibrium labor? Explain the economic intuition behind your answer.\n4. Holding everything else constant, according to equation (1), what effect will an increase in household consumption have on equilibrium labor? Explain the economic intuition behind your answer.\n\n**Answers**\n\n1. The left-hand side is the derivative of the household's period $t$ utility flow with respect to $1-L_t$ and is therefore the marginal utility of leisure. A marginal increase in work effort leads to a marginal decrease in leisure of equal magnitude so the left-hand side of equation (1) reflects the utility cost at the margin of working. \n2. The right-hand side of equation (1) is the marginal product of labor times the marginal utility of consumption. A marginal increase in work effort raises household income, and therefore consumption, by the marginal product of labor: $(1-\\alpha)A_t K_t^{\\alpha}L_t^{-\\alpha}$. Accodring to the chain rule: $\\partial u /\\partial L= (\\partial u /\\partial C)(\\partial C /\\partial L)$, and so equation (1) is the additional utility at the margin of working.\n3. Multiply both sides of equation (1) by $L^{\\alpha}$ and obtain $\\varphi L^{\\alpha}/(1-L_t) = (1-\\alpha)A_tK_t^{\\alpha}/C_t$. Increasing TFP increases the right-hand side and therefore increases labor supplied because the left-hand side is an increasing function of $L$. Intuitively, an increase in TFP increases the margianl product of labor which effectively raises the price of leisure relative to consumption so the household cuts back on leisure. \n4. Increasing consumption decreases labor supplied. Intuitively, an increase in consumption reduces the marginal utility of income, reduces the household's incentive to earn income from working, and so the household takes enjoys more leisure. \n\n## Exercise: The Euler Equation\n\n\\begin{align}\n\\frac{1}{C_t} & = \\beta \\left[\\frac{\\alpha A_{t+1}K_{t+1}^{\\alpha-1}L_{t+1}^{1-\\alpha} +1-\\delta }{C_{t+1}}\\right]\\tag{2}\n\\end{align}\n\n**Questions** \n\n1. Explain words why the left-hand side of equation (2) represents the marginal cost to the household of saving (i.e., building new capital). A complete answer will make use of the term *marginal utility* .\n2. Explain words why the right-hand side of equation (2) represents the marginal benefit to the household of saving. A complete answer will make use of the terms *marginal utility* and *marginal product*.\n3. Holding everything else constant, according to equation (2), what effect will an increase in TFP in period $t+1$ have on the household's choice for capital in period $t+1$? Explain the economic intuition behind your answer.\n3. Holding everything else constant, according to equation (2), what effect will an increase in consumption in period $t$ have on the household's choice for capital in period $t+1$? Explain the economic intuition behind your answer.\n3. Holding everything else constant, according to equation (2), what effect will an increase in consumption in period $t+1$ have on the household's choice for capital in period $t+1$? Explain the economic intuition behind your answer.\n\n**Answers**\n\n1. The left-hand side is the derivative of the household's period $t$ utility flow with respect to $C_t$ and is therefore the marginal utility of consumption in period $t$. A marginal increase in saving reduces current consuption by an equal magnitude and so the left-hand side of equation (1) reflects the utility cost at the margin of saving. \n2. The right-hand side of equation (2) represents the marginal benefit to the household of saving because a marginal increase in period $t+1$ capital increases period $t+1$ consumption by the marginal product of capital plus the share of that capital that doesn't depreciate and so, by the chain rule, the increase in the $t+1$ utility flow is: $(\\alpha A_{t+1} K^{\\alpha-1}L^{1-\\alpha}+1-\\delta)/C_{t+1}$. Since the houshold realizes this change in the future, it's discounted by the subjective discount factor $\\beta$. \n3. An increase in TFP in $t+1$ would raise the $t+1$ marginal product of capital and so, since the left-hand side is unchanged, period $t+1$ capital increases to so that the marginal product of capital remains unchanged. Intuitively, an increase in future TFP raises the return to saving (in terms of future consumption) and so the household saves more. \n3. An increase in consumption in $t$ lowers the marginal utility of consumption in period $t$. Therefore the household will try to save more and so period $t+1$ capital increases. Intuitively, a household that suddenly gains more consumption in the current period will try to also increase future consumption by saving more. \n4. An increase in consumption in $t+1$ lowers the marginal utility of consumption in period $t+1$. Therefore the household will try to save less and so period $t+1$ capital increases. Intuitively, a household that suddenly gains more consumption in the next period period will try to also increase current consumption by saving less. \n", "meta": {"hexsha": "33ed4f09f64df976565c6837a69ee9cc19a524e9", "size": 7512, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Homework/Econ126_Winter2020_Homework_07.ipynb", "max_stars_repo_name": "t-hdd/econ126", "max_stars_repo_head_hexsha": "17029937bd6c40e606d145f8d530728585c30a1d", "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": "Homework/Econ126_Winter2020_Homework_07.ipynb", "max_issues_repo_name": "t-hdd/econ126", "max_issues_repo_head_hexsha": "17029937bd6c40e606d145f8d530728585c30a1d", "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": "Homework/Econ126_Winter2020_Homework_07.ipynb", "max_forks_repo_name": "t-hdd/econ126", "max_forks_repo_head_hexsha": "17029937bd6c40e606d145f8d530728585c30a1d", "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": 66.4778761062, "max_line_length": 550, "alphanum_fraction": 0.6859691161, "converted": true, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.1801066618860355, "lm_q1q2_score": 0.0781629555832518}} {"text": " **Chapter 4: [Spectroscopy](CH4-Spectroscopy.ipynb)** \n\nt3_do_train == False).\"\n\nHTML(t3_s1_display)\n```\n\n\n\n\nt3_do_train == False).\n\n\n\n**Komentar**\n\nUmjesto svakih $5000$ epoha, ovo ćemo raditi jednom po epohi. Ne vidim razlog zašto bi se to radilo češće jer je trening ovakve mreže volatilan samo na početku, pa bi češće spremanje slika bilo opravdano jedino u prvoj epohi.\n\n### Podzadatak 2\n\nNa kraju učenja prikažite kretanje gubitka kroz epohe (Matplotlib).\n\n**Odgovor**:\n\nPrvo ćemo učitati sve puteve do datoteka:\n\n\n```python\nt3_s2_folder_paths = [os.path.join(t3_root_path, f\"lambda{x:.03f}\") for x in t3_weight_decays]\n\nt3_s2_image_paths = list()\nt3_s2_results_paths = list()\n\nfor folder_path in t3_s2_folder_paths:\n last_filter_path = sorted([x for x in os.listdir(folder_path) if x.endswith(\".png\")],\n key=lambda x: x.lower())[-1]\n \n t3_s2_image_paths.append(os.path.join(folder_path, last_filter_path))\n t3_s2_results_paths.append(os.path.join(folder_path, t3_results_filename))\n```\n\nZatim možemo prikazati posljednje filtre za različite parametre $\\lambda$:\n\n\n```python\nt3_s2_figure, t3_s2_axes = plt.subplots(3, 1, figsize=(12, 9))\n\nfor i, image_path in enumerate(t3_s2_image_paths):\n t3_s2_axes[i].imshow(plt.imread(image_path), interpolation=\"nearest\")\n t3_s2_axes[i].set_title(f\"λ = {t2_weight_decays[i]}\")\n t3_s2_axes[i].axis(\"off\")\n```\n\nKonačno, možemo prikazati ovisnost gubitaka o epohama za sve 3 instance učenja:\n\n\n```python\nt3_s2_figure_l, t3_s2_axes_l = plt.subplots(1, 3, figsize=(16,5), sharey=True)\n\nfor i, result_path in enumerate(t3_s2_results_paths):\n with open(result_path) as file:\n loss_dict = json.load(file)\n \n loss, val_loss = [loss_dict[x] for x in [\"loss\", \"val_loss\"]]\n \n t3_s2_axes_l[i].set_title(f\"Gubitak za λ = {t3_weight_decays[i]}\")\n t3_s2_axes_l[i].set_xlabel(f\"Epohe\")\n t3_s2_axes_l[i].set_ylabel(f\"Gubitak\")\n \n t3_s2_axes_l[i].plot(range(len(loss)), loss, label=\"Gubitak učenja\", marker=\"o\")\n t3_s2_axes_l[i].plot(range(len(val_loss)), val_loss, label=\"Gubitak validacije\", marker=\"o\")\n \n t3_s2_axes_l[i].legend()\n```\n\n# Zadatak 4 (25%)\n\n### Klasifikacija na skupu CIFAR-10\n\n#### [<- Zadatak 3](#Zadatak-3-%C2%A0%C2%A0%C2%A0-(25%))\n\n## Postavke zadatka\n\n\n```python\nt4_do_train = False # True ako želite pokrenuti trening u podzadatku 2, False inače.\n # Upozorenje - to traje 30 minuta, ali sama validacija zauzima\n # oko 33 GB RAMa - pripremite veliki SWAP!\n\nt4_root_path = \"out_task4\"\n\nt4_results_tr_file_path = os.path.join(t4_root_path, \"results_tr.json\")\nt4_results_val_file_path = os.path.join(t4_root_path, \"results_val.json\")\nt4_learning_rates_file_path = os.path.join(t4_root_path, \"learning_rates.json\")\n\nt4_model_path = os.path.join(t4_root_path, \"model.pt\")\n\nt4_s5_path = os.path.join(t4_root_path, \"t4_s5\")\nt4_s5_best_classes_path = os.path.join(t4_s5_path, \"best_classes.json\")\nt4_s5_worst_classes_path = os.path.join(t4_s5_path, \"worst_classes.json\")\n```\n\nSkup podataka [CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html) sastoji se od $50000$ slika za učenje i validaciju te $10000$ slika za testiranje dimenzija $32 \\times 32$ podijeljenih u $10$ razreda.\n\n### Podzadatak 1\n\nNajprije skinite dataset pripremljen za Python [odavde](https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz) ili korištenjem [`torchvision.datasets.CIFAR10`](https://pytorch.org/docs/stable/torchvision/datasets.html#cifar).\n\n**Odgovor**:\n\nSkup podataka je inicijalno preuzet s [sljedeće poveznice](https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz), raspakiran i smješten u `datasets/CIFAR`.\n\n### Podzadatak 2\n\nVaš zadatak je da u PyTorchu naučite konvolucijski model na ovom skupu.\n\n**Odgovor**:\n\nOvo ćemo učiniti s nešto drukčijom arhitekturom od predložene:\n\n$\n\\begin{align}\n & \\mathrm{Conv2D \\space 64 @ 7 \\times 7} \\\\\n & \\mathrm{MaxPool(2,2)} \\\\\n & \\mathrm{PReLU} \\\\\n & \\mathrm{BatchNorm2D} \\\\\\\\\n%\n & \\mathrm{Conv2D \\space 64 @ 5 \\times 5} \\\\\n & \\mathrm{MaxPool(2,2)} \\\\\n & \\mathrm{PReLU} \\\\\n & \\mathrm{BatchNorm2D} \\\\\\\\\n%\n & \\mathrm{Conv2D \\space 64 @ 3 \\times 3} \\\\\n & \\mathrm{PReLU} \\\\\n & \\mathrm{BatchNorm2D} \\\\\n & \\mathrm{Conv2D \\space 128 @ 3 \\times 3} \\\\\n & \\mathrm{MaxPool(2,2)} \\\\\n & \\mathrm{PReLU} \\\\\n & \\mathrm{BatchNorm2D} \\\\\\\\\n%\n & \\mathrm{Flatten} \\\\\\\\\n%\n & \\mathrm{Dense(512)} \\\\\n & \\mathrm{PReLU} \\\\\n & \\mathrm{BatchNorm} \\\\\\\\\n%\n & \\mathrm{Dense(256)} \\\\\n & \\mathrm{PReLU} \\\\\n & \\mathrm{BatchNorm} \\\\\\\\\n%\n & \\mathrm{Dense(10)} \\\\\n\\end{align}\n$\n\n**Komentar**:\n\nRazlog za ovoliko drukčiji model su bolje performanse, i u smislu brže konvergencije, i u smislu postizanja bolje točnost bez augmentacije.\n\n\n```python\nt4_s2_cifar_dict = prepare_CIFAR()\n```\n\n\n```python\nt4_s2_display = \"\"\n\nif t4_do_train:\n model = CNNT4()\n model.float()\n\n model.tr(t4_s2_cifar_dict[\"x\"][0], t4_s2_cifar_dict[\"y\"][0],\n t4_s2_cifar_dict[\"x\"][1], t4_s2_cifar_dict[\"y\"][1],\n n_epochs=16, batch_size=16, weight_decay=1e-4)\n\n torch.save(model, os.path.join(t4_root_path, \"model.pt\"))\nelse:\n t4_s2_display = \"| \n | project_number | \nseries_number | \nrun_number | \ntest_number | \nmodel_number | \nship_name | \nloading_condition_id | \nascii_name | \nship_speed | \ncomment | \nfile_path_ascii | \nfile_path_ascii_temp | \nfile_path_log | \nfile_path_hdf5 | \ndate | \ntest_type | \nfacility | \nangle1 | \nangle2 | \nKörfallstyp | \nname | \nlcg | \nkg | \ngm | \nCW | \nTF | \nTA | \nBWL | \nKXX | \nKZZ | \nBTT1 | \nCP | \nVolume | \nA0 | \nRH | \nscale_factor | \nlpp | \nbeam | \nABULB | \nBKX | \nTWIN | \nDCLR | \nVDES | \nRHBL | \nASKEG | \nPD | \nARH | \nCFP | \nAIX | \nPDTDES | \nRTYPE | \nSFP | \nBKL | \nBKB | \nPROT | \nD | \nLSKEG | \nRR | \nXSKEG | \nNDES | \nAR | \nBR | \nBRA | \nIRUD | \nPTYPE | \nXRUD | \nAI | \nHSKEG | \nRSKEG | \nLOA | \nship_type_id | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| id | \n\n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n |
| 21337 | \n40178362 | \n1 | \n94 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n94.0 | \n0.0 | \nRoll decay, 0 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-04-03 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n
| 21338 | \n40178362 | \n1 | \n95 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n95.0 | \n0.0 | \nRoll decay, 0 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-04-03 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n
| 21339 | \n40178362 | \n1 | \n96 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n96.0 | \n0.0 | \nRoll decay, 0 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-11-28 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n
| 21340 | \n40178362 | \n1 | \n97 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n97.0 | \n15.5 | \nRoll decay, 15.5 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-04-04 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n
Generator: BufferStockTheory-make/notebooks_byname
\n\nFor the following badges: GitHub does not allow click-through redirects; right-click to get the link, then paste into navigation bar
\n\n\n\n[](https://colab.research.google.com/github/econ-ark/REMARK/blob/master/REMARKs/BufferStockTheory/BufferStockTheory.ipynb)\n\n[This notebook](https://github.com/econ-ark/REMARK/blob/master/REMARKs/BufferStockTheory/BufferStockTheory.ipynb) uses the [Econ-ARK/HARK](https://github.com/econ-ark/hark) toolkit to describe the main results and reproduce the figures in the paper [Theoretical Foundations of Buffer Stock Saving](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory) \n\nIf you are not familiar with the HARK toolkit, you may wish to browse the [\"Gentle Introduction to HARK\"](https://mybinder.org/v2/gh/econ-ark/DemARK/master?filepath=Gentle-Intro-To-HARK.ipynb) before continuing (since you are viewing this document, you presumably know a bit about [Jupyter Notebooks](https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/)).\n\nFor instructions on how to install the [Econ-ARK/HARK](https://github.com/econ-ark/hark) toolkit on your computer, please refer to the [QUICK START GUIDE](https://github.com/econ-ark/HARK/blob/master/README.md). \n\nThe main HARK tool used here is $\\texttt{ConsIndShockModel.py}$, in which agents have CRRA utility and face idiosyncratic shocks to permanent and transitory income. For an introduction to this module, see the [ConsIndShockModel.ipynb](https://econ-ark.org/notebooks) notebook at the [Econ-ARK](https://econ-ark.org) website.\n\n\n\n\n```python\n# This cell does some setup; please be patient, it may take 3-5 minutes\n\n# The tools for navigating the filesystem\nimport sys\nimport os\n\n# Determine the platform so we can do things specific to each \nimport platform\npform = ''\npform = platform.platform().lower()\nif 'darwin' in pform:\n pf = 'darwin' # MacOS\nif 'debian'in pform:\n pf = 'debian' # Probably cloud (MyBinder, CoLab, ...)\nif 'ubuntu'in pform:\n pf = 'debian' # Probably cloud (MyBinder, CoLab, ...)\nif 'win' in pform:\n pf = 'win'\n\n# Test whether latex is installed (some of the figures require it)\nfrom distutils.spawn import find_executable\n\niflatexExists=False\n\nif find_executable('latex'):\n iflatexExists=True\n\n# if not iflatexExists:\n# print('Some of the figures below require a full installation of LaTeX')\n \n# # If running on Mac or Win, user can be assumed to be able to install\n# # any missing packages in response to error messages; but not on cloud\n# # so load LaTeX by hand (painfully slowly)\n# if 'debian' in pf: # CoLab and MyBinder are both ubuntu\n# print('Installing LaTeX now; please wait 3-5 minutes')\n# from IPython.utils import io\n \n# with io.capture_output() as captured: # Hide hideously long output \n# os.system('apt-get update')\n# os.system('apt-get install texlive texlive-latex-extra texlive-xetex dvipng')\n# iflatexExists=True\n# else:\n# print('Please install a full distributon of LaTeX on your computer then rerun.')\n# print('A full distribution means textlive, texlive-latex-extras, texlive-xetex, dvipng, and ghostscript')\n# sys.exit()\n\n# This is a jupytext paired notebook that autogenerates BufferStockTheory.py\n# which can be executed from a terminal command line via \"ipython BufferStockTheory.py\"\n# But a terminal does not permit inline figures, so we need to test jupyter vs terminal\n# Google \"how can I check if code is executed in the ipython notebook\"\n\nfrom IPython import get_ipython # In case it was run from python instead of ipython\n\n# If the ipython process contains 'terminal' assume not in a notebook\ndef in_ipynb():\n try:\n if 'terminal' in str(type(get_ipython())):\n return False\n else:\n return True\n except NameError:\n return False\n\nif in_ipynb():\n # Now install stuff aside from LaTeX (if not already installed)\n os.system('pip install econ-ark==0.10.0.dev3')\n os.system('pip install matplotlib')\n os.system('pip install numpy')\n os.system('pip install scipy')\n os.system('pip install ipywidgets')\n os.system('pip install jupyter_contrib_nbextensions')\n os.system('jupyter contrib nbextension install --user')\n os.system('jupyter nbextension enable codefolding/main')\n os.system('jupyter nbextension enable latex_envs/latex_envs')\n os.system('jupyter nbextension enable navigation-hotkeys')\n os.system('pip install cite2c')\n os.system('python -m cite2c.install')\nelse:\n print('In batch mode')\n \n# Import related generic python packages\nimport numpy as np\nfrom time import clock\nmystr = lambda number : \"{:.4f}\".format(number)\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import plot, draw, show\n\n# In order to use LaTeX to manage all text layout in our figures, \n# we import rc settings from matplotlib.\nfrom matplotlib import rc\n\nplt.rc('font', family='serif')\nplt.rc('text', usetex=iflatexExists)\n\n# The warnings package allows us to ignore some harmless but alarming warning messages\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom copy import copy, deepcopy\n\n# Determine whether to make the figures inline (for spyder or jupyter)\n# vs whatever is the automatic setting that will apply if run from the terminal\nif in_ipynb():\n # %matplotlib inline generates a syntax error when run from the shell\n # so do this instead\n get_ipython().run_line_magic('matplotlib', 'inline')\nelse:\n get_ipython().run_line_magic('matplotlib', 'auto')\n\n# Code to allow a master \"Generator\" and derived \"Generated\" versions\nGenerator=False # Is this notebook the master or is it generated?\n\n# Define (and create, if necessary) the figures directory \"Figures\"\nif Generator:\n my_file_path = os.path.dirname(os.path.abspath(\"BufferStockTheory.ipynb\")) # Find pathname to this file:\n Figures_HARK_dir = os.path.join(my_file_path,\"Figures/\") # LaTeX document assumes figures will be here\n Figures_HARK_dir = os.path.join(my_file_path,\"/tmp/Figures/\") # Uncomment to make figures outside of git path\n if not os.path.exists(Figures_HARK_dir):\n os.makedirs(Figures_HARK_dir)\n \nif not in_ipynb(): # running in batch mode\n print('You appear to be running from a terminal')\n print('By default, figures will appear one by one')\n```\n\n\n```python\n# Import HARK tools needed\n\nfrom HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType\nfrom HARK.utilities import plotFuncsDer, plotFuncs\n```\n\n## [The Problem](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#The-Problem) \n\nThe paper defines and calibrates a small set of parameters: \n\n| Parameter | Description | Code | Value |\n|:---:| --- | --- | :---: |\n| $\\Gamma$ | Permanent Income Growth Factor | $\\texttt{PermGroFac}$ | 1.03 |\n| $\\mathsf{R}$ | Interest Factor | $\\texttt{Rfree}$ | 1.04 |\n| $\\beta$ | Time Preference Factor | $\\texttt{DiscFac}$ | 0.96 |\n| $\\rho$ | Coefficient of Relative Risk Aversion| $\\texttt{CRRA}$ | 2 |\n| $\\wp$ | Probability of Unemployment | $\\texttt{UnempPrb}$ | 0.005 |\n| $\\mu$ | Income when Unemployed | $\\texttt{IncUnemp}$ | 0. |\n| $\\sigma_\\psi$ | Std Dev of Log Permanent Shock| $\\texttt{PermShkStd}$ | 0.1 |\n| $\\sigma_\\theta$ | Std Dev of Log Transitory Shock| $\\texttt{TranShkStd}$ | 0.1 |\n\nFor a microeconomic consumer with 'Market Resources' (net worth plus current income) $M_{t}$, end-of-period assets $A_{t}$ will be the amount remaining after consumption of $C_{t}$. \n\\begin{eqnarray}\nA_{t} &=&M_{t}-C_{t}\n\\end{eqnarray}\n\nThe consumer's permanent noncapital income $P$ grows by a predictable factor $\\Gamma$ and is subject to an unpredictable lognormally distributed multiplicative shock $\\mathbb{E}_{t}[\\psi_{t+1}]=1$, \n\\begin{eqnarray}\nP_{t+1} & = & P_{t} \\Gamma \\psi_{t+1}\n\\end{eqnarray}\n\nand actual income is permanent income multiplied by a logormal multiplicative transitory shock, $\\mathbb{E}_{t}[\\theta_{t+1}]=1$, so that next period's market resources are\n\\begin{eqnarray}\n%M_{t+1} &=& B_{t+1} +P_{t+1}\\theta_{t+1}, \\notag\nM_{t+1} &=& A_{t}\\mathsf{R} +P_{t+1}\\theta_{t+1}. \\notag\n\\end{eqnarray}\n\nWhen the consumer has a CRRA utility function $u(c)=\\frac{c^{1-\\rho}}{1-\\rho}$, the paper shows that the problem can be written in terms of ratios of money variables to permanent income, e.g. $m_{t} \\equiv M_{t}/P_{t}$, and the Bellman form of [the problem reduces to](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#The-Related-Problem):\n\n\\begin{eqnarray*}\nv_t(m_t) &=& \\max_{c_t}~~ u(c_t) + \\beta~\\mathbb{E}_{t} [(\\Gamma\\psi_{t+1})^{1-\\rho} v_{t+1}(m_{t+1}) ] \\\\\n& s.t. & \\\\\na_t &=& m_t - c_t \\\\\nm_{t+1} &=& R/(\\Gamma \\psi_{t+1}) a_t + \\theta_{t+1} \\\\\n\\end{eqnarray*}\n\n\n\n```python\n# Define a parameter dictionary with baseline parameter values\n\n# Set the baseline parameter values \nPermGroFac = 1.03\nRfree = 1.04\nDiscFac = 0.96\nCRRA = 2.00\nUnempPrb = 0.005\nIncUnemp = 0.0\nPermShkStd = 0.1\nTranShkStd = 0.1\n# Import default parameter values\nimport HARK.ConsumptionSaving.ConsumerParameters as Params \n\n# Make a dictionary containing all parameters needed to solve the model\nbase_params = Params.init_idiosyncratic_shocks\n\n# Set the parameters for the baseline results in the paper\n# using the variable values defined in the cell above\nbase_params['PermGroFac'] = [PermGroFac] # Permanent income growth factor\nbase_params['Rfree'] = Rfree # Interest factor on assets\nbase_params['DiscFac'] = DiscFac # Time Preference Factor\nbase_params['CRRA'] = CRRA # Coefficient of relative risk aversion\nbase_params['UnempPrb'] = UnempPrb # Probability of unemployment (e.g. Probability of Zero Income in the paper)\nbase_params['IncUnemp'] = IncUnemp # Induces natural borrowing constraint\nbase_params['PermShkStd'] = [PermShkStd] # Standard deviation of log permanent income shocks\nbase_params['TranShkStd'] = [TranShkStd] # Standard deviation of log transitory income shocks\n\n# Some technical settings that are not interesting for our purposes\nbase_params['LivPrb'] = [1.0] # 100 percent probability of living to next period\nbase_params['CubicBool'] = True # Use cubic spline interpolation\nbase_params['T_cycle'] = 1 # No 'seasonal' cycles\nbase_params['BoroCnstArt'] = None # No artificial borrowing constraint\n```\n\n## Convergence of the Consumption Rules\n\nUnder the given parameter values, [the paper's first figure](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#Convergence-of-the-Consumption-Rules) depicts the successive consumption rules that apply in the last period of life $(c_{T}(m))$, the second-to-last period, and earlier periods $(c_{T-n})$. $c(m)$ is the consumption function to which these converge as \n\n\\[\nc(m) = \\lim_{n \\uparrow \\infty} c_{T-n}(m)\n\\]\n\n\n\n```python\n# Create a buffer stock consumer instance by passing the dictionary to the class.\nbaseEx = IndShockConsumerType(**base_params)\nbaseEx.cycles = 100 # Make this type have a finite horizon (Set T = 100)\n\nbaseEx.solve() # Solve the model\nbaseEx.unpackcFunc() # Make the consumption function easily accessible\n\n\n\n```\n\n\n```python\n# Plot the different periods' consumption rules.\n\nm1 = np.linspace(0,9.5,1000) # Set the plot range of m\nm2 = np.linspace(0,6.5,500)\nc_m = baseEx.cFunc[0](m1) # c_m can be used to define the limiting infinite-horizon consumption rule here\nc_t1 = baseEx.cFunc[-2](m1) # c_t1 defines the second-to-last period consumption rule\nc_t5 = baseEx.cFunc[-6](m1) # c_t5 defines the T-5 period consumption rule\nc_t10 = baseEx.cFunc[-11](m1) # c_t10 defines the T-10 period consumption rule\nc_t0 = m2 # c_t0 defines the last period consumption rule\nplt.figure(figsize = (12,9))\nplt.plot(m1,c_m,color=\"black\")\nplt.plot(m1,c_t1,color=\"black\")\nplt.plot(m1,c_t5,color=\"black\")\nplt.plot(m1,c_t10,color=\"black\")\nplt.plot(m2,c_t0,color=\"black\")\nplt.xlim(0,11)\nplt.ylim(0,7)\nplt.text(7,6,r'$c_{T}(m) = 45$ degree line',fontsize = 22,fontweight='bold')\nplt.text(9.6,5.3,r'$c_{T-1}(m)$',fontsize = 22,fontweight='bold')\nplt.text(9.6,2.6,r'$c_{T-5}(m)$',fontsize = 22,fontweight='bold')\nplt.text(9.6,2.1,r'$c_{T-10}(m)$',fontsize = 22,fontweight='bold')\nplt.text(9.6,1.7,r'$c(m)$',fontsize = 22,fontweight='bold')\nplt.arrow(6.9,6.05,-0.6,0,head_width= 0.1,width=0.001,facecolor='black',length_includes_head='True')\nplt.tick_params(labelbottom=False, labelleft=False,left='off',right='off',bottom='off',top='off')\nplt.text(0,7.05,\"$c$\",fontsize = 26)\nplt.text(11.1,0,\"$m$\",fontsize = 26)\n# Save the figures in several formats\nif Generator:\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncsConverge.png'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncsConverge.jpg'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncsConverge.pdf'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncsConverge.svg'))\nif not in_ipynb():\n plt.ioff()\n plt.draw()\n# plt.show(block=False) \n plt.pause(1)\nelse:\n plt.show(block=True) # Change to False if you want to run uninterrupted\n \n\n\n```\n\n## Factors and Conditions\n\n### [The Finite Human Wealth Condition](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#Human-Wealth)\n\nHuman wealth for a perfect foresight consumer is defined as the present discounted value of future income:\n\n\\begin{eqnarray}\nH_{t} & = & \\mathbb{E}_{t}[P_{t} + \\mathsf{R}^{-1} P_{t+1} + \\mathsf{R}^{2} P_{t+2} ... ] \\\\ \n & = & P_{t} \\left(1 + (\\Gamma/\\mathsf{R}) + (\\Gamma/\\mathsf{R})^{2} ... \\right)\n\\end{eqnarray}\nwhich is an infinite number if $\\Gamma/\\mathsf{R} \\geq 1$. We say that the 'Finite Human Wealth Condition' (FHWC) holds if \n$0 \\leq (\\Gamma/\\mathsf{R}) < 1$.\n\n### [Absolute Patience and the AIC](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#AIC)\n\nThe paper defines the Absolute Patience Factor as being equal to the ratio of $C_{t+1}/C_{t}$ for a perfect foresight consumer. The Old English character \"Þ\" is used for this object in the paper, but \"Þ\" cannot currently be rendered conveniently in Jupyter notebooks, so we will substitute $\\Phi$ here:\n\n\\begin{equation}\n\\Phi = (\\mathsf{R} \\beta)^{1/\\rho} \n\\end{equation}\n\nIf $\\Phi = 1$, a perfect foresight consumer will spend exactly the amount that can be sustained perpetually (given their current and future resources). If $\\Phi < 1$ (the consumer is 'absolutely impatient'; or, 'the absolute impatience condition holds'), the consumer is consuming more than the sustainable amount, so consumption will fall, and if the consumer is 'absolutely patient' with $\\Phi > 1$ consumption will grow over time.\n\n\n\n### [Growth Patience and the GIC](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#GIC)\n\nFor a [perfect foresight consumer](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA), whether the ratio of consumption to the permanent component of income $P$ is rising, constant, or falling depends on the relative growth rates of consumption and permanent income, which is measured by the \"Perfect Foresight Growth Patience Factor\":\n\n\\begin{eqnarray}\n\\Phi_{\\Gamma} & = & \\Phi/\\Gamma\n\\end{eqnarray}\nand whether the ratio is falling or rising over time depends on whether $\\Phi_{\\Gamma}$ is below or above 1.\n\nAn analogous condition can be defined when there is uncertainty about permanent income. Defining $\\tilde{\\Gamma} = (\\mathbb{E}[\\psi^{-1}])^{-1}\\Gamma$, the 'Growth Impatience Condition' (GIC) is that \n\\begin{eqnarray}\n \\Phi/\\tilde{\\Gamma} & < & 1\n\\end{eqnarray}\n\n### [The Finite Value of Autarky Condition (FVAC)](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#Autarky-Value)\n\nThe paper [shows](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#Autarky-Value) that a consumer who planned to spend his permanent income $\\{ p_{t}, p_{t+1}, ...\\} $ in every period would have value defined by\n\n\\begin{equation}\nv_{t}^{\\text{autarky}} = u(p_{t})\\left(\\frac{1}{1-\\beta \\Gamma^{1-\\rho} \\mathbb{E}[\\psi^{1-\\rho}]}\\right)\n\\end{equation}\n\nand defines the 'Finite Value of Autarky Condition' as the requirement that the denominator of this expression be a positive finite number:\n\n\\begin{equation}\n\\beta \\Gamma^{1-\\rho} \\mathbb{E}[\\psi^{1-\\rho}] < 1\n\\end{equation}\n\n### [The Weak Return Impatience Condition (WRIC)](http://www.econ2.jhu.edu/people/ccarroll/papers/BufferStockTheory/#WRIC)\n\nThe 'Return Impatience Condition' $\\Phi/\\mathsf{R} < 1$ has long been understood to be required for the perfect foresight model to have a nondegenerate solution (when $\\rho=1$, this reduces to $\\beta < R$). If the RIC does not hold, the consumer is so patient that the optimal consumption function approaches zero as the horizon extends.\n\nWhen the probability of unemployment is $\\wp$, the paper articulates an analogous (but weaker) condition:\n\n\\begin{eqnarray}\n \\wp^{1/\\rho} \\Phi/\\mathsf{R} & < & 1\n\\end{eqnarray}\n\n# Key Results\n\n## [Nondegenerate Solution Requires FVAC and WRIC](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#Sufficient-Conditions-For-Nondegenerate-Solution)\n\nA main result of the paper is that the conditions required for the model to have a nondegenerate solution ($0 < c(m) < \\infty$ for feasible $m$) are that the Finite Value of Autarky (FVAC) and Weak Return Impatience Condition (WRAC) hold.\n\n## [Natural Borrowing Constraint limits to Artificial Borrowing Constraint](http://www.econ2.jhu.edu/people/ccarroll/papers/BufferStockTheory/#The-Liquidity-Constrained-Solution-as-a-Limit)\n\nDefining $\\chi(\\wp)$ as the consumption function associated with any particular value of $\\wp$, and defining $\\hat{\\chi}$ as the consumption function that would apply in the absence of the zero-income shocks but in the presence of an 'artificial' borrowing constraint requiring $a \\geq 0$, a la Deaton (1991), the paper shows that \n\n\\begin{eqnarray}\n\\lim_{\\wp \\downarrow 0}~\\chi(\\wp) & = & \\hat{\\chi}\n\\end{eqnarray}\n\nThat is, as $\\wp$ approaches zero the problem with uncertainty becomes identical to the problem that instead has constraints. (See [Precautionary Saving and Liquidity Constraints](http://econ.jhu.edu/people/ccarroll/papers/LiqConstr) for a full treatment of the relationship between precautionary saving and liquidity constraints).\n\n## [$c(m)$ is Finite Even When Human Wealth Is Infinite](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#When-The-GIC-Fails)\n\nIn the perfect foresight model, if $\\mathsf{R} < \\Gamma$ the present discounted value of future labor income is infinite and so the limiting consumption function is $c(m) = \\infty$ for all $m$. Many models have no well-defined solution in this case.\n\nThe presence of uncertainty changes this: The limiting consumption function is finite for all values of $m$. \n\nThis is because uncertainty imposes a \"natural borrowing constraint\" that deters the consumer from borrowing against their unbounded future labor income.\n\nA [table](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#Sufficient-Conditions-For-Nondegenerate-Solution) puts this result in the context of implications of other conditions and restrictions.\n\n\n\n## [If the GIC Holds, $\\exists$ a finite 'target' $m$](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#onetarget)\n\nSection [There Is Exactly One Target $m$ Ratio, Which Is Stable](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#onetarget) shows that, under parameter values for which the limiting consumption function exists, if the GIC holds then there will be a value $\\check{m}$ such that:\n\n\\begin{eqnarray}\n\\mathbb{E}[m_{t+1}] & > & m_{t}~\\text{if $m_{t} < \\check{m}$} \\\\\n\\mathbb{E}[m_{t+1}] & < & m_{t}~\\text{if $m_{t} > \\check{m}$} \\\\\n\\mathbb{E}[m_{t+1}] & = & m_{t}~\\text{if $m_{t} = \\check{m}$}\n\\end{eqnarray} \n\n## [If the GIC Fails, Target Wealth is Infinite ](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#The-GIC)\n\n[A figure](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#FVACnotGIC) depicts a solution when the **FVAC** (Finite Value of Autarky Condition) and **WRIC** hold (so that the model has a solution) but the **GIC** (Growth Impatience Condition) fails. In this case the target wealth ratio is infinity. \n\nThe parameter values in this specific example are:\n\n| Param | Description | Code | Value |\n| :---: | --- | --- | :---: |\n| $\\Gamma$ | Permanent Income Growth Factor | $\\texttt{PermGroFac}$ | 1.00 |\n| $\\mathrm{\\mathsf{R}}$ | Interest Factor | $\\texttt{Rfree}$ | 1.08 |\n\nThe figure is reproduced below.\n\n\n```python\n# Construct the \"GIC fails\" example.\n\nGIC_fail_dictionary = dict(base_params)\nGIC_fail_dictionary['Rfree'] = 1.08\nGIC_fail_dictionary['PermGroFac'] = [1.00]\n\nGICFailExample = IndShockConsumerType(\n cycles=0, # cycles=0 makes this an infinite horizon consumer\n **GIC_fail_dictionary)\n```\n\n The given type violates the absolute impatience condition with the supplied parameter values; the AIF is 1.01823 \n The given parameter values violate the growth impatience condition for this consumer type; the GIF is: 1.0088\n\n\nThe $\\mathtt{IndShockConsumerType}$ tool automatically checks various parametric conditions, and will give a warning as well as the values of the factors if any conditions fail to be met. \n\nWe can also directly check the conditions, in which case results will be a little more verbose by default.\n\n\n```python\n# The checkConditions method does what it sounds like it would\nGICFailExample.checkConditions(verbose=True)\n```\n\n The given type violates the absolute impatience condition with the supplied parameter values; the AIF is 1.01823 \n Therefore, the absolute amount of consumption is expected to grow over time\n The given parameter values violate the growth impatience condition for this consumer type; the GIF is: 1.0088\n Therefore, a target level of wealth does not exist.\n The weak return impatience factor value for the supplied parameter values satisfies the weak return impatience condition.\n The finite value of autarky factor value for the supplied parameter values satisfies the finite value of autarky condition.\n \n [!] For more information on the conditions, see Table 3 in \"Theoretical Foundations of Buffer Stock Saving\" at http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/\n\n\nNext we define the function $\\mathrm{\\mathbb{E}}_{t}[\\Delta m_{t+1}]$ that shows the ‘sustainable’ level of spending at which $m$ is expected to remain unchanged.\n\n\n```python\n# Calculate \"Sustainable\" consumption that leaves expected m unchanged\n# In the perfect foresight case, this is just permanent income plus interest income\n# A small adjustment is required to take account of the consequences of uncertainty\nInvEpShInvAct = np.dot(GICFailExample.PermShkDstn[0][0], GICFailExample.PermShkDstn[0][1]**(-1))\nInvInvEpShInvAct = (InvEpShInvAct) ** (-1)\nPermGroFacAct = GICFailExample.PermGroFac[0] * InvInvEpShInvAct\nER = GICFailExample.Rfree / PermGroFacAct\nEr = ER - 1\nmSSfunc = lambda m : 1 + (m-1)*(Er/ER)\n```\n\n\n```python\n# Plot GICFailExample consumption function against the sustainable level of consumption\n\nGICFailExample.solve() # Above, we set up the problem but did not solve it \nGICFailExample.unpackcFunc() # Make the consumption function easily accessible for plotting\nm = np.linspace(0,5,1000)\nc_m = GICFailExample.cFunc[0](m)\nE_m = mSSfunc(m)\nplt.figure(figsize = (12,8))\nplt.plot(m,c_m,color=\"black\")\nplt.plot(m,E_m,color=\"black\")\nplt.xlim(0,5.5)\nplt.ylim(0,1.6)\nplt.text(0,1.63,\"$c$\",fontsize = 26)\nplt.text(5.55,0,\"$m$\",fontsize = 26)\nplt.tick_params(labelbottom=False, labelleft=False,left='off',right='off',bottom='off',top='off')\nplt.text(1,0.6,\"$c(m_{t})$\",fontsize = 18)\nplt.text(1.5,1.2,\"$\\mathsf{E}_{t}[\\Delta m_{t+1}] = 0$\",fontsize = 18)\nplt.arrow(0.98,0.62,-0.2,0,head_width= 0.02,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(2.2,1.2,0.3,-0.05,head_width= 0.02,width=0.001,facecolor='black',length_includes_head='True')\nif Generator:\n plt.savefig(os.path.join(Figures_HARK_dir, 'FVACnotGIC.png'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'FVACnotGIC.jpg'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'FVACnotGIC.pdf'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'FVACnotGIC.svg'))\n\n# This figure reproduces the figure shown in the paper. \n# The gap between the two functions actually increases with $m$ in the limit.\nif not in_ipynb():\n plt.show(block=False) \n plt.pause(1)\nelse:\n plt.show(block=True) # Change to False if you want to run uninterrupted\n```\n\nAs a foundation for the remaining figures, we define another instance of the class $\\texttt{IndShockConsumerType}$, which has the same parameter values as the instance $\\texttt{baseEx}$ defined previously but is solved to convergence (our definition of an infinite horizon agent type)\n\n\n\n```python\n# cycles=0 tells the solver to find the infinite horizon solution\nbaseEx_inf = IndShockConsumerType(cycles=0,**base_params)\n\nbaseEx_inf.solve()\nbaseEx_inf.unpackcFunc()\n```\n\n### [Target $m$, Expected Consumption Growth, and Permanent Income Growth](https://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#AnalysisoftheConvergedConsumptionFunction)\n\nThe next figure is shown in [Analysis of the Converged Consumption Function](https://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#cGroTargetFig), which shows the expected consumption growth factor $\\mathrm{\\mathbb{E}}_{t}[c_{t+1}/c_{t}]$ for a consumer behaving according to the converged consumption rule.\n\n\n\n```python\n# Define a function to calculate expected consumption \ndef exp_consumption(a):\n '''\n Taking end-of-period assets as input, return expectation of next period's consumption\n Inputs:\n a: end-of-period assets\n Returns:\n expconsump: next period's expected consumption\n '''\n GrowFactp1 = baseEx_inf.PermGroFac[0]* baseEx_inf.PermShkDstn[0][1]\n Rnrmtp1 = baseEx_inf.Rfree / GrowFactp1\n # end-of-period assets plus normalized returns\n btp1 = Rnrmtp1*a\n # expand dims of btp1 and use broadcasted sum of a column and a row vector\n # to obtain a matrix of possible beginning-of-period assets next period\n mtp1 = np.expand_dims(btp1, axis=1) + baseEx_inf.TranShkDstn[0][1]\n part_expconsumption = GrowFactp1*baseEx_inf.cFunc[0](mtp1).T\n # finish expectation over permanent income shocks by right multiplying with\n # the weights\n part_expconsumption = np.dot(part_expconsumption, baseEx_inf.PermShkDstn[0][0])\n # finish expectation over transitory income shocks by right multiplying with\n # weights\n expconsumption = np.dot(part_expconsumption, baseEx_inf.TranShkDstn[0][0])\n # return expected consumption\n return expconsumption\n```\n\n\n```python\n# Calculate the expected consumption growth factor\nm1 = np.linspace(1,baseEx_inf.solution[0].mNrmSS,50) # m1 defines the plot range on the left of target m value (e.g. m <= target m)\nc_m1 = baseEx_inf.cFunc[0](m1)\na1 = m1-c_m1\nexp_consumption_l1 = []\nfor i in range(len(a1)):\n exp_consumption_tp1 = exp_consumption(a1[i])\n exp_consumption_l1.append(exp_consumption_tp1)\n\n# growth1 defines the values of expected consumption growth factor when m is less than target m\ngrowth1 = np.array(exp_consumption_l1)/c_m1\n\n# m2 defines the plot range on the right of target m value (e.g. m >= target m)\nm2 = np.linspace(baseEx_inf.solution[0].mNrmSS,1.9,50)\n\nc_m2 = baseEx_inf.cFunc[0](m2)\na2 = m2-c_m2\nexp_consumption_l2 = []\nfor i in range(len(a2)):\n exp_consumption_tp1 = exp_consumption(a2[i])\n exp_consumption_l2.append(exp_consumption_tp1)\n\n# growth 2 defines the values of expected consumption growth factor when m is bigger than target m\ngrowth2 = np.array(exp_consumption_l2)/c_m2\n```\n\n\n```python\n# Define a function to construct the arrows on the consumption growth rate function\ndef arrowplot(axes, x, y, narrs=15, dspace=0.5, direc='neg',\n hl=0.01, hw=3, c='black'):\n '''\n The function is used to plot arrows given the data x and y.\n\n Input:\n narrs : Number of arrows that will be drawn along the curve\n\n dspace : Shift the position of the arrows along the curve.\n Should be between 0. and 1.\n\n direc : can be 'pos' or 'neg' to select direction of the arrows\n\n hl : length of the arrow head\n\n hw : width of the arrow head\n\n c : color of the edge and face of the arrow head\n '''\n\n # r is the distance spanned between pairs of points\n r = np.sqrt(np.diff(x)**2+np.diff(y)**2)\n r = np.insert(r, 0, 0.0)\n\n # rtot is a cumulative sum of r, it's used to save time\n rtot = np.cumsum(r)\n\n # based on narrs set the arrow spacing\n aspace = r.sum() / narrs\n\n if direc is 'neg':\n dspace = -1.*abs(dspace)\n else:\n dspace = abs(dspace)\n\n arrowData = [] # will hold tuples of x,y,theta for each arrow\n arrowPos = aspace*(dspace) # current point on walk along data\n # could set arrowPos to 0 if you want\n # an arrow at the beginning of the curve\n\n ndrawn = 0\n rcount = 1\n while arrowPos < r.sum() and ndrawn < narrs:\n x1,x2 = x[rcount-1],x[rcount]\n y1,y2 = y[rcount-1],y[rcount]\n da = arrowPos-rtot[rcount]\n theta = np.arctan2((x2-x1),(y2-y1))\n ax = np.sin(theta)*da+x1\n ay = np.cos(theta)*da+y1\n arrowData.append((ax,ay,theta))\n ndrawn += 1\n arrowPos+=aspace\n while arrowPos > rtot[rcount+1]:\n rcount+=1\n if arrowPos > rtot[-1]:\n break\n\n for ax,ay,theta in arrowData:\n # use aspace as a guide for size and length of things\n # scaling factors were chosen by experimenting a bit\n\n dx0 = np.sin(theta)*hl/2.0 + ax\n dy0 = np.cos(theta)*hl/2.0 + ay\n dx1 = -1.*np.sin(theta)*hl/2.0 + ax\n dy1 = -1.*np.cos(theta)*hl/2.0 + ay\n\n if direc is 'neg' :\n ax0 = dx0\n ay0 = dy0\n ax1 = dx1\n ay1 = dy1\n else:\n ax0 = dx1\n ay0 = dy1\n ax1 = dx0\n ay1 = dy0\n\n axes.annotate('', xy=(ax0, ay0), xycoords='data',\n xytext=(ax1, ay1), textcoords='data',\n arrowprops=dict( headwidth=hw, frac=1., ec=c, fc=c))\n```\n\n\n```python\n# Plot consumption growth as a function of market resources\n# Calculate Absolute Patience Factor Phi = lower bound of consumption growth factor\nAbsPatientFac = (baseEx_inf.Rfree*baseEx_inf.DiscFac)**(1.0/baseEx_inf.CRRA)\n\nfig = plt.figure(figsize = (12,8))\nax = fig.add_subplot(111)\n# Plot the Absolute Patience Factor line\nax.plot([0,1.9],[AbsPatientFac,AbsPatientFac],color=\"black\")\n\n# Plot the Permanent Income Growth Factor line\nax.plot([0,1.9],[baseEx_inf.PermGroFac[0],baseEx_inf.PermGroFac[0]],color=\"black\")\n\n# Plot the expected consumption growth factor on the left side of target m\nax.plot(m1,growth1,color=\"black\")\n\n# Plot the expected consumption growth factor on the right side of target m\nax.plot(m2,growth2,color=\"black\")\n\n# Plot the arrows\narrowplot(ax, m1,growth1)\narrowplot(ax, m2,growth2, direc='pos')\n\n# Plot the target m\nax.plot([baseEx_inf.solution[0].mNrmSS,baseEx_inf.solution[0].mNrmSS],[0,1.4],color=\"black\",linestyle=\"--\")\nax.set_xlim(1,2.05)\nax.set_ylim(0.98,1.08)\nax.text(1,1.082,\"Growth Rate\",fontsize = 26,fontweight='bold')\nax.text(2.055,0.98,\"$m_{t}$\",fontsize = 26,fontweight='bold')\nax.text(1.9,1.01,\"$\\mathsf{E}_{t}[c_{t+1}/c_{t}]$\",fontsize = 22,fontweight='bold')\nax.text(baseEx_inf.solution[0].mNrmSS,0.975, r'$\\check{m}$', fontsize = 26,fontweight='bold')\nax.tick_params(labelbottom=False, labelleft=False,left='off',right='off',bottom='off',top='off')\nax.text(1.9,0.998,r'$\\Phi = (\\mathrm{\\mathsf{R}}\\beta)^{1/\\rho}$',fontsize = 22,fontweight='bold')\nax.text(1.9,1.03, r'$\\Gamma$',fontsize = 22,fontweight='bold')\nif Generator:\n fig.savefig(os.path.join(Figures_HARK_dir, 'cGroTargetFig.png'))\n fig.savefig(os.path.join(Figures_HARK_dir, 'cGroTargetFig.jpg'))\n fig.savefig(os.path.join(Figures_HARK_dir, 'cGroTargetFig.pdf'))\n fig.savefig(os.path.join(Figures_HARK_dir, 'cGroTargetFig.svg'))\nif not in_ipynb():\n plt.show(block=False) \n plt.pause(1)\nelse:\n plt.show(block=True) # Change to False if you want to run uninterrupted\n```\n\n### [Consumption Function Bounds](https://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#AnalysisOfTheConvergedConsumptionFunction)\n[The next figure](https://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#cFuncBounds)\nillustrates theoretical bounds for the consumption function.\n\nWe define two useful variables: lower bound of $\\kappa$ (marginal propensity to consume) and limit of $h$ (Human wealth), along with some functions such as limiting perfect foresight consumption functions ($\\bar{c}(m)$), $\\bar{\\bar c}(m)$ and $\\underline{c}(m)$.\n\n\n```python\n# Define k_lower, h_inf and perfect foresight consumption function, upper bound of consumption function and lower\n# bound of consumption function.\nk_lower = 1.0-(baseEx_inf.Rfree**(-1.0))*(baseEx_inf.Rfree*baseEx_inf.DiscFac)**(1.0/baseEx_inf.CRRA)\nh_inf = (1.0/(1.0-baseEx_inf.PermGroFac[0]/baseEx_inf.Rfree))\nconFunc_PF = lambda m: (h_inf -1)* k_lower + k_lower*m\nconFunc_upper = lambda m: (1 - baseEx_inf.UnempPrb ** (1.0/baseEx_inf.CRRA)*(baseEx_inf.Rfree*baseEx_inf.DiscFac)**(1.0/baseEx_inf.CRRA)/baseEx_inf.Rfree)*m\nconFunc_lower = lambda m: (1 -(baseEx_inf.Rfree*baseEx_inf.DiscFac)**(1.0/baseEx_inf.CRRA)/baseEx_inf.Rfree) * m\nintersect_m = ((h_inf-1)* k_lower)/((1 - baseEx_inf.UnempPrb\n **(1.0/baseEx_inf.CRRA)*(baseEx_inf.Rfree*baseEx_inf.DiscFac)**(1.0/baseEx_inf.CRRA)/baseEx_inf.Rfree)-k_lower)\n```\n\n\n```python\n# Plot the consumption function and its bounds\n\nx1 = np.linspace(0,25,1000)\nx3 = np.linspace(0,intersect_m,300)\nx4 = np.linspace(intersect_m,25,700)\ncfunc_m = baseEx_inf.cFunc[0](x1)\ncfunc_PF_1 = conFunc_PF(x3)\ncfunc_PF_2 = conFunc_PF(x4)\ncfunc_upper_1 = conFunc_upper(x3)\ncfunc_upper_2 = conFunc_upper(x4)\ncfunc_lower = conFunc_lower(x1)\nplt.figure(figsize = (12,8))\nplt.plot(x1,cfunc_m, color=\"black\")\nplt.plot(x1,cfunc_lower, color=\"black\",linewidth=2.5)\nplt.plot(x3,cfunc_upper_1, color=\"black\",linewidth=2.5)\nplt.plot(x4,cfunc_PF_2 , color=\"black\",linewidth=2.5)\nplt.plot(x4,cfunc_upper_2 , color=\"black\",linestyle=\"--\")\nplt.plot(x3,cfunc_PF_1 , color=\"black\",linestyle=\"--\")\nplt.tick_params(labelbottom=False, labelleft=False,left='off',right='off',bottom='off',top='off')\nplt.xlim(0,25)\nplt.ylim(0,1.12*conFunc_PF(25))\nplt.text(0,1.12*conFunc_PF(25)+0.05,\"$c$\",fontsize = 22)\nplt.text(25+0.1,0,\"$m$\",fontsize = 22)\nplt.text(2.5,1,r'$c(m)$',fontsize = 22,fontweight='bold')\nplt.text(6,5,r'$\\overline{\\overline{c}}(m)= \\overline{\\kappa}m = (1-\\wp^{1/\\rho}\\Phi_{R})m$',fontsize = 22,fontweight='bold')\nplt.text(2.2,3.8, r'$\\overline{c}(m) = (m-1+h)\\underline{\\kappa}$',fontsize = 22,fontweight='bold')\nplt.text(9,4.1,r'Upper Bound $ = $ Min $[\\overline{\\overline{c}}(m),\\overline{c}(m)]$',fontsize = 22,fontweight='bold')\nplt.text(7,0.7,r'$\\underline{c}(m)= (1-\\Phi_{R})m = \\underline{\\kappa}m$',fontsize = 22,fontweight='bold')\nplt.arrow(2.45,1.05,-0.5,0.02,head_width= 0.05,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(2.15,3.88,-0.5,0.1,head_width= 0.05,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(8.95,4.15,-0.8,0.05,head_width= 0.05,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(5.95,5.05,-0.4,0,head_width= 0.05,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(14,0.70,0.5,-0.1,head_width= 0.05,width=0.001,facecolor='black',length_includes_head='True')\nif Generator:\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncBounds.png'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncBounds.jpg'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncBounds.pdf'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cFuncBounds.svg'))\nif not in_ipynb():\n plt.show(block=False) \n plt.pause(1)\nelse:\n plt.show(block=True) # Change to False if you want to run uninterrupted\n```\n\n### [The Consumption Function and Target $m$](https://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#cFuncBounds)\n\nThis figure shows the $\\mathrm{\\mathbb{E}}_{t}[\\Delta m_{t+1}]$ and consumption function $c(m_{t})$, along with the intrsection of these two functions, which defines the target value of $m$\n\n\n```python\n# This just plots objects that have already been constructed\n\nm1 = np.linspace(0,4,1000)\ncfunc_m = baseEx_inf.cFunc[0](m1)\nmSSfunc = lambda m:(baseEx_inf.PermGroFac[0]/baseEx_inf.Rfree)+(1.0-baseEx_inf.PermGroFac[0]/baseEx_inf.Rfree)*m\nmss = mSSfunc(m1)\nplt.figure(figsize = (12,8))\nplt.plot(m1,cfunc_m, color=\"black\")\nplt.plot(m1,mss, color=\"black\")\nplt.xlim(0,3)\nplt.ylim(0,1.45)\nplt.plot([baseEx_inf.solution[0].mNrmSS, baseEx_inf.solution[0].mNrmSS],[0,2.5],color=\"black\",linestyle=\"--\")\nplt.tick_params(labelbottom=False, labelleft=False,left='off',right='off',bottom='off',top='off')\nplt.text(0,1.47,r\"$c$\",fontsize = 26)\nplt.text(3.02,0,r\"$m$\",fontsize = 26)\nplt.text(2.3,0.95,r'$\\mathsf{E}[\\Delta m_{t+1}] = 0$',fontsize = 22,fontweight='bold')\nplt.text(2.3,1.1,r\"$c(m_{t})$\",fontsize = 22,fontweight='bold')\nplt.text(baseEx_inf.solution[0].mNrmSS,-0.05, r\"$\\check{m}$\",fontsize = 26)\nplt.arrow(2.28,1.12,-0.1,0.03,head_width= 0.02,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(2.28,0.97,-0.1,0.02,head_width= 0.02,width=0.001,facecolor='black',length_includes_head='True')\nif Generator:\n plt.savefig(os.path.join(Figures_HARK_dir, 'cRatTargetFig.png'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cRatTargetFig.jpg'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cRatTargetFig.pdf'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'cRatTargetFig.svg'))\nif not in_ipynb():\n plt.show(block=False)\n plt.pause(1)\nelse:\n plt.show(block=True)\n```\n\n### [Upper and Lower Limits of the Marginal Propensity to Consume](https://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#MPCLimits)\n\nThe paper shows that as $m_{t}~\\uparrow~\\infty$ the consumption function in the presence of risk gets arbitrarily close to the perfect foresight consumption function. Defining $\\underline{\\kappa}$ as the perfect foresight model's MPC, this implies that $\\lim_{m_{t}~\\uparrow~\\infty} c^{\\prime}(m) = \\underline{\\kappa}$. \n\nThe paper also derives an analytical limit $\\bar{\\kappa}$ for the MPC as $m$ approaches 0., its bounding value. Strict concavity of the consumption function implies that the consumption function will be everywhere below a function $\\bar{\\kappa}m$, and strictly declining everywhere. The last figure plots the MPC between these two limits.\n\n\n```python\n# The last figure shows the upper and lower limits of the MPC\nplt.figure(figsize = (12,8))\n# Set the plot range of m\nm = np.linspace(0.001,8,1000)\n\n# Use the HARK method derivative to get the derivative of cFunc, and the values are just the MPC\nMPC = baseEx_inf.cFunc[0].derivative(m)\n\n# Define the upper bound of MPC\nMPCUpper = (1 - baseEx_inf.UnempPrb ** (1.0/baseEx_inf.CRRA)*(baseEx_inf.Rfree*baseEx_inf.DiscFac)**(1.0/baseEx_inf.CRRA)/baseEx_inf.Rfree)\n\n# Define the lower bound of MPC\nMPCLower = k_lower\n\nplt.plot(m,MPC,color = 'black')\nplt.plot([0,8],[MPCUpper,MPCUpper],color = 'black')\nplt.plot([0,8],[MPCLower,MPCLower],color = 'black')\nplt.xlim(0,8)\nplt.ylim(0,1)\nplt.text(1.5,0.6,r'$\\kappa(m) \\equiv c^{\\prime}(m)$',fontsize = 26,fontweight='bold')\nplt.text(6,0.87,r'$(1-\\wp^{1/\\rho}\\Phi_{R})\\equiv \\overline{\\kappa}$',fontsize = 26,fontweight='bold')\nplt.text(0.5,0.07,r'$\\underline{\\kappa}\\equiv(1-\\Phi_{R})$',fontsize = 26,fontweight='bold')\nplt.text(8.05,0,\"$m$\",fontsize = 26)\nplt.arrow(1.45,0.61,-0.4,0,head_width= 0.02,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(1.7,0.07,0.2,-0.01,head_width= 0.02,width=0.001,facecolor='black',length_includes_head='True')\nplt.arrow(5.95,0.875,-0.2,0.03,head_width= 0.02,width=0.001,facecolor='black',length_includes_head='True')\nif Generator:\n plt.savefig(os.path.join(Figures_HARK_dir, 'MPCLimits.png'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'MPCLimits.jpg'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'MPCLimits.pdf'))\n plt.savefig(os.path.join(Figures_HARK_dir, 'MPCLimits.svg'))\nif not in_ipynb():\n plt.show(block=False) \n plt.pause(1)\nelse:\n plt.show(block=True) # Change to False if you want to run uninterrupted\n```\n\n# Summary\n\n[Two tables in the paper](https://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#Sufficient-Conditions-For-Nondegenerate-Solution) summarize the various definitions, and then articulate conditions required for the problem to have a nondegenerate solution.\n\nThe main other contribution of the paper is to show that, under parametric combinations where the solution is nondegenerate, if the Growth Impatience Condition holds there will be a target level of wealth.\n", "meta": {"hexsha": "58d53292680e22363c30d6fa362dd41e1d527cea", "size": 106963, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "REMARKs/BufferStockTheory/BufferStockTheory.ipynb", "max_stars_repo_name": "npalmer-professional/REMARK", "max_stars_repo_head_hexsha": "eb97159ccac109b04467d716a6731888b60de00f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REMARKs/BufferStockTheory/BufferStockTheory.ipynb", "max_issues_repo_name": "npalmer-professional/REMARK", "max_issues_repo_head_hexsha": "eb97159ccac109b04467d716a6731888b60de00f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REMARKs/BufferStockTheory/BufferStockTheory.ipynb", "max_forks_repo_name": "npalmer-professional/REMARK", "max_forks_repo_head_hexsha": "eb97159ccac109b04467d716a6731888b60de00f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.3425712086, "max_line_length": 49592, "alphanum_fraction": 0.7760253546, "converted": true, "num_tokens": 12262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.16238003261321476, "lm_q1q2_score": 0.07612223724033884}} {"text": "Lambda School Data Science\n\n*Unit 2, Sprint 3, Module 1*\n\n---\n\n\n# Define ML problems\n\nYou will use your portfolio project dataset for all assignments this sprint.\n\n## Assignment\n\nComplete these tasks for your project, and document your decisions.\n\n- [ ] Choose your target. Which column in your tabular dataset will you predict?\n- [ ] Is your problem regression or classification?\n- [ ] How is your target distributed?\n - Classification: How many classes? Are the classes imbalanced?\n - Regression: Is the target right-skewed? If so, you may want to log transform the target.\n- [ ] Choose which observations you will use to train, validate, and test your model.\n - Are some observations outliers? Will you exclude them?\n - Will you do a random split or a time-based split?\n- [ ] Choose your evaluation metric(s).\n - Classification: Is your majority class frequency > 50% and < 70% ? If so, you can just use accuracy if you want. Outside that range, accuracy could be misleading. What evaluation metric will you choose, in addition to or instead of accuracy?\n- [ ] Begin to clean and explore your data.\n- [ ] Begin to choose which features, if any, to exclude. Would some features \"leak\" future information?\n\n\n```python\nimport pandas as pd\nadoption_url = 'https://data.austintexas.gov/resource/9t4d-g238.csv?$limit=100000'\nadoption = pd.read_csv(adoption_url)\n# in order to see all of the columns:\npd.options.display.max_columns = 100\n```\n\n# Target\n\n\n```python\nadoption.head()\n```\n\n\n\n\n| \n | animal_id | \nname | \ndatetime | \nmonthyear | \ndate_of_birth | \noutcome_type | \noutcome_subtype | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \nA808320 | \nKyha | \n2019-11-14T15:37:00.000 | \n2019-11-14T15:37:00.000 | \n2017-11-07T00:00:00.000 | \nRto-Adopt | \nNaN | \nDog | \nSpayed Female | \n2 years | \nGerman Shepherd Mix | \nSable | \n
| 1 | \nA781697 | \nPookie | \n2019-11-14T15:33:00.000 | \n2019-11-14T15:33:00.000 | \n2017-10-05T00:00:00.000 | \nAdoption | \nNaN | \nDog | \nSpayed Female | \n2 years | \nCairn Terrier | \nWhite/Brown | \n
| 2 | \nA808382 | \nNaN | \n2019-11-14T14:57:00.000 | \n2019-11-14T14:57:00.000 | \n2014-11-08T00:00:00.000 | \nTransfer | \nPartner | \nCat | \nIntact Male | \n5 years | \nDomestic Shorthair | \nOrange Tabby | \n
| 3 | \nA806701 | \n*Emerald | \n2019-11-14T14:41:00.000 | \n2019-11-14T14:41:00.000 | \n2019-09-02T00:00:00.000 | \nAdoption | \nFoster | \nCat | \nNeutered Male | \n2 months | \nDomestic Shorthair | \nBlue Tabby/White | \n
| 4 | \nA804553 | \n*Wendy | \n2019-11-14T14:36:00.000 | \n2019-11-14T14:36:00.000 | \n2019-08-09T00:00:00.000 | \nAdoption | \nFoster | \nCat | \nSpayed Female | \n3 months | \nDomestic Shorthair | \nCalico | \n
| \n | animal_id | \nname | \ndatetime | \nmonthyear | \ndate_of_birth | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \n
|---|---|---|---|---|---|---|---|---|---|---|---|
| 59 | \nA808636 | \nUnknown | \n2019-11-13 13:46:00 | \n2019-11-13T13:46:00.000 | \n2004-11-11 | \nCat | \nIntact Female | \nNaN | \nSiamese | \nSeal Point | \nNot adopted | \n
| 96 | \nA808702 | \nKeepers | \n2019-11-12 15:20:00 | \n2019-11-12T15:20:00.000 | \n2009-11-12 | \nDog | \nNeutered Male | \nNaN | \nGolden Retriever | \nGold | \nNot adopted | \n
| 131 | \nA808649 | \nUnknown | \n2019-11-11 17:49:00 | \n2019-11-11T17:49:00.000 | \n2019-10-11 | \nCat | \nIntact Male | \nNaN | \nDomestic Shorthair | \nBrown Tabby | \nNot adopted | \n
| 132 | \nA738697 | \nBoots | \n2019-11-11 17:48:00 | \n2019-11-11T17:48:00.000 | \n2007-11-17 | \nDog | \nNaN | \nNaN | \nMiniature Schnauzer Mix | \nBlack | \nNot adopted | \n
| 161 | \nA808626 | \nUnknown | \n2019-11-11 13:57:00 | \n2019-11-11T13:57:00.000 | \n2019-09-11 | \nCat | \nIntact Female | \nNaN | \nDomestic Shorthair | \nBrown Tabby | \nNot adopted | \n
| 214 | \nA808466 | \nUnknown | \n2019-11-10 09:35:00 | \n2019-11-10T09:35:00.000 | \n2019-09-09 | \nCat | \nIntact Male | \nNaN | \nDomestic Shorthair | \nBrown/Black | \nNot adopted | \n
| 347 | \nA808352 | \nUnknown | \n2019-11-07 16:15:00 | \n2019-11-07T16:15:00.000 | \n2011-11-07 | \nDog | \nIntact Male | \nNaN | \nDachshund Mix | \nTan | \nNot adopted | \n
| 6649 | \nA752967 | \nGray | \n2019-07-24 11:42:00 | \n2019-07-24T11:42:00.000 | \n2015-06-29 | \nDog | \nNaN | \nNaN | \nPit Bull Mix | \nBlue/White | \nNot adopted | \n
| \n | animal_id | \nname | \ndatetime | \nmonthyear | \ndate_of_birth | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \n
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | \nA781697 | \nPookie | \n2019-11-14 15:33:00 | \n2019-11-14T15:33:00.000 | \n2017-10-05 | \nDog | \nSpayed Female | \n2 years | \nCairn Terrier | \nWhite/Brown | \nAdopted | \n
| 2 | \nA808382 | \nUnknown | \n2019-11-14 14:57:00 | \n2019-11-14T14:57:00.000 | \n2014-11-08 | \nCat | \nIntact Male | \n5 years | \nDomestic Shorthair | \nOrange Tabby | \nNot adopted | \n
| 3 | \nA806701 | \n*Emerald | \n2019-11-14 14:41:00 | \n2019-11-14T14:41:00.000 | \n2019-09-02 | \nCat | \nNeutered Male | \n2 months | \nDomestic Shorthair | \nBlue Tabby/White | \nAdopted | \n
| 4 | \nA804553 | \n*Wendy | \n2019-11-14 14:36:00 | \n2019-11-14T14:36:00.000 | \n2019-08-09 | \nCat | \nSpayed Female | \n3 months | \nDomestic Shorthair | \nCalico | \nAdopted | \n
| 5 | \nA804552 | \n*Tinkerbell | \n2019-11-14 14:35:00 | \n2019-11-14T14:35:00.000 | \n2019-08-09 | \nCat | \nSpayed Female | \n3 months | \nDomestic Shorthair | \nCalico | \nAdopted | \n
| \n | animal_id | \nname | \ndatetime | \nmonthyear | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \nmonth_arrived | \n
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | \nA781697 | \nPookie | \n2019-11-14 15:33:00 | \n2019-11-14 15:33:00 | \nDog | \nSpayed Female | \n2 years | \nCairn Terrier | \nWhite/Brown | \nAdopted | \n11 | \n
| 2 | \nA808382 | \nUnknown | \n2019-11-14 14:57:00 | \n2019-11-14 14:57:00 | \nCat | \nIntact Male | \n5 years | \nDomestic Shorthair | \nOrange Tabby | \nNot adopted | \n11 | \n
| 3 | \nA806701 | \n*Emerald | \n2019-11-14 14:41:00 | \n2019-11-14 14:41:00 | \nCat | \nNeutered Male | \n2 months | \nDomestic Shorthair | \nBlue Tabby/White | \nAdopted | \n11 | \n
| 4 | \nA804553 | \n*Wendy | \n2019-11-14 14:36:00 | \n2019-11-14 14:36:00 | \nCat | \nSpayed Female | \n3 months | \nDomestic Shorthair | \nCalico | \nAdopted | \n11 | \n
| 5 | \nA804552 | \n*Tinkerbell | \n2019-11-14 14:35:00 | \n2019-11-14 14:35:00 | \nCat | \nSpayed Female | \n3 months | \nDomestic Shorthair | \nCalico | \nAdopted | \n11 | \n
| \n | animal_id | \nname | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \nmonth_arrived | \nseason_arrived | \nyear_arrived | \n
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | \nA781697 | \nPookie | \nDog | \nSpayed Female | \n2 years | \nCairn Terrier | \nWhite/Brown | \nAdopted | \n11 | \nFall | \n2019 | \n
| 2 | \nA808382 | \nUnknown | \nCat | \nIntact Male | \n5 years | \nDomestic Shorthair | \nOrange Tabby | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 3 | \nA806701 | \n*Emerald | \nCat | \nNeutered Male | \n2 months | \nDomestic Shorthair | \nBlue Tabby/White | \nAdopted | \n11 | \nFall | \n2019 | \n
| 4 | \nA804553 | \n*Wendy | \nCat | \nSpayed Female | \n3 months | \nDomestic Shorthair | \nCalico | \nAdopted | \n11 | \nFall | \n2019 | \n
| 5 | \nA804552 | \n*Tinkerbell | \nCat | \nSpayed Female | \n3 months | \nDomestic Shorthair | \nCalico | \nAdopted | \n11 | \nFall | \n2019 | \n
| 6 | \nA808132 | \nDaryl | \nCat | \nNeutered Male | \n5 years | \nDomestic Shorthair | \nBrown Tabby/White | \nAdopted | \n11 | \nFall | \n2019 | \n
| 7 | \nA805655 | \n*Fezzik | \nCat | \nNeutered Male | \n2 months | \nDomestic Shorthair | \nOrange Tabby | \nAdopted | \n11 | \nFall | \n2019 | \n
| 9 | \nA808526 | \nJugez | \nDog | \nSpayed Female | \n13 years | \nShih Tzu | \nBrown/Cream | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 10 | \nA787448 | \nWatermelon | \nDog | \nSpayed Female | \n3 years | \nLabrador Retriever Mix | \nBrown Tiger/White | \nAdopted | \n11 | \nFall | \n2019 | \n
| 11 | \nA808522 | \nUnknown | \nCat | \nIntact Female | \n4 years | \nDomestic Shorthair | \nBrown Tabby | \nNot adopted | \n11 | \nFall | \n2019 | \n
| \n | animal_id | \nname | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \nmonth_arrived | \nseason_arrived | \nyear_arrived | \n
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | \nA781697 | \nPookie | \nDog | \nSpayed Female | \n2 years | \nCairn Terrier | \nWhite/Brown | \nAdopted | \n11 | \nFall | \n2019 | \n
| 9 | \nA808526 | \nJugez | \nDog | \nSpayed Female | \n13 years | \nShih Tzu | \nOTHER | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 10 | \nA787448 | \nWatermelon | \nDog | \nSpayed Female | \n3 years | \nLabrador Retriever Mix | \nOTHER | \nAdopted | \n11 | \nFall | \n2019 | \n
| 17 | \nA808589 | \nLola | \nDog | \nSpayed Female | \n5 years | \nOTHER | \nBrown Brindle | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 18 | \nA808590 | \nCheyenne | \nDog | \nSpayed Female | \n7 years | \nAustralian Shepherd Mix | \nBrown/White | \nNot adopted | \n11 | \nFall | \n2019 | \n
| \n | animal_id | \nname | \nanimal_type | \nsex_upon_outcome | \nage_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \nmonth_arrived | \nseason_arrived | \nyear_arrived | \n
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | \nA781697 | \nPookie | \nDog | \n2 | \n2.0 | \nCairn Terrier | \nWhite/Brown | \nAdopted | \n11 | \nFall | \n2019 | \n
| 9 | \nA808526 | \nJugez | \nDog | \n2 | \n13.0 | \nShih Tzu | \nOTHER | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 10 | \nA787448 | \nWatermelon | \nDog | \n2 | \n3.0 | \nLabrador Retriever Mix | \nOTHER | \nAdopted | \n11 | \nFall | \n2019 | \n
| 17 | \nA808589 | \nLola | \nDog | \n2 | \n5.0 | \nOTHER | \nBrown Brindle | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 18 | \nA808590 | \nCheyenne | \nDog | \n2 | \n7.0 | \nAustralian Shepherd Mix | \nBrown/White | \nNot adopted | \n11 | \nFall | \n2019 | \n
| \n | animal_id | \nname | \nanimal_type | \nsex_upon_outcome | \nbreed | \ncolor | \nnew_outcome_type | \nmonth_arrived | \nseason_arrived | \nyear_arrived | \n
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | \nA781697 | \nPookie | \nDog | \n2 | \nCairn Terrier | \nWhite/Brown | \nAdopted | \n11 | \nFall | \n2019 | \n
| 9 | \nA808526 | \nJugez | \nDog | \n2 | \nShih Tzu | \nOTHER | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 10 | \nA787448 | \nWatermelon | \nDog | \n2 | \nLabrador Retriever Mix | \nOTHER | \nAdopted | \n11 | \nFall | \n2019 | \n
| 17 | \nA808589 | \nLola | \nDog | \n2 | \nOTHER | \nBrown Brindle | \nNot adopted | \n11 | \nFall | \n2019 | \n
| 18 | \nA808590 | \nCheyenne | \nDog | \n2 | \nAustralian Shepherd Mix | \nBrown/White | \nNot adopted | \n11 | \nFall | \n2019 | \n
| ID | YARN Application ID | Kind | State | Spark UI | Driver log | Current session? |
|---|---|---|---|---|---|---|
| 2 | application_1571347151292_0003 | pyspark | idle | Link | Link | ✔ |
| \n View on QuantumAI\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
| \n | Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license.(c) Carlos Alberto Alvarez Henao | \n
\n \n
\n\n\n \n
\n\n\n\n\nConsidere un proyectil lanzado en el punto $(x_0, y_0)$, con una velocidad inicial de $v_0$, cuyas componentes son $v_{0x}$ y $v_{0y}$. Cuando se hace caso omiso de la resistencia del aire, la única fuerza que actúa en el proyectil es su peso, el cual hace que el proyectil tenga una aceleración dirigida hacia abajo constante de aproximadamente $a_c=g=9.81 m/s^2=32.2 pies/s^2$.\n\n### Movimiento horizontal\n\nComo $a_x=0$, se pueden aplicar las ecuaciones de aceleración constante vistas en el [Capítulo 1: Movimiento Rectilíneo, numeral 2.6 Aceleración constante](./C01_CinematicaCineticaParticulas_MovRectilineo.ipynb#ac), resultando en:\n\n\n\\begin{equation*}\n\\begin{array}{crl}\n\\left(\\underrightarrow{+}\\right) &v=&v_0+a_ct& \\quad &v_x=v_{0x} \\\\\n\\left(\\underrightarrow{+}\\right) &x=&x_0+v_0t+\\frac{1}{2}a_ct^2& \\quad &x=x_0+v_{0x}t \\\\\n\\left(\\underrightarrow{+}\\right) &v^2=&v_0^2+2a_c(x-x_0)& \\quad &v_x=v_{0x} \\\\\n\\end{array}\n\\label{eq:Ec3_1} \\tag{3.1}\n\\end{equation*}\n\n\n### Movimiento vertical\n\nEstableciendo el sistema de coordenadas con el eje $y$ positivo hacia arriba, se tiene entonces que $a_y=-g$ y aplicando las ecuaciones de aceleración constante como visto en el ítem anterior, se llega a:\n\n\n\\begin{equation*}\n\\begin{array}{crl}\n\\left(+\\uparrow \\right) &v=&v_0+a_ct& \\quad &v_y=v_{0y}-gt \\\\\n\\left(+\\uparrow \\right) &y=&y_0+v_0t+\\frac{1}{2}a_ct^2& \\quad &y=y_0+v_{0y}t-\\frac{1}{2}gt^2 \\\\\n\\left(+\\uparrow \\right) &v^2=&v_0^2+2a_c(y-y_0)& \\quad &v_y^2=v_{0y}^2-2g \\left(y-y_0 \\right) \\\\\n\\end{array}\n\\label{eq:Ec3_2} \\tag{3.2}\n\\end{equation*}\n\n\n### Comentarios al movimiento curvilíneo\n\n- En el movimiento horizontal la primera y la tercera ecuación implican que la componente horizontal de la velocidad siempre permanece constante durante la realización del movimiento.\n\n\n- En el movimiento vertical, la última ecuación puede formularse eliminando el término del tiempo de las dos primeras ecuaciones, por lo que, solo dos de las tres ecuaciones son independientes entre ellas.\n\n\n- De lo anterior se concluye que los problemas que involucran movimiento parabólico pueden tener como máximo tres incógnitas, ya que solo se podrán escribir tres ecuaciones independientes: una ecuación en la dirección horizontal y dos en la dirección vertical.\n\n\n- La velocidad resultante $v$, que siempre será tangente a la trayectoria, se determinará por medio de la suma vectorial de sus componentes $v_x$ y $v_y$.\n\n### Ejemplos movimiento parabólico\n\n| \n | \n\n Ejemplo 12.11: Hibbeler R. Engineering Mechanics: Dynamics \n\nUn saco se desliza por la rampa, como se ve en la figura, con una velocidad horizontal de $12 m/s$. Si la altura de la rampa es de $6 m$, determine el tiempo necesario para que el saco choque con el suelo y la distancia $R$ donde los sacos comienzan a apilarse \n | \n
\n \n
\n\n\n\nA veces es más conveniente emplear como sistema de referencia las coordenadas $n-t$, que expresan las componentes *normal* y *tangencial* a la trayectoria.\n\n### Movimiento plano\n\n\n \n
\n\n\n\nSea una partícula que se desplaza en el plano a lo largo de una curva fija, tal que en un instante dado está en la posición $s$ medida respecto a $O'$. Considere un sistema de ejes coordenados con origen en un punto fijo de la curva y, en un instante determinado, éste coincide con la ubicación de la partícula. El eje $t$ es tangente a la curva en el punto y positivo en la dirección de $s$, denominada con el vector unitario $\\vec{\\boldsymbol{u}}_t$. La determinación del eje normal, $\\vec{\\boldsymbol{u}}_n$ es inmediata, ya que solo existe una única posibilidad, siendo positivo en la dirección hacia el centro de la curva. La curva se forma por una serie de segmentos de arco de tamaño $ds$ y cada uno de estos segmentos es formado por el arco de un círculo con radio de curvatura $\\rho$ y centro $O'$. El plano que se genera por los ejes $n-t$ se denomina *[plano osculador](https://es.wikipedia.org/wiki/Geometr%C3%ADa_diferencial_de_curvas#Plano_osculador)*, y está fijo en el plano del movimiento.\n\n\n\n### Velocidad\n\n\n \n
\n\n\n\nComo se ha indicado en las secciones anteriores, la partícula se encuentra en movimiento, por lo que el desplazamiento es una función del tiempo, $s(t)$. La dirección de la velocidad de la partícula siempre es tangente a la trayectoria y su magnitud se determina por la derivada respecto al tiempo de la función de la trayectoria. Entonces:\n\n\n\\begin{equation*}\n\\boldsymbol{v}=v\\boldsymbol{u}_t\n\\label{eq:Ec3_3} \\tag{3.3}\n\\end{equation*}\n\ndonde\n\n\n\\begin{equation*}\nv=\\dot{s}\n\\label{eq:Ec3_4} \\tag{3.4}\n\\end{equation*}\n\n\n### Aceleración\n\n\n \n
\n\n\n\nEl cambio de la velocidad de la partícula respecto al tiempo es la aceleración. Entonces\n\n\n\\begin{equation*}\n\\boldsymbol{a}=\\dot{\\boldsymbol{v}}=\\dot{v}\\boldsymbol{u}_t + v\\dot{\\boldsymbol{u}}_t\n\\label{eq:Ec3_5} \\tag{3.5}\n\\end{equation*}\n\nFalta determinar la derivada de $\\dot{\\boldsymbol{u}}_t$ respecto al tiempo. A medida que la partícula se desplaza a lo largo de un arco $ds$ en un diferencial de tiempo $dt$, $\\boldsymbol{u}_t$ su dirección varía y pasa a ser $\\boldsymbol{u}'_t$, donde $\\boldsymbol{u}'_t=\\boldsymbol{u}_t+d\\boldsymbol{u}_t$. Observe que $d\\boldsymbol{u}_t$ va de las puntas de $\\boldsymbol{u}_t$ a $\\boldsymbol{u}'_t$, que se extienden en un arco infinitesimal de magnitud $u_t=1$ (unitaria). Por lo tanto, $d\\boldsymbol{u}_t=d\\theta \\boldsymbol{u}_n$, por lo que la derivada con respecto al tiempo es $\\dot{\\boldsymbol{u}}_t=\\dot{\\theta}\\boldsymbol{u}_n$. \n\n\n \n
\n\n\n\nObserve también que $ds=\\rho d\\theta$, entonces $\\dot{\\theta}=\\dot{s}/\\rho$, resultando\n\n$$\\dot{\\boldsymbol{u}}_t=\\dot{\\theta}\\boldsymbol{u}_n=\\frac{\\dot{s}}{\\rho}\\boldsymbol{u}_n=\\frac{v}{\\rho}\\boldsymbol{u}_n$$\n\nSustituyendo en la [Ec. 3.4](#Ec3_4) se puede reescribir $\\boldsymbol{a}$ como la suma de las componentes tangencial y normal:\n\n\n \n
\n\n\n\n\n\\begin{equation*}\n\\boldsymbol{a} = a_t \\boldsymbol{u}_t + a_n \\boldsymbol{u}_n\n\\label{eq:Ec3_6} \\tag{3.6}\n\\end{equation*}\n\ndonde la componente tangencial es dada por\n\n\n\\begin{equation*}\na_t = \\dot{v} \\qquad \\text{o} \\qquad a_t ds = vdv\n\\label{eq:Ec3_7} \\tag{3.7}\n\\end{equation*}\n\nla componente normal, por\n\n\n\\begin{equation*}\na_n = \\frac{v^2}{\\rho}\n\\label{eq:Ec3_8} \\tag{3.8}\n\\end{equation*}\n\ny la magnitud de la aceleración está dada por\n\n\n\\begin{equation*}\na = \\sqrt{a^2_t + a^2_n}\n\\label{eq:Ec3_9} \\tag{3.9}\n\\end{equation*}\n\n\n***Comentarios***\n\n- Si la partícula se mueve a lo largo de una línea recta entonces $\\rho \\rightarrow \\infty$ y por la [Ec. 3.8](#Ec3_8), $a_=0$. Con esto $a=a_t = \\dot{v}$, y se puede concluir que *la componente tangencial de la aceleración representa el cambio en la magnitud de la velocidad*.\n\n\n- Si la partícula se mueve a lo largo de una curva con velocidad constante, entonces $a_t=\\dot{v}=0$ y $a=a_n=v^2/\\rho$. Por lo tanto, *la componente normal de la aceleración representa el cambio en la dirección de la velocidad*. Como $a_n$ siempre actúa hacia el centro de la curvatura, esta componente en ocasiones se conoce como la [aceleración centrípeta](https://en.wikipedia.org/wiki/Centripetal_force) (\"*que busca el centro*\").\n\n\n- Expresando la trayectoria de la partícula como $y=f(x)$, el radio de curvatura en cualquier punto de la trayectoria se determina por la ecuación:\n\n\n\\begin{equation*}\n\\rho=\\frac{\\left[1 + (dy/dx)^2\\right]^{3/2}}{|d^2y/dx^2|}\n\\label{eq:Ec3_10} \\tag{3.10}\n\\end{equation*}\n\nComo consecuencia de lo anterior, una partícula que se mueve a lo largo de una trayectoria curva tendrá una aceleración como la mostrada en la figura:\n\n\n \n
\n\n\n\n### Ejemplos componentes normal y tangencial\n\n| \n | \n\n Ejemplo 12.14: Hibbeler R. Engineering Mechanics: Dynamics \n\nCuando el esquiador llega al punto $A$ a lo largo de la trayectoria parabólica en la figura, su rapidez es de $6 m/s$, la cual se incrementa a $2 m/s^2$. Determine la dirección de su velocidad y la dirección y magnitud de su aceleración en este instante. Al hacer el cálculo, pase por alto la estatura del esquiador.. \n | \n
\n \n
\n\n\n\npor último, la magnitud de la aceleración está dada por\n\n$$a=\\sqrt{(2m/s^2)^2+(1.273 m/s^2)^2}=2.37 m/s^2$$\n\nel ángulo sería\n\n$$\\phi = \\tan^{-1}\\left(\\frac{2}{1.273} \\right)=57.5^{\\circ}$$\n\nDe la figura:\n\n$$45^{\\circ}+90^{\\circ}+57.5^{\\circ}-180^{\\circ}=12.5^{\\circ}$$\n\nentonces, \n\n$$\\boldsymbol{a}=2.37 m/s^2 \\quad 12.5^{\\circ} \\measuredangle$$\n\nAhora vamos a realizar la solución empleando programación con el ecosistema `python`\n\n\n```python\nx = symbols('x')\nut, un = symbols('ut un')\n```\n\nLa ecuación que determina la trayectoria de la partícula está dada por\n\n\n```python\ny = x**2 / 20\n```\n\nY la velocidad de la partícula, cuya magnitud es la misma rapidez, segun el enunciado es\n\n\n```python\nv = 6\n```\n\nAhora se deriva la ecuación de la trayectoria respecto a la variable $x$\n\n\n```python\ndydx = diff(y,x)\ndydx\n```\n\nreemplazando en $x=10m$\n\n\n```python\ndydx = N(dydx.subs(x,10),4)\nprint(\"{0:6.1f}\".format(dydx))\n```\n\ncon esto, se calcula el ángulo que determina la direccion de la velocidad\n\n\n```python\ntheta = N(atan(dydx)*180/np.pi,4)\nprint(\"{0:6.1f}\".format(theta))\n```\n\nEl cálculo de la aceleración se realiza mediante la siguiente ecuación:\n\n$$\\boldsymbol{a} = \\dot{v} \\boldsymbol{u}_t + \\frac{v^2}{\\rho} \\boldsymbol{u}_n$$\n\nse debe calcular el radio de curvatura $\\rho$ con la [Ec. 3.10](#Ec3_10), que a su vez requiere del cálculo de la segunda derivada de la función de la trayectoria, $y$, respecto a $x$. Del enunciado se determina que $\\dot{v}=2 m/s$.\n\n\n```python\nd2ydx2 = diff(y,x,2)\nd2ydx2\n```\n\n\n```python\nrho = N((1 + dydx**2)**(3/2) / d2ydx2,4)\nprint(\"{0:6.4f}\".format(rho))\n```\n\n\n```python\nv_dot = 2\n```\n\nCon lo anterior, se construye la expresión para la aceleración\n\n\n```python\nv2rho = v**2 / rho\n```\n\n\n```python\na_A = v_dot * ut + v2rho * un\na_A\n```\n\nAhora se calculará la magnitud de la aceleración, dada por la [Ec. 3.9](#Ec3_9)\n\n\n```python\na_mag = sqrt(v_dot**2 + v2rho**2)\nprint(\"{0:6.1f}\".format(a_mag))\n```\n\npor último, calculamos el ángulo para la dirección de la aceleración\n\n\n```python\nphi = atan(v_dot / v2rho) * 180 / np.pi\nprint(\"{0:6.1f}\".format(phi))\n```\n\nDe la [figura](#Fig_angulos) donde se expresan los ángulos, se determina cuál sería la dirección\n\n\n```python\na = 45 + 90 + phi - 180\nprint(\"{0:6.1f}\".format(a))\n```\n\n\n \n
\n\n\n\nLa posición de la partícula en la figura se determina mediante una coordenada radial $r$, que se extiende desde el origen $O$ hasta la partícula, y el ángulo $\\theta$ entre un eje horizontal que sirve como referencia y $r$, medido en sentido antihorario. Las componentes $\\boldsymbol{u}_r$ y $\\boldsymbol{u}_{\\theta}$ se defienen en la dirección positiva de $r$ y $\\theta$ respectivamente.\n\n#### Posición\n\nLa posición de la partícula se define por el vector posición\n\n\n\\begin{equation*}\n\\boldsymbol{r}=r\\boldsymbol{u}_r\n\\label{eq:Ec3_11} \\tag{3.11}\n\\end{equation*}\n\n#### Velocidad\n\nLa velocidad es la derivada de $\\boldsymbol{r}$ respecto al tiempo\n\n\n\\begin{equation*}\n\\boldsymbol{v}=\\boldsymbol{\\dot{r}}=\\dot{r}\\boldsymbol{u}_r+r\\boldsymbol{\\dot{u}}_r\n\\label{eq:Ec3_12} \\tag{3.12}\n\\end{equation*}\n\nEn la evaluación de $\\boldsymbol{\\dot{u}}_r$, obsérvese que $\\boldsymbol{u}_r$ únicamente cambia de dirección respecto al tiempo, ya que por definición la magnitud del vector es unitaria. En un tiempo $\\Delta t$, el cambio $\\Delta r$ no cambiará la dirección de $\\boldsymbol{u}_r$, sin embargo, un cambio $\\Delta \\theta$ proporcionará que $\\boldsymbol{u}_r$ cambie a $\\boldsymbol{u}'_r$, con $\\boldsymbol{u}'_r=\\boldsymbol{u}_r+\\Delta \\boldsymbol{u}_r$. Entonces, el cambio de $\\boldsymbol{u}_r$ es por lo tanto $\\Delta \\boldsymbol{u}_r$. Si $\\Delta \\theta$ es pequeño, la magnitud del vector es $\\Delta u_r \\approx 1 (\\Delta \\theta)$, en la dirección $\\boldsymbol{u}_{\\theta}$. Entonces $\\Delta \\boldsymbol{u}_r=\\Delta \\theta \\boldsymbol{u}_{\\theta}$, y\n\n$$\\boldsymbol{\\dot{u}}_r=\\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta \\boldsymbol{u}_r}{\\Delta t} = \\left( \\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta \\theta}{\\Delta t}\\right) \\boldsymbol{u}_{\\theta}\n$$\n\n\n\\begin{equation*}\n\\boldsymbol{\\dot{u}}_r=\\dot{\\theta}\\boldsymbol{u}_{\\theta}\n\\label{eq:Ec3_13} \\tag{3.13}\n\\end{equation*}\n\nSustituyendo en la ecuación anterior, la velocidad se escribe a través de sus componentes como\n\n\n\\begin{equation*}\n\\boldsymbol{v}=v_r \\boldsymbol{u}_r+v_{\\theta}\\boldsymbol{u}_{\\theta}\n\\label{eq:Ec3_14} \\tag{3.14}\n\\end{equation*}\n \ndonde\n \n\n\\begin{equation*}\nv_r=\\dot{r} \\\\\nv_{\\theta} = r\\dot{\\theta}\n\\label{eq:Ec3_15} \\tag{3.15}\n\\end{equation*}\n\n\n\n \n
\n\n\n\nEn la gráfica se observa la descomposición del vector velocidad en las componentes radial, $\\boldsymbol{v}_r$, que mide la tasa de incremento (decremento) de la longitud en la coordenada radial, o sea, $\\dot{r}$, y la componente transversal, $\\boldsymbol{v}_{\\theta}$, que es la tasa de movimiento a lo largo de una circunferencia de radio $r$. El término $\\dot{\\theta}=d\\theta / dt$ también se conoce como *velocidad angular*, ya que es la razón de cambio del ángulo $\\theta$ respecto al tiempo. Las unidades de la velocidad angular se dan en $rad/s$.\n\nConsiderando que $\\boldsymbol{v}_r$ y $\\boldsymbol{v}_{\\theta}$ son perpendiculares, la magnitud de la velocidad estará dada por el valor positivo de:\n\n\n\\begin{equation*}\nv = \\sqrt{(\\dot{r})^2+(r\\dot{\\theta})^2}\n\\label{eq:Ec3_16} \\tag{3.16}\n\\end{equation*}\n\ndonde la dirección de $\\boldsymbol{v}$ es tangente a la trayectoria.\n\n#### Aceleración\n\nLa aceleración es la derivada de la velocidad respecto al tiempo. De las ecs. [(3.14)](#Ec3_14) y [(3.15)](#Ec3_15), se llega a la aceleración instantánea de la partícula.\n\n\n\\begin{equation*}\n\\boldsymbol{a}=\\boldsymbol{\\dot{v}}=\\ddot{r}\\boldsymbol{u}_r+\\dot{r}\\dot{\\boldsymbol{u}}_r+\\dot{r}\\dot{\\theta}\\boldsymbol{u}_{\\theta}+r\\ddot{\\theta}\\boldsymbol{u}_{\\theta}+r\\dot{\\theta}\\boldsymbol{\\dot{u}}_{\\theta}\n\\label{eq:Ec3_17} \\tag{3.17}\n\\end{equation*}\n\nDe la anterior ecuación se requiere determinar el valor de $\\dot{\\boldsymbol{u}}_{\\theta}$, que es el cambio de la dirección $\\boldsymbol{u}_{\\theta}$ respecto al tiempo, con magnitud unitaria.\n\n\n \n
\n\n\n\nDe la gráfica se tiene que en un tiempo $\\Delta t$, un cambio $\\Delta r$ no cambiará la dirección $\\boldsymbol{u}_{\\theta}$, sin embargo, un cambio $\\Delta \\theta$ hará que $\\boldsymbol{u}_{\\theta}$ pase a $\\boldsymbol{u}'_{\\theta}$, con $\\boldsymbol{u}'_{\\theta}=\\boldsymbol{u}_{\\theta}+\\Delta\\boldsymbol{u}_{\\theta}$. Para pequeñas variaciones del ángulo, la magnitud del vector es $\\Delta u_{\\theta}\\approx 1(\\Delta \\theta)$, actuando en la dirección $-\\boldsymbol{u}_r$, o sea, $\\Delta u_{\\theta}=-\\Delta \\theta\\boldsymbol{u}_r$, entonces\n\n$$\\boldsymbol{\\dot{u}}_{\\theta}=\\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta \\boldsymbol{u}_{\\theta}}{\\Delta t} = -\\left( \\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta \\theta}{\\Delta t}\\right) \\boldsymbol{u}_{r}\n$$\n\n\n\\begin{equation*}\n\\boldsymbol{\\dot{u}}_{\\theta}=-\\dot{\\theta}\\boldsymbol{u}_{r}\n\\label{eq:Ec3_18} \\tag{3.18}\n\\end{equation*}\n\nSustituyendo el anterior resultado y la Ec. [(3.13)](#Ec3_13) en la ecuación para la aceleración, se escribe la aceleración en forma de componentes como \n\n\n\\begin{equation*}\n\\boldsymbol{a}=a_r\\boldsymbol{u}_{r}+a_{\\theta}\\boldsymbol{u}_{\\theta}\n\\label{eq:Ec3_19} \\tag{3.19}\n\\end{equation*}\n\ncon \n\n\n\\begin{equation*}\na_r=\\ddot{r}-r\\dot{\\theta}^2 \\\\\na_{\\theta}=r\\ddot{\\theta}+2\\dot{r}\\dot{\\theta}\n\\label{eq:Ec3_20} \\tag{3.20}\n\\end{equation*}\n\ndonde $\\ddot{\\theta}=d^2\\theta/dt^2=d/dt(d\\theta /dt)$ se conoce como *aceleración angular y sus unidades son $rad/s^2$*. $\\boldsymbol{a}_r$ y $\\boldsymbol{a}_{\\theta}$ son perpendiculares, entonces la magnitud d ela aceleración está dada por el valor positivo de\n\n\n\\begin{equation*}\na=\\sqrt{(\\ddot{r}-r\\dot{\\theta}^2)^2+(r\\ddot{\\theta}+2\\dot{r}\\dot{\\theta})^2}\n\\label{eq:Ec3_21} \\tag{3.21}\n\\end{equation*}\n\n\n \n
\n\n\n\n### Coordenadas cilíndricas\n\n\n \n
\n\n\n\nSi la partícula se mueve a lo largo de una curva espacial, entonces su ubicación se especifica por medio de las tres coordenadas cilíndricas, $r$, $\\theta$, $z$. La coordenada $z$ es idéntica a la que se utilizó para coordenadas rectangulares. Como el vector unitario que define su dirección $\\boldsymbol{u}_z$, es constante, las derivadas con respecto al tiempo de este vector son cero, y por consiguiente la posición, velocidad y aceleración de la partícula se escriben en función de sus coordenadas cilíndricas como sigue:\n\n\n\\begin{equation*}\n\\begin{split}\n\\boldsymbol{r}_p &= r\\boldsymbol{u}_r+z\\boldsymbol{u}_z \\\\\n\\boldsymbol{v} &= \\dot{r}\\boldsymbol{u}_r+r\\dot{\\theta}\\boldsymbol{u}_{\\theta}+\\dot{z}\\boldsymbol{u}_{z} \\\\\n\\boldsymbol{a} &= (\\ddot{r}-r\\dot{\\theta}^2)\\boldsymbol{u}_r+(r\\ddot{\\theta}+2\\dot{r}\\dot{\\theta})\\boldsymbol{u}_{\\theta}+\\ddot{z}\\boldsymbol{u}_z\n\\end{split}\n\\label{eq:Ec3_22} \\tag{3.22}\n\\end{equation*}\n\n\n### Derivadas respecto al tiempo\n\nLas ecuaciones anteriores requieren que obtengamos las derivadas con respecto al tiempo $\\dot{r}$, $\\ddot{r}$, $\\dot{\\theta}$ y $\\ddot{\\theta}$, para evaluar las componentes $r$ y $\\theta$ de $\\boldsymbol{v}$ y $\\boldsymbol{a}. En general se presentan dos tipos de problema:\n\n1. Si las coordenadas polares se especifican como ecuaciones paramétricas en función del tiempo, $r = r(t)$ y $\\theta=\\theta(t)$, entonces las derivadas con respecto al tiempo pueden calcularse directamente.\n\n\n2. Si no se dan las ecuaciones paramétricas en función del tiempo, entonces debe conocerse la trayectoria $r=f(\\theta)$. Si utilizamos la regla de la cadena del cálculo podemos encontrar entonces la relación entre $\\dot{r}$ y $\\dot{\\theta}$ y entre $\\ddot{r}$ y $\\ddot{\\theta}$\n\n### Ejemplos componentes cilíndricos\n\n| \n | \n\n Ejemplo 12.20: Hibbeler R. Engineering Mechanics: Dynamics \n\nDebido a la rotación de la barra ahorquillada, la bola en la figura se mueve alrededor de una trayectoria ranurada, una parte de la cual tiene la forma de un cardioide, $r=0.5(1 - cos(\\theta)) pies$, donde $\\theta$ está en radianes. Si la velocidad de la bola es $v=4 pies/s$ y su aceleración es $a=30 pies/s^2$ en el instante $\\theta=180^{\\circ}$, determine la velocidad angular $\\dot{theta}$ y la aceleración angular $\\ddot{\\theta}$ de la horquilla. \n | \n
| \n View on QuantumAI\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
Maximum likelihood estimate vs. true parameter. Note that the estimate is slightly off from the true value. This is a consequence of the fact that the estimator is a function of the data and lacks knowledge of the true underlying value.
\n\n\n\n\n\n[Figure](#fig:Maximum_likelihood_10_2) shows that our estimator $\\hat{p}$\n(circle) is not equal to the true value of $p$ (square), despite being\nthe maximum of the likelihood function. This may sound disturbing, but keep in\nmind this estimate is a function of the random data; and since that data can\nchange, the ultimate estimate can likewise change. I invite you to run this\ncode in the corresponding IPython notebook a few times to observe this.\nRemember that the estimator is a *function* of the data and is thus also a\n*random variable*, just like the data is. This means it has its own probability\ndistribution with corresponding mean and variance. So, what we are observing is\na consequence of that variance.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nHistogram of maximum likelihood estimates. The title shows the estimated mean and standard deviation of the samples.
\n\n\n\n\n\n[Figure](#fig:Maximum_likelihood_30_2) shows what happens when you run many\nthousands of coin experiments and compute the maximum likelihood\nestimate for each experiment, given a particular number of samples \nper experiment. This simulation gives us a histogram of the maximum likelihood\nestimates, which is an approximation of the probability distribution of the\n$\\hat{p}$ estimator itself. This figure shows that the sample mean\nof the estimator ($\\mu = \\frac{1}{n}\\sum \\hat{p}_i$) is pretty close to the\ntrue value, but looks can be deceiving. The only way to know for sure is to\ncheck if the estimator is unbiased, namely, if\n\n$$\n\\mathbb{E}(\\hat{p}) = p\n$$\n\n Because this problem is simple, we can solve for this in general\nnoting that the terms above are either $p$, if $x_i=1$ or $1-p$ if $x_i=0$.\nThis means that we can write\n\n$$\n\\mathcal{L}(p\\vert \\mathbf{x})= p^{\\sum_{i=1}^n x_i}(1-p)^{n-\\sum_{i=1}^n x_i}\n$$\n\n with corresponding logarithm as\n\n$$\nJ=\\log(\\mathcal{L}(p\\vert \\mathbf{x})) = \\log(p) \\sum_{i=1}^n x_i + \\log(1-p) \\left(n-\\sum_{i=1}^n x_i\\right)\n$$\n\n Taking the derivative of this gives:\n\n$$\n\\frac{dJ}{dp} = \\frac{1}{p}\\sum_{i=1}^n x_i + \\frac{(n-\\sum_{i=1}^n x_i)}{p-1}\n$$\n\n and solving this for $p$ leads to\n\n$$\n\\hat{p} = \\frac{1}{ n} \\sum_{i=1}^n x_i\n$$\n\nThis is our *estimator* for $p$. Up until now, we have been using Sympy to\nsolve for this based on the data $x_i$ but now that we have it analytically we\ndon't have to solve for it each time. To check if this estimator is biased, we\ncompute its expectation:\n\n$$\n\\mathbb{E}\\left(\\hat{p}\\right) =\\frac{1}{n}\\sum_i^n \\mathbb{E}(x_i) = \\frac{1}{n} n \\mathbb{E}(x_i)\n$$\n\n by linearity of the expectation and where\n\n$$\n\\mathbb{E}(x_i) = p\n$$\n\n Therefore,\n\n$$\n\\mathbb{E}\\left(\\hat{p}\\right) =p\n$$\n\n This means that the estimator is *unbiased*. Similarly,\n\n$$\n\\mathbb{E}\\left(\\hat{p}^2\\right) = \\frac{1}{n^2} \\mathbb{E}\\left[\\left( \\sum_{i=1}^n x_i \\right)^2 \\right]\n$$\n\n and where\n\n$$\n\\mathbb{E}\\left(x_i^2\\right) =p\n$$\n\n and by the independence assumption,\n\n$$\n\\mathbb{E}\\left(x_i x_j\\right) =\\mathbb{E}(x_i)\\mathbb{E}(x_j) =p^2\n$$\n\n Thus,\n\n$$\n\\mathbb{E}\\left(\\hat{p}^2\\right) =\\left(\\frac{1}{n^2}\\right) n \\left[ p+(n-1)p^2 \\right]\n$$\n\n So, the variance of the estimator, $\\hat{p}$, is the following:\n\n$$\n\\mathbb{V}(\\hat{p}) = \\mathbb{E}\\left(\\hat{p}^2\\right)- \\mathbb{E}\\left(\\hat{p}\\right)^2 = \\frac{p(1-p)}{n}\n$$\n\n Note that the $n$ in the denominator means that the variance\nasymptotically goes to zero as $n$ increases (i.e., we consider more and\nmore samples). This is good news because it means that more and\nmore coin flips lead to a better estimate of the underlying $p$.\n\nUnfortunately, this formula for the variance is practically useless because we\nneed $p$ to compute it and $p$ is the parameter we are trying to estimate in\nthe first place! However, this is where the *plug-in* principle [^invariance-property] \nsaves the day. It turns out in this situation, you can\nsimply substitute the maximum likelihood estimator, $\\hat{p}$, for the $p$ in\nthe above equation to obtain the asymptotic variance for $\\mathbb{V}(\\hat{p})$.\nThe fact that this works is guaranteed by the asymptotic theory of maximum\nlikelihood estimators.\n\n[^invariance-property]: This is also known as the *invariance property*\nof maximum likelihood estimators. It basically states that the \nmaximum likelihood estimator of any function, say, $h(\\theta)$, is\nthe same $h$ with the maximum likelihood estimator for $\\theta$ substituted\nin for $\\theta$; namely, $h(\\theta_{ML})$.\n\nNevertheless, looking at $\\mathbb{V}(\\hat{p})^2$, we can immediately notice\nthat if $p=0$, then there is no estimator variance because the outcomes are\nguaranteed to be tails. Also, for any $n$, the maximum of this variance\nhappens at $p=1/2$. This is our worst case scenario and the only way to\ncompensate is with larger $n$.\n\nAll we have computed is the mean and variance of the estimator. In general,\nthis is insufficient to characterize the underlying probability density of\n$\\hat{p}$, except if we somehow knew that $\\hat{p}$ were normally distributed.\nThis is where the powerful *Central Limit Theorem* we discussed in the section ref{ch:stats:sec:limit} comes in. The form of the estimator, which is just a\nsample mean, implies that we can apply this theorem and conclude that $\\hat{p}$\nis asymptotically normally distributed. However, it doesn't quantify how many\nsamples $n$ we need. In our simulation this is no problem because we can\ngenerate as much data as we like, but in the real world, with a costly\nexperiment, each sample may be precious [^edgeworth]. \n\n[^edgeworth]: It turns out that the central limit theorem augmented with an\nEdgeworth expansion tells us that convergence is regulated by the skewness\nof the distribution [[feller1950introduction]](#feller1950introduction). In other words, the \nmore symmetric the distribution, the faster it converges to the normal\ndistribution according to the central limit theorem.\n\nIn the following, we won't apply the Central Limit Theorem and instead proceed\nanalytically.\n\n### Probability Density for the Estimator\n\nTo write out the full density for $\\hat{p}$, we first have to ask what is\nthe probability that the estimator will equal a specific value and the tally up\nall the ways that could happen with their corresponding probabilities. For\nexample, what is the probability that\n\n$$\n\\hat{p} = \\frac{1}{n}\\sum_{i=1}^n x_i = 0\n$$\n\n This can only happen one way: when $x_i=0 \\hspace{0.5em} \\forall i$. The\nprobability of this happening can be computed from the density\n\n$$\nf(\\mathbf{x},p)= \\prod_{i=1}^n \\left(p^{x_i} (1-p)^{1-x_i} \\right)\n$$\n\n$$\nf\\left(\\sum_{i=1}^n x_i = 0,p\\right)= \\left(1-p\\right)^n\n$$\n\n Likewise, if $\\lbrace x_i \\rbrace$ has only one nonzero element, then\n\n$$\nf\\left(\\sum_{i=1}^n x_i = 1,p\\right)= n p \\prod_{i=1}^{n-1} \\left(1-p\\right)\n$$\n\n where the $n$ comes from the $n$ ways to pick one element\nfrom the $n$ elements $x_i$. Continuing this way, we can construct the\nentire density as\n\n$$\nf\\left(\\sum_{i=1}^n x_i = k,p\\right)= \\binom{n}{k} p^k (1-p)^{n-k}\n$$\n\n where the first term on the right is the binomial coefficient of $n$ things\ntaken $k$ at a time. This is the binomial distribution and it's not the\ndensity for $\\hat{p}$, but rather for $n\\hat{p}$. We'll leave this as-is\nbecause it's easier to work with below. We just have to remember to keep\ntrack of the $n$ factor.\n\n**Confidence Intervals**\n\nNow that we have the full density for $\\hat{p}$, we are ready to ask some\nmeaningful questions. For example, what is the probability the estimator is within\n$\\epsilon$ fraction of the true value of $p$?\n\n$$\n\\mathbb{P}\\left( \\vert \\hat{p}-p \\vert \\le \\epsilon p \\right)\n$$\n\n More concretely, we want to know how often the\nestimated $\\hat{p}$ is trapped within $\\epsilon$ of the actual value. That is,\nsuppose we ran the experiment 1000 times to generate 1000 different estimates\nof $\\hat{p}$. What percentage of the 1000 so-computed values are trapped within\n$\\epsilon$ of the underlying value. Rewriting the above equation as the\nfollowing,\n\n$$\n\\mathbb{P}\\left(p-\\epsilon p < \\hat{p} < p + \\epsilon p \\right) = \\mathbb{P}\\left( n p - n \\epsilon p < \\sum_{i=1}^n x_i < n p + n \\epsilon p \\right)\n$$\n\n Let's plug in some live numbers here for our worst case\nscenario (i.e., highest variance scenario) where $p=1/2$. Then, if\n$\\epsilon = 1/100$, we have\n\n$$\n\\mathbb{P}\\left( \\frac{99 n}{100} < \\sum_{i=1}^n x_i < \\frac{101 n}{100} \\right)\n$$\n\n Since the sum in integer-valued, we need $n> 100$ to even compute this.\nThus, if $n=101$ we have,\n\n$$\n\\begin{eqnarray*}\n\\mathbb{P}\\left(\\frac{9999}{200} < \\sum_{i=1}^{101} x_i < \\frac{10201}{200} \\right) = f\\left(\\sum_{i=1}^{101} x_i = 50,p\\right) & \\ldots \\\\\\\n= \\binom{101}{50} (1/2)^{50} (1-1/2)^{101-50} & = & 0.079\n\\end{eqnarray*}\n$$\n\n This means that in the worst-case scenario for $p=1/2$, given $n=101$\ntrials, we will only get within 1\\% of the actual $p=1/2$ about 8\\% of the\ntime. If you feel disappointed, that only means you've been paying attention.\nWhat if the coin was really heavy and it was hard work to repeat this 101 times?\n\nLet's come at this another way: given I could only flip the coin 100\ntimes, how close could I come to the true underlying value with high\nprobability (say, 95\\%)? In this case, instead of picking a value for\n$\\epsilon$, we are solving for $\\epsilon$. Plugging in gives,\n\n$$\n\\mathbb{P}\\left(50 - 50\\epsilon < \\sum_{i=1}^{100} x_i < 50 + 50 \\epsilon \\right) = 0.95\n$$\n\n which we have to solve for $\\epsilon$. Fortunately, all the tools we\nneed to solve for this are already in Scipy.\n\n\n```python\nfrom scipy.stats import binom\n# n=100, p = 0.5, distribution of the estimator phat\nb=binom(100,.5) \n# symmetric sum the probability around the mean\ng = lambda i:b.pmf(np.arange(-i,i)+50).sum() \nprint g(10) # approx 0.95\n```\n\n 0.953955933071\n\n\n\n```python\n%matplotlib inline\n\nfrom matplotlib.pylab import subplots, arange\nfig,ax= subplots()\nfig.set_size_inches((10,5))\n# here is the density of the sum of x_i\n_=ax.stem(arange(0,101),b.pmf(arange(0,101)),\n linefmt='k-', markerfmt='ko') \n_=ax.vlines( [50+10,50-10],0 ,ax.get_ylim()[1] ,color='k',lw=3.)\n_=ax.axis(xmin=30,xmax=70)\n_=ax.tick_params(labelsize=18)\n#fig.savefig('fig-statistics/Maximum_likelihood_20_2.png')\nfig.tight_layout()\n```\n\n\n\n\n\nProbability mass function for $\\hat{p}$. The two vertical lines form the confidence interval.
\n\n\n\n\n\n The two vertical lines in the plot show how far out from the mean we\nhave to go to accumulate 95\\% of the probability. Now, we can solve this as\n\n$$\n50+50\\epsilon=60\n$$\n\n which makes $\\epsilon=1/5$ or 20\\%. So, flipping 100 times means I can\nonly get within 20\\% of the real $p$ 95\\% of the time in the worst case\nscenario (i.e., $p=1/2$). The following code verifies the situation.\n\n\n```python\nfrom scipy.stats import bernoulli \nb=bernoulli(0.5) # coin distribution\nxs = b.rvs(100) # flip it 100 times\nphat = np.mean(xs) # estimated p\nprint abs(phat-0.5) < 0.5*0.20 # make it w/in interval?\n```\n\n True\n\n\n Let's keep doing this and see if we can get within this interval 95\\% of\nthe time.\n\n\n```python\nout=[]\nb=bernoulli(0.5) # coin distribution\nfor i in range(500): # number of tries\n xs = b.rvs(100) # flip it 100 times\n phat = np.mean(xs) # estimated p\n out.append(abs(phat-0.5) < 0.5*0.20 ) # within 20% ?\n\n# percentage of tries w/in 20% interval\nprint 100*np.mean(out)\n```\n\n 97.4\n\n\n Well, that seems to work! Now we have a way to get at the quality of\nthe estimator, $\\hat{p}$.\n\n**Maximum Likelihood Estimator Without Calculus**\n\nThe prior example showed how we can use calculus to compute the maximum\nlikelihood estimator. It's important to emphasize that the maximum likelihood\nprinciple does *not* depend on calculus and extends to more general situations\nwhere calculus is impossible. For example, let $X$ be uniformly distributed in\nthe interval $[0,\\theta]$. Given $n$ measurements of $X$, the likelihood\nfunction is the following:\n\n$$\nL(\\theta) = \\prod_{i=1}^n \\frac{1}{\\theta} = \\frac{1}{\\theta^n}\n$$\n\n where each $x_i \\in [0,\\theta]$. Note that the slope of this function\nis not zero anywhere so the usual calculus approach is not going to work here.\nBecause the likelihood is the product of the individual uniform densities, if\nany of the $x_i$ values were outside of the proposed $[0,\\theta]$ interval,\nthen the likelihood would go to zero, because the uniform density is zero\noutside of the $[0,\\theta]$. Naturally, this is no good for maximization. Thus,\nobserving that the likelihood function is strictly decreasing with increasing\n$\\theta$, we conclude that the value for $\\theta$ that maximizes the likelihood\nis the maximum of the $x_i$ values. To summarize, the maximum likelihood\nestimator is the following:\n\n$$\n\\theta_{ML} = \\max_i x_i\n$$\n\n As always, we want the distribution of this estimator to judge its\nperformance. In this case, this is pretty straightforward. The cumulative\ndensity function for the $\\max$ function is the following:\n\n$$\n\\mathbb{P} \\left( \\hat{\\theta}_{ML} < v \\right) = \\mathbb{P}( x_0 \\leq v \\wedge x_1 \\leq v \\ldots \\wedge x_n \\leq v)\n$$\n\n and since all the $x_i$ are uniformly distributed in $[0,\\theta]$, we have\n\n$$\n\\mathbb{P} \\left( \\hat{\\theta}_{ML} < v \\right) = \\left(\\frac{v}{\\theta}\\right)^n\n$$\n\n So, the probability density function is then,\n\n$$\nf_{\\hat{\\theta}_{ML}}(\\theta_{ML}) = n \\theta_{ML}^{ n-1 } \\theta^{ -n }\n$$\n\n Then, we can compute the $\\mathbb{E}(\\theta_{ML}) = (\\theta n)/(n+1)$ with\ncorresponding variance as $\\mathbb{V}(\\theta_{ML}) = (\\theta^2 n)/(n+1)^2/(n+2)$.\n\nFor a quick sanity check, we can write the following simulation for $\\theta =1$\nas in the following:\n\n\n```python\n>>> from scipy import stats\n>>> rv = stats.uniform(0,1) # define uniform random variable\n>>> mle=rv.rvs((100,500)).max(0) # max along row-dimension\n>>> print mean(mle) # approx n/(n+1) = 100/101 ~= 0.99\n0.989942138048\n>>> print var(mle) #approx n/(n+1)**2/(n+2) ~= 9.61E-5\n9.95762009884e-05\n```\n\n 0.990250835019\n 9.41473660278e-05\n\n\n\n\n\n 9.95762009884e-05\n\n\n\n**Programming Tip.**\n\nThe `max(0)` suffix on for the `mle` computation takes\nthe maximum of the so-computed array along the column (`axis=0`)\ndimension.\n\n\n\n You can also plot `hist(mle)` to see the histogram of the simulated\nmaximum likelihood estimates and match it up against the probability density\nfunction we derived above. \n\n\nIn this section, we explored the concept of maximum\nlikelihood estimation using a coin flipping experiment both analytically and\nnumerically with the scientific Python stack. We also explored the case when\ncalculus is not workable for maximum likelihood estimation. There are two key\npoints to remember. First, maximum likelihood estimation produces a function of\nthe data that is itself a random variable, with its own probability\ndistribution. We can get at the quality of the so-derived estimators by\nexamining the confidence intervals around the estimated values using the\nprobability distributions associated with the estimators themselves. \nSecond, maximum likelihood estimation applies even in situations \nwhere using basic calculus is not applicable [[wasserman2004all]](#wasserman2004all).\n\n\n## Delta Method\n\n\nThe Central Limit Theorem provides a way to get at the distribution of a random\nvariable. However, sometimes we are more interested in a function of the random\nvariable. In order to extend and generalize the central limit theorem in this\nway, we need the Taylor series expansion. Recall that the Taylor series\nexpansion is an approximation of a function of the following form,\n\n$$\nT_r(x) =\\sum_{i=0}^r \\frac{g^{(i)}(a)}{i!}(x-a)^i\n$$\n\n this basically says that a function $g$ can be adequately\napproximated about a point $a$ using a polynomial based on its derivatives\nevaluated at $a$. Before we state the general theorem, let's examine\nan example to understand how the mechanics work.\n\n**Example.** Suppose that $X$ is a random variable with\n$\\mathbb{E}(X)=\\mu\\neq 0$. Furthermore, supposedly have a suitable\nfunction $g$ and we want the distribution of $g(X)$. Applying the\nTaylor series expansion, we obtain the following,\n\n$$\ng(X) \\approx g(\\mu)+ g^{\\prime}(\\mu)(X-\\mu)\n$$\n\n If we use $g(X)$ as an estimator for $g(\\mu)$, then we can say that\nwe approximately have the following\n\n$$\n\\begin{align*}\n\\mathbb{E}(g(X)) &=g(\\mu) \\\\\\\n\\mathbb{V}(g(X)) &=(g^{\\prime}(\\mu))^2 \\mathbb{V}(X) \\\\\\\n\\end{align*}\n$$\n\n Concretely, suppose we want to estimate the odds, $\\frac{p}{1-p}$.\nFor example, if $p=2/3$, then we say that the odds is `2:1` meaning that the\nodds of the one outcome are twice as likely as the odds of the other outcome.\nThus, we have $g(p)=\\frac{p}{1-p}$ and we want to find\n$\\mathbb{V}(g(\\hat{p}))$. In our coin-flipping problem, we have the\nestimator $\\hat{p}=\\frac{1}{n}\\sum X_k$ from the Bernoulli-distributed data\n$X_k$ individual coin-flips. Thus,\n\n$$\n\\begin{align*}\n\\mathbb{E}(\\hat{p}) &= p \\\\\\\n\\mathbb{V}(\\hat{p}) &= \\frac{p(1-p)}{n} \\\\\\\n\\end{align*}\n$$\n\n Now, $g^\\prime(p)=1/(1-p)^2$, so we have,\n\n$$\n\\begin{align*}\n\\mathbb{V}(g(\\hat{p}))&=(g^\\prime(p))^2 \\mathbb{V}(\\hat{p}) \\\\\\\n &=\\left(\\frac{1}{(1-p)^2}\\right)^2 \\frac{p(1-p)}{n} \\\\\\\n &= \\frac{p}{n(1-p)^3} \\\\\\\n\\end{align*}\n$$\n\n which is an approximation of the variance of the estimator\n$g(\\hat{p})$. Let's simulate this and see how it agrees.\n\n\n```python\nfrom scipy import stats\n# compute MLE estimates \nd=stats.bernoulli(0.1).rvs((10,5000)).mean(0)\n# avoid divide-by-zero\nd=d[np.logical_not(np.isclose(d,1))]\n# compute odds ratio\nodds = d/(1-d)\nprint 'odds ratio=',np.mean(odds),'var=',np.var(odds)\n```\n\n odds ratio= 0.123638095238 var= 0.017607461164\n\n\n The first number above is the mean of the simulated odds\nratio and the second is the variance of the estimate. According to\nthe variance estimate above, we have $\\mathbb{V}(g(1/10))\\approx\n0.0137$, which is not too bad for this approximation. Recall we want\nto estimate the odds from the $\\hat{p}$. The code above takes $5000$\nestimates of the $\\hat{p}$ to estimate $\\mathbb{V}(g)$. The odds ratio\nfor $p=1/10$ is $1/9\\approx 0.111$.\n\n**Programming Tip.**\n\nThe code above uses the `np.isclose` function to identify the ones from\nthe simulation and the `np.logical_not` removes these elements from the\ndata because the odds ratio has a zero in the denominator\nfor these values.\n\n\n\nLet's try this again with a probability of heads of `0.5` instead of\n`0.3`.\n\n\n```python\nfrom scipy import stats\nd=stats.bernoulli(.5).rvs((10,5000)).mean(0)\nd=d[np.logical_not(np.isclose(d,1))]\nprint 'odds ratio=',np.mean(d),'var=',np.var(d)\n```\n\n odds ratio= 0.498458458458 var= 0.024323949976\n\n\n The odds ratio is this case is equal to one, which\nis not close to what was reported. According to our\napproximation, we have $\\mathbb{V}(g)=0.4$, which does not\nlook like what our simulation just reported. This is\nbecause the approximation is best when the odds ratio is\nnearly linear and worse otherwise.\n\n\n\n\n\nThe odds ratio is close to linear for small values but becomes unbounded as $p$ approaches one. The delta method is more effective for small underlying values of $p$, where the linear approximation is better.
\n\n\n\n", "meta": {"hexsha": "9bdeaa9defe9ea3c40ef8bfbbbb7a47f640a4488", "size": 209160, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/statistics/notebooks/Maximum_likelihood.ipynb", "max_stars_repo_name": "nsydn/Python-for-Probability-Statistics-and-Machine-Learning", "max_stars_repo_head_hexsha": "d3e0f8ea475525a694a975dbfd2bf80bc2967cc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 570, "max_stars_repo_stars_event_min_datetime": "2016-05-05T19:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:09:19.000Z", "max_issues_repo_path": "chapters/statistics/notebooks/Maximum_likelihood.ipynb", "max_issues_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_issues_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-12T22:18:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-06T14:37:06.000Z", "max_forks_repo_path": "chapters/statistics/notebooks/Maximum_likelihood.ipynb", "max_forks_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_forks_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276, "max_forks_repo_forks_event_min_datetime": "2016-05-27T01:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:20:27.000Z", "avg_line_length": 130.8886107635, "max_line_length": 114721, "alphanum_fraction": 0.8650889271, "converted": true, "num_tokens": 9252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.23934934189686402, "lm_q1q2_score": 0.07119923499655552}} {"text": "# Modeling the Dynamic Interaction of Hebbian and Homeostatic Plasticity\n# Notebook developed by: Awadh Al Hawwash for BME 695\n# Edited by: David M Umulis \n\n*## It is expected from the user to read the published paper [5] before attempting to solve the tasks within this project*\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.sparse\nimport scipy.sparse.linalg\nfrom scipy import sparse\nfrom IPython.display import Image\nimport math as ma\nfrom IPython.core.display import HTML\nfrom IPython.core.display import Image, display\nfrom scipy.integrate import odeint # import ODE integrating function\n```\n\n## Introduction and Background \n\n\nThe ability to learn new skills and keep or lose memory depends on the neural networks’ change and reorganization. Neuroscientists refer to that modification as the neuroplasticity or brain plasticity. The interaction between neurons within neural circuits builds the basis of neuroplasticity through synaptic plasticity. According to Citri and Malenka, synaptic plasticity is defined as “Activity-dependent modification of the strength or efficacy of synaptic transmission…[1].” Neuroscientists have identified several mechanisms and functions of synaptic plasticity, in which all fundamentally agree that synapses are to be stronger or weaker over time [1, 2]. The mechanism of plasticity in general is an alternation of the quantity of neurotransmitters receptors, protein molecules, or enzymes that alter the cellular signaling pathway within synapses, which controls learning and memory processing in the brain [3]. Thus, the activity-dependent efficacy of the synapses might undergo reduction, known as long-term depression (LTD) or experience strength increase known as long-term potentiation (LTP) [4,5]. \n\n\nThe two major forms of plasticity that have been the subject of many recent studies are Hebbian and homeostatic plasticity [4, 5]. Hebbian plasticity, introduced 1949 by Donald Hebb, is when presynaptic and postsynaptic activities are strong or weak over time, the gain of the synapse follows the strength level of those activity [4, 5]. On the other hand, homeostatic plasticity is a nonspecific excitatory or inhibitory mechanism that scales the overall synaptic strength as shown in figure 1 [4, 5].\n\n\n\n\n\n\n\n**Figure 1:** A schematic diagram shows the relationship between Hebbian and homeostatic plasticity in a behavioral study example. Modified from [6].\n\nWhen it comes to investigate Hebbian and homeostatic plasticity interaction and dependence, ocular dominance plasticity (ODP) responses in the visual cortex have been the standard subject [5]. Experimentally, there is a critical behavior during and after the monocular deprivation (MD)-closing one eye- that assists scientists to distinguish between Hebbian and homeostatic plasticity responses; especially when blocking one mechanism without the other [5, 6]. The biological process was hypothsized to be a competing process, but in fact it is complex. Hebbian plasticity is characterize by its instability; which is a result of the positive feedback process that derives synaptic strength to be unstable in the absence of other mechanisms [5]. In contrast, the homeostatic plasticity is known to scale the overall synaptic strength or weight to reach equilibrium and stabilize the neural circuits through a negative feedback process [5]. \n\nDuring MD, three processes have been identified [5]:\n1. The response of the closed eye is getting weaker over MD time and it is mediated by fast Hebbian plasticity. It depends on the calcium entry through N-methyl-D-aspartate (NMDA) receptors acting on calcium calmodulin kinase type II, which makes this process depends on protein synthesis [5].\n2. The open eye’s response is getting stronger over the MD time, but it is a slower process and assumed to be mediated by homeostatic scaling. This process can be prevented by blockade of tumor necrosis factor-$\\alpha$ (TNF-$\\alpha$) [5].\n3. Recovery from MD can be prevented by blockade of tropomyosin-related kinase B (TrkB) receptor. TrkB is an essential synapses’ growth factor in neuronal cell culture and plays a role in stabilizing Hebbian LTP [5]. \n\n\nExisting mathematical models of synaptic plasticity lack to show the interaction of Hebbian and homeostatic plasticity and there are several controversial theories that require a development of a realistic model that captures the response of ocular dominance [5]. In this project, we are going to implement and analyze three mathematical models that capture the synaptic strength behavior as a function of the Hebbian and homeostatic plasticity parameters. The aim of this exercise is to compare the findings with the published experimental results and comments on the proposed model accuracy. The main results the authors obtained are the sensitivity of the time constants that control each process and the predictions during MD. The authors discussed and implemented a complex methodology to simulate multiple presynaptic neurons with respect to monocular or binocular cortex. The method requires statistical calculation of the variables’ covariance and they made several assumptions to minimize its complexity. Thus, it is also aimed to reproduce their multiple presynaptic model results and investigate those findings. \n\n# Learning Outcomes\n\nBy completing these tasks, the user will be able to:\n1. Derive or modify the provided single-synapse models in the form of multi-synaptic models.\n2. Simulate the synaptic strength as a function of time with respect to contralateral or ipsilateral eye in monocular and binocular cortex. \n3. Comment on the stability of the single-synapse models. \n4. Critically comment on the models results.\n\n---\n\n\n# **Model development**\n# Modeling Theory \nModeling the synaptic strength behavior in visual cortices over time is assumed to be an input-output system such that, the post-synaptic output activity $Y$ is the product of the pre-synaptic activity **X** and the synaptic strength **W**, where **W** consists of the LTD and LTP of the Hebbian dynamics and an overall homeostatic plasticity factor. The simple schematic below help to recognizing how the output activity is related to the synaptic strength and the input activity.\n\\\n\\begin{equation*}\nY=XW\n\\end{equation*}\n\n\n\n\n**Figure 2:** A schematic diagram shows how the synaptic strength consists of Hebbian and homeostatic plasticity factors during modeling.\n\nOne of the main assumptions to be made is that during normal vision x=1 while x$<$1 under MD [5]. In order to develop a realistic model, the physiological conditions of the visual cortices synapses need to be considered. Thus, the modeling theory can be classified based on the physiological structure into single-synapse models and multi-synapse models. \n\n# Single-synapse Models\nIn the single-synapse models, it is assumed that there is only one input presynaptic activity that produces a single postsynaptic activity in one-synapse model in the monocular cortex [5]. Although it is not physiologically realistic it helps understanding the quantitative measures, tuning the model parameters, and analyzing its stability. \n\n### **Assumptions:** \n1. The synapses projecting to the monocular cortex are homogeneous\n2. The synaptic strength **W** is an average synaptic strength of all inputs activity **X** from contralateral eye to the Lateral geniculate nucleus (LGN)\n3. The post-synaptic output activity **Y** is the average activity of monocular cortex\n\n# Multi-synaptic Models\nOppose to the single-synapse models, multi-synaptic models are more realistic as the number of multiple presynaptic neurons is considered. The authors illustrated and assumed several key aspects to account for multiple inputs. \n\n### **Assumptions:** \n\n1. They assumed that the postsynaptic activity is the linear sum of all the presynaptic activitys resulting from total number of neurons **N**, such that [5]: \n\\begin{equation*}\ny=\\sum_{i=1}^N x_i w_i\n\\end{equation*}\n\n2. The postsynaptic neuron receives $N_c$ = $RN$ synapses from the contralateral eye and $N_i$ = $N-N_c$ synapses from the ipsilateral eye. Where **R** is the ratio of contralateral eye neurons.\n\n3. To be more realistic, the authors also included an anatomical strength of axonal arborization when dealing with multiple inputs. This function is $A_i$ which is defined as: \n\\begin{equation*}\nA_i \\propto \\frac{1}{1+exp(\\frac{3(z_i-0.5)^2}{0.2^2-1})}\n\\end{equation*}\n\n where $z_i$ is the parameter used to distinguish the simulation conditions in terms of contralateral or ipsilateral eye and the inputs locations with respect to the retinotopic axis, whether monocular or binocular cortex. \n\n4. Assuming the inputs are uniformly spaced with N=500, $z_i$ is defined as:\n\n| \n View on QuantumLib\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
┌──────────────────┐ ┌──────────────────┐\n(0, 0): ───H───ZZ─────ZZ─────Z^(0.5*g)───X^b────────────────────────────────────────────────────────────────────────────────────────────M('m')───\n │ │ │\n(0, 1): ───H───┼──────ZZ^g───ZZ──────────ZZ──────Z^(0.5*g)─────────────X^b──────────────────────────────────────────────────────────────M────────\n │ │ │ │\n(0, 2): ───H───┼─────────────┼───────────ZZ^g────ZZ────────────────────Z^(0.5*g)────X^b─────────────────────────────────────────────────M────────\n │ │ │ │\n(1, 0): ───H───ZZ^g───ZZ─────┼───────────ZZ──────┼────────Z^(0.5*g)────X^b──────────────────────────────────────────────────────────────M────────\n │ │ │ │ │\n(1, 1): ───H──────────┼──────ZZ^g────────ZZ^g────┼────────ZZ───────────ZZ───────────Z^(0.5*g)─────────────X^b───────────────────────────M────────\n │ │ │ │ │\n(1, 2): ───H──────────┼──────────────────────────ZZ^g─────┼────────────ZZ^g─────────ZZ────────────────────Z^(0.5*g)───X^b───────────────M────────\n │ │ │ │\n(2, 0): ───H──────────ZZ^g────────────────────────────────┼────────────ZZ───────────┼────────Z^(0.5*g)────X^b───────────────────────────M────────\n │ │ │ │\n(2, 1): ───H──────────────────────────────────────────────ZZ^g─────────ZZ^g─────────┼─────────────────────ZZ──────────Z^(0.5*g)───X^b───M────────\n │ │ │\n(2, 2): ───H────────────────────────────────────────────────────────────────────────ZZ^g──────────────────ZZ^g────────Z^(0.5*g)───X^b───M────────\n └──────────────────┘ └──────────────────┘\n\n\n\nNow we'll instantiate a simulator and measure the output of the circuit repeatedly:\n\n\n```\nnum_reps = 10**3 # Try different numbers of repetitions\ngamma, beta = 0.2,0.25 # Try different values of the parameters\nsimulator = cirq.Simulator()\nparams = cirq.ParamResolver({'g':gamma, 'b':beta})\nresult = simulator.run(measurement_circuit, param_resolver = params, repetitions=num_reps)\n```\n\nFinally, we'll compute the energy for each of our measurement outcoems and look at the statistics. We start with a helper function which calculates the energy given a set of measurement outcomes:\n\n\n```\ndef compute_energy(meas, h):\n Z_vals = 1-2*meas.reshape(n_rows,n_cols)\n energy = 0\n for i in range(n_rows):\n for j in range(n_cols):\n if i < n_rows-1:\n energy -= Z_vals[i, j]*Z_vals[i+1, j]\n if j < n_cols-1:\n energy -= Z_vals[i, j]*Z_vals[i, j+1]\n energy -= h[i,j]*Z_vals[i,j]\n return energy/(n_rows*n_cols)\n```\n\nNow consider the 10 most common outputs of our measurements, and compute the energies of those:\n\n\n```\nhist = result.histogram(key='m')\nnum = 10\nprobs = [v/result.repetitions for _,v in hist.most_common(num)]\nconfigs = [c for c,_ in hist.most_common(num)]\n```\n\n\n```\nplt.title('Probability of {} Most Common Outputs'.format(num))\nplt.bar([x for x in range(len(probs))],probs)\nplt.show()\nmeas = [[int(s) for s in ''.join([str(b) for b in bin(k)[2:]]).zfill(n_rows*n_cols)] for k in configs]\ncosts = [compute_energy(np.array(m), h) for m in meas]\nplt.title('Energy of {} Most Common Outputs'.format(num))\nplt.bar([x for x in range(len(costs))],costs)\nplt.show()\nprint('Fraction of outputs displayed: {}'.format(np.sum(probs).round(2)))\n```\n\nWe see that, for a good choice of $\\gamma$ and $\\beta$, ground state is the most probable outcome.\n\nTry changing the values of $\\gamma$ and $\\beta$ away from the optimal ones. You'll see that this experiment no longer finds the ground state for us.\n\n### Exercise: Experiment with Different Numbers of Layers\nSee if you can get a closer to the true ground state (i.e., a larger fraction of measurements yielding the minimal energy) by adding more layers to the circuit.\n\n### Exercise: Try Ising Model on a different graph, or With Different Interaction Strengths\nInstead of a square lattice, you can try to formulate the Ising Model on any graph you like. This just changes which qubits you link in the $U(\\gamma, C)$ layer. Each edge of the graph could also come with a different interaction coefficient, so that instead of $\\exp(i\\pi \\gamma Z_iZ_j/2)$ for that edge you would have $\\exp(i\\pi \\gamma J_{ij}Z_iZ_j/2)$ for some matrix $J_{ij}$ of coefficients. Note that you have to change both the $U(\\gamma, C)$ layer and the definition of the energy function to make this work.\n\n### Exercise: Repeat Using Sampling\n\nOn real hardware we need to use sampling to estimate expectation values.\n\nAdjust your code so that sampling is used instead of wavefunction evaluation.\n\nHow many samples do you need to take to get good results? Try different values.\n\n\n### Exercise: Transverse field Ising Model\nThe Ising Model with transverse field replaces the $\\sum h_i Z_i$ term with a $\\sum h_i X_i$ term. Can we use the QAOA here as well? What are the differences?\nThis is no longer a classical problem: in general the ground state will now be a superposition of elements of the computational basis. Can you make a circuit that prepares a state close to the gound state?\n\n", "meta": {"hexsha": "07ba65e33e30c1671b161179299cf47d742f6ef6", "size": 84224, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/educators/qaoa_ising.ipynb", "max_stars_repo_name": "lilies/Cirq", "max_stars_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:06:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T17:06:10.000Z", "max_issues_repo_path": "docs/tutorials/educators/qaoa_ising.ipynb", "max_issues_repo_name": "lilies/Cirq", "max_issues_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/educators/qaoa_ising.ipynb", "max_forks_repo_name": "lilies/Cirq", "max_forks_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T15:29:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T15:29:29.000Z", "avg_line_length": 74.1408450704, "max_line_length": 17136, "alphanum_fraction": 0.6811360182, "converted": true, "num_tokens": 9058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.22270014914315836, "lm_q1q2_score": 0.07069087956435881}}
{"text": "```python\n%run ../../common/import_all.py\n\nfrom common.setup_notebook import set_css_style, setup_matplotlib, config_ipython\nconfig_ipython()\nsetup_matplotlib()\nset_css_style()\n```\n\n\n\n\n\n\n\n\n\n\n# The Naive Bayes classifier\n\nThe Naive Bayes is a probabilistic classifier based on (surprise surprise!) the Bayes' theorem and it uses a Maximum A Priori estimate to classify the labels. \n\nIn a nutshell, its properties are:\n\n* It assumes independence among features used for the classification. \n* It is usually used for text classification\n* Is fast\n* Requires small training data\n* The probability of the outcome classification is unreliable\n\n## How does it work\n\nGiven a target variable $y$ (the class) and features $x_1, x_2, \\ldots, x_n$, by Bayes' theorem we can write\n\n$$\nP(y \\ | \\ x_1, x_2, \\ldots, x_n) = \\frac{P(x_1, x_2, \\ldots, x_n \\ | \\ y) P(y)}{P(x_1, x_2, \\ldots, x_n)} \\ ,\n$$\n\n$P(y)$ being the frequency of the class $y$.\n\nThe *naive* assumption of the algorithm is that features are independent of each other, that is, the likelihood at the second member can be factorised into the product of the likelihood of single feature:\n$$\nP(x_i | y, x_1, \\ldots, x_{i-1}, x_{i+1}, \\ldots, x_n) = P(x_i | y) \\ \\ \\ \\forall i \\ .\n$$\n\nThis way, we can simplify and write\n\n$$\nP(y \\ | \\ x_1, \\ldots, x_n) = \\frac{\\prod_{i=1}^{i=n} P(x_i \\ | \\ y) P(y)}{P(x_1, \\ldots, x_n)} \\ ,\n$$\n\nWe apply the [MAP estimation](../../prob-stats/methods/map.ipynb) to find the $y$ that maximises the posterior. The denominator only gives a constant of normalisation, so the maximising value is found via\n\n$$\n\\hat{y} = arg \\max_y P(y) \\prod_{i=1}^{i=n} P(x_i | y)\n$$\n\nWhat this means is that the classifier assigns the class label $\\hat y$ as the one which maximises the posterior probability.\n\n## The different classifiers in the family (some cases)\n\nThe different Naive Bayes classifiers differ in the assumptions for the likelihood distribution $P(x_i | y)$.\n\n### Gaussian Naive Bayes\n\nIn a Gaussian Naive Bayes, it is assumed to be a gaussian:\n\n$$\nP(x_i | y) = \\frac{1}{\\sqrt{2 \\pi \\sigma_y^2}} e^{- \\frac{(x_i - \\mu_y)^2}{2 \\sigma_y^2}} \\ ,\n$$\n\nwith parameters $\\mu_y$ and $\\sigma_y$ being the mean and the standard deviation of feature $x_i$ in class $y$, estimated using the Maximum Likelihood estimation.\n\n### Bernoulli Naive Bayes\n\nIn a Bernoulli Naive Bayes, used when features are binary, it is assumed that \n\n$$\nP(x_i | y) = P(i | y) x_i + (1 - P(i | y))(1-x_i) \\ .\n$$\n\n### Multinomial Naive Bayes\n\nIn a Multinomial Naive Bayes, with feature vector $\\mathbf{x}$ and $k_i$ being the number of successes for variable $x_i$, the likelihood is given as\n\n$$\nP(\\mathbf{x} | y_k) = \\frac{\\Big(\\sum_i x_i\\Big)!}{\\prod_i x_i!} \\prod p_{k_i}^{x_i}\n$$\n\nNote that the multinomial Naive Bayes classifier becomes a linear classifier when expressed in logarithmic scale:\n\n\\begin{align}\n\\log P(y_k | \\mathbf{x}) &\\propto \\log \\Big[p(y_k) \\prod_{i=1}^n p_{k_i}^{x_i}\\Big] \\\\\n&= \\log p(y_k) + \\sum_{i=1}^n x_i \\log p_{k_i} \\\\\n&= b + \\mathbf{w}_k^t \\mathbf{x}\n\\end{align}\n\nwith $b = \\log p(y_k)$ (a constant) and $\\mathbf{w}_k = \\log p_{k_i}$.\n\n## Regularised Naive Bayes: the smoothing\n\nIf in the training data there is no value for which feature $x_i$ is determined by the class $y$, meaning there is no occurrences where feature and class are together, the likelihood would equal zero: this is a problem as there would be a zero in the multiplication.\n\nA correction to remedy this problem (*regularised Naive Bayes*) is obtained via adding an addend in the calculation of the likelihood as a frequency so as to have a small but non-zero probability. While in general we would calculate it as\n\n$$\np_i = \\frac{n_i}{n_y} \\ ,\n$$\n\nwhere $n_i$ is the number of times feature $x_i$ appears in the sample for class $y$ in the training set and $n_y$ is the total count of occurrences of class $y$, we smoothen as\n\n$$\np_i = \\frac{n_i + \\alpha}{n_y + \\alpha n}\n$$\n\nwhere $\\alpha$ is a chosen factor and $n$ the number of possible values for feature $x_i$. This procedure is called *Lidstone smoothing*, with $\\alpha = 1$ it's the *Laplace smoothing*.\n\n## An example: sex classification\n\nThis small example, as well as the ones below are taken and reworked from [the Wikipedia page on the topic](https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Sex_classification). The problem is about classifying if a person is a male (M) or a female (F) based on height (h, in feet), weight (w, in pounds) and foot size (f, in inches). This is the training data we assume to have collected:\n\n| Gender | h (feet) | w (lbs) | f (inches) |\n| ------ |:--------:| :------:| :--------: | \n| M | 6 | 180 | 12 | \n| M | 5.92 | 190 | 11 | \n| M | 5.58 | 170 | 12 | \n| M | 5.92 | 165 | 10 | \n| F | 5 | 100 | 6 | \n| M | 5.5 | 150 | 8 | \n| M | 5.42 | 130 | 7 | \n| M | 5.75 | 150 | 9 | \n\n\nWe use a gaussian assumption, so we assume the likelihood for each feature to be\n\n$$\nP(x_i | y) = \\frac{1}{\\sqrt{2 \\pi \\sigma_y^2}} e^{- \\frac{(x_i - \\mu_y)^2}{2 \\sigma_y^2}}\n$$\n\nand we estimate the parameters of said gaussians via [MLE](../../prob-stats/methods/mle.ipynb), obtaining:\n\n| Gender | $\\mu_h$ | $\\sigma^2_h$ | $\\mu_w$ | $\\sigma^2_w$ | $\\mu_f$ | $\\sigma^2_f$ |\n| ------ |:-------:| :---------:| :-----: | :----------: | :-----: | :----------: |\n| M | 5.86 | $3.5 \\cdot 10^{-2}$ | 176.25 | $1.23 \\cdot 10^2$ | 11.25 | $9.19 \\cdot 10^{-1}$ |\n| F | 5.42 | $9.72 \\cdot 10^{-2}$ | 132.5 | $5.58 \\cdot 10^2$ | 7.5 | 1.67 |\n\nThe two classes are equiprobable because we got the same number of training points for each, so $P(M) = P(F) = 0.5$, and these are the priors for each class. Note that we could also give the priors from the population, assuming that each gender is equiprobable.\n\nNow, given a new sample point whose height is 6 feet, weight 130 lbs and foot size 8 inches, we want to classify its gender, so we determine which class maximises the posterior:\n\n$$\nP(M | h, w, f) = \\frac{P(h, w, f | M) P(M)}{P(E)} \\ ,\n$$\n\nwhere, under the Naive Bayes assumption,\n\n$$\nP(h, w, f | M) = P(h | M) P(w | M) P(f | M) \\ ,\n$$\n\nand \n\n$$\nP(E) = P(h, w, f | M)P(M) + P(h, w, f | F)P(F) \\ ,\n$$\n\nwhich is just a normalising constant so can be ignored. Now,\n\n$$\nP(h | M) = \\frac{1}{\\sqrt{2 \\pi \\sigma^2}} e^{- \\frac{(6 - \\mu)^2}{2 \\sigma^2}} \\approx 1.5789\n$$\n\nIn the same way we compute $P(w | M) = 5.9881 \\cdot 10^{-6}$ and $P(f | M) = 1.3112 \\cdot 10^{-3}$, so that in the end we obtain $P(M | h, w, f) = 6.1984 \\cdot 10^{-9}$. Similarly we get $P(F | h, w, f) = 5.3779 \\cdot 10^{-4}$, which is larger so we predict that the sample is a female.\n\n## Other examples, on classifying text\n\n### Spam filter\n\nThis is a common application of a Naive Bayes classifier and it is a case of text classification. \n\nSome words are more frequent than others in spam e-mails (for example \"Viagra\" is definitely a recurring word in spam e-mails). The user manually and continuously trains the filter of their e-mail provider by indicating whether a mail is spam or not. For all words in each training mail, the filter then adjusts the probability that it will appear in a spam or legitimate e-mail.\n\nLet $S$ be the event that an e-mail is spam and $w$ a word, then we compute the probability that an e-mail is spam given that it contains $w$ as ($\\neg S$ is the event that mail is not spam, or \"ham\"):\n\n$$\nP(S | w) = \\frac{P(w | S) P(S)}{P(w | S) P(S) + P(w | \\neg S) P(\\neg S)} \\ ,\n$$\n\nwhere $P(S)$, the prior, is the probability that a message is spam in general, and $P(w | S)$ is the probability that $w$ appears in spam messages. \n\nA non biased filter will assume $P(S) = P(\\neg S) = 0.5$, biased filters will assume higher probability for mail being spam. $P(S | w)$ is approximated by the frequency of mails containing word $w$ and being identified as spam in the learning phase, and similarly for $P(w | \\neg S)$. \n\nNow, this is valid for a single word, but a functional spam classifier uses several words and a Naive Bayes hypothesis, assuming that the presence of each word is an independent event. Note that this is a crude assumption as in reality in natural language words co-occurrence is key. Nevertheless, it is a useful idealisation, useful for the calculation in the Naive Bayes fashion.\n\nSo, with more words considered [[1]](#graham),\n\n$$\nP(S | w_1, \\ldots, w_n) = \\frac{P(w_1 | S) \\cdots P(w_N | S)}{P(w_1 | S) \\cdots P(w_N | S) + P(w_1 | \\neg S) \\cdots P(w_N | \\neg S)}\n$$\n\n### Text classification\n\nGiven texts which can fall into categories (for example literary genres), we use\n\n$$\nP(C | w_1, \\ldots, w_n) = \\frac{\\Pi_{i=1}^n P(w_i | C) P(C)}{\\mathcal{N}}\n$$\n\nwith $C$ being the genre, $w_i$ the words and the denominator is an irrelevant factor.\n\nWith a bag of words approach, if we have a training set $D$ and a vocabulary $V$ containing all the words in the documents, considering $D_i$ the subset of texts in category $C_i$, then\n\n$$\nP(C_i) = \\frac{|D_i|}{|D|}\n$$\n\n(fraction of samples in category $C_i$). Now, we concatenate all documents in $D_i$, obtaining $n_i$ words and $\\forall w_j \\in V$ we call $n_{ij}$ the number of occurrences of $w_j$ in $D_i$, so\n\n$$\nP(w_j | C_i) = \\frac{n_{ij} + 1}{n_i + |V|}\n$$\n\n(we use smoothing). The predicted category is then\n\n$$\narg \\max_{C_k \\in \\mathcal{C}} P(C_k) \\Pi_{i=1}^n P(w_i | C_k)\n$$\n\n## References\n\n1. P Graham, [*A Plan for Spam*](http://www.paulgraham.com/spam.html), 2002\n\n\n```python\n\n```\n", "meta": {"hexsha": "2450bb87dacca5c02a99b3db76402baff297b666", "size": 15826, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ml-algorithms/supervised/nb.ipynb", "max_stars_repo_name": "walkenho/tales-science-data", "max_stars_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-11T09:39:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T09:39:10.000Z", "max_issues_repo_path": "ml-algorithms/supervised/nb.ipynb", "max_issues_repo_name": "walkenho/tales-science-data", "max_issues_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "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": "ml-algorithms/supervised/nb.ipynb", "max_forks_repo_name": "walkenho/tales-science-data", "max_forks_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "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": 39.8639798489, "max_line_length": 402, "alphanum_fraction": 0.5202830785, "converted": true, "num_tokens": 3595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.2068940439256578, "lm_q1q2_score": 0.07067138464302715}}
{"text": "# Language Classification with Naive Bayes in Python\n\n## Recommended Prerequisites for Successful Completion\n* Intermediate level understanding of Python 3+ (e.g. list and dictionary comprehension)\n* Basics of machine learning (e.g. the distinction between training and validation data)\n* Mathematical probability (e.g. understanding Bayes' Theorem at a basic level)\n\n\n## Project Outline\n[**Introduction**](#intro)\n\n[**Task 1**](#task1): Exploratory Data Analysis + Visualization\n\n[**Task 2**](#task2): Data Cleaning and Preprocessing\n\n[**Task 3**](#task3): Naive Bayes Model Introduction and Training\n\n[**Task 4**](#task4): Highlighting Problems with Basic Model and Simple Fixes\n\n[**Task 5**](#task5): Advanced Approach to Further Improve Performance\n\n\n```python\nimport matplotlib\n%matplotlib inline\n%config InlineBackend.figure_format = 'svg'\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\nimport numpy as np\nimport string\n\nfrom collections import defaultdict\n\nfrom sklearn.metrics import f1_score\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nimport joblib\nimport pickle as pkl\n\nfrom helper_code import *\n```\n\n\n# Introduction\n\n\n```python\nmodel = joblib.load('Data/Models/final_model.joblib')\nvectorizer = joblib.load('Data/Vectorizers/final_model.joblib')\n```\n\n## [Slovak Wikipedia Entry](https://sk.wikipedia.org/wiki/Jazveč%C3%ADk)\nMnohí ľudia, ktorí vidia na ulici jazvečíka s podlhovastým telom vôbec nevedia o tom, že tento malý štvornohý a veľmi obľúbený spoločník je pri dobrom výcviku obratným, vynikajúcim a spoľahlivým poľovným psom. Ako poľovný pes je mnohostranne využiteľný, okrem iného ako durič na brlohárenie. Králičí jazvečík sa dokáže obratne pohybovať v králičej nore. S inými psami a deťmi si nie vždy rozumie.\n\n## [Czech Wikipedia Entry](https://cs.wikipedia.org/wiki/Jezevč%C3%ADk)\nÚplně první zmínky o psech podobných dnešním jezevčíkům nacházíme až ve Starém Egyptě, kde jsou vyobrazeni na soškách a rytinách krátkonozí psi s dlouhým hřbetem a krátkou srstí. Jednalo se ale o neustálený typ bez ustáleného jména. Další zmínky o jezevčících nacházíme až ve 14 - 15. století. Jedná se o psa, který se nejvíce podobá dnešnímu typu hladkosrstého standardního jezevčíka.\n\n\n## [English Wikipedia Entry](https://en.wikipedia.org/wiki/Dachshund)\nWhile classified in the hound group or scent hound group in the United States and Great Britain, the breed has its own group in the countries which belong to the Fédération Cynologique Internationale (World Canine Federation). Many dachshunds, especially the wire-haired subtype, may exhibit behavior and appearance that are similar to that of the terrier group of dogs.\n\n\n```python\ntext = 'okrem iného ako durič na brlohárenie'\ntext = preprocess_function(text)\ntext = [split_into_subwords_function(text)]\ntext_vectorized = vectorizer.transform(text)\n\nmodel.predict(text_vectorized)\n\n```\n\n\n\n\n array(['sk'], dtype='Iterate over the elements of a sequence (such as a string, tuple, list or array) or other iterable object
\nTake Note
\nNote the double colon (`:`) at the end of the `for` statement and the indentation infront of the body. This tells *Python* where the header ends and which program statements (lines of code) belong to the body that will be repeated.\n
\nMore Information
\nYou can get more information about the `for` statement by executing `help(\"for\")` in a *Code Cell*
\nTake Note
\nBe very careful and aware of indentation when typing your programs, as this can sometimes lead to unexpected results and logic errors.
\nThere is a big difference between the following two examples. Make sure you know the difference in the results of these two examples and why they are different !!!
\nMore Information
\nMost editors (like *Jupyter Notebook*) will automatically add 4 spaces when you push the `tab` key. And `Shift + tab` will automatically remove 4 spaces. This can also be used if you have highlighted several lines of code. Try it !!
\nMore Information
\nRemember that you can use the `numpy.math.factorial(N)` function to verify the result of this example.
\nTake Note
\nNotice the indentation for this nested loop example above. Lines 5 to 9 require 4 spaces in front of the program statements to \"tell\" *Python* that they are inside the first (outer) `for` loop. Lines 7 and 8 require 4+4 spaces in front of the program statements to \"tell\" *Python* that they are inside the second (inner) `for` loop.
\nMake sure you understand the behaviour and output of the following three examples and why they are different!!
\n| \n | ID | \nName | \nInChI | \nInChIKey | \nSMILES | \nSolubility | \nSD | \nOcurrences | \nGroup | \nMolWt | \n... | \nNumAromaticRings | \nNumSaturatedRings | \nNumAliphaticRings | \nRingCount | \nTPSA | \nLabuteASA | \nBalabanJ | \nBertzCT | \nprocessed_smiles | \nclass | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \nA-3 | \nN,N,N-trimethyloctadecan-1-aminium bromide | \nInChI=1S/C21H46N.BrH/c1-5-6-7-8-9-10-11-12-13-... | \nSZEMGTQCPRNXEG-UHFFFAOYSA-M | \n[Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C | \n-3.616127 | \n0.0 | \n1 | \nG1 | \n392.510 | \n... | \n0.0 | \n0.0 | \n0.0 | \n0.0 | \n0.00 | \n158.520601 | \n0.000000 | \n210.377334 | \nCCCCCCCCCCCCCCCCCC[N+](C)(C)C | \nslightly soluble | \n
| 1 | \nA-4 | \nBenzo[cd]indol-2(1H)-one | \nInChI=1S/C11H7NO/c13-11-8-5-1-3-7-4-2-6-9(12-1... | \nGPYLCFQEKPUWLD-UHFFFAOYSA-N | \nO=C1Nc2cccc3cccc1c23 | \n-3.254767 | \n0.0 | \n1 | \nG1 | \n169.183 | \n... | \n2.0 | \n0.0 | \n1.0 | \n3.0 | \n29.10 | \n75.183563 | \n2.582996 | \n511.229248 | \nO=C1Nc2cccc3cccc1c23 | \nslightly soluble | \n
| 2 | \nA-5 | \n4-chlorobenzaldehyde | \nInChI=1S/C7H5ClO/c8-7-3-1-6(5-9)2-4-7/h1-5H | \nAVPYQKSLYISFPO-UHFFFAOYSA-N | \nClc1ccc(C=O)cc1 | \n-2.177078 | \n0.0 | \n1 | \nG1 | \n140.569 | \n... | \n1.0 | \n0.0 | \n0.0 | \n1.0 | \n17.07 | \n58.261134 | \n3.009782 | \n202.661065 | \nO=Cc1ccc(Cl)cc1 | \nslightly soluble | \n
| 3 | \nA-10 | \nvinyltoluene | \nInChI=1S/C9H10/c1-3-9-6-4-5-8(2)7-9/h3-7H,1H2,2H3 | \nJZHGRUMIRATHIU-UHFFFAOYSA-N | \nCc1cccc(C=C)c1 | \n-3.123150 | \n0.0 | \n1 | \nG1 | \n118.179 | \n... | \n1.0 | \n0.0 | \n0.0 | \n1.0 | \n0.00 | \n55.836626 | \n3.070761 | \n211.033225 | \nC=Cc1cccc(C)c1 | \nslightly soluble | \n
| 4 | \nA-11 | \n3-(3-ethylcyclopentyl)propanoic acid | \nInChI=1S/C10H18O2/c1-2-8-3-4-9(7-8)5-6-10(11)1... | \nWVRFSLWCFASCIS-UHFFFAOYSA-N | \nCCC1CCC(CCC(O)=O)C1 | \n-3.286116 | \n0.0 | \n1 | \nG1 | \n170.252 | \n... | \n0.0 | \n1.0 | \n1.0 | \n1.0 | \n37.30 | \n73.973655 | \n2.145839 | \n153.917569 | \nCCC1CCC(CCC(=O)O)C1 | \nslightly soluble | \n
5 rows × 28 columns
\n| \n | 0 | \n
|---|---|
| MolLogP | \n0.618195 | \n
| MolWt | \n0.451355 | \n
| MolMR | \n0.444390 | \n
| LabuteASA | \n0.423057 | \n
| NumValenceElectrons | \n0.366864 | \n
| \n | 0 | \n
|---|---|
| NumRotatableBonds | \n0.080012 | \n
| NumHeteroatoms | \n0.070472 | \n
| NumHDonors | \n0.059317 | \n
| NumAliphaticRings | \n0.024100 | \n
| NumSaturatedRings | \n0.019100 | \n
Sánchez, Juan Pablo (jpsanchez@fi.uba.ar) - 105.865
\nde Luca Andrea, Felipe (fdeluca@fi.uba.ar) - 105.646
\nLitteri, Iván (ilitteri@fi.uba.ar - 106.223
\n \nSassano
\n\n26 de mayo del 2021
\n\nPython
\n\nAyudamos a un familiar a la hora de ajustar el volumen del celular para poder ver una película. Decidimos emplear el método de bisección para hallar el volumen adecuado.
\n\nEl método consiste en obtener, mediante un intervalo ($\\tau$), una raíz definida como cero en el método. Para ello, necesitamos conocer si existe un cambio de signo en el mismo, de lo contrario no podemos garantizar la existencia de la raíz buscada. En caso de no encontrarla, se divide el intervalo en dos y se vuelve a evaluar el cambio de signo antedicho. El proceso debe repetirse hasta mejorar la aproximación, de acuerdo con el error que estemos dispuestos a aceptar.
\n\nComo raíz o cero tomamos\n\n $$\\text{raíz o cero = volúmen adecuado}$$\n\nen donde nuestra función es\n\n$$f(x) = \\text{volúmen del celular}$$\n\nPara la comprobación por el método de Bolzano\n\n\\begin{equation}\n f(\\text{volúmen bajo}) < 0 \\text{ y } f(\\text{volúmen alto}) > 0\n \\quad (\\rho)\n\\end{equation}\n\n\n \n Fig.1 En naranja y amarillo se ve el máximo y mínimo del diálogo. La segunda vez que preguntamos vemos el volumen en verde, en magenta el valor requerido por el usuario.
Con lo cual, por lo dicho en ($\\rho$) debemos obtener un valor que no necesariamente se encuentre en el medio, ya que dependerá de la subjetividad del usuario en cuestión, pero que por el Teorema del Valor Intermedio sabemos que debe existir dentro del intervalo que poseemos.
\n\nDicho esto, procederemos a preguntar:\n\n- *¿El volumen está muy alto o bajo?* ($\\lambda$)\n- *Muy alto*\n\n> Bajamos el volumen y volvemos a preguntar ($\\lambda$)\n\n- *Muy bajo*\n\n>Vemos entonces la definición del intervalo que buscábamos ($\\tau$) para aplicar el método que necesitamos. Como quedan dos intervalos (el primero, y el definido en el diálogo, lógicamente comprendido en el anterior) chequeamos cada uno por separado. Por ende, subimos y/o bajamos el volumen del teléfono y volvemos a preguntar.
\n\n> Lo haremos tantas veces como haga falta y de esa forma hallaremos el volumen adecuado.\n\nRespecto al error, el mismo queda limitado por la cantidad de divisiones que posea la escala de volúmenes en el teléfono, con lo cual no podremos controlar ese aspecto.
\n\n## (b) Comentar la experiencia.\n\nSe nos ocurrió esta idea ya que hace unos meses uno de los integrantes del grupo estaba ayudando a su abuela a usar su teléfono, siendo que ella no lo sabe utilizar muy bien.
\n\nEn ese entonces, ella había estado recibiendo llamados pero tenía el teléfono silenciado y no se acordaba como subirle el volumen, por lo que me pidio ayuda ya que había pasado por su casa a dejarle unas cosas.
\n\nLa experiencia fue muy similar a lo expresado anteriormente: puse un video de youtube para poder ir testeando el sonido, lo puse a la mitad y le pregunté si estaba muy alto o muy bajo. Así una o dos veces más y se lo deje, no tuvo más inconviententes.
\n\n\n\n\n# 2. Hallar $\\pi$ por dos caminos\n\n\n## (a) Algoritmo de Newton-Raphson\n\n\n```python\n# Realiza las cuentas con y devuelve el mismo tipo de dato que tiene la semilla\ndef nr(funcion, derivada, semilla, max_iter = 10000, corte = 0):\n tolerancia_cero = tol_cero(type(semilla))\n lista = [semilla]\n for i in range(1, max_iter):\n divisor = derivada(lista[-1])\n if (abs(divisor) < tolerancia_cero):\n raise ZeroDivisionError\n \n lista.append(lista[-1] - funcion(lista[-1])/divisor)\n if (abs(lista[i - 1] - lista[i]) <= corte):\n break\n\n return np.array(lista)\n```\n\n## (b) Algoritmo de Leibniz\n\n\n```python\ndef leibniz(iteraciones, tipo):\n pi = tipo(0.0)\n signo = tipo(1.0)\n for iteracion in range(1, iteraciones, 2):\n pi += signo / tipo(iteracion)\n signo *= tipo(-1.0)\n \n return pi * tipo(4)\n```\n\n## (c) Ejecutar los algoritmos anteriores con iteraciones $n=10, n=100, n=1000, n=10000, n=100000$ utilizando una representación de punto flotante de $32$ bits.\n\n\n```python\nITERACIONES = [10, 100, 1000, 10000, 100000]\n```\n\n### Con Newton-Raphson\n\n\n```python\n iteraciones_32 = nr(lambda x : np.sin(x), lambda x : np.cos(x), np.float64(3))\n\n print(\"Con punto flotante de 32 bits:\")\n imprimir_iteraciones(iteraciones_32)\n```\n\n Con punto flotante de 32 bits:\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 3.000000000000000\n Iteracion 1\t\t 3.142546543074277\t\t 0.142546543074277\n Iteracion 2\t\t 3.141592653300476\t\t 0.000953889773800\n Iteracion 3\t\t 3.141592653589793\t\t 0.000000000289316\n Iteracion 4\t\t 3.141592653589793\t\t 0.000000000000000\n\n\n> No hicimos las siguientes iteraciones ya que el valor permanecía invariante desde la $4^{ta}$ iteración\n\n### Con Leibniz\n\n\n```python\nprint(*[f'{x} iteraciones: {leibniz(x, np.float32)}' for x in ITERACIONES], sep = '\\n')\n```\n\n 10 iteraciones: 3.3396823406219482\n 100 iteraciones: 3.121594190597534\n 1000 iteraciones: 3.1395931243896484\n 10000 iteraciones: 3.14139723777771\n 100000 iteraciones: 3.141575813293457\n\n\n## (d) Ejecutar los algoritmos anteriores con iteraciones $n=10, n=100, n=1000, n=10000, n=100000$ utilizando una representación de punto flotante de $64$ bits.\n\n### Con Newton-Raphson\n\n\n```python\n iteraciones_64 = nr(lambda x : np.sin(x), lambda x : np.cos(x), np.float64(3))\n print(\"Con punto flotante de 64 bits:\")\n imprimir_iteraciones(iteraciones_64)\n```\n\n Con punto flotante de 64 bits:\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 3.000000000000000\n Iteracion 1\t\t 3.142546543074277\t\t 0.142546543074277\n Iteracion 2\t\t 3.141592653300476\t\t 0.000953889773800\n Iteracion 3\t\t 3.141592653589793\t\t 0.000000000289316\n Iteracion 4\t\t 3.141592653589793\t\t 0.000000000000000\n\n\n> No hicimos las siguientes iteraciones ya que el valor permanecía invariante desde la $4^{ta}$ iteración\n\n### Con Leibniz\n\n\n```python\nprint(*[f'{x} iteraciones: {leibniz(x, np.float64)}' for x in ITERACIONES], sep = '\\n')\n```\n\n 10 iteraciones: 3.3396825396825403\n 100 iteraciones: 3.121594652591011\n 1000 iteraciones: 3.139592655589785\n 10000 iteraciones: 3.141392653591791\n 100000 iteraciones: 3.1415726535897814\n\n\n## (e) Ejecutar los programas solicitados en a y b con una calculadora (aclarar marca y modelo) y comparar las respuestas obtenidas con $n = 10, n = 100, n = 1000, n = 10000$ y $n = 100000$ (en caso de no alcanzar la memoria de la calculadora utilizar el máximo $n$ posible).\n\nPara realizar este item utilizamos una calculadora CASIO fx-991ES PLUS. Cuenta con las siguientes especificaciones:\n\n\n### Con Newton-Raphson\n\nSe obtuvieron los siguientes resultados:\n\n\n* $p_0 = 3$\n* $p_1 = 3.142546543$\n* $p_2 = 3.141592653$\n* $p_3 = \\pi = 3.141592654$\n\nA partir de las siguientes iteraciones la calculadora continuaba mostrando $\\pi$, siendo el error tan pequeño que esta ya no podía diferenciarlo de acuerdo a sus especificaciones.
\n\n\n### Con Leibniz\n\nSe obtuvieron los siguientes resultados:\n* $p_0 = 1$\n* $p_1 = \\frac{2}{3}$\n* $p_{10} = 0.8080789524$\n* $p_{100} = 0.7878733593$\n* $p_{1000} = 0.7856479136$\n* $p_{10000} = 0.7854231609$\n* $p_{100000} = 0.7854006633$\n\nAclaración: La serie de Leibniz converge a $\\frac{1}{4}\\pi$ y en este caso se calculó sin multiplicar el valor por 4. Por comodidad, el valor real de este número es $\\frac{1}{4}\\pi = 0.7853981634 \\pm 0.0000000001$.
\n\nSe puede notar que al llegar a $100000$ iteraciones (tras 2 horas calculando), la calculadora acumuló más error del que venía con $10000$.
\n\n## (f) Representar las dos respuestas finales obtenidas (para $n = 100000$ y el método de Newton Raphson) en c, d y e de manera de expresarlo como $\\pi = \\overline{\\pi} + ∆\\pi$.\n\n### Con punto flotante de 32 bits\n\nLas siguientes iteraciones de Newton Raphson ya no variaban, por lo que el error del método ya era más pequeño que el del tipo de dato utilizado en el cálculo. Por lo tanto, el error del resultado será el del tipo de dato.
\n\nUn punto flotante de 32 bits tiene reservados 23 dígitos para la mantisa, más el dígito implícito, por lo que en base 10 tendrá $log_{10}(2^{24}) \\rfloor = 7$ dígitos significativos. Por lo tanto:
\n $$\\pi = 3.141592 \\pm 0.000001$$\n\n### Con punto flotante de 64 bits\n\nNuevamente el error será el de la representación del tipo de dato. Un punto flotante de 64 bits tiene reservados 52 dígitos para la mantisa, más el dígito implícito, por lo que en base 10 tendrá $\\log_{10}(2^{53}) \\rfloor = 15$ dígitos significativos. Por lo tanto:
\n$$\\pi = 3.14159265358979 \\pm 0.00000000000001$$\n\n### Con calculadora CASIO fx-991ES PLUS\n\nEn este caso, por las mismas razones expresadas anteriormente, el error va a ser el de la calculadora. En este caso, esta especificaba un error de $\\pm 1$ en el décimo dígito, es decir, 10 cifras significativas:
\n$$\\pi = 3.141592654 \\pm 0.000000001$$\n\n## (g) ¿Podemos afirmar que para la computadora el número $π$ es una constante?\n\n\nSi bien la calculadora guarda el número como una constante, se debería considerar una variable a la hora de calcular el error y su propagación, ya que al ser $\\pi$ un número irracional este tiene infinitos dígitos que son imposibles de almacenar en una computadora, y mucho menos hacer cálculos con todos ellos. El error a considerar dependerá de las especificaciones del tipo de dato que se este utilizando para almacenarlo.
\n\n# 3. Búsqueda de raíces\n\n$$\nf_{1}(x) = x^2 - 2\\\\\nf_{2}(x) = x^5 - 6.6 \\cdot x^4 + 5.12 \\cdot x^3 + 21.312 \\cdot x^2 - 38.016 \\cdot x + 17.28\\\\\nf_{3}(x) = (x-1.5) \\cdot e^{-4 \\cdot (x-1.5)^{2}}\n$$\n\n\n```python\nf1 = lambda x : x*x - 2 \nf1_der = lambda x : 2*x\nf1_der_2 = lambda x : 2\n \nf2 = lambda x : x ** 5 - 6.6 * x ** 4 + 5.12 * x ** 3 + 21.312 * x ** 2 - 38.016 * x + 17.28\nf2_der = lambda x : 5 * x ** 4 - 26.4 * x ** 3 + 15.36 * x ** 2 + 42.624 * x - 38.016\nf2_der_2 = lambda x : 20 * x ** 3 - 79.2 * x ** 2 + 30.72 * x + 42.624\n\nf3 = lambda x : (x - 1.5) * np.exp(-4 * (x - 1.5) ** 2)\nf3_der = lambda x : np.exp(-4 * (x - 1.5) ** 2) * ((-8 * x + 12) * (x - 1.5) + 1)\nf3_der_2 = lambda x : np.exp(-4 * (x - 1.5) ** 2) * (-24 * x + (x - 1.5) * (8 * x - 12) ** 2 + 36)\n```\n\n\n```python\nINTERVALO = [0, 2]\n```\n\n\n```python\n# CONSTANTES\n# Cotas de error\nERRORES = [np.float64(10**-5), np.float64(10**-13)]\n# Funciones a evaluar\nFUNCIONES = [f1, f2, f3]\nFUNCIONES_DER = [f1_der, f2_der, f3_der]\nFUNCIONES_DER_2 = [f1_der_2, f2_der_2, f3_der_2]\n# Mensajes\nSTR_ERRORES = ['10^(-5)', '10^(-13)']\nSTR_FUNCIONES = ['x**2 - 2', 'x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28', '(x - 1.5) * np.exp(-4 * (x - 1.5)**2)']\n# Resultados\nresultados_raices = {'biseccion': {}, 'nr': {}, 'nr_mod': {}, 'secante': {}}\n```\n\n\n```python\n# Función auxiliar para imprimir las distintas raíces de los métodos\ndef imprimir_raices_de_funciones(algoritmo, raices: dict, semillas, funciones = (1, 2, 3)) -> None:\n cant_semillas = 1\n k = 0\n nombre_metodo = algoritmo.__name__\n for i in funciones:\n for j, e in enumerate(ERRORES):\n print(f'Funcion {STR_FUNCIONES[i-1]} con error de {STR_ERRORES[j]}')\n try:\n if nombre_metodo == 'nr_mod':\n raices['nr_mod'][f'{i}'] = algoritmo(FUNCIONES[i-1], FUNCIONES_DER[i-1], FUNCIONES_DER_2[i-1], semillas[k], corte = e)\n elif nombre_metodo == 'nr':\n raices['nr'][f'{i}'] = algoritmo(FUNCIONES[i-1], FUNCIONES_DER[i-1], semillas[k], corte = e)\n else:\n raices[nombre_metodo][f'{i}'] = algoritmo(FUNCIONES[i-1], *semillas[k], e)\n cant_semillas = 2\n except Exception:\n print(f\"ERROR: Divisor se hizo 0 al calcular la siguiente iteración\\n\")\n continue\n imprimir_iteraciones(raices[nombre_metodo][f'{i}'], cant_semillas)\n print(\"\\n\")\n k += 1\n```\n\n## (a) Graficar las funciones $f_{1}(x), f_{2}(x), f_{3}(x)$ en el intervalo $[0, 2]$\n\n\n```python\nx = np.linspace(0,2,num=1000)\n\nplt.plot(x, list(map(f1, x)), label=r'$x^2 - 2$')\nplt.plot(x, list(map(f2, x)), label=r'$x^5 - 6.6x^4 + 5.12x^2 - 38.016x + 17.28$')\nplt.plot(x, list(map(f3, x)), label=r'$(x-1.5) \\cdot e^{(-4(x-1.5)^{2})}$')\n\nplt.axhline(0, color=\"black\")\nplt.axvline(0, color=\"black\")\n\nplt.xlim(INTERVALO)\nplt.ylim(-2, 2)\n\nplt.legend()\nplt.show()\n```\n\n## (b) Hallar las raices de las funciones $f_{1}(x), f_{2}(x), f_{3}(x)$ en el intervalo $[0, 2]$ con los métodos de Bisección, Newton-Raphson, Newton-Raphson modificado y Secante.\n\n### Algoritmo de Bisección\n\n\n```python\ndef biseccion(funcion, q0, q1, corte = 0, max_iter = 10000):\n contador = 1\n lista = [q0, q1]\n\n while abs(lista[contador] - lista[contador-1]) > corte:\n q2 = (q0 + q1) / 2 \n if funcion(q0) * funcion(q2) <= 0:\n q1 = q2\n lista.append(q1)\n else:\n q0 = q2\n lista.append(q0)\n contador = contador + 1\n if (contador >= max_iter):\n break\n\n return np.array(lista)\n```\n\n### Algoritmo de Newton Raphson Modificado\n\n\n```python\ndef nr_mod(funcion, derivada, derivada_2, semilla, corte = 0, max_iter = 10000):\n tolerancia_cero = tol_cero(type(semilla))\n lista = [semilla]\n for i in range(1, max_iter):\n divisor = derivada(lista[-1]) ** 2 - funcion(lista[-1]) * derivada_2(lista[-1])\n if (abs(divisor) < tolerancia_cero):\n raise ZeroDivisionError\n\n lista.append(lista[-1] - funcion(lista[-1]) * derivada(lista[-1]) / divisor)\n if (abs(lista[i - 1] - lista[i]) <= corte):\n break\n\n return np.array(lista)\n```\n\n### Algoritmo de Secante\n\n\n```python\ndef secante(f, a, b, corte = 0, max_iter = 1000):\n tolerancia_cero = tol_cero(type(a))\n p = [a, b]\n p_n_div = lambda f, n, p: f(p[n-1]) - f(p[n-2])\n p_n = lambda f, n, p: p[n-1] - ((f(p[n-1]) * (p[n-1] - p[n-2])) / (p_n_div(f, n, p)))\n for n in range(2, max_iter-1):\n if (abs(p_n_div(f, n, p)) < tolerancia_cero):\n raise ZeroDivisionError\n p.append(p_n(f, n, p))\n if abs(p[n-1] - p[n]) <= corte:\n break\n\n return np.array(p)\n```\n\n### Por Bisección\n\n\n```python\nimprimir_raices_de_funciones(biseccion, resultados_raices, [(np.float64(0), np.float64(2))] * 3)\n\n```\n\n Funcion x**2 - 2 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 4\t\t 1.250000000000000\t\t 0.250000000000000\n Iteracion 5\t\t 1.375000000000000\t\t 0.125000000000000\n Iteracion 6\t\t 1.437500000000000\t\t 0.062500000000000\n Iteracion 7\t\t 1.406250000000000\t\t 0.031250000000000\n Iteracion 8\t\t 1.421875000000000\t\t 0.015625000000000\n Iteracion 9\t\t 1.414062500000000\t\t 0.007812500000000\n Iteracion 10\t\t 1.417968750000000\t\t 0.003906250000000\n Iteracion 11\t\t 1.416015625000000\t\t 0.001953125000000\n Iteracion 12\t\t 1.415039062500000\t\t 0.000976562500000\n Iteracion 13\t\t 1.414550781250000\t\t 0.000488281250000\n Iteracion 14\t\t 1.414306640625000\t\t 0.000244140625000\n Iteracion 15\t\t 1.414184570312500\t\t 0.000122070312500\n Iteracion 16\t\t 1.414245605468750\t\t 0.000061035156250\n Iteracion 17\t\t 1.414215087890625\t\t 0.000030517578125\n Iteracion 18\t\t 1.414199829101562\t\t 0.000015258789062\n Iteracion 19\t\t 1.414207458496093\t\t 0.000007629394531\n \n \n Funcion x**2 - 2 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 4\t\t 1.250000000000000\t\t 0.250000000000000\n Iteracion 5\t\t 1.375000000000000\t\t 0.125000000000000\n Iteracion 6\t\t 1.437500000000000\t\t 0.062500000000000\n Iteracion 7\t\t 1.406250000000000\t\t 0.031250000000000\n Iteracion 8\t\t 1.421875000000000\t\t 0.015625000000000\n Iteracion 9\t\t 1.414062500000000\t\t 0.007812500000000\n Iteracion 10\t\t 1.417968750000000\t\t 0.003906250000000\n Iteracion 11\t\t 1.416015625000000\t\t 0.001953125000000\n Iteracion 12\t\t 1.415039062500000\t\t 0.000976562500000\n Iteracion 13\t\t 1.414550781250000\t\t 0.000488281250000\n Iteracion 14\t\t 1.414306640625000\t\t 0.000244140625000\n Iteracion 15\t\t 1.414184570312500\t\t 0.000122070312500\n Iteracion 16\t\t 1.414245605468750\t\t 0.000061035156250\n Iteracion 17\t\t 1.414215087890625\t\t 0.000030517578125\n Iteracion 18\t\t 1.414199829101562\t\t 0.000015258789062\n Iteracion 19\t\t 1.414207458496093\t\t 0.000007629394531\n Iteracion 20\t\t 1.414211273193359\t\t 0.000003814697265\n Iteracion 21\t\t 1.414213180541992\t\t 0.000001907348632\n Iteracion 22\t\t 1.414214134216308\t\t 0.000000953674316\n Iteracion 23\t\t 1.414213657379150\t\t 0.000000476837158\n Iteracion 24\t\t 1.414213418960571\t\t 0.000000238418579\n Iteracion 25\t\t 1.414213538169860\t\t 0.000000119209289\n Iteracion 26\t\t 1.414213597774505\t\t 0.000000059604644\n Iteracion 27\t\t 1.414213567972183\t\t 0.000000029802322\n Iteracion 28\t\t 1.414213553071022\t\t 0.000000014901161\n Iteracion 29\t\t 1.414213560521602\t\t 0.000000007450580\n Iteracion 30\t\t 1.414213564246892\t\t 0.000000003725290\n Iteracion 31\t\t 1.414213562384247\t\t 0.000000001862645\n Iteracion 32\t\t 1.414213561452925\t\t 0.000000000931322\n Iteracion 33\t\t 1.414213561918586\t\t 0.000000000465661\n Iteracion 34\t\t 1.414213562151417\t\t 0.000000000232830\n Iteracion 35\t\t 1.414213562267832\t\t 0.000000000116415\n Iteracion 36\t\t 1.414213562326040\t\t 0.000000000058207\n Iteracion 37\t\t 1.414213562355143\t\t 0.000000000029103\n Iteracion 38\t\t 1.414213562369695\t\t 0.000000000014551\n Iteracion 39\t\t 1.414213562376971\t\t 0.000000000007275\n Iteracion 40\t\t 1.414213562373333\t\t 0.000000000003637\n Iteracion 41\t\t 1.414213562371514\t\t 0.000000000001818\n Iteracion 42\t\t 1.414213562372424\t\t 0.000000000000909\n Iteracion 43\t\t 1.414213562372879\t\t 0.000000000000454\n Iteracion 44\t\t 1.414213562373106\t\t 0.000000000000227\n Iteracion 45\t\t 1.414213562372992\t\t 0.000000000000113\n Iteracion 46\t\t 1.414213562373049\t\t 0.000000000000056\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 4\t\t 1.250000000000000\t\t 0.250000000000000\n Iteracion 5\t\t 1.125000000000000\t\t 0.125000000000000\n Iteracion 6\t\t 1.187500000000000\t\t 0.062500000000000\n Iteracion 7\t\t 1.218750000000000\t\t 0.031250000000000\n Iteracion 8\t\t 1.203125000000000\t\t 0.015625000000000\n Iteracion 9\t\t 1.195312500000000\t\t 0.007812500000000\n Iteracion 10\t\t 1.199218750000000\t\t 0.003906250000000\n Iteracion 11\t\t 1.201171875000000\t\t 0.001953125000000\n Iteracion 12\t\t 1.200195312500000\t\t 0.000976562500000\n Iteracion 13\t\t 1.199707031250000\t\t 0.000488281250000\n Iteracion 14\t\t 1.199951171875000\t\t 0.000244140625000\n Iteracion 15\t\t 1.200073242187500\t\t 0.000122070312500\n Iteracion 16\t\t 1.200012207031250\t\t 0.000061035156250\n Iteracion 17\t\t 1.199981689453125\t\t 0.000030517578125\n Iteracion 18\t\t 1.199996948242187\t\t 0.000015258789062\n Iteracion 19\t\t 1.200004577636718\t\t 0.000007629394531\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 4\t\t 1.250000000000000\t\t 0.250000000000000\n Iteracion 5\t\t 1.125000000000000\t\t 0.125000000000000\n Iteracion 6\t\t 1.187500000000000\t\t 0.062500000000000\n Iteracion 7\t\t 1.218750000000000\t\t 0.031250000000000\n Iteracion 8\t\t 1.203125000000000\t\t 0.015625000000000\n Iteracion 9\t\t 1.195312500000000\t\t 0.007812500000000\n Iteracion 10\t\t 1.199218750000000\t\t 0.003906250000000\n Iteracion 11\t\t 1.201171875000000\t\t 0.001953125000000\n Iteracion 12\t\t 1.200195312500000\t\t 0.000976562500000\n Iteracion 13\t\t 1.199707031250000\t\t 0.000488281250000\n Iteracion 14\t\t 1.199951171875000\t\t 0.000244140625000\n Iteracion 15\t\t 1.200073242187500\t\t 0.000122070312500\n Iteracion 16\t\t 1.200012207031250\t\t 0.000061035156250\n Iteracion 17\t\t 1.199981689453125\t\t 0.000030517578125\n Iteracion 18\t\t 1.199996948242187\t\t 0.000015258789062\n Iteracion 19\t\t 1.200004577636718\t\t 0.000007629394531\n Iteracion 20\t\t 1.200000762939453\t\t 0.000003814697265\n Iteracion 21\t\t 1.200002670288085\t\t 0.000001907348632\n Iteracion 22\t\t 1.200003623962402\t\t 0.000000953674316\n Iteracion 23\t\t 1.200004100799560\t\t 0.000000476837158\n Iteracion 24\t\t 1.200003862380981\t\t 0.000000238418579\n Iteracion 25\t\t 1.200003981590270\t\t 0.000000119209289\n Iteracion 26\t\t 1.200004041194915\t\t 0.000000059604644\n Iteracion 27\t\t 1.200004070997238\t\t 0.000000029802322\n Iteracion 28\t\t 1.200004085898399\t\t 0.000000014901161\n Iteracion 29\t\t 1.200004093348979\t\t 0.000000007450580\n Iteracion 30\t\t 1.200004097074270\t\t 0.000000003725290\n Iteracion 31\t\t 1.200004098936915\t\t 0.000000001862645\n Iteracion 32\t\t 1.200004099868237\t\t 0.000000000931322\n Iteracion 33\t\t 1.200004099402576\t\t 0.000000000465661\n Iteracion 34\t\t 1.200004099635407\t\t 0.000000000232830\n Iteracion 35\t\t 1.200004099751822\t\t 0.000000000116415\n Iteracion 36\t\t 1.200004099810030\t\t 0.000000000058207\n Iteracion 37\t\t 1.200004099839134\t\t 0.000000000029103\n Iteracion 38\t\t 1.200004099853686\t\t 0.000000000014551\n Iteracion 39\t\t 1.200004099846410\t\t 0.000000000007275\n Iteracion 40\t\t 1.200004099850048\t\t 0.000000000003637\n Iteracion 41\t\t 1.200004099848229\t\t 0.000000000001818\n Iteracion 42\t\t 1.200004099849138\t\t 0.000000000000909\n Iteracion 43\t\t 1.200004099849593\t\t 0.000000000000454\n Iteracion 44\t\t 1.200004099849820\t\t 0.000000000000227\n Iteracion 45\t\t 1.200004099849934\t\t 0.000000000000113\n Iteracion 46\t\t 1.200004099849991\t\t 0.000000000000056\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 4\t\t 1.250000000000000\t\t 0.250000000000000\n Iteracion 5\t\t 1.375000000000000\t\t 0.125000000000000\n Iteracion 6\t\t 1.437500000000000\t\t 0.062500000000000\n Iteracion 7\t\t 1.468750000000000\t\t 0.031250000000000\n Iteracion 8\t\t 1.484375000000000\t\t 0.015625000000000\n Iteracion 9\t\t 1.492187500000000\t\t 0.007812500000000\n Iteracion 10\t\t 1.496093750000000\t\t 0.003906250000000\n Iteracion 11\t\t 1.498046875000000\t\t 0.001953125000000\n Iteracion 12\t\t 1.499023437500000\t\t 0.000976562500000\n Iteracion 13\t\t 1.499511718750000\t\t 0.000488281250000\n Iteracion 14\t\t 1.499755859375000\t\t 0.000244140625000\n Iteracion 15\t\t 1.499877929687500\t\t 0.000122070312500\n Iteracion 16\t\t 1.499938964843750\t\t 0.000061035156250\n Iteracion 17\t\t 1.499969482421875\t\t 0.000030517578125\n Iteracion 18\t\t 1.499984741210937\t\t 0.000015258789062\n Iteracion 19\t\t 1.499992370605468\t\t 0.000007629394531\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 4\t\t 1.250000000000000\t\t 0.250000000000000\n Iteracion 5\t\t 1.375000000000000\t\t 0.125000000000000\n Iteracion 6\t\t 1.437500000000000\t\t 0.062500000000000\n Iteracion 7\t\t 1.468750000000000\t\t 0.031250000000000\n Iteracion 8\t\t 1.484375000000000\t\t 0.015625000000000\n Iteracion 9\t\t 1.492187500000000\t\t 0.007812500000000\n Iteracion 10\t\t 1.496093750000000\t\t 0.003906250000000\n Iteracion 11\t\t 1.498046875000000\t\t 0.001953125000000\n Iteracion 12\t\t 1.499023437500000\t\t 0.000976562500000\n Iteracion 13\t\t 1.499511718750000\t\t 0.000488281250000\n Iteracion 14\t\t 1.499755859375000\t\t 0.000244140625000\n Iteracion 15\t\t 1.499877929687500\t\t 0.000122070312500\n Iteracion 16\t\t 1.499938964843750\t\t 0.000061035156250\n Iteracion 17\t\t 1.499969482421875\t\t 0.000030517578125\n Iteracion 18\t\t 1.499984741210937\t\t 0.000015258789062\n Iteracion 19\t\t 1.499992370605468\t\t 0.000007629394531\n Iteracion 20\t\t 1.499996185302734\t\t 0.000003814697265\n Iteracion 21\t\t 1.499998092651367\t\t 0.000001907348632\n Iteracion 22\t\t 1.499999046325683\t\t 0.000000953674316\n Iteracion 23\t\t 1.499999523162841\t\t 0.000000476837158\n Iteracion 24\t\t 1.499999761581420\t\t 0.000000238418579\n Iteracion 25\t\t 1.499999880790710\t\t 0.000000119209289\n Iteracion 26\t\t 1.499999940395355\t\t 0.000000059604644\n Iteracion 27\t\t 1.499999970197677\t\t 0.000000029802322\n Iteracion 28\t\t 1.499999985098838\t\t 0.000000014901161\n Iteracion 29\t\t 1.499999992549419\t\t 0.000000007450580\n Iteracion 30\t\t 1.499999996274709\t\t 0.000000003725290\n Iteracion 31\t\t 1.499999998137354\t\t 0.000000001862645\n Iteracion 32\t\t 1.499999999068677\t\t 0.000000000931322\n Iteracion 33\t\t 1.499999999534338\t\t 0.000000000465661\n Iteracion 34\t\t 1.499999999767169\t\t 0.000000000232830\n Iteracion 35\t\t 1.499999999883584\t\t 0.000000000116415\n Iteracion 36\t\t 1.499999999941792\t\t 0.000000000058207\n Iteracion 37\t\t 1.499999999970896\t\t 0.000000000029103\n Iteracion 38\t\t 1.499999999985448\t\t 0.000000000014551\n Iteracion 39\t\t 1.499999999992724\t\t 0.000000000007275\n Iteracion 40\t\t 1.499999999996362\t\t 0.000000000003637\n Iteracion 41\t\t 1.499999999998181\t\t 0.000000000001818\n Iteracion 42\t\t 1.499999999999090\t\t 0.000000000000909\n Iteracion 43\t\t 1.499999999999545\t\t 0.000000000000454\n Iteracion 44\t\t 1.499999999999772\t\t 0.000000000000227\n Iteracion 45\t\t 1.499999999999886\t\t 0.000000000000113\n Iteracion 46\t\t 1.499999999999943\t\t 0.000000000000056\n \n \n\n\n### Por Newton-Rhapson\n\n\n```python\nimprimir_raices_de_funciones(nr, resultados_raices, [np.float64(1)]*3)\n```\n\n Funcion x**2 - 2 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 2\t\t 1.416666666666666\t\t 0.083333333333333\n Iteracion 3\t\t 1.414215686274509\t\t 0.002450980392156\n Iteracion 4\t\t 1.414213562374689\t\t 0.000002123899820\n \n \n Funcion x**2 - 2 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.500000000000000\t\t 0.500000000000000\n Iteracion 2\t\t 1.416666666666666\t\t 0.083333333333333\n Iteracion 3\t\t 1.414215686274509\t\t 0.002450980392156\n Iteracion 4\t\t 1.414213562374689\t\t 0.000002123899820\n Iteracion 5\t\t 1.414213562373095\t\t 0.000000000001594\n Iteracion 6\t\t 1.414213562373094\t\t 0.000000000000000\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.067039106145254\t\t 0.067039106145254\n Iteracion 2\t\t 1.111500862584999\t\t 0.044461756439744\n Iteracion 3\t\t 1.141056567216819\t\t 0.029555704631820\n Iteracion 4\t\t 1.160727268147251\t\t 0.019670700930432\n Iteracion 5\t\t 1.173827768369525\t\t 0.013100500222274\n Iteracion 6\t\t 1.182555936035558\t\t 0.008728167666032\n Iteracion 7\t\t 1.188372391418122\t\t 0.005816455382564\n Iteracion 8\t\t 1.192249031514232\t\t 0.003876640096109\n Iteracion 9\t\t 1.194833025735817\t\t 0.002583994221585\n Iteracion 10\t\t 1.196555499438189\t\t 0.001722473702371\n Iteracion 11\t\t 1.197703732101451\t\t 0.001148232663262\n Iteracion 12\t\t 1.198469183878466\t\t 0.000765451777014\n Iteracion 13\t\t 1.198979468909419\t\t 0.000510285030953\n Iteracion 14\t\t 1.199319651889759\t\t 0.000340182980339\n Iteracion 15\t\t 1.199546437748632\t\t 0.000226785858872\n Iteracion 16\t\t 1.199697626550762\t\t 0.000151188802129\n Iteracion 17\t\t 1.199798419005017\t\t 0.000100792454254\n Iteracion 18\t\t 1.199865617415838\t\t 0.000067198410821\n Iteracion 19\t\t 1.199910427112309\t\t 0.000044809696470\n Iteracion 20\t\t 1.199940311395558\t\t 0.000029884283248\n Iteracion 21\t\t 1.199960238848694\t\t 0.000019927453136\n Iteracion 22\t\t 1.199973667897056\t\t 0.000013429048362\n Iteracion 23\t\t 1.199982656971679\t\t 0.000008989074622\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.067039106145254\t\t 0.067039106145254\n Iteracion 2\t\t 1.111500862584999\t\t 0.044461756439744\n Iteracion 3\t\t 1.141056567216819\t\t 0.029555704631820\n Iteracion 4\t\t 1.160727268147251\t\t 0.019670700930432\n Iteracion 5\t\t 1.173827768369525\t\t 0.013100500222274\n Iteracion 6\t\t 1.182555936035558\t\t 0.008728167666032\n Iteracion 7\t\t 1.188372391418122\t\t 0.005816455382564\n Iteracion 8\t\t 1.192249031514232\t\t 0.003876640096109\n Iteracion 9\t\t 1.194833025735817\t\t 0.002583994221585\n Iteracion 10\t\t 1.196555499438189\t\t 0.001722473702371\n Iteracion 11\t\t 1.197703732101451\t\t 0.001148232663262\n Iteracion 12\t\t 1.198469183878466\t\t 0.000765451777014\n Iteracion 13\t\t 1.198979468909419\t\t 0.000510285030953\n Iteracion 14\t\t 1.199319651889759\t\t 0.000340182980339\n Iteracion 15\t\t 1.199546437748632\t\t 0.000226785858872\n Iteracion 16\t\t 1.199697626550762\t\t 0.000151188802129\n Iteracion 17\t\t 1.199798419005017\t\t 0.000100792454254\n Iteracion 18\t\t 1.199865617415838\t\t 0.000067198410821\n Iteracion 19\t\t 1.199910427112309\t\t 0.000044809696470\n Iteracion 20\t\t 1.199940311395558\t\t 0.000029884283248\n Iteracion 21\t\t 1.199960238848694\t\t 0.000019927453136\n Iteracion 22\t\t 1.199973667897056\t\t 0.000013429048362\n Iteracion 23\t\t 1.199982656971679\t\t 0.000008989074622\n Iteracion 24\t\t 1.199988485096395\t\t 0.000005828124716\n Iteracion 25\t\t 1.199992892039387\t\t 0.000004406942991\n Iteracion 26\t\t 1.199998674815197\t\t 0.000005782775809\n Iteracion 27\t\t 1.200109601049251\t\t 0.000110926234054\n Iteracion 28\t\t 1.200073069843097\t\t 0.000036531206154\n Iteracion 29\t\t 1.200048737564417\t\t 0.000024332278679\n Iteracion 30\t\t 1.200032583841324\t\t 0.000016153723092\n Iteracion 31\t\t 1.200021759988341\t\t 0.000010823852983\n Iteracion 32\t\t 1.200014766941075\t\t 0.000006993047265\n Iteracion 33\t\t 1.200010747490507\t\t 0.000004019450567\n Iteracion 34\t\t 1.200007374996902\t\t 0.000003372493604\n Iteracion 35\t\t 1.200007374996902\t\t 0.000000000000000\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-5)\n ERROR: Divisor se hizo 0 al calcular la siguiente iteración\n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-13)\n ERROR: Divisor se hizo 0 al calcular la siguiente iteración\n \n\n\nMientras que con las funciones $f_{1}(x)$ y $f_{2}(x)$ no hubo ningún problema al utilizar el algoritmo de Newton Raphson, la función $ f_{3}(x) = (x-1.5) \\cdot e^{-4 \\cdot (x-1.5)^{2}} $ da error. Esto se debe a que una derivada de las que el algoritmo evaluó al calcular la siguiente iteración dio nula, lo que fue resultado de que la sucesión diverja. En este caso, esto sucede ya que la semilla no esta lo suficientemente próxima a la raíz (se utiliza raiz = 1 como fue indicado).
\n\nEl método de Newton Raphson se basa en utilizar la iteración por punto fijo de la función $ g(x) = x - \\frac{f(x)}{f'(x)} $, ya que si $ g(r) = r $ entonces $\\frac{f(r)}{f'(r)} = 0$ por lo que tenemos una raíz de $ f $ ($f'(r) \\neq 0$).
\n\nLa raíz de esta función se encuentra en $ r = 1,5 $, y una de las hipótesis utilizadas en la demostración de la convergencia de la iteración de punto fijo\nes que para $ \\forall x \\in [a, b]$, $|g'(x)| < 1$ (unicidad del punto fijo), \ndonde $[a, b]$ es el intervalo dentro del cual estamos iterando.
\n\nEn este caso, $g'(x) = 1 - \\frac{f'(x)^2 - f(x)f''(x)}{f'(x)^2} = \\frac{f(x)f''(x)}{f'(x)^2}$ pero $g'(1) = -2$, por lo que incluir $ x = 1 $ en este intervalo implica que el método puede no converger.
\n\n\nOtra forma de verlo es notar que la expresión de Newton-Rhapson se puede deducir a partir del polinomio de Taylor de $f(x)$ alrededor de un $x_{n}$. En tal caso, $f(x) = f(x_{n}) + f'(x_{n})(x - x_{n}) + \\frac{f''(\\xi)}{2}(x - x_{n})^2$, con $\\xi$ entre $x$ y $x_{n}$. Entonces, si evaluamos la función en la raíz $r$ de $f(x)$ queda $0 = f(r) = f(x_{n}) + f'(x_{n})(r - x_{n}) + \\frac{f''(\\xi)}{2}(r - x_{n})^2$. El método de Newton-Raphson asume que $x_n$ esta lo suficientemente cerca de $r$ tal que $(r-x_n)^2 << (r-x_n)$ lo que nos permite despreciar el último término del polinomio y asi obtener la expresión $r \\approx x_n - \\frac{f(x_n)}{f'(x_n)} \\Rightarrow x_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}$. En este caso, la semilla no es lo suficientemente cercana como para que esto se cumpla.
\n\nPara poder hacere que converja, podemos acercar la semilla un poco (a 1,3):
\n\n\n```python\nimprimir_raices_de_funciones(nr, resultados_raices, [np.float64(1.3)], funciones = (3,))\n```\n\n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.300000000000000\n Iteracion 1\t\t 1.594117647058823\t\t 0.294117647058823\n Iteracion 2\t\t 1.492821654209128\t\t 0.101295992849694\n Iteracion 3\t\t 1.500002960343984\t\t 0.007181306134856\n Iteracion 4\t\t 1.499999999999999\t\t 0.000002960343985\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.300000000000000\n Iteracion 1\t\t 1.594117647058823\t\t 0.294117647058823\n Iteracion 2\t\t 1.492821654209128\t\t 0.101295992849694\n Iteracion 3\t\t 1.500002960343984\t\t 0.007181306134856\n Iteracion 4\t\t 1.499999999999999\t\t 0.000002960343985\n Iteracion 5\t\t 1.500000000000000\t\t 0.000000000000000\n \n \n\n\n### Por Newton-Rhapson Modificado\n\n\n```python\nimprimir_raices_de_funciones(nr_mod, resultados_raices, [np.float64(1)] * 3)\n```\n\n Funcion x**2 - 2 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.333333333333333\t\t 0.333333333333333\n Iteracion 2\t\t 1.411764705882352\t\t 0.078431372549019\n Iteracion 3\t\t 1.414211438474870\t\t 0.002446732592517\n Iteracion 4\t\t 1.414213562371500\t\t 0.000002123896630\n \n \n Funcion x**2 - 2 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.333333333333333\t\t 0.333333333333333\n Iteracion 2\t\t 1.411764705882352\t\t 0.078431372549019\n Iteracion 3\t\t 1.414211438474870\t\t 0.002446732592517\n Iteracion 4\t\t 1.414213562371500\t\t 0.000002123896630\n Iteracion 5\t\t 1.414213562373094\t\t 0.000000000001594\n Iteracion 6\t\t 1.414213562373095\t\t 0.000000000000000\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.198429561200949\t\t 0.198429561200949\n Iteracion 2\t\t 1.199999958931438\t\t 0.001570397730488\n Iteracion 3\t\t 1.199999939960625\t\t 0.000000018970812\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.000000000000000\n Iteracion 1\t\t 1.198429561200949\t\t 0.198429561200949\n Iteracion 2\t\t 1.199999958931438\t\t 0.001570397730488\n Iteracion 3\t\t 1.199999939960625\t\t 0.000000018970812\n Iteracion 4\t\t 1.199999912385445\t\t 0.000000027575179\n Iteracion 5\t\t 1.199999871258021\t\t 0.000000041127424\n Iteracion 6\t\t 1.199999807715154\t\t 0.000000063542867\n Iteracion 7\t\t 1.199999711987405\t\t 0.000000095727749\n Iteracion 8\t\t 1.199999711987405\t\t 0.000000000000000\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-5)\n ERROR: Divisor se hizo 0 al calcular la siguiente iteración\n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-13)\n ERROR: Divisor se hizo 0 al calcular la siguiente iteración\n \n\n\nEn este caso, la función 2 convergió mucho más rápido que con Newton-Raphson ya que es una función cuya raíz tenía multiplicidad mayor a uno, por lo que con este método conservamos la convergencia cuadrática.
\n\nEn cuanto a la función 3, nuevamente falló al calcular alguna de las iteraciones debido a que el divisor se hizo 0. Esto se debe a que la función no convergió a la raíz por las mismas razones que Newton-Raphson, y podemos solucionarlo acercando la semilla:
\n\n\n```python\nimprimir_raices_de_funciones(nr_mod, resultados_raices, [np.float64(1.3)], funciones = (3,))\n```\n\n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.300000000000000\n Iteracion 1\t\t 1.403030303030303\t\t 0.103030303030303\n Iteracion 2\t\t 1.486431596392994\t\t 0.083401293362691\n Iteracion 3\t\t 1.499960091346067\t\t 0.013528494953072\n Iteracion 4\t\t 1.499999999998983\t\t 0.000039908652915\n Iteracion 5\t\t 1.500000000000000\t\t 0.000000000001016\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 1.300000000000000\n Iteracion 1\t\t 1.403030303030303\t\t 0.103030303030303\n Iteracion 2\t\t 1.486431596392994\t\t 0.083401293362691\n Iteracion 3\t\t 1.499960091346067\t\t 0.013528494953072\n Iteracion 4\t\t 1.499999999998983\t\t 0.000039908652915\n Iteracion 5\t\t 1.500000000000000\t\t 0.000000000001016\n Iteracion 6\t\t 1.500000000000000\t\t 0.000000000000000\n \n \n\n\n### Por Secante\n\n\n```python\nimprimir_raices_de_funciones(secante, resultados_raices, [(np.float64(0), np.float64(2))]*3)\n```\n\n Funcion x**2 - 2 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.333333333333333\t\t 0.333333333333333\n Iteracion 4\t\t 1.428571428571428\t\t 0.095238095238095\n Iteracion 5\t\t 1.413793103448275\t\t 0.014778325123152\n Iteracion 6\t\t 1.414211438474870\t\t 0.000418335026594\n Iteracion 7\t\t 1.414213562688869\t\t 0.000002124213999\n \n \n Funcion x**2 - 2 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.000000000000000\t\t 1.000000000000000\n Iteracion 3\t\t 1.333333333333333\t\t 0.333333333333333\n Iteracion 4\t\t 1.428571428571428\t\t 0.095238095238095\n Iteracion 5\t\t 1.413793103448275\t\t 0.014778325123152\n Iteracion 6\t\t 1.414211438474870\t\t 0.000418335026594\n Iteracion 7\t\t 1.414213562688869\t\t 0.000002124213999\n Iteracion 8\t\t 1.414213562373094\t\t 0.000000000315774\n Iteracion 9\t\t 1.414213562373094\t\t 0.000000000000000\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.475409836065574\t\t 0.524590163934425\n Iteracion 3\t\t 1.452611812121219\t\t 0.022798023944355\n Iteracion 4\t\t 1.375615183141658\t\t 0.076996628979561\n Iteracion 5\t\t 1.336718258411820\t\t 0.038896924729838\n Iteracion 6\t\t 1.302029414616354\t\t 0.034688843795465\n Iteracion 7\t\t 1.277401409498029\t\t 0.024628005118324\n Iteracion 8\t\t 1.258345986729271\t\t 0.019055422768758\n Iteracion 9\t\t 1.244086150835949\t\t 0.014259835893321\n Iteracion 10\t\t 1.233278489277362\t\t 0.010807661558587\n Iteracion 11\t\t 1.225128158694202\t\t 0.008150330583159\n Iteracion 12\t\t 1.218970580971631\t\t 0.006157577722571\n Iteracion 13\t\t 1.214322212037839\t\t 0.004648368933791\n Iteracion 14\t\t 1.210812345088710\t\t 0.003509866949129\n Iteracion 15\t\t 1.208162528877272\t\t 0.002649816211438\n Iteracion 16\t\t 1.206162000870271\t\t 0.002000528007000\n Iteracion 17\t\t 1.204651727883742\t\t 0.001510272986529\n Iteracion 18\t\t 1.203511582198426\t\t 0.001140145685315\n Iteracion 19\t\t 1.202650870698435\t\t 0.000860711499991\n Iteracion 20\t\t 1.202001114853348\t\t 0.000649755845086\n Iteracion 21\t\t 1.201510615051329\t\t 0.000490499802019\n Iteracion 22\t\t 1.201140340044438\t\t 0.000370275006890\n Iteracion 23\t\t 1.200860823175217\t\t 0.000279516869221\n Iteracion 24\t\t 1.200649819712207\t\t 0.000211003463009\n Iteracion 25\t\t 1.200490536930929\t\t 0.000159282781278\n Iteracion 26\t\t 1.200370296883105\t\t 0.000120240047823\n Iteracion 27\t\t 1.200279529022556\t\t 0.000090767860549\n Iteracion 28\t\t 1.200211014117034\t\t 0.000068514905521\n Iteracion 29\t\t 1.200159290976704\t\t 0.000051723140329\n Iteracion 30\t\t 1.200120251662231\t\t 0.000039039314473\n Iteracion 31\t\t 1.200090772794012\t\t 0.000029478868218\n Iteracion 32\t\t 1.200068548524957\t\t 0.000022224269054\n Iteracion 33\t\t 1.200051781243777\t\t 0.000016767281179\n Iteracion 34\t\t 1.200039179083400\t\t 0.000012602160377\n Iteracion 35\t\t 1.200029586394158\t\t 0.000009592689242\n \n \n Funcion x**5 - 6.6 * x**4 + 5.12 * x**3 + 21.312 * x ** 2 - 38.016 * x + 17.28 con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.000000000000000\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.475409836065574\t\t 0.524590163934425\n Iteracion 3\t\t 1.452611812121219\t\t 0.022798023944355\n Iteracion 4\t\t 1.375615183141658\t\t 0.076996628979561\n Iteracion 5\t\t 1.336718258411820\t\t 0.038896924729838\n Iteracion 6\t\t 1.302029414616354\t\t 0.034688843795465\n Iteracion 7\t\t 1.277401409498029\t\t 0.024628005118324\n Iteracion 8\t\t 1.258345986729271\t\t 0.019055422768758\n Iteracion 9\t\t 1.244086150835949\t\t 0.014259835893321\n Iteracion 10\t\t 1.233278489277362\t\t 0.010807661558587\n Iteracion 11\t\t 1.225128158694202\t\t 0.008150330583159\n Iteracion 12\t\t 1.218970580971631\t\t 0.006157577722571\n Iteracion 13\t\t 1.214322212037839\t\t 0.004648368933791\n Iteracion 14\t\t 1.210812345088710\t\t 0.003509866949129\n Iteracion 15\t\t 1.208162528877272\t\t 0.002649816211438\n Iteracion 16\t\t 1.206162000870271\t\t 0.002000528007000\n Iteracion 17\t\t 1.204651727883742\t\t 0.001510272986529\n Iteracion 18\t\t 1.203511582198426\t\t 0.001140145685315\n Iteracion 19\t\t 1.202650870698435\t\t 0.000860711499991\n Iteracion 20\t\t 1.202001114853348\t\t 0.000649755845086\n Iteracion 21\t\t 1.201510615051329\t\t 0.000490499802019\n Iteracion 22\t\t 1.201140340044438\t\t 0.000370275006890\n Iteracion 23\t\t 1.200860823175217\t\t 0.000279516869221\n Iteracion 24\t\t 1.200649819712207\t\t 0.000211003463009\n Iteracion 25\t\t 1.200490536930929\t\t 0.000159282781278\n Iteracion 26\t\t 1.200370296883105\t\t 0.000120240047823\n Iteracion 27\t\t 1.200279529022556\t\t 0.000090767860549\n Iteracion 28\t\t 1.200211014117034\t\t 0.000068514905521\n Iteracion 29\t\t 1.200159290976704\t\t 0.000051723140329\n Iteracion 30\t\t 1.200120251662231\t\t 0.000039039314473\n Iteracion 31\t\t 1.200090772794012\t\t 0.000029478868218\n Iteracion 32\t\t 1.200068548524957\t\t 0.000022224269054\n Iteracion 33\t\t 1.200051781243777\t\t 0.000016767281179\n Iteracion 34\t\t 1.200039179083400\t\t 0.000012602160377\n Iteracion 35\t\t 1.200029586394158\t\t 0.000009592689242\n Iteracion 36\t\t 1.200022595112167\t\t 0.000006991281990\n Iteracion 37\t\t 1.200016515736524\t\t 0.000006079375643\n Iteracion 38\t\t 1.200013242226562\t\t 0.000003273509961\n Iteracion 39\t\t 1.200009968716600\t\t 0.000003273509961\n Iteracion 40\t\t 1.200007513584128\t\t 0.000002455132471\n Iteracion 41\t\t 1.200007513584128\t\t 0.000000000000000\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-5)\n ERROR: Divisor se hizo 0 al calcular la siguiente iteración\n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-13)\n ERROR: Divisor se hizo 0 al calcular la siguiente iteración\n \n\n\nSe puede notar como a este método le toman mas iteraciones converger que para otro método como Newton-Raphson, ya que al estar basado en este pero utilizar la secante como aproximación de la derivada de una función es normal que tarde más.
\n\nNuevamente, este método falla con la tercera función. Al estar este basado en Newton-Raphson, también puede fallar si las semillas se encuentran muy alejadas de la raíz.
\n\nPor lo tanto, podemos acercársela un poco para que converja:
\n\n\n```python\nimprimir_raices_de_funciones(secante, resultados_raices, [(np.float64(0.7), np.float64(2))], funciones = (3,))\n```\n\n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-5)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.699999999999999\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.027104650345444\t\t 0.972895349654555\n Iteracion 3\t\t 1.525649236494845\t\t 0.498544586149401\n Iteracion 4\t\t 1.467387499691451\t\t 0.058261736803394\n Iteracion 5\t\t 1.499976699062182\t\t 0.032589199370731\n Iteracion 6\t\t 1.500000099411637\t\t 0.000023400349455\n Iteracion 7\t\t 1.499999999999999\t\t 0.000000099411638\n \n \n Funcion (x - 1.5) * np.exp(-4 * (x - 1.5)**2) con error de 10^(-13)\n #\t\t\t Valor calculado\t\t Variación respecto al anterior\n Semilla 0\t\t 0.699999999999999\n Semilla 1\t\t 2.000000000000000\n Iteracion 2\t\t 1.027104650345444\t\t 0.972895349654555\n Iteracion 3\t\t 1.525649236494845\t\t 0.498544586149401\n Iteracion 4\t\t 1.467387499691451\t\t 0.058261736803394\n Iteracion 5\t\t 1.499976699062182\t\t 0.032589199370731\n Iteracion 6\t\t 1.500000099411637\t\t 0.000023400349455\n Iteracion 7\t\t 1.499999999999999\t\t 0.000000099411638\n Iteracion 8\t\t 1.500000000000000\t\t 0.000000000000000\n \n \n\n\n## (c) Halle la raíz mediante la función de búsqueda de raíces de un lenguaje o paquete orientado a cálculo numérico (e.g. Python+SciPy: `scipy.optimize.brentq`).\n\n\n```python\nprint(f\"Raiz de f1 segun SciPy: {optimize.brentq(f1, 0, 2)}\")\nprint(f\"Raiz de f2 segun SciPy: {optimize.brentq(f2, 0, 2)}\")\nprint(f\"Raiz de f3 segun SciPy: {optimize.brentq(f3, 0, 2)}\")\n```\n\n Raiz de f1 segun SciPy: 1.4142135623731364\n Raiz de f2 segun SciPy: 1.2000081652661798\n Raiz de f3 segun SciPy: 1.5000000000000198\n\n\n## (d) Compare los resultados obtenidos para los distintos métodos y cotas, grafique el orden de convergencia P y la constante asisntotica λ para todos los casos. Discuta ventajas y desventajas.\n## ¿Son las que esperaba en base a la teoría?\n\n\n```python\n# Titulos\nTITULOS = {\n 'biseccion': 'Método Biseccion',\n 'nr': 'Método Newton-Raphson',\n 'nr_mod': 'Método Newton-Raphson Modificado',\n 'secante': 'Método Secante'\n}\n\n# Funciones LaTeX\nLATEX_FUNCIONES = [\n r'$x^2 - 2$',\n r'$x^5 - 6.6x^4 + 5.12x^2 - 38.016x + 17.28$',\n r'$(x-1.5) \\cdot e^{(-4(x-1.5)^{2})}$'\n]\n\ndef graficar(funcion, nombre, min = None, max = None):\n fig, ax = plt.subplots(4, 3, figsize=(18.5, 20))\n metodos = list(resultados_raices.keys())\n plt.subplots_adjust(top = 0.99, bottom=0.01, hspace=0.5, wspace=0.4)\n for j in range(3):\n\t for i in range(4):\n\t if (j == 1):\n\t \t ax[i][j].set_title(\"\\n\\n\" + TITULOS[metodos[i]] + \"\\n\\n\")\n \n\t x, y = funcion(resultados_raices[metodos[i]][str(j+1)])\n\t ax[i][j].plot(x, y, label = LATEX_FUNCIONES[j])\n\t ax[i][j].set_xlabel('número de iteración')\n\t ax[i][j].set_ylabel(nombre)\n\t ax[i][j].legend()\n\t ax[i][j].set_ylim(bottom = min, top = max)\n\t ax[i][j].set_xticks(x[::len(x) // 10 + 1])\n```\n\n### Algoritmo para calcular el orden de convergencia por iteración\n\n\n```python\ndef ordenes_convergencia(iteraciones):\n tolerancia_cero = tol_cero(type(iteraciones[0]))\n ordenes = []\n # La función no calcula con la ultima iteración si esta es igual a la anteúltima (ya había convergido)\n if (iteraciones[-1] == iteraciones[-2]):\n \titeraciones = iteraciones[:-1]\n\n x = range(2, len(iteraciones) - 1)\n for i in x:\n num = np.log(abs((iteraciones[i + 1] - iteraciones[i]) / (iteraciones[i] - iteraciones[i - 1])))\n den = np.log(abs((iteraciones[i] - iteraciones[i - 1]) / (iteraciones[i - 1] - iteraciones[i - 2])))\n \n # Si denominador es 0, significa que el error no varió entre 2 iteraciones, consideramos orden 0.\n if (abs(den) <= tolerancia_cero):\n \t ordenes.append(0)\n \t continue\n ordenes.append(num / den)\n return x , ordenes\n```\n\n###Algoritmo para calcular la constante asintótica por iteración\n\n\n```python\ndef constante_asintotica(iteraciones):\n tolerancia_cero = tol_cero(type(iteraciones[0]))\n ctes = []\n # La función no calcula con la ultima iteración si esta es igual a la anteúltima (ya había convergido)\n if (iteraciones[-1] == iteraciones[-2]):\n \titeraciones = iteraciones[:-1]\n\n _, ordenes = ordenes_convergencia(iteraciones)\n x = range(2, len(iteraciones) - 1)\n for i in x:\n \tnum = abs(iteraciones[i] - iteraciones[i -1])\n \tden = abs((iteraciones[i - 1] - iteraciones[i - 2])) ** ordenes[i - 2]\n\n # Si denominador es 0, significa que el error no varió entre 2 iteraciones, consideramos constante 0.\n \tif (abs(den) <= tolerancia_cero):\n \t ctes.append(0)\n \t continue\n \tctes.append(num / den)\n\n return x, ctes\n```\n\n### Gráficos de orden de convergencia\n\n\n```python\ngraficar(ordenes_convergencia, nombre = 'orden de convergencia')\n```\n\n#### Bisección\n\nEl orden de convergencia de la bisección dio exactamente igual a lo esperado. Siempre va a ser 1 ya que se trata de un método que iteración por iteración va reduciendo el error a la mitad linealmente, por lo que nunca va a variar.
\n\n#### Newton-Raphson\n\nEn el caso de la primera y última función, estuvo bastante cerca del valor esperado de 2 (o incluso superior) durante la mayor parte de las iteraciones.
\n\nEn cuanto a la segunda función, se sostuvo más que nada alrededor de 1, que también era de esperar al ser una función con raíz doble con lo cual este método no mantiene la convergencia cuadrática.
\n\n#### Newton-Raphson modificado\n\nPara la primera y última función, nuevamente el orden estuvo alrededor de 2 como se esperaba.
\n\nAún así, en la segunda función esperabamos un orden de convergencia más cercano a 2 ya que se supone que este método mantiene convergencia cuadrática incluso cuando la raíz es múltiple. Es posible que esto se deba a la poca cantidad de iteraciones realizadas.
\n\n#### Secante\n\nLa primera función tuvo un orden promediando entre 1 y 2, como es esperado, ya que debe ser mayor a 1 pero menor a 2 al aproximar la derivada con una recta secante.
\n\nPara la segunda función, se mantuvo principalmente en 1 una vez más debido a la raíz múltiple de esta.
\n\nPara la tercera, el orden oscilo en valores alrededor de 2, lo cual es un poco superior a lo esperado pero sigue estando dentro de un rango esperado.
\n\n###Gráficos de constante asintótica\n\n\n```python\ngraficar(constante_asintotica, nombre = 'constante asintótica', min = 0, max = 1)\n```\n\n#### Bisección\n\nEn este caso, la constante asintótica es la esperada ya que como el orden de convergencia es 1, esto significa que $\\varepsilon_n = 0,5 \\cdot \\varepsilon_{n-1}$, lo cual es exactamente lo que hace el método: va dividiendo a la mitad el intervalo de búsqueda, por lo que el error lo hace también.
\n\n#### Demás métodos\n\nEn cuanto a los otros métodos, la mayoría de las iteraciones lograron una constante asintótica entre 0 y 1, que es lo esperado, ya que implica que el error esta en efecto bajando con el orden de convergencia calculado.
\n\nForzamos la escala del eje y entre 0 y 1 para que se pueda apreciar esto, ya que había ciertas iteraciones con picos muy pronunciados que hacían que la escala se agrande mucho y parezca que la constante valía 0 en la mayoría de las iteraciones. Esto provocó que los gráficos de Newton-Raphson y Newton-Raphson modificado queden vacíos para la tercera función, ya que estaban dando valores por fuera de este rango.
\n\nEn aquellas iteraciones que se van de rango y en caso de las iteraciones con picos muy pronunciados, es bastante probable que se deban a la poca cantidad de iteraciones que se necesitaron para alcanzar el error buscado, lo que hace que las aproximaciones realizadas para el cálculo de la constante asintótica, que incluso arrastra también el error del orden de convergencia, no sean tan buenas. Calcular el valor real implicaría un limite con iteraciones tendiendo a infinito.
\n", "meta": {"hexsha": "8d6dda2e93a71d535a120e8e0c15c46adf09e7e2", "size": 658596, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tp1.ipynb", "max_stars_repo_name": "ilitteri/7512-AnalisisNumerico", "max_stars_repo_head_hexsha": "944c70729d7d4570c0a550bebeb5a0135eba1d7e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tp1.ipynb", "max_issues_repo_name": "ilitteri/7512-AnalisisNumerico", "max_issues_repo_head_hexsha": "944c70729d7d4570c0a550bebeb5a0135eba1d7e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tp1.ipynb", "max_forks_repo_name": "ilitteri/7512-AnalisisNumerico", "max_forks_repo_head_hexsha": "944c70729d7d4570c0a550bebeb5a0135eba1d7e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 319.0872093023, "max_line_length": 255672, "alphanum_fraction": 0.9105597362, "converted": true, "num_tokens": 21022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.16238002855971875, "lm_q1q2_score": 0.06922611237348626}} {"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility here.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''''')\n# display(tag)\n```\n\n\n\nToggle cell visibility here.\n\n\n\n```python\nimport sympy as sp # Symbolic Python\nimport numpy as np # Arrays, matrices and corresponding mathematical operations\nfrom IPython.display import Latex, display, Markdown, clear_output # For displaying Markdown and LaTeX code\nfrom ipywidgets import widgets # Interactivity module\nfrom IPython.display import Javascript\n\n# Function for the conversion of array/matrix to LaTeX/Markdown format.\ndef vmatrix(a):\n if len(a.shape) > 2:\n raise ValueError('bmatrix can at most display two dimensions')\n lines = str(a).replace('[', '').replace(']', '').splitlines()\n rv = [r'\\begin{vmatrix}']\n rv += [' ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n rv += [r'\\end{vmatrix}']\n return '\\n'.join(rv)\n```\n\n## Routhov in Hurwitzov kriterij stabilnosti\n\nV teoriji krmiljenja Routh-Hurwitzov kriterij stabilnosti je matematični test, ki se uporablja za detekcijo polov prenosne funkcije zaprtozančnega sistema, ki imajo pozitivne realne komponente. Število sprememb predznakov elementov v prvem stolpcu Routhovega razporeda podaja število polov, ki ležijo v desni polovici kompleksne ravnine. Zadosten in potreben pogoj stabilnosti lineranih časovno nespremenljivih sistemov je ta, da imajo vsi poli zaprtozančnega sistema negativne realne komponente. To pomeni, da ne sme priti do sprememb predznakov elementov v prvem stolpcu omenjenega razporeda. Podoben kriterij stabilnosti temelji na determinantah sistema, ki ja imenujemo Hurwitzov kriterij stabilnost.\n\nZačetna točka za določanje stabilnosti sistema je karakteristični polinom, definiran kot:\n\n\\begin{equation}\n a_ns^n+a_{n-1}s^{n-1}+...+a_1s+a_0\n\\end{equation}\n\nV primeru Routhovega kriterija zapišemo ti. Routhov razpored:\n\n\\begin{array}{l|ccccc}\n & 1 & 2 & 3 & 4 & 5 \\\\\n \\hline\n s^n & a_n & a_{n-2} & a_{n-4} & a_{n-6} & \\dots \\\\\n s^{n-1} & a_{n-1} & a_{n-3} & a_{n-5} & a_{n-7} &\\dots \\\\\n s^{n-2} & b_1 & b_2 & b_3 & b_4 & \\dots \\\\\n s^{n-3} & c_1 & c_2 & c_3 & c_4 & \\dots \\\\\n s^{n-4} & d_1 & d_2 & d_3 & d_4 & \\dots \\\\\n \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\ddots\\\\\n\\end{array}\n\nKoeficiente prvih dveh vrstic ($a_i$) dobimo iz karakterističnega polnima. Vse ostale koeficiente določimo z uporabo naslednjih formul:\n\n\\begin{array}{cccc}\n \\, \\! \\! \\! \\! b_1 \\! = \\! \\frac{a_{n-1}a_{n-2}-a_n a_{n-3}}{a_{n-1}} & \\! \\! \\! \\! \\, \\! \\! b_2 \\! = \\! \\frac{a_{n-1}a_{n-4}-a_n a_{n-5}}{a_{n-1}} & \\, \\! \\! b_3 \\! = \\! \\frac{a_{n-1}a_{n-6}-a_n a_{n-7}}{a_{n-1}} & \\, \\! \\! \\! \\! \\dots \\\\\n c_1=\\frac{b_1a_{n-3}-a_{n-1} b_2}{b_1} & c_2=\\frac{b_1a_{n-5}-a_{n-1}b_3}{b_1} & c_3=\\frac{b_1a_{n-7}-a_{n-1}b_4}{b_1} & \\, \\! \\! \\! \\! \\dots \\\\\n d_1=\\frac{c_1 b_2-b_1 c_2}{c_1} & d_2=\\frac{c_1 b_3-b_1 c_3}{c_1} & d_3=\\frac{c_1 b_4-b_1 c_4}{c_1} & \\, \\! \\! \\! \\! \\dots \\\\\n \\vdots & \\vdots & \\vdots & \\, \\! \\! \\! \\! \\ddots \\\\\n\\end{array}\n\nČe imajo vsi koeficienti v prvem stolpcu (koeficienti $n+1$) enak predznak (bodisi vsi pozitivnega ali vsi negativnega), je sistem stabilen. Število sprememb predznakov koeficientov v prvem stolpcu podaja število ničel karakterističnega polinoma, ki ležijo v levi polovici kompleksne ravnine.\n\nV primeru Hurwitzovega kriterija najprej zapišemo determinanto $\\Delta_n$ oblike $n\\times n$ na podlagi karakterističnega polinoma.\n\n\\begin{equation}\n \\Delta_n=\n \\begin{array}{|cccccccc|}\n a_{n-1} & a_{n-3} & a_{n-5} & \\dots & \\left[ \\begin{array}{cc} a_0 & \\mbox{če je\n }n \\mbox{ liho št.} \\\\ a_1 & \\mbox{če je }n \\mbox{ sodo št.} \\end{array}\n \\right] & 0 & \\dots & 0 \\\\[3mm]\n a_{n} & a_{n-2} & a_{n-4} & \\dots & \\left[ \\begin{array}{cc} a_1 & \\mbox{če je }n \\mbox{ liho št.} \\\\ a_0 & \\mbox{če je }n \\mbox{ sodo št.} \\end{array} \\right] & 0 & \\dots & 0 \\\\\n 0 & a_{n-1} & a_{n-3} & a_{n-5} & \\dots & \\dots & \\dots & 0 \\\\\n 0 & a_{n} & a_{n-2} & a_{n-4} & \\dots & \\dots & \\dots & 0 \\\\\n 0 & 0 & a_{n-1} & a_{n-3} & \\dots & \\dots & \\dots & 0 \\\\\n 0 & 0 & a_{n} & a_{n-2} & \\dots & \\dots & \\dots & 0 \\\\\n \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\n 0 & \\dots & \\dots & \\dots & \\dots & \\dots & \\dots & a_0 \\\\\n \\end{array}\n\\end{equation}\n\nNa podlagi determinante $\\Delta_n$ tvorimo poddeterminante po glavni diagonali. Subdeterminanto $\\Delta_1$ tako zapišemo kot\n\n\\begin{equation}\n \\Delta_1=a_{n-1},\n\\end{equation}\n\nsubdterminanto $\\Delta_2$ kot\n\n\\begin{equation}\n \\Delta_2=\n \\begin{array}{|cc|}\n a_{n-1} & a_{n-3} \\\\\n a_{n} & a_{n-2} \\\\\n \\end{array},\n\\end{equation}\n\nin subdeterminanto $\\Delta_3$ kot\n\n\\begin{equation}\n \\Delta_3=\n \\begin{array}{|ccc|}\n a_{n-1} & a_{n-3} & a_{n-5} \\\\\n a_{n} & a_{n-2} & a_{n-4} \\\\\n 0 & a_{n-1} & a_{n-3} \\\\\n \\end{array}.\n\\end{equation}\n\nTako nadaljujemo vse dokler ne pridemo do subdeterminante $\\Delta_{n-1}$. Sistem je stabilen, če so vse subdeterminante po glavni diagonali (od $\\Delta_1$ do $\\Delta_{n-1}$) ter determinanta $\\Delta_n$ strogo večje od 0.\n\n---\n\n### Kako upravljati s tem interaktivnim primerom?\n\nNajprej definiraj želen karakteristični polinom, z izbiro njegove stopnje ter vrednosti koeficientov, nato pa izberi želen kriterij stabilnosti (Routhov ali Hurwitzov).\n\n\n\n\n```python\npolynomialOrder = input (\"Vnesi stopnjo karakterističnega polinoma (pritisni Enter za potrditev):\")\ntry:\n val = int(polynomialOrder)\nexcept ValueError:\n display(Markdown('Stopnja polinoma mora biti pozitivno celo število. Prosim ponovno vnesi stopnjo.'))\ndisplay(Markdown('Vnesi koeficiente karakterističnega polinoma (uporabi $K$ za nedoločne koeficiente) in klikni na gumb \"Potrdi\".'))\ntext=[None]*(int(polynomialOrder)+1)\nfor i in range(int(polynomialOrder)+1):\n text[i]=widgets.Text(description=('$s^%i$'%(-(i-int(polynomialOrder)))))\n display(text[i])\nbtn1=widgets.Button(description=\"Potrdi\")\nbtnReset=widgets.Button(description=\"Ponastavi\")\ndisplay(widgets.HBox((btn1, btnReset)))\n\nbtn2=widgets.Button(description=\"Potrdi\")\nw=widgets.Select(\n options=['Routh', 'Hurwitz'],\n rows=3,\n description='Izberi:',\n disabled=False\n)\n\ncoef=[None]*(int(polynomialOrder)+1)\n\ndef on_button_clickedReset(ev):\n display(Javascript(\"Jupyter.notebook.execute_cells_below()\"))\n\n\ndef on_button_clicked1(btn1):\n clear_output()\n for i in range(int(polynomialOrder)+1):\n if text[i].value=='' or text[i].value=='Vnesi koeficient':\n text[i].value='Vnesi koeficient'\n else:\n try:\n coef[i]=float(text[i].value)\n except ValueError:\n if text[i].value!='' or text[i].value!='Vnesi koeficient':\n coef[i]=sp.var(text[i].value)\n coef.reverse()\n enacba=\"$\"\n for i in range (int(polynomialOrder),-1,-1):\n if i==int(polynomialOrder):\n enacba=enacba+str(coef[i])+\"s^\"+str(i)\n elif i==1:\n enacba=enacba+\"+\"+str(coef[i])+\"s\"\n elif i==0:\n enacba=enacba+\"+\"+str(coef[i])+\"$\"\n else:\n enacba=enacba+\"+\"+str(coef[i])+\"s^\"+str(i)\n coef.reverse()\n display(Markdown('Izbran karakterisitčni polinom je enak:'), Markdown(enacba))\n display(Markdown('Ali bi uporabil Routhov ali Hurwitzov kriterij stabilnosti?'))\n display(w)\n display(widgets.HBox((btn2, btnReset)))\n display(out)\n\ndef on_button_clicked2(btn2):\n \n if w.value=='Routh':\n\n s=np.zeros((len(coef), len(coef)//2+(len(coef)%2)),dtype=object)\n xx=np.zeros((len(coef), len(coef)//2+(len(coef)%2)),dtype=object)\n check_index=0\n \n if len(s[0]) == len(coef[::2]):\n s[0] = coef[::2]\n elif len(s[0])-1 == len(coef[::2]):\n s[0,:-1] = coef[::2]\n #soda mesta\n if len(s[1]) == len(coef[1::2]):\n s[1] = coef[1::2]\n elif len(s[1])-1 == len(coef[1::2]):\n s[1,:-1] = coef[1::2]\n \n for i in range(len(s[2:,:])):\n i+=2\n for j in range(len(s[0,0:-1])):\n s[i,j] = (s[i-1,0]*s[i-2,j+1]-s[i-2,0]*s[i-1,j+1]) / s[i-1,0]\n if s[i,0] == 0:\n epsilon=sp.Symbol('\\u03B5')\n s[i,0] = epsilon\n check_index=1\n \n if check_index==1:\n for i in range(len(s)):\n for j in range(len(s[0])):\n xx[i,j] = sp.limit(s[i,j],epsilon,0)\n \n positive_check=xx[:,0]>0\n negative_check=xx[:,0]<0\n if all(positive_check)==True:\n with out:\n clear_output()\n display(Markdown('En izmed elementov v prvem stolpcu Routhovega razporeda je enak 0. Nadomestimo ga z $\\epsilon$ in opazujemo kaj se dogaja s predzanki ko gre vrednost $\\epsilon$ proti 0.')) \n display(Markdown('Routhov razpored $%s$\\n' % vmatrix(s)))\n display(Markdown('Sistem je stabilen, ker so vsi predznaki koeficientov v prvem stolpcu Routhovega razporeda pozitivni.'))\n display(Markdown('Routhov razpored $%s$\\n' % vmatrix(xx)))\n\n elif all(negative_check)==True:\n with out:\n clear_output()\n display(Markdown('En izmed elementov v prvem stolpcu Routhovega razporeda je enak 0. Nadomestimo ga z $\\epsilon$ in opazujemo kaj se dogaja s predzanki ko gre vrednost $\\epsilon$ proti 0-')) \n display(Markdown('Routhov razpored $%s$\\n' % vmatrix(s)))\n display(Markdown('Sistem je stabilen, ker so vsi predznaki koeficientov v prvem stolpcu Routhovega razporeda negativni.'))\n display(Markdown('Routhov razpored $%s$\\n' % vmatrix(xx))) \n else:\n with out:\n clear_output()\n display(Markdown('One of the elements in the first column of the Routh table is equal to 0. We replace it with $\\epsilon$ and observe the values of the elements when value of $\\epsilon$ goes to zero.')) \n display(Markdown('Routhov razpored $%s$\\n' % vmatrix(s)))\n display(Markdown('Sistem je nestabilen, ker se spreminja predznak koeficientov v prvem stolpcu Routhovega razporeda.'))\n display(Markdown('Routhov razpored $%s$\\n' % vmatrix(xx)))\n \n \n elif check_index==0: \n\n if all(isinstance(x, (int,float)) for x in coef):\n positive_check=s[:,0]>0\n negative_check=s[:,0]<0\n if all(positive_check)==True:\n with out:\n clear_output()\n display(Markdown('Sistem je stabilen, ker so vsi predznaki koeficientov v prvem stolpcu Routhovega razporeda pozitivni.'))\n display(Markdown('Routhov razpored $%s$' % vmatrix(s)))\n elif all(negative_check)==True:\n with out:\n clear_output()\n display(Markdown('Sistem je stabilen, ker so vsi predznaki koeficientov v prvem stolpcu Routhovega razporeda negativni.'))\n display(Markdown('Routhov razpored $%s$' % vmatrix(s)))\n else:\n with out:\n clear_output()\n display(Markdown('Sistem je nestabilen, ker se spreminja predznak koeficientov v prvem stolpcu Routhovega razporeda.'))\n display(Markdown('Routhov razpored $%s$' % vmatrix(s)))\n\n else:\n testSign=[]\n for i in range(len(s)):\n if isinstance(s[i,0],(int,float)):\n testSign.append(s[i,0]>0)\n solution=[]\n if all(elem == True for elem in testSign):\n for x in s[:,0]:\n if not isinstance(x,(sp.numbers.Integer,sp.numbers.Float,int,float)):\n solution.append(sp.solve(x>0,K)) # Define the solution for each value of the determinant\n with out:\n clear_output()\n display(Markdown('Routhov razpored $%s$' % vmatrix(s)))\n display(Markdown('Vsi določni koeficienti v prvem stolpcu so negativne, zato je sistem stabilen za::'))\n print(solution) \n elif all(elem == False for elem in test):\n for x in s[:,0]:\n if not isinstance(x,(sp.numbers.Integer,sp.numbers.Float,int,float)):\n solution.append(sp.solve(x<0,K)) # Define the solution for each value of the determinant\n with out:\n clear_output()\n display(Markdown('Routhov razpored $%s$' % vmatrix(s)))\n display(Markdown('Vsi določni koeficienti v prvem stolpcu so negativne, zato je sistem stabilen za:'))\n print(solution)\n else:\n with out:\n display(Markdown('Routhov razpored $%s$' % vmatrix(s)))\n display(Markdown('Sistem je nestabilen, ker se spreminja predznak koeficientov v prvem stolpcu.'))\n\n\n\n elif w.value=='Hurwitz':\n\n # Check if all the coefficients are numbers or not and preallocate basic determinant.\n\n if all(isinstance(x, (int,float)) for x in coef):\n determinant=np.zeros([len(coef)-1,len(coef)-1])\n else:\n determinant=np.zeros([len(coef)-1,len(coef)-1],dtype=object)\n\n # Define the first two rows of the basic determinant. \n for i in range(len(coef)-1):\n try:\n determinant[0,i]=coef[2*i+1]\n except:\n determinant[0,i]=0\n\n for i in range(len(coef)-1):\n try:\n determinant[1,i]=coef[2*i]\n except:\n determinant[1,i]=0\n # Define the remaining rows of the basic determinant by shifting the first two rows. \n for i in range(2,len(coef)-1):\n determinant[i,:]=np.roll(determinant[i-2,:],1)\n determinant[2:,0]=0\n\n # Define all the subdeterminants.\n subdet=[];\n for i in range(len(determinant)-1):\n subdet.append(determinant[0:i+1,0:i+1])\n\n # Append the basic determinant to the subdeterminants' array.\n subdet.append(determinant)\n\n # Check if all coefficients are numbers.\n if all(isinstance(x, (int,float)) for x in coef):\n det_value=[] # Preallocate array containing values of all determinants.\n for i in range(len(subdet)):\n det_value.append(np.linalg.det(subdet[i])); # Calculate determinant and append the values to det_value.\n\n if all(i > 0 for i in det_value)==True: # Check if all values in det_value are positive or not.\n with out:\n clear_output()\n display(Markdown('Sistem je stabilen, ker so vse determinante pozitivne.'))\n for i in range(len(subdet)):\n display(Markdown('$\\Delta_{%i}=$'%(i+1) + '$%s$' %vmatrix(subdet[i]) + '$=%s$' %det_value[i]))\n else:\n with out:\n clear_output()\n display(Markdown('Sistem je nestabilen, ker niso vse determinante pozitivne.'))\n for i in range(len(subdet)):\n display(Markdown('$\\Delta_{%i}=$'%(i+1) + '$%s$' %vmatrix(subdet[i]) + '$=%s$' %det_value[i]))\n else:\n subdetSym=[] # Preallocate subdetSym.\n det_value=[] # Preallocate det_value.\n solution=[] # Preallocate solution.\n for i in subdet:\n subdetSym.append(sp.Matrix(i)) # Transform matrix subdet to symbolic.\n for i in range(len(subdetSym)):\n det_value.append(subdetSym[i].det()) # Calculate the value of the determinant.\n testSign=[]\n for i in range(len(det_value)):\n if isinstance(s[i,0],(int,float,sp.numbers.Integer,sp.numbers.Float)):\n testSign.append(s[i,0]>0)\n if all(elem == True for elem in testSign):\n solution=[]\n for x in det_value:\n if not isinstance(x,(sp.numbers.Integer,sp.numbers.Float,int,float)):\n solution.append(sp.solve(x>0,K)) # Define the solution for each value of the determinant\n for i in range(len(subdet)):\n with out:\n clear_output()\n display(Markdown('$\\Delta_{%i}=$'%(i+1) + '$%s$' %vmatrix(subdet[i]) + '$=%s$' %det_value[i]))\n display(Markdown('Sistem je stabilen za:'))\n print(solution) \n\n else:\n with out:\n clear_output()\n display(Markdown('Sistem je nestabilen, ker vse determinante niso pozitivne.'))\n for i in range(len(subdet)):\n display(Markdown('$\\Delta_{%i}=$'%(i+1) + '$%s$' %vmatrix(subdet[i]) + '$=%s$' %det_value[i]))\n\nglobal out\nout=widgets.Output()\n\nbtn3=widgets.Button(description=\"Ponastavivse\")\nw=widgets.Select(\n options=['Routh', 'Hurwitz'],\n rows=3,\n description='Izberi:',\n disabled=False\n)\n\nbtn1.on_click(on_button_clicked1)\nbtn2.on_click(on_button_clicked2) \nbtnReset.on_click(on_button_clickedReset) \n```\n\n\n| Titik | $x$ | $y$ | $z$ | \n
| A | 1 | 2 | 3 | \n
| B | -1 | -2 | -3 | \n
| Titik | $x$ | $y$ | $z$ | \n
| A | 1 | 2 | 3 | \n
| B | -1 | -2 | -3 | \n
| TensorMesh | \n12 cells | \n|||||
| \n | \n | MESH EXTENT | \nCELL WIDTH | \nFACTOR | \n||
|---|---|---|---|---|---|---|
| dir | \nnC | \nmin | \nmax | \nmin | \nmax | \nmax | \n
| x | \n3 | \n0.00 | \n1.00 | \n0.33 | \n0.33 | \n1.00 | \n
| y | \n4 | \n0.00 | \n1.00 | \n0.25 | \n0.25 | \n1.00 | \n
| Header 1 | \nHeader 2 | \n
|---|---|
| row 1, cell 1 | \nrow 1, cell 2 | \n
| row 2, cell 1 | \nrow 2, cell 2 | \n
| Header 1 | \nHeader 2 | \n
|---|---|
| row 1, cell 1 | \nrow 1, cell 2 | \n
| row 2, cell 1 | \nrow 2, cell 2 | \n
| Header 1 | \nHeader 2 | \n
|---|---|
| row 1, cell 1 | \nrow 1, cell 2 | \n
| row 2, cell 1 | \nrow 2, cell 2 | \n
| Header 1 | \nHeader 2 | \n
|---|---|
| row 1, cell 1 | \nrow 1, cell 2 | \n
| row 2, cell 1 | \nrow 2, cell 2 | \n
| \n | symboling | \nnormalized_losses | \nmake | \nfuel_type | \naspiration | \nnum_doors | \nbody_style | \ndrive_wheels | \nengine_location | \nwheel_base | \n... | \nengine_size | \nfuel_system | \nbore | \nstroke | \ncompression_ratio | \nhorsepower | \npeak_rpm | \ncity_mpg | \nhighway_mpg | \nprice | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n3 | \nNaN | \nalfa-romero | \ngas | \nstd | \ntwo | \nconvertible | \nrwd | \nfront | \n88.6 | \n... | \n130 | \nmpfi | \n3.47 | \n2.68 | \n9.0 | \n111.0 | \n5000.0 | \n21 | \n27 | \n13495.0 | \n
| 1 | \n3 | \nNaN | \nalfa-romero | \ngas | \nstd | \ntwo | \nconvertible | \nrwd | \nfront | \n88.6 | \n... | \n130 | \nmpfi | \n3.47 | \n2.68 | \n9.0 | \n111.0 | \n5000.0 | \n21 | \n27 | \n16500.0 | \n
| 2 | \n1 | \nNaN | \nalfa-romero | \ngas | \nstd | \ntwo | \nhatchback | \nrwd | \nfront | \n94.5 | \n... | \n152 | \nmpfi | \n2.68 | \n3.47 | \n9.0 | \n154.0 | \n5000.0 | \n19 | \n26 | \n16500.0 | \n
| 3 | \n2 | \n164.0 | \naudi | \ngas | \nstd | \nfour | \nsedan | \nfwd | \nfront | \n99.8 | \n... | \n109 | \nmpfi | \n3.19 | \n3.40 | \n10.0 | \n102.0 | \n5500.0 | \n24 | \n30 | \n13950.0 | \n
| 4 | \n2 | \n164.0 | \naudi | \ngas | \nstd | \nfour | \nsedan | \n4wd | \nfront | \n99.4 | \n... | \n136 | \nmpfi | \n3.19 | \n3.40 | \n8.0 | \n115.0 | \n5500.0 | \n18 | \n22 | \n17450.0 | \n
5 rows × 26 columns
\n| \n | original | \nencoder | \n
|---|---|---|
| 0 | \nfour | \n2 | \n
| 1 | \nfour | \n2 | \n
| 2 | \nsix | \n3 | \n
| 12 | \nsix | \n3 | \n
| 4 | \nfive | \n1 | \n
| 5 | \nfive | \n1 | \n
| 71 | \neight | \n0 | \n
| 72 | \neight | \n0 | \n
| 55 | \ntwo | \n6 | \n
| 56 | \ntwo | \n6 | \n
| 18 | \nthree | \n4 | \n
| 49 | \ntwelve | \n5 | \n
| \n | original | \nnum_cylinders | \n
|---|---|---|
| 0 | \nfour | \n3 | \n
| 1 | \nfour | \n3 | \n
| 2 | \nsix | \n5 | \n
| 12 | \nsix | \n5 | \n
| 4 | \nfive | \n4 | \n
| 5 | \nfive | \n4 | \n
| 71 | \neight | \n6 | \n
| 72 | \neight | \n6 | \n
| 55 | \ntwo | \n1 | \n
| 56 | \ntwo | \n1 | \n
| 18 | \nthree | \n2 | \n
| 49 | \ntwelve | \n7 | \n
| \n | original | \ndrive_wheels_1 | \ndrive_wheels_2 | \ndrive_wheels_3 | \n
|---|---|---|---|---|
| 3 | \nfwd | \n0 | \n1 | \n0 | \n
| 5 | \nfwd | \n0 | \n1 | \n0 | \n
| 0 | \nrwd | \n1 | \n0 | \n0 | \n
| 1 | \nrwd | \n1 | \n0 | \n0 | \n
| 4 | \n4wd | \n0 | \n0 | \n1 | \n
| 9 | \n4wd | \n0 | \n0 | \n1 | \n
| \n | original | \ndrive_wheels_0 | \ndrive_wheels_1 | \ndrive_wheels_2 | \n
|---|---|---|---|---|
| 3 | \nfwd | \n0 | \n1 | \n0 | \n
| 5 | \nfwd | \n0 | \n1 | \n0 | \n
| 0 | \nrwd | \n0 | \n0 | \n1 | \n
| 1 | \nrwd | \n0 | \n0 | \n1 | \n
| 4 | \n4wd | \n0 | \n1 | \n1 | \n
| 9 | \n4wd | \n0 | \n1 | \n1 | \n
| \n | original | \nmake_0 | \nmake_1 | \nmake_2 | \nmake_3 | \nmake_4 | \nmake_5 | \n
|---|---|---|---|---|---|---|---|
| 150 | \ntoyota | \n0 | \n1 | \n0 | \n1 | \n0 | \n0 | \n
| 151 | \ntoyota | \n0 | \n1 | \n0 | \n1 | \n0 | \n0 | \n
| 89 | \nnissan | \n0 | \n0 | \n1 | \n1 | \n0 | \n1 | \n
| 90 | \nnissan | \n0 | \n0 | \n1 | \n1 | \n0 | \n1 | \n
| 50 | \nmazda | \n0 | \n0 | \n1 | \n0 | \n0 | \n1 | \n
| 51 | \nmazda | \n0 | \n0 | \n1 | \n0 | \n0 | \n1 | \n
| 30 | \nhonda | \n0 | \n0 | \n0 | \n1 | \n1 | \n0 | \n
| 31 | \nhonda | \n0 | \n0 | \n0 | \n1 | \n1 | \n0 | \n
| 76 | \nmitsubishi | \n0 | \n0 | \n1 | \n1 | \n0 | \n0 | \n
| 77 | \nmitsubishi | \n0 | \n0 | \n1 | \n1 | \n0 | \n0 | \n
| 182 | \nvolkswagen | \n0 | \n1 | \n0 | \n1 | \n0 | \n1 | \n
| 183 | \nvolkswagen | \n0 | \n1 | \n0 | \n1 | \n0 | \n1 | \n
| 138 | \nsubaru | \n0 | \n1 | \n0 | \n0 | \n1 | \n1 | \n
| 139 | \nsubaru | \n0 | \n1 | \n0 | \n0 | \n1 | \n1 | \n
| 194 | \nvolvo | \n0 | \n1 | \n0 | \n1 | \n1 | \n0 | \n
| 195 | \nvolvo | \n0 | \n1 | \n0 | \n1 | \n1 | \n0 | \n
| 107 | \npeugot | \n0 | \n0 | \n1 | \n1 | \n1 | \n0 | \n
| 108 | \npeugot | \n0 | \n0 | \n1 | \n1 | \n1 | \n0 | \n
| 21 | \ndodge | \n0 | \n0 | \n0 | \n1 | \n0 | \n1 | \n
| 22 | \ndodge | \n0 | \n0 | \n0 | \n1 | \n0 | \n1 | \n
| 10 | \nbmw | \n0 | \n0 | \n0 | \n0 | \n1 | \n1 | \n
| 11 | \nbmw | \n0 | \n0 | \n0 | \n0 | \n1 | \n1 | \n
| 67 | \nmercedes-benz | \n0 | \n0 | \n1 | \n0 | \n1 | \n0 | \n
| 68 | \nmercedes-benz | \n0 | \n0 | \n1 | \n0 | \n1 | \n0 | \n
| 3 | \naudi | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n
| 4 | \naudi | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n
| 118 | \nplymouth | \n0 | \n0 | \n1 | \n1 | \n1 | \n1 | \n
| 119 | \nplymouth | \n0 | \n0 | \n1 | \n1 | \n1 | \n1 | \n
| 132 | \nsaab | \n0 | \n1 | \n0 | \n0 | \n1 | \n0 | \n
| 133 | \nsaab | \n0 | \n1 | \n0 | \n0 | \n1 | \n0 | \n
| 125 | \nporsche | \n0 | \n1 | \n0 | \n0 | \n0 | \n0 | \n
| 126 | \nporsche | \n0 | \n1 | \n0 | \n0 | \n0 | \n0 | \n
| 43 | \nisuzu | \n0 | \n0 | \n0 | \n1 | \n1 | \n1 | \n
| 44 | \nisuzu | \n0 | \n0 | \n0 | \n1 | \n1 | \n1 | \n
| 0 | \nalfa-romero | \n0 | \n0 | \n0 | \n0 | \n0 | \n1 | \n
| 1 | \nalfa-romero | \n0 | \n0 | \n0 | \n0 | \n0 | \n1 | \n
| 18 | \nchevrolet | \n0 | \n0 | \n0 | \n1 | \n0 | \n0 | \n
| 19 | \nchevrolet | \n0 | \n0 | \n0 | \n1 | \n0 | \n0 | \n
| 47 | \njaguar | \n0 | \n0 | \n1 | \n0 | \n0 | \n0 | \n
| 48 | \njaguar | \n0 | \n0 | \n1 | \n0 | \n0 | \n0 | \n
| 130 | \nrenault | \n0 | \n1 | \n0 | \n0 | \n0 | \n1 | \n
| 131 | \nrenault | \n0 | \n1 | \n0 | \n0 | \n0 | \n1 | \n
| 75 | \nmercury | \n0 | \n0 | \n1 | \n0 | \n1 | \n1 | \n
| \n | original | \nintercept | \ndrive_wheels_0 | \ndrive_wheels_1 | \n
|---|---|---|---|---|
| 3 | \nfwd | \n1 | \n0.666667 | \n-0.333333 | \n
| 5 | \nfwd | \n1 | \n0.666667 | \n-0.333333 | \n
| 0 | \nrwd | \n1 | \n-0.333333 | \n-0.333333 | \n
| 1 | \nrwd | \n1 | \n-0.333333 | \n-0.333333 | \n
| 4 | \n4wd | \n1 | \n-0.333333 | \n0.666667 | \n
| 9 | \n4wd | \n1 | \n-0.333333 | \n0.666667 | \n
| \n | original | \nintercept | \ndrive_wheels_0 | \ndrive_wheels_1 | \n
|---|---|---|---|---|
| 3 | \nfwd | \n1 | \n0.0 | \n1.0 | \n
| 5 | \nfwd | \n1 | \n0.0 | \n1.0 | \n
| 0 | \nrwd | \n1 | \n1.0 | \n0.0 | \n
| 1 | \nrwd | \n1 | \n1.0 | \n0.0 | \n
| 4 | \n4wd | \n1 | \n-1.0 | \n-1.0 | \n
| 9 | \n4wd | \n1 | \n-1.0 | \n-1.0 | \n
| \n | original | \nintercept | \nnum_cylinders_0 | \nnum_cylinders_1 | \nnum_cylinders_2 | \nnum_cylinders_3 | \nnum_cylinders_4 | \nnum_cylinders_5 | \n
|---|---|---|---|---|---|---|---|---|
| 0 | \nfour | \n1 | \n-1.889822e-01 | \n-3.273268e-01 | \n4.082483e-01 | \n0.080582 | \n-5.455447e-01 | \n0.493464 | \n
| 1 | \nfour | \n1 | \n-1.889822e-01 | \n-3.273268e-01 | \n4.082483e-01 | \n0.080582 | \n-5.455447e-01 | \n0.493464 | \n
| 2 | \nsix | \n1 | \n1.889822e-01 | \n-3.273268e-01 | \n-4.082483e-01 | \n0.080582 | \n5.455447e-01 | \n0.493464 | \n
| 12 | \nsix | \n1 | \n1.889822e-01 | \n-3.273268e-01 | \n-4.082483e-01 | \n0.080582 | \n5.455447e-01 | \n0.493464 | \n
| 4 | \nfive | \n1 | \n1.617449e-17 | \n-4.364358e-01 | \n-1.109626e-16 | \n0.483494 | \n-6.714569e-16 | \n-0.657952 | \n
| 5 | \nfive | \n1 | \n1.617449e-17 | \n-4.364358e-01 | \n-1.109626e-16 | \n0.483494 | \n-6.714569e-16 | \n-0.657952 | \n
| 71 | \neight | \n1 | \n3.779645e-01 | \n1.195122e-17 | \n-4.082483e-01 | \n-0.564076 | \n-4.364358e-01 | \n-0.197386 | \n
| 72 | \neight | \n1 | \n3.779645e-01 | \n1.195122e-17 | \n-4.082483e-01 | \n-0.564076 | \n-4.364358e-01 | \n-0.197386 | \n
| 55 | \ntwo | \n1 | \n-5.669467e-01 | \n5.455447e-01 | \n-4.082483e-01 | \n0.241747 | \n-1.091089e-01 | \n0.032898 | \n
| 56 | \ntwo | \n1 | \n-5.669467e-01 | \n5.455447e-01 | \n-4.082483e-01 | \n0.241747 | \n-1.091089e-01 | \n0.032898 | \n
| 49 | \ntwelve | \n1 | \n5.669467e-01 | \n5.455447e-01 | \n4.082483e-01 | \n0.241747 | \n1.091089e-01 | \n0.032898 | \n
| 18 | \nthree | \n1 | \n-3.779645e-01 | \n9.521795e-17 | \n4.082483e-01 | \n-0.564076 | \n4.364358e-01 | \n-0.197386 | \n
| \n | original | \nintercept | \nbody_style_0 | \nbody_style_1 | \nbody_style_2 | \nbody_style_3 | \n
|---|---|---|---|---|---|---|
| 3 | \nsedan | \n1 | \n0.0 | \n2.0 | \n-1.0 | \n-1.0 | \n
| 4 | \nsedan | \n1 | \n0.0 | \n2.0 | \n-1.0 | \n-1.0 | \n
| 2 | \nhatchback | \n1 | \n1.0 | \n-1.0 | \n-1.0 | \n-1.0 | \n
| 9 | \nhatchback | \n1 | \n1.0 | \n-1.0 | \n-1.0 | \n-1.0 | \n
| 7 | \nwagon | \n1 | \n0.0 | \n0.0 | \n3.0 | \n-1.0 | \n
| 28 | \nwagon | \n1 | \n0.0 | \n0.0 | \n3.0 | \n-1.0 | \n
| 69 | \nhardtop | \n1 | \n0.0 | \n0.0 | \n0.0 | \n4.0 | \n
| 74 | \nhardtop | \n1 | \n0.0 | \n0.0 | \n0.0 | \n4.0 | \n
| 0 | \nconvertible | \n1 | \n-1.0 | \n-1.0 | \n-1.0 | \n-1.0 | \n
| 1 | \nconvertible | \n1 | \n-1.0 | \n-1.0 | \n-1.0 | \n-1.0 | \n
| \n | original | \nintercept | \nbody_style_0 | \nbody_style_1 | \nbody_style_2 | \nbody_style_3 | \n
|---|---|---|---|---|---|---|
| 0 | \nconvertible | \n1 | \n-0.8 | \n-0.6 | \n-0.4 | \n-0.2 | \n
| 1 | \nconvertible | \n1 | \n-0.8 | \n-0.6 | \n-0.4 | \n-0.2 | \n
| 2 | \nhatchback | \n1 | \n0.2 | \n-0.6 | \n-0.4 | \n-0.2 | \n
| 9 | \nhatchback | \n1 | \n0.2 | \n-0.6 | \n-0.4 | \n-0.2 | \n
| 3 | \nsedan | \n1 | \n0.2 | \n0.4 | \n-0.4 | \n-0.2 | \n
| 4 | \nsedan | \n1 | \n0.2 | \n0.4 | \n-0.4 | \n-0.2 | \n
| 7 | \nwagon | \n1 | \n0.2 | \n0.4 | \n0.6 | \n-0.2 | \n
| 28 | \nwagon | \n1 | \n0.2 | \n0.4 | \n0.6 | \n-0.2 | \n
| 69 | \nhardtop | \n1 | \n0.2 | \n0.4 | \n0.6 | \n0.8 | \n
| 74 | \nhardtop | \n1 | \n0.2 | \n0.4 | \n0.6 | \n0.8 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n0.585366 | \n
| 5 | \nfwd | \n0.585366 | \n
| 0 | \nrwd | \n0.370732 | \n
| 1 | \nrwd | \n0.370732 | \n
| 4 | \n4wd | \n0.043902 | \n
| 9 | \n4wd | \n0.043902 | \n
| \n | original | \ncol_0 | \ncol_1 | \ncol_2 | \ncol_3 | \ncol_4 | \ncol_5 | \ncol_6 | \ncol_7 | \n
|---|---|---|---|---|---|---|---|---|---|
| 0 | \nrwd | \n0 | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n0 | \n
| 1 | \nrwd | \n0 | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n0 | \n
| 3 | \nfwd | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n0 | \n0 | \n
| 5 | \nfwd | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n0 | \n0 | \n
| 4 | \n4wd | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n
| 9 | \n4wd | \n0 | \n0 | \n0 | \n0 | \n0 | \n0 | \n1 | \n0 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n9244.779661 | \n
| 5 | \nfwd | \n9244.779661 | \n
| 0 | \nrwd | \n19757.613333 | \n
| 1 | \nrwd | \n19757.613333 | \n
| 4 | \n4wd | \n10243.702296 | \n
| 9 | \n4wd | \n10243.702296 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n9244.779661 | \n
| 5 | \nfwd | \n9244.779661 | \n
| 0 | \nrwd | \n19757.613333 | \n
| 1 | \nrwd | \n19757.613333 | \n
| 4 | \n4wd | \n10241.000000 | \n
| 9 | \n4wd | \n10241.000000 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n9278.076717 | \n
| 5 | \nfwd | \n9278.076717 | \n
| 0 | \nrwd | \n19671.422755 | \n
| 1 | \nrwd | \n19671.422755 | \n
| 4 | \n4wd | \n10570.569928 | \n
| 9 | \n4wd | \n10570.569928 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n9244.779661 | \n
| 5 | \nfwd | \n9244.779661 | \n
| 0 | \nrwd | \n19757.613333 | \n
| 1 | \nrwd | \n19757.613333 | \n
| 4 | \n4wd | \n10241.000000 | \n
| 9 | \n4wd | \n10241.000000 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n9278.076717 | \n
| 5 | \nfwd | \n9278.076717 | \n
| 0 | \nrwd | \n19671.422755 | \n
| 1 | \nrwd | \n19671.422755 | \n
| 4 | \n4wd | \n10570.569928 | \n
| 9 | \n4wd | \n10570.569928 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n0.275848 | \n
| 5 | \nfwd | \n0.275848 | \n
| 0 | \nrwd | \n-0.435318 | \n
| 1 | \nrwd | \n-0.435318 | \n
| 4 | \n4wd | \n0.162519 | \n
| 9 | \n4wd | \n0.162519 | \n
| \n | original | \ndrive_wheels | \n
|---|---|---|
| 3 | \nfwd | \n0.287682 | \n
| 5 | \nfwd | \n0.287682 | \n
| 0 | \nrwd | \n-0.448132 | \n
| 1 | \nrwd | \n-0.448132 | \n
| 4 | \n4wd | \ninf | \n
| 9 | \n4wd | \ninf | \n
| Software | Version |
|---|---|
| Python | 3.5.4 64bit [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] |
| IPython | 6.2.1 |
| OS | Darwin 18.6.0 x86_64 i386 64bit |
| numpy | 1.16.3 |
| matplotlib | 3.0.1 |
| pandas | 0.23.4 |
| scipy | 1.1.0 |
| statsmodels | 0.9.0 |
| Fri Jun 07 14:29:42 2019 CST | |
Name
|Date
|\n| ---------------------------------------------------| ------------------------------------- |\n|Diaaeldin SHALABY
| 18.06.2021 |\n\nu7_utils.py which can be seen and treated as a black box. However, for further understanding, you can look at the implementations of the helper functions. In order to run this notebook, the packages which are imported at the beginning of u7_utils.py need to be installed.\n\n\n```python\n# Import pre-defined utilities specific to this notebook.\nimport u7_utils as u7\n\n# Import additional utilities needed in this notebook.\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport sys\nimport time\n\nfrom IPython import display\nfrom typing import Any, Dict, Tuple\n\n# Setup Jupyter notebook (warning: this may affect all Jupyter notebooks running on the same Jupyter server).\nu7.setup_jupyter()\n```\n\n\n\n\n\n\nSetting up notebook ... finished.
\n\n\n\n\nAll exercises in this assignment are referring to the FrozenLake-v0 environment of OpenAI Gym. This environment is descibed according to its official OpenAI Gym website as follows:\n
There are four types of surfaces described in this environment:\n
S $\\rightarrow$ starting point (safe)F $\\rightarrow$ frozen surface (safe)H $\\rightarrow$ hole (fall to your doom)G $\\rightarrow$ goal (frisbee location)gym module is available in the lecture's notebook.\n\nThe first and naïve approach to solve this task is by simply brute forcing it applying random search. The outline of this approach is the following:\n
| Step | \nDescription | \n
|---|---|
| 0 | \nChoose a random action with respect to the current state. | \n
| 1 | \nExecute previously chosen action and transition into a new state. | \n
| 2 | \nRepeat the previous steps as long as the current episode is still ongoing. | \n
n of the action_space and observation_space of the respective environment gives the amount of actions as well as states.\n\n\n```python\nnum_actions = enviroment_lake.action_space.n\nnum_states = enviroment_lake.observation_space.n\nprint(f'The FrozenLake-v0 environment comprises <{num_actions}> actions and <{num_states}> states.')\n```\n\n The FrozenLake-v0 environment comprises <4> actions and <16> states.\n\n\n\n```python\ncurrent_state_id = enviroment_lake.s\nenviroment_lake.P[current_state_id]\n```\n\n\n\n\n {0: [(0.3333333333333333, 0, 0.0, False),\n (0.3333333333333333, 0, 0.0, False),\n (0.3333333333333333, 4, 0.0, False)],\n 1: [(0.3333333333333333, 0, 0.0, False),\n (0.3333333333333333, 4, 0.0, False),\n (0.3333333333333333, 1, 0.0, False)],\n 2: [(0.3333333333333333, 4, 0.0, False),\n (0.3333333333333333, 1, 0.0, False),\n (0.3333333333333333, 0, 0.0, False)],\n 3: [(0.3333333333333333, 1, 0.0, False),\n (0.3333333333333333, 0, 0.0, False),\n (0.3333333333333333, 0, 0.0, False)]}\n\n\n\nEach entry of the reward table contains a dictionary of the form s: {a: [] for a in range(nA)} for s in range(nS).\n
| Element | \nDescription | \n
|---|---|
nS=nrows*ncols | \n The number of possible moves. | \n
nA=4 | \n Number of surfaces. [S,F,H,G] | \n
a | \n Potential state based on the surface of the next move. | \n
Previously, we talked about solving this task in a naïve way by simply applying brute force: using random search. In the meantime we analyzed the action as well as the state space and came to the conclusion, that such an approach is more than feasible. To repeat the outline of such an approach:\n
I $\\rightarrow$ choose a random action with respect to the current state.II $\\rightarrow$ execute previously chosen action and transition into a new state.III $\\rightarrow$ if the episode is finished, but the goal not reached, reset the position of the disc retrieving entity.IV). Adapt the function apply_random_search as discussed during the lecture. Mark the corresponding sections of the code using I, II, III and IV. Note that our random search is not guaranteed to find the solution of a task in finite time, hence an upper border on the runtime is often applied as a safety net (in our case the number of allowed steps).\n\nTo drill down on the drawbacks of plain random search, we are designing the following experimental setup (hint: it is actually the same experimental setup as already discussed during the exercise, so you might orient yourself on the implementation presented during class):\n
In a simplified version of $Q$-learning, the $\\boldsymbol{Q}$-value\n\\begin{equation}\n Q(s,a)\n\\end{equation}
\n\nis the expected future reward of being in state $s$ and taking action $a$. Intuitively, if the the $Q$-values are learned correctly, a good policy would be to take the action which maximizes the expected future reward. This is what $Q$-learning is doing. $Q$-learning lets the agent use the environment's rewards to learn, over time, the best action to take in a given state. $Q$-values are initialized to an arbitrary value, and as the agent exposes itself to the environment and receives different rewards by executing different actions, the $Q$-values are updated using the equation:\n\\begin{equation}\n Q(s_t,a_t) \\leftarrow (1 - \\alpha) \\cdot Q(s_t,a_t) + \\alpha \\cdot \\left( r + \\max_{a_{t+1}} Q(s_{t+1}, a_{t+1})\\right)\n\\end{equation}
\n\nWe are assigning $\\leftarrow$, or updating, the $Q$-value of the agent's current state and action, denoted as $Q(s_t,a_t)$ with $\\alpha$ as the learning rate, i.e the extent to which our $Q$-values are being updated in every iteration.
\n\nThe $\\boldsymbol{Q}$-table is a matrix where we have a row for every state and a column for every action – $500$ and $6$, respectively, when referring to the Taxi-v3 example, as discussed during class. It's first initialized to $0$, and then values are updated after training.
\n\nPreviously, we talked about solving this task in a naïve way by simply applying brute force: using random search. This time we want to apply a more sophisticated algorithm – $Q$-learning:\n
I $\\rightarrow$ Choose action $a_t$.\n II $\\rightarrow$ Go from state $s_t$ to state $s_{t+1}$ by taking action $a_{t}$.\n III $\\rightarrow$ For all possible $Q$-values from the state $s_{t+1}$, select the highest.\n IV $\\rightarrow$ Update $Q$-table values using the equation from above.\n V $\\rightarrow$ Set the next state as the current state.\nVI).\n\nVery likely the $Q$-table of the previous experiment looked a little bit odd. Try to add exploration to your algorithm by adapting your $Q$-learning implementation:\n
I $\\rightarrow$ Throw a random uniform number between $0$ and $1$. \n II $\\rightarrow$ If the number is smaller than $0.1$, sample a random action.\n III $\\rightarrow$ Otherwise, choose your action as usual.\n \n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n\n**Result:**\n```python\ndef square(x):\n return x ** 2\n```\nThis is `inline` code. No syntax highlighting here.\n\n**Now it's your turn to have some Markdown fun.** In the next cell, try out some of the commands. You can just throw in some things, or do something more structured (like a small notebook).\n\n# Math for devs\n## Author: Antonio DIchev\n\nThis is a list:\n* 1\n* 2\n* 3\n\n\n| Cell1 | Cell2 | Cell3 |\n|-------|-------|-------|\n| 1.1 | 1.2 | 1.3 |\n| 2.1 | 2.2 | 2.3 |\n| 3.1 | 3.2 | 3.3 |\n\n\n\n### Problem 2. Formulas and LaTeX\nWriting math formulas has always been hard. But scientists don't like difficulties and prefer standards. So, thanks to Donald Knuth (a very popular computer scientist, who also invented a lot of algorithms), we have a nice typesetting system, called LaTeX (pronounced _lah_-tek). We'll be using it mostly for math formulas, but it has a lot of other things to offer.\n\nThere are two main ways to write formulas. You could enclose them in single `$` signs like this: `$ ax + b $`, which will create an **inline formula**: $ ax + b $. You can also enclose them in double `$` signs `$$ ax + b $$` to produce $$ ax + b $$.\n\nMost commands start with a backslash and accept parameters either in square brackets `[]` or in curly braces `{}`. For example, to make a fraction, you typically would write `$$ \\frac{a}{b} $$`: $$ \\frac{a}{b} $$.\n\n[Here's a resource](http://www.stat.pitt.edu/stoffer/freetex/latex%20basics.pdf) where you can look up the basics of the math syntax. You can also search StackOverflow - there are all sorts of solutions there.\n\nYou're on your own now. Research and recreate all formulas shown in the next cell. Try to make your cell look exactly the same as mine. It's an image, so don't try to cheat by copy/pasting :D.\n\nNote that you **do not** need to understand the formulas, what's written there or what it means. We'll have fun with these later in the course.\n\n\n\n$$y=ax+b$$\n\n$$ax^2+bx+c=0$$\n\n$$x_{1,2}= \\frac{-b\\pm \\sqrt{b^2-4ac}}{2a}$$\n\n$$f(x)|_{x=a} = f(a)+f'(a)(x-a)+\\frac{f''(a)}{2!}(x-a)^2+...+\\frac{f^(n)(a)}{n!}(x-a)^n+...$$\n\n$$(x+y)^n=\\begin{pmatrix}n\\\\0\\end{pmatrix}x^ny^0+\\begin{pmatrix}n\\\\1\\end{pmatrix}x^1y^{n-1}+...\\begin{pmatrix}n\\\\n\\end{pmatrix}x^0y^{n}=\\sum^n\\limits_{k=0}\\begin{pmatrix}n\\\\k\\end{pmatrix}x^{n-k}y^{k} $$\n\n$$\\int_{-\\infty}^{+\\infty}e^{-x^2}dx=\\sqrt\\pi$$\n\n$$\\begin{pmatrix}\n2 & 1 & 3 \\\\\n2 & 6 & 8 \\\\\n6 & 8 & 18\n\\end{pmatrix} $$\n\n\n$$A = \\begin{bmatrix} \n a_{11} & a_{12} & \\dots & a_{1n} \\\\\n a_{21} & a_{22} & \\dots & a_{2n} \\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m2} & \\dots & a_{mn} \\\\\n \\end{bmatrix}$$\n \n \n\n### Problem 3. Solving with Python\nLet's first do some symbolic computation. We need to import `sympy` first. \n\n**Should your imports be in a single cell at the top or should they appear as they are used?** There's not a single valid best practice. Most people seem to prefer imports at the top of the file though. **Note: If you write new code in a cell, you have to re-execute it!**\n\nLet's use `sympy` to give us a quick symbolic solution to our equation. First import `sympy` (you can use the second cell in this notebook): \n```python \nimport sympy \n```\n\nNext, create symbols for all variables and parameters. You may prefer to do this in one pass or separately:\n```python \nx = sympy.symbols('x')\na, b, c = sympy.symbols('a b c')\n```\n\nNow solve:\n```python \nsympy.solve(a * x**2 + b * x + c)\n```\n\nHmmmm... we didn't expect that :(. We got an expression for $a$ because the library tried to solve for the first symbol it saw. This is an equation and we have to solve for $x$. We can provide it as a second paramter:\n```python \nsympy.solve(a * x**2 + b * x + c, x)\n```\n\nFinally, if we use `sympy.init_printing()`, we'll get a LaTeX-formatted result instead of a typed one. This is very useful because it produces better-looking formulas.\n\nHow about a function that takes $a, b, c$ (assume they are real numbers, you don't need to do additional checks on them) and returns the **real** roots of the quadratic equation?\n\nRemember that in order to calculate the roots, we first need to see whether the expression under the square root sign is non-negative.\n\nIf $b^2 - 4ac > 0$, the equation has two real roots: $x_1, x_2$\n\nIf $b^2 - 4ac = 0$, the equation has one real root: $x_1 = x_2$\n\nIf $b^2 - 4ac < 0$, the equation has zero real roots\n\nWrite a function which returns the roots. In the first case, return a list of 2 numbers: `[2, 3]`. In the second case, return a list of only one number: `[2]`. In the third case, return an empty list: `[]`.\n\n\n```python\nimport math\ndef solve_quadratic_equation(a, b, c):\n \"\"\"\n Returns the real solutions of the quadratic equation ax^2 + bx + c = 0\n \"\"\"\n D = b**2 - 4*a*c\n\n if D < 0:\n return []\n elif D == 0:\n x = (-b+math.sqrt(b**2-4*a*c))/2*a\n return x\n else:\n x1 = (-b-math.sqrt(b**2-4*a*c))/2*a\n x2 = (-b+math.sqrt(b**2-4*a*c))/2*a\n return x1, x2\n```\n\n\n```python\n# Testing: Execute this cell. The outputs should match the expected outputs. Feel free to write more tests\nprint(solve_quadratic_equation(1, -1, -2)) # [-1.0, 2.0]\nprint(solve_quadratic_equation(1, -8, 16)) # [4.0]\nprint(solve_quadratic_equation(1, 1, 1)) # []\n```\n\n (-1.0, 2.0)\n 4.0\n []\n\n\n**Bonus:** Last time we saw how to solve a linear equation. Remember that linear equations are just like quadratic equations with $a = 0$. In this case, however, division by 0 will throw an error. Extend your function above to support solving linear equations (in the same way we did it last time).\n\n### Problem 4. Equation of a Line\nLet's go back to our linear equations and systems. There are many ways to define what \"linear\" means, but they all boil down to the same thing.\n\nThe equation $ax + b = 0$ is called *linear* because the function $f(x) = ax+b$ is a linear function. We know that there are several ways to know what one particular function means. One of them is to just write the expression for it, as we did above. Another way is to **plot** it. This is one of the most exciting parts of maths and science - when we have to fiddle around with beautiful plots (although not so beautiful in this case).\n\nThe function produces a straight line and we can see it.\n\nHow do we plot functions in general? Ww know that functions take many (possibly infinitely many) inputs. We can't draw all of them. We could, however, evaluate the function at some points and connect them with tiny straight lines. If the points are too many, we won't notice - the plot will look smooth.\n\nNow, let's take a function, e.g. $y = 2x + 3$ and plot it. For this, we're going to use `numpy` arrays. This is a special type of array which has two characteristics:\n* All elements in it must be of the same type\n* All operations are **broadcast**: if `x = [1, 2, 3, 10]` and we write `2 * x`, we'll get `[2, 4, 6, 20]`. That is, all operations are performed at all indices. This is very powerful, easy to use and saves us A LOT of looping.\n\nThere's one more thing: it's blazingly fast because all computations are done in C, instead of Python.\n\nFirst let's import `numpy`. Since the name is a bit long, a common convention is to give it an **alias**:\n```python\nimport numpy as np\n```\n\nImport that at the top cell and don't forget to re-run it.\n\nNext, let's create a range of values, e.g. $[-3, 5]$. There are two ways to do this. `np.arange(start, stop, step)` will give us evenly spaced numbers with a given step, while `np.linspace(start, stop, num)` will give us `num` samples. You see, one uses a fixed step, the other uses a number of points to return. When plotting functions, we usually use the latter. Let's generate, say, 1000 points (we know a straight line only needs two but we're generalizing the concept of plotting here :)).\n```python\nx = np.linspace(-3, 5, 1000)\n```\nNow, let's generate our function variable\n```python\ny = 2 * x + 3\n```\n\nWe can print the values if we like but we're more interested in plotting them. To do this, first let's import a plotting library. `matplotlib` is the most commnly used one and we usually give it an alias as well.\n```python\nimport matplotlib.pyplot as plt\n```\n\nNow, let's plot the values. To do this, we just call the `plot()` function. Notice that the top-most part of this notebook contains a \"magic string\": `%matplotlib inline`. This hints Jupyter to display all plots inside the notebook. However, it's a good practice to call `show()` after our plot is ready.\n```python\nplt.plot(x, y)\nplt.show()\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nx = np.linspace(-3, 5, 1000)\ny = 2 * x + 3\nplt.plot(x, y)\nplt.show()\n```\n\nIt doesn't look too bad bit we can do much better. See how the axes don't look like they should? Let's move them to zeto. This can be done using the \"spines\" of the plot (i.e. the borders).\n\nAll `matplotlib` figures can have many plots (subfigures) inside them. That's why when performing an operation, we have to specify a target figure. There is a default one and we can get it by using `plt.gca()`. We usually call it `ax` for \"axis\".\nLet's save it in a variable (in order to prevent multiple calculations and to make code prettier). Let's now move the bottom and left spines to the origin $(0, 0)$ and hide the top and right one.\n```python\nax = plt.gca()\nax.spines[\"bottom\"].set_position(\"zero\")\nax.spines[\"left\"].set_position(\"zero\")\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n```\n\n**Note:** All plot manipulations HAVE TO be done before calling `show()`. It's up to you whether they should be before or after the function you're plotting.\n\nThis should look better now. We can, of course, do much better (e.g. remove the double 0 at the origin and replace it with a single one), but this is left as an exercise for the reader :).\n\n\n```python\nplt.plot(x, y)\nax = plt.gca()\nax.spines[\"bottom\"].set_position(\"zero\")\nax.spines[\"left\"].set_position(\"zero\")\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nplt.show()\n```\n\n### * Problem 5. Linearizing Functions\nWhy is the line equation so useful? The main reason is because it's so easy to work with. Scientists actually try their best to linearize functions, that is, to make linear functions from non-linear ones. There are several ways of doing this. One of them involves derivatives and we'll talk about it later in the course. \n\nA commonly used method for linearizing functions is through algebraic transformations. Try to linearize \n$$ y = ae^{bx} $$\n\nHint: The inverse operation of $e^{x}$ is $\\ln(x)$. Start by taking $\\ln$ of both sides and see what you can do. Your goal is to transform the function into another, linear function. You can look up more hints on the Internet :).\n\n$$\\ln y=b*x+\\ln a$$\n\n### * Problem 6. Generalizing the Plotting Function\nLet's now use the power of Python to generalize the code we created to plot. In Python, you can pass functions as parameters to other functions. We'll utilize this to pass the math function that we're going to plot.\n\nNote: We can also pass *lambda expressions* (anonymous functions) like this: \n```python\nlambda x: x + 2```\nThis is a shorter way to write\n```python\ndef some_anonymous_function(x):\n return x + 2\n```\n\nWe'll also need a range of x values. We may also provide other optional parameters which will help set up our plot. These may include titles, legends, colors, fonts, etc. Let's stick to the basics now.\n\nWrite a Python function which takes another function, x range and number of points, and plots the function graph by evaluating it at every point.\n\n**BIG hint:** If you want to use not only `numpy` functions for `f` but any one function, a very useful (and easy) thing to do, is to vectorize the function `f` (e.g. to allow it to be used with `numpy` broadcasting):\n```python\nf_vectorized = np.vectorize(f)\ny = f_vectorized(x)\n```\n\n\n```python\ndef plot_math_function(f, min_x, max_x, num_points):\n \n \n f_vectorized = np.vectorize(f)\n x=np.linspace(min_x,max_x,num_points)\n y = f_vectorized(x)\n \n plt.plot(x, y)\n ax = plt.gca()\n ax.spines[\"bottom\"].set_position(\"zero\")\n ax.spines[\"left\"].set_position(\"zero\")\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n plt.show()\n```\n\n\n```python\n#x = np.linspace(-15,15,100) # 100 linearly spaced numbers\n#y = np.sin(x)/x # computing the values of sin(x)/x\n\n# compose plot\n#plt.plot(x,y) # sin(x)/x\n#plt.plot(x,y,'co') # same function with cyan dots\n#plt.plot(x,2*y,x,3*y) # 2*sin(x)/x and 3*sin(x)/x\n#plt.show() # show the plot\n```\n\n\n```python\n\n```\n\n\n```python\nplot_math_function(lambda x: 2 * x + 3, -3, 5, 1000)\nplot_math_function(lambda x: -x + 8, -1, 10, 1000)\nplot_math_function(lambda x: x**2 - x - 2, -3, 4, 1000)\nplot_math_function(lambda x: np.sin(x), -np.pi, np.pi, 1000)\nplot_math_function(lambda x: np.sin(x) / x, -4 * np.pi, 4 * np.pi, 1000)\n```\n\n### * Problem 7. Solving Equations Graphically\nNow that we have a general plotting function, we can use it for more interesting things. Sometimes we don't need to know what the exact solution is, just to see where it lies. We can do this by plotting the two functions around the \"=\" sign ans seeing where they intersect. Take, for example, the equation $2x + 3 = 0$. The two functions are $f(x) = 2x + 3$ and $g(x) = 0$. Since they should be equal, the point of their intersection is the solution of the given equation. We don't need to bother marking the point of intersection right now, just showing the functions.\n\nTo do this, we'll need to improve our plotting function yet once. This time we'll need to take multiple functions and plot them all on the same graph. Note that we still need to provide the $[x_{min}; x_{max}]$ range and it's going to be the same for all functions.\n\n```python\nvectorized_fs = [np.vectorize(f) for f in functions]\nys = [vectorized_f(x) for vectorized_f in vectorized_fs]\n```\n\n\n```python\ndef plot_math_functions(functions, min_x, max_x, num_points):\n \n vectorized_fs = [np.vectorize(f) for f in functions]\n x=np.linspace(min_x,max_x,num_points) \n \n ys = [vectorized_f(x) for vectorized_f in vectorized_fs]\n \n \n #y = [y for y in ys]\n\n for i in ys: #ys is my range of y values on the chart\n plt.plot(x, i)\n ax = plt.gca()\n ax.spines[\"bottom\"].set_position(\"zero\")\n ax.spines[\"left\"].set_position(\"zero\")\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n plt.show()\n \n```\n\n\n```python\nplot_math_functions([lambda x: 2 * x + 3, lambda x: 0], -3, 5, 1000)\nplot_math_functions([lambda x: 3 * x**2 - 2 * x + 5, lambda x: 3 * x + 7], -2, 3, 1000)\n```\n\nThis is also a way to plot the solutions of systems of equation, like the one we solved last time. Let's actually try it.\n\n\n```python\nplot_math_functions([lambda x: (-4 * x + 7) / 3, lambda x: (-3 * x + 8) / 5, lambda x: (-x - 1) / -2], -1, 4, 1000)\n```\n\n### Problem 8. Trigonometric Functions\nWe already saw the graph of the function $y = \\sin(x)$. But, how do we define the trigonometric functions once again? Let's quickly review that.\n\n\n\nThe two basic trigonometric functions are defined as the ratio of two sides:\n$$ \\sin(x) = \\frac{\\text{opposite}}{\\text{hypotenuse}} $$\n$$ \\cos(x) = \\frac{\\text{adjacent}}{\\text{hypotenuse}} $$\n\nAnd also:\n$$ \\tan(x) = \\frac{\\text{opposite}}{\\text{adjacent}} = \\frac{\\sin(x)}{\\cos(x)} $$\n$$ \\cot(x) = \\frac{\\text{adjacent}}{\\text{opposite}} = \\frac{\\cos(x)}{\\sin(x)} $$\n\nThis is fine, but using this, \"right-triangle\" definition, we're able to calculate the trigonometric functions of angles up to $90^\\circ$. But we can do better. Let's now imagine a circle centered at the origin of the coordinate system, with radius $r = 1$. This is called a \"unit circle\".\n\n\n\nWe can now see exactly the same picture. The $x$-coordinate of the point in the circle corresponds to $\\cos(\\alpha)$ and the $y$-coordinate - to $\\sin(\\alpha)$. What did we get? We're now able to define the trigonometric functions for all degrees up to $360^\\circ$. After that, the same values repeat: these functions are **periodic**: \n$$ \\sin(k.360^\\circ + \\alpha) = \\sin(\\alpha), k = 0, 1, 2, \\dots $$\n$$ \\cos(k.360^\\circ + \\alpha) = \\cos(\\alpha), k = 0, 1, 2, \\dots $$\n\nWe can, of course, use this picture to derive other identities, such as:\n$$ \\sin(90^\\circ + \\alpha) = \\cos(\\alpha) $$\n\nA very important property of the sine and cosine is that they accept values in the range $(-\\infty; \\infty)$ and produce values in the range $[-1; 1]$. The two other functions take values in the range $(-\\infty; \\infty)$ **except when their denominators are zero** and produce values in the same range. \n\n#### Radians\nA degree is a geometric object, $1/360$th of a full circle. This is quite inconvenient when we work with angles. There is another, natural and intrinsic measure of angles. It's called the **radian** and can be written as $\\text{rad}$ or without any designation, so $\\sin(2)$ means \"sine of two radians\".\n\n\nIt's defined as *the central angle of an arc with length equal to the circle's radius* and $1\\text{rad} \\approx 57.296^\\circ$.\n\nWe know that the circle circumference is $C = 2\\pi r$, therefore we can fit exactly $2\\pi$ arcs with length $r$ in $C$. The angle corresponding to this is $360^\\circ$ or $2\\pi\\ \\text{rad}$. Also, $\\pi rad = 180^\\circ$.\n\n(Some people prefer using $\\tau = 2\\pi$ to avoid confusion with always multiplying by 2 or 0.5 but we'll use the standard notation here.)\n\n**NOTE:** All trigonometric functions in `math` and `numpy` accept radians as arguments. In order to convert between radians and degrees, you can use the relations $\\text{[deg]} = 180/\\pi.\\text{[rad]}, \\text{[rad]} = \\pi/180.\\text{[deg]}$. This can be done using `np.deg2rad()` and `np.rad2deg()` respectively.\n\n#### Inverse trigonometric functions\nAll trigonometric functions have their inverses. If you plug in, say $\\pi/4$ in the $\\sin(x)$ function, you get $\\sqrt{2}/2$. The inverse functions (also called, arc-functions) take arguments in the interval $[-1; 1]$ and return the angle that they correspond to. Take arcsine for example:\n$$ \\arcsin(y) = x: sin(y) = x $$\n$$ \\arcsin\\left(\\frac{\\sqrt{2}}{2}\\right) = \\frac{\\pi}{4} $$\n\nPlease note that this is NOT entirely correct. From the relations we found:\n$$\\sin(x) = sin(2k\\pi + x), k = 0, 1, 2, \\dots $$\n\nit follows that $\\arcsin(x)$ has infinitely many values, separated by $2k\\pi$ radians each:\n$$ \\arcsin\\left(\\frac{\\sqrt{2}}{2}\\right) = \\frac{\\pi}{4} + 2k\\pi, k = 0, 1, 2, \\dots $$\n\nIn most cases, however, we're interested in the first value (when $k = 0$). It's called the **principal value**.\n\nNote 1: There are inverse functions for all four basic trigonometric functions: $\\arcsin$, $\\arccos$, $\\arctan$, $\\text{arccot}$. These are sometimes written as $\\sin^{-1}(x)$, $cos^{-1}(x)$, etc. These definitions are completely equivalent. \n\nJust notice the difference between $\\sin^{-1}(x) := \\arcsin(x)$ and $\\sin(x^{-1}) = \\sin(1/x)$.\n\n#### Exercise\nUse the plotting function you wrote above to plot the inverse trigonometric functions.\n\n\n```python\nplot_math_functions([lambda x:np.arcsin(x)], -1, 1, 1000)\nplot_math_functions([lambda x:np.arccos(x)], -1, 1, 1000)\nplot_math_functions([lambda x:np.arctan(x)], -1, 1, 1000)\nplot_math_functions([lambda x:np.arctan(1/x)], -1, 1, 1000)\n```\n\n\n```python\ndef plot_circle(x_c, y_c, r):\n \"\"\"\n Plots the circle with center C(x_c; y_c) and radius r.\n This corresponds to plotting the equation x^2 + y^2 = r^2\n \"\"\"\n ##(x−x_c)**2 + (y−y_c)**2 = r**2\n\n x = np.linspace(-r+x_c,r+x_c,1000)\n y = y_c+np.sqrt(-(x-x_c)**2+r**2)\n y2 = y_c-np.sqrt(-(x-x_c)**2+r**2)\n plt.plot(x, y,'b')\n plt.plot(x, y2,'b')\n plt.gca().set_aspect('equal')\n plt.show()\n```\n\n\n```python\nplot_circle(300, 300, 600)\n```\n\n### ** Problem 9. Perlin Noise\nThis algorithm has many applications in computer graphics and can serve to demonstrate several things... and help us learn about math, algorithms and Python :).\n#### Noise\nNoise is just random values. We can generate noise by just calling a random generator. Note that these are actually called *pseudorandom generators*. We'll talk about this later in this course.\nWe can generate noise in however many dimensions we want. For example, if we want to generate a single dimension, we just pick N random values and call it a day. If we want to generate a 2D noise space, we can take an approach which is similar to what we already did with `np.meshgrid()`.\n\n$$ \\text{noise}(x, y) = N, N \\in [n_{min}, n_{max}] $$\n\nThis function takes two coordinates and returns a single number N between $n_{min}$ and $n_{max}$. (This is what we call a \"scalar field\").\n\nRandom variables are always connected to **distributions**. We'll talk about these a great deal but now let's just say that these define what our noise will look like. In the most basic case, we can have \"uniform noise\" - that is, each point in our little noise space $[n_{min}, n_{max}]$ will have an equal chance (probability) of being selected.\n\n#### Perlin noise\nThere are many more distributions but right now we'll want to have a look at a particular one. **Perlin noise** is a kind of noise which looks smooth. It looks cool, especially if it's colored. The output may be tweaked to look like clouds, fire, etc. 3D Perlin noise is most widely used to generate random terrain.\n\n#### Algorithm\n... Now you're on your own :). Research how the algorithm is implemented (note that this will require that you understand some other basic concepts like vectors and gradients).\n\n#### Your task\n1. Research about the problem. See what articles, papers, Python notebooks, demos, etc. other people have created\n2. Create a new notebook and document your findings. Include any assumptions, models, formulas, etc. that you're using\n3. Implement the algorithm. Try not to copy others' work, rather try to do it on your own using the model you've created\n4. Test and improve the algorithm\n5. (Optional) Create a cool demo :), e.g. using Perlin noise to simulate clouds. You can even do an animation (hint: you'll need gradients not only in space but also in time)\n6. Communicate the results (e.g. in the Softuni forum)\n\nHint: [This](http://flafla2.github.io/2014/08/09/perlinnoise.html) is a very good resource. It can show you both how to organize your notebook (which is important) and how to implement the algorithm.\n", "meta": {"hexsha": "ea75c3c9414d0a4c237814370a64b5fac8d62f38", "size": 260882, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "High_Shool_Maths/High-School-Maths-Exercise.ipynb", "max_stars_repo_name": "ivaylokanov/Math_Concepts_for_Developers", "max_stars_repo_head_hexsha": "646d4d5de48535c22b9a8fcb624973b917661c5e", "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": "High_Shool_Maths/High-School-Maths-Exercise.ipynb", "max_issues_repo_name": "ivaylokanov/Math_Concepts_for_Developers", "max_issues_repo_head_hexsha": "646d4d5de48535c22b9a8fcb624973b917661c5e", "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": "High_Shool_Maths/High-School-Maths-Exercise.ipynb", "max_forks_repo_name": "ivaylokanov/Math_Concepts_for_Developers", "max_forks_repo_head_hexsha": "646d4d5de48535c22b9a8fcb624973b917661c5e", "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": 264.0506072874, "max_line_length": 18312, "alphanum_fraction": 0.8983640113, "converted": true, "num_tokens": 7896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203222625389934, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.06481462081510274}} {"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Ion Device Class\n\n
| \n View on QuantumAI\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
| \n | Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license.(c) Carlos Alberto Alvarez Henao | \n
\n \n
\n\n\n \n
\n\n\n \n
\n\n\n \n
\n\n\n \n
\n\n\n\nLa trayectoria rectilínea de una partícula se definirá por medio de un solo eje de coordenadas $s$. \n\nEl origen $O$ en la trayectoria es un punto fijo, y a partir de él se utiliza la coordenada de posición s para especificar la ubicación de la partícula en cualquier instante dado. La magnitud de $s$ es la distancia de $O$ a la partícula (en unidades de longitud), y su signo algebraico define el sentido de su dirección.\n\nLa posición es una cantidad vectorial puesto que tiene tanto magnitud como dirección, aunque en este caso se representa por el escalar algebraico $s$ puesto que la dirección se mantiene a lo largo del eje de coordenadas.\n\n\n### Desplazamiento\n\n\n \n
\n\n\n\nEl desplazamiento de la partícula se define como el cambio de su posición, y es dado por:\n\n\n\\begin{equation*}\n\\Delta s= s'-s\n\\label{eq:Ec1_1} \\tag{1.1}\n\\end{equation*}\n\nEn este caso $\\Delta s$ es positivo puesto que la posición final de la partícula queda a la derecha de su posición inicial, es decir, $s'>s$. Asimismo, si la posición final quedara a la izquierda de su posición inicial, $\\Delta s$ sería negativo.\n\nEl desplazamiento de una partícula también es una cantidad vectorial, y deberá distinguirse de la distancia que recorre la partícula. Específicamente, la distancia recorrida es un escalar positivo que representa la longitud total de la trayectoria a lo largo de la cual viaja la partícula.\n\n### Velocidad\n\n\n \n
\n\n\n\nSi la partícula recorre una distancia $\\Delta s$ durante el intervalo $\\Delta t$, su velocidad promedio durante este intervalo es\n\n\n\\begin{equation*}\n\\textbf{v}_{prom}=\\frac{\\Delta s}{\\Delta t}\n\\label{eq:Ec1_2} \\tag{1.2}\n\\end{equation*}\n\nLa velocidad instantánea es una cantidad vectorial definida como \n\n\n\\begin{equation*}\n\\textbf{v}=\\lim_{\\Delta t \\rightarrow 0}\\frac{\\Delta s}{\\Delta t}=\\frac{ds}{dt}\n\\label{eq:Ec1_3} \\tag{1.3}\n\\end{equation*}\n\nComo la dirección temporal siempre será positiva, entonces el signo para determinar el sentido de la velocidad le corresponderá a $ds$. La magnitud de la velocidad es lo que se conoce como *rapidez*.\n\n### Aceleración\n\n\n \n
\n\n\n\nConocida la velocidad de la partícula en dos puntos, la aceleración promedio en un intervalo de tiempo $\\Delta t$ está dada por\n\n\n\\begin{equation*}\n\\textbf{a}_{prom}=\\frac{\\Delta \\textbf{v}}{\\Delta t}\n\\label{eq:Ec1_4} \\tag{1.4}\n\\end{equation*}\n\nLa aceleración instantánea es una cantidad vectorial definida como \n\n\n\\begin{equation*}\n\\textbf{a}=\\lim_{\\Delta t \\rightarrow 0}\\frac{\\Delta \\textbf{v}}{\\Delta t}=\\frac{d\\textbf{v}}{dt}\n\\label{eq:Ec1_5} \\tag{1.5}\n\\end{equation*}\n\nLa aceleración también se puede interpretar como la segunda derivada del desplazamiento respecto al tiempo.\nUna relación diferencial que incluye el desplazamiento, la velocidad y la aceleración a lo largo de una trayectoria, eliminando la dependencia del tiempo es:\n\n\n\\begin{equation*}\n\\textbf{a}ds=\\textbf{v}d\\textbf{v}\n\\label{eq:Ec1_6} \\tag{1.6}\n\\end{equation*}\n\n\n### Aceleración constante\n\nSi la aceleración es constante, se pueden integrar las tres ecuaciones cinemáticas vistas:\n\n$$\\textbf{a}_c=\\frac{d\\textbf{v}}{dt}; \\quad \\textbf{v}=\\frac{ds}{dt}; \\quad \\textbf{a}ds=\\textbf{v}d\\textbf{v}$$\n\n\n#### Velocidad como función del tiempo\n\nIntegrando $a_c=\\frac{d\\textbf{v}}{dt}$, con condiciones iniciales $\\textbf{v}=v_0$ cuando $𝑡=0$\n\n$$\\int_{v_0}^v d\\textbf{v} = \\int_0^t a_c dt$$\n\nSe llega a\n\n\n\\begin{equation*}\n\\textbf{v} = v_0 + a_c t\n\\label{eq:Ec1_7} \\tag{1.7}\n\\end{equation*}\n\n\n#### Posición como función del tiempo\n\nIntegrando $\\textbf{v}=ds/dt=v_0 + a_c t$, con condiciones iniciales $s=s_0$ cuando $𝑡=0$\n\n$$\\int_{s_0}^s ds = \\int_0^t (v_0 +a_c t) dt$$\n\nSe llega a\n\n\n\\begin{equation*}\ns = s_0 + v_0 t +\\frac{1}{2} a_c t^2\n\\label{eq:Ec1_8} \\tag{1.8}\n\\end{equation*}\n\n\n#### Velocidad como función de la posición\n\nIntegrando $\\textbf{v}d\\textbf{v}=a_c ds$, con condiciones iniciales $v=v_0$ cuando $s=s_0$\n\n$$\\int_{v_0}^v \\textbf{v}d\\textbf{v} = \\int_{s_0}^s a_c ds$$\n\nSe llega a\n\n\n\\begin{equation*}\nv^2 = v_0^2 + 2a_c (s-s_0)\n\\label{eq:Ec1_9} \\tag{1.9}\n\\end{equation*}\n\n#### Observaciones\n\n- Las ecuaciones anteriores son útiles cuando la aceleración es constante y cuando $t=0$, $s=s_0$ y $v=v_0$.\n\n\n- Si se conoce una relación entre dos de las cuatro variables, $\\textbf{a}$, $\\textbf{v}$, $s$ y $t$, entonces se puede obtener una tercera variable con una de las ecuaciones cinemáticas, $\\textbf{a}=d\\textbf{v}/dt$, $\\textbf{v}=ds/dt$ o $\\textbf{a}ds=\\textbf{v}d\\textbf{v}$, puesto que cada ecuación relaciona las tres variables.\n\n\n- Siempre que se realice una integración, es importante que se conozcan la posición y la velocidad en un instante dado para evaluar o la constante de integración si se utiliza una integral indefinida, o los límites de integración si se utiliza una integral definida.\n\n### Recapitulando\n\n- La dinámica se ocupa de cuerpos que tienen movimiento acelerado.\n\n\n- La cinemática es un estudio de la geometría del movimiento.\n\n\n- La cinética es un estudio de las fuerzas que causan el movimiento.\n\n\n- La cinemática rectilínea se refiere al movimiento en línea recta.\n\n\n- La rapidez se refiere a la magnitud de la velocidad.\n\n\n- La rapidez promedio es la distancia total recorrida, dividida entre el tiempo total. Ésta es diferente de la velocidad promedio, la cual es el desplazamiento dividido entre el tiempo.\n\n\n- Una partícula que reduce el paso está desacelerando.\n\n\n- Una partícula puede tener una aceleración y al mismo tiempo una velocidad cero.\n\n\n- La relación $\\textbf{a}ds=\\textbf{v} d\\textbf{v}$ se deriva de $\\textbf{a}=d\\textbf{v}/dt$ y $\\textbf{v}=ds/dt$, al eliminar $dt$.\n\n\n### Ejemplos\n\n#### Desplazamiento rectilíneo de un Automovil\n\n| \n | \n\n Ejemplo 12.1: Hibbeler R. Engineering Mechanics: Dynamics \n\nEl automóvil de la figura se desplaza en línea recta de modo que durante un corto tiempo su velocidad está definida por $\\textbf{v}=3t^2 + 2t$ pies/s, donde $t$ está en segundos. Determine su posición y aceleración cuando $t = 3 s$. Cuando $t = 0, s = 0$. \n | \n
| \n | \n Ejemplo 12.3: Hibbeler R. Engineering Mechanics: Dynamics \nDurante una prueba un cohete asciende a $75 m/s$ y cuando está a $40 m$ del suelo su motor falla. Determine la altura máxima $s_B$ alcanzada por el cohete y su velocidad justo antes de chocar con el suelo. Mientras está en movimiento, el cohete se ve sometido a una aceleración constante dirigida hacia abajo de $9.81 m/s^2$ debido a la gravedad. Ignore la resistencia del aire. \n | \n
| \n | \n Ejemplo 12.3: Hibbeler R. Engineering Mechanics: Dynamics \nUna partícula metálica se somete a la influencia de un campo magnético a medida que desciende a través de un fluido que se extiende de la placa $A$ a la placa $B$. Si la partícula se libera del reposo en el punto medio $C$, $s=100 mm$ y la aceleración es $a=(4s) m/s^2$, donde $s$ está en metros, determine la velocidad de la partícula cuando llega a la placa $B$, $s=200 mm$ y el tiempo que le lleva para ir de $C$ a $B$. \n | \n
| Hibbeler R. Engineering Mechanics: Dynamics | \n\n \n La gráfica de $v-t$ se construye a partir de la gráfica de $s-t$, fig. (a), se utilizará la ecuación $v=ds/dt$, ya que relaciona las variables $s$ y $t$ con $v$. Esta ecuación establece que\n \n\n $$\\underbrace{\\frac{ds}{dt}}_{\\text{pendiente gráfica s-t}}=\\underbrace{v}_{velocidad}$$\n \n\n Por ejemplo, si se mide la pendiente en la gráfica de $s-t$ cuando $t=t_1$, la velocidad es $v_1$, la cual se traza en la fig. (b). La gráfica de $v-t$ se construye trazando ésta y otros valores en cada instante. \n \n | \n
| Hibbeler R. Engineering Mechanics: Dynamics | \n\n \n La gráfica de $a-t$ se construye a partir de la gráfica de $v-t$ del mismo modo, figs. (a) y (b) puesto que\n \n\n $$\\underbrace{\\frac{dv}{dt}}_{\\text{pendiente gráfica v-t}}=\\underbrace{a}_{acelereción}$$\n \n\nSi la curva $s-t$ correspondiente a cada intervalo de movimiento puede\nexpresarse mediante una función matemática $s=s(t)$, entonces la ecuación\nde la gráfica de $v-t$ correspondiente al mismo intervalo se obtiene\ndiferenciando esta función con respecto al tiempo puesto que $v=ds/dt$.\n \n\nAsimismo, la ecuación de la gráfica de $a-t$ en el mismo intervalo se determina\nal diferenciar $v=v(t)$ puesto que $a=dv/dt$. Como la diferenciación\nreduce un polinomio de grado $n$ a uno de grado $n-1$, en tal caso si la\ngráfica de $s-t$ es parabólica (una curva de segundo grado), la gráfica de\n$v-t$ será una línea inclinada (una curva de primer grado) y la gráfica de $a-t$\nserá una constante o una línea horizontal (una curva de grado cero). \n \n | \n
| Hibbeler R. Engineering Mechanics: Dynamics | \n\n \n Si se tiene la gráfica de $a-t$, como se muestra en la figura al lado, la gráfica de $v-t$ se construye mediante $a=dv/dt$, escrita como\n \n\n$$\\underbrace{\\Delta v}_{\\text{Cambio de la velocidad}}=\\underbrace{\\int adt}_{\\text{área bajo la curva de a-t}}$$\n \n\nPara construir la gráfica $v-t$, se parte de la velocidad inicial de la partícula, $v_0$ y luego se va adicionando pequeños incrementos de área ($\\Delta v$) determinados a partir de la gráfica $a-t$. Con esto, se tienen una serie de puntos sucesivos, $v_i=v_{i-1}+\\Delta v$ que irán conformando la gráfica $v-t$\n \n\nLa adición algebráica de los incrementos de área de la gráfica $a-t$ es necesaria, ya que las áreas situadas por encima del eje $t$ corresponden a un incremento de $v$ (área \"positiva\"), mientras que las que quedan debajo del eje indican una reducción de $v$ (área \"negativa\"). \n \n | \n
| Hibbeler R. Engineering Mechanics: Dynamics | \n\n \n De igual forma, si se tiene la gráfica de $v-t$, como se muestra en la figura al lado, la gráfica de $s-t$ se construye mediante $v=ds/dt$, escrita como\n \n\n$$\\underbrace{\\Delta s}_{\\text{desplazamiento}}=\\underbrace{\\int vdt}_{\\text{área bajo la curva de v-t}}$$\n \n\nigual que en la anterior gráfica, se parte de la posición inicial de la partícula, $s_0$ y luego se va adicionando pequeños incrementos de área ($\\Delta s$) determinados a partir de la gráfica $v-t$.\n \n\nLos segmentos de la gráfica $a-t$ pueden describirse mediante una serie de ecuaciones, que a su vez pueden integrarse para obtener los segmentos correspondientes a l gráfica $v-t$. Por lo tanto, si la gráfica $a-t$ es lineal, la integración dará una gráfica para $v-t$ cuadrática, y para $s-t$, una cúbica.\n \n | \n
| Hibbeler R. Engineering Mechanics: Dynamics | \n\n \n Los puntos de la gráfica $v-s$ se determinana por medio de la ecuación $vdv=ads$. Integrando esta ecuación en los límites $v=v_0$ con $s=s_0$ y $v=v_1$ con $s=s_1$, se tiene\n \n\n$$\\frac{1}{2}\\left( v_1^2 - v_0^2\\right)=\\underbrace{\\int_{s_0}^{s_1} ads}_{\\text{área bajo la curva de a-s}}$$\n \n\nSi se determina el área de color gris y se conoce la velocidad $v_0$ en $s_0=0$, entonces $v_1=\\left( 2 \\int_{s_0}^{s_1}ads+v_0^2\\right)^{1/2}$. De esta forma se pueden marcar puntos sucesivos en la gráfica $v-s$.\n \n | \n
| Hibbeler R. Engineering Mechanics: Dynamics | \n\n \nSi se conoce la gráfica $v-s$, la aceleración $a$ en cualquier posición $s$ se determinar por $ads=vdv$, que se escribe como\n \n\n$$\\underbrace{a}_\\text{aceleración}=\\underbrace{v \\left( \\frac{dv}{ds} \\right)}_{\\text{velocidad por la pendiente de la gráfica de v-s}}$$\n \n\nEntonces, en cualquier punto $(s,v)$ se mide la pendiente $ds/dv$ de la gráfica de $v-s$. Entonces, con $v$ y $dv/ds$ conocidas, se calcula el valor de $a$.\n \n\nLa gráfica de $v-s$ también se construye a partir de la gráfica de $a-s$ o viceversa, por aproximación de la gráfica conocida en varios intervalos con funciones matemáticas, $v=f(s)$ o $a=g(s)$ y luego por $ads=vdv$ para obtener la otra gráfica.\n \n | \n
| \n | \n Ejemplo 12.6: Hibbeler R. Engineering Mechanics: Dynamics \nUna bicicleta rueda a lo largo de una carretera recta de modo que la gráfica de la figura describe su posición. Construya las gráficas de $v-t$ y $a-t$ en el intervalo $0 \\leq t \\leq 30 s$ \n | \n
| \n | \n \n- Gráfica $v-t$: teniendo que $v=ds/dt$, la gráfica de $v-t$ se determina diferenciando las ecuaciones que definen la gráfica $s-t$. En la gráfica se observan dos segmentos:\n\n - ***Segmento 1:*** en el intervalo $0\\leq t<10s$ la función de desplazamiento está dada por la ecuación $s=t^2 pies$, diferenciando esta ecuación respecto al tiempo para determinar la velocidad en ese trayecto, quedaría $v=\\frac{ds}{dt}=(2t) pies/s$.\n\n - ***Segmento 2:*** en el intervalo $10s\\leq t<30s$ la función de desplazamiento está dada por la ecuación $s=(20t-100)pies$, diferenciando esta ecuación respecto al tiempo para determinar la velocidad en ese trayecto, quedaría $v=\\frac{ds}{dt}=(20)pies/s$.\n\n\n|$0\\leq t | \n
| \n | \n \n- Gráfica $a-t$: Similarmente, como $a=dv/dt$, la gráfica de $a-t$ se determina diferenciando las ecuaciones que definen la gráfica $v-t$:\n\n - ***Segmento 1:*** en el intervalo $0\\leq t<10s$ la función de velocidad está dada por la ecuación $s=2t pies/s$, diferenciando esta ecuación respecto al tiempo para determinar la aceleración en ese trayecto, quedaría $a=\\frac{dv}{dt}=(2) pies/s^2$.\n\n - ***Segmento 2:*** en el intervalo $10s\\leq t<30s$ la función de velocidad está dada por la ecuación $v=(20)pies/s$, diferenciando esta ecuación respecto al tiempo para determinar la aceleración en ese trayecto, quedaría $a=\\frac{dv}{dt}=(0)pies/s^2$.\n\nSe observa que el primer tramo de la gráfica $a-t$ es una constante de valor $2$, y en el segundo tramo también se tiene una constante, pero de valor cero, $0$.\n \n | \n
| \n View on QuantumAI\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
Given the point $\\mathbf{y}$ (black square) we want to find the $\\mathbf{x}$ along the line that is closest to it. The gray circle is the locus of points within a fixed distance from $\\mathbf{y}$.
\n\n\n\n\n\n**Programming Tip.**\n\n[Figure](#fig:probability_001) uses the `matplotlib.patches` module. This\nmodule contains primitive shapes like circles, ellipses, and rectangles that\ncan be assembled into complex graphics. As shown in the code in the IPython\nNotebook corresponding to this chapter, after importing a particular shape, you\ncan apply that shape to an existing axis using the `add_patch` method. The\npatches themselves can by styled using the usual formatting keywords like\n`color` and `alpha`.\n\n\n\n\n\n\n\nThe closest point on the line occurs when the line is tangent to the circle. When this happens, the black line and the line (minimum distance) are perpedicular.
\n\n\n\n\n\n Now that we can see what's going on, we can construct the the solution\nanalytically. We can represent an arbitrary point along the black line as:\n\n$$\n\\mathbf{x}=\\alpha\\mathbf{v}\n$$\n\n where $\\alpha\\in\\mathbb{R}$ slides the point up and down the line with\n\n$$\n\\mathbf{v} = \\left[ 1,1 \\right]^T\n$$\n\n Formally, $\\mathbf{v}$ is the *subspace* onto which we want to\n*project* $\\mathbf{y}$. At the closest point, the vector between\n$\\mathbf{y}$ and $\\mathbf{x}$ (the *error* vector above) is\nperpedicular to the line. This means that\n\n$$\n(\\mathbf{y}-\\mathbf{x} )^T \\mathbf{v} = 0\n$$\n\n and by substituting and working out the terms, we obtain\n\n$$\n\\alpha = \\frac{\\mathbf{y}^T\\mathbf{v}}{ \\|\\mathbf{v} \\|^2}\n$$\n\n The *error* is the distance between $\\alpha\\mathbf{v}$ and $\n\\mathbf{y}$. This is a right triangle, and we can use the Pythagorean\ntheorem to compute the squared length of this error as\n\n$$\n\\epsilon^2 = \\|( \\mathbf{y}-\\mathbf{x} )\\|^2 = \\|\\mathbf{y}\\|^2 - \\alpha^2 \\|\\mathbf{v}\\|^2 = \\|\\mathbf{y}\\|^2 - \\frac{\\|\\mathbf{y}^T\\mathbf{v}\\|^2}{\\|\\mathbf{v}\\|^2}\n$$\n\n where $ \\|\\mathbf{v}\\|^2 = \\mathbf{v}^T \\mathbf{v} $. Note that since $\\epsilon^2 \\ge 0 $, this also shows that\n\n$$\n\\| \\mathbf{y}^T\\mathbf{v}\\| \\le \\|\\mathbf{y}\\| \\|\\mathbf{v}\\|\n$$\n\n which is the famous and useful Cauchy-Schwarz inequality which we\nwill exploit later. Finally, we can assemble all of this into the *projection*\noperator\n\n$$\n\\mathbf{P}_v = \\frac{1}{\\|\\mathbf{v}\\|^2 } \\mathbf{v v}^T\n$$\n\n With this operator, we can take any $\\mathbf{y}$ and find the closest\npoint on $\\mathbf{v}$ by doing\n\n$$\n\\mathbf{P}_v \\mathbf{y} = \\mathbf{v} \\left( \\frac{ \\mathbf{v}^T \\mathbf{y} }{\\|\\mathbf{v}\\|^2} \\right)\n$$\n\n where we recognize the term in parenthesis as the $\\alpha$ we\ncomputed earlier. It's called an *operator* because it takes a vector\n($\\mathbf{y}$) and produces another vector ($\\alpha\\mathbf{v}$). Thus,\nprojection unifies geometry and optimization.\n\n## Weighted distance\n\nWe can easily extend this projection operator to cases where the measure of\ndistance between $\\mathbf{y}$ and the subspace $\\mathbf{v}$ is weighted. We can\naccommodate these weighted distances by re-writing the projection operator as\n\n\n\n\n$$\n\\begin{equation}\n\\mathbf{P}_v=\\mathbf{v}\\frac{\\mathbf{v}^T\\mathbf{Q}^T}{\\mathbf{v}^T\\mathbf{Q v}}\n\\end{equation}\n\\label{eq:weightedProj} \\tag{1}\n$$\n\n where $\\mathbf{Q}$ is positive definite matrix. In the previous\ncase, we started with a point $\\mathbf{y}$ and inflated a circle centered at\n$\\mathbf{y}$ until it just touched the line defined by $\\mathbf{v}$ and this\npoint was closest point on the line to $\\mathbf{y}$. The same thing happens\nin the general case with a weighted distance except now we inflate an\nellipse, not a circle, until the ellipse touches the line.\n\n\n\n\n\n\n\nIn the weighted case, the closest point on the line is tangent to the ellipse and is still perpedicular in the sense of the weighted distance.
\n\n\n\n\n\nNote that the error vector ($\\mathbf{y}-\\alpha\\mathbf{v}$) in [Figure](#fig:probability_003) is still perpendicular to the line (subspace\n$\\mathbf{v}$), but in the space of the weighted distance. The difference\nbetween the first projection (with the uniform circular distance) and the\ngeneral case (with the elliptical weighted distance) is the inner product\nbetween the two cases. For example, in the first case we have $\\mathbf{y}^T\n\\mathbf{v}$ and in the weighted case we have $\\mathbf{y}^T \\mathbf{Q}^T\n\\mathbf{v}$. To move from the uniform circular case to the weighted ellipsoidal\ncase, all we had to do was change all of the vector inner products. Before we\nfinish, we need a formal property of projections:\n\n$$\n\\mathbf{P}_v \\mathbf{P}_v = \\mathbf{P}_v\n$$\n\n known as the *idempotent* property which basically says that once we\nhave projected onto a subspace, subsequent projections leave us in the\nsame subspace. You can verify this by computing Equation ref{eq:weightedProj}.\n\nThus, projection ties a minimization problem (closest point to a line) to an\nalgebraic concept (inner product). It turns out that these same geometric ideas\nfrom linear algebra [[strang2006linear]](#strang2006linear) can be translated to the conditional\nexpectation. How this works is the subject of our next section.\n", "meta": {"hexsha": "79b3606f6ede7166657e3d2a91106e6b55d316de", "size": 126799, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/probability/notebooks/projection.ipynb", "max_stars_repo_name": "nsydn/Python-for-Probability-Statistics-and-Machine-Learning", "max_stars_repo_head_hexsha": "d3e0f8ea475525a694a975dbfd2bf80bc2967cc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 570, "max_stars_repo_stars_event_min_datetime": "2016-05-05T19:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:09:19.000Z", "max_issues_repo_path": "chapters/probability/notebooks/projection.ipynb", "max_issues_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_issues_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-12T22:18:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-06T14:37:06.000Z", "max_forks_repo_path": "chapters/probability/notebooks/projection.ipynb", "max_forks_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_forks_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276, "max_forks_repo_forks_event_min_datetime": "2016-05-27T01:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:20:27.000Z", "avg_line_length": 364.3649425287, "max_line_length": 114721, "alphanum_fraction": 0.9255199173, "converted": true, "num_tokens": 2225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.1581743587009343, "lm_q1q2_score": 0.06323995213753228}} {"text": "# Longitudinal Data Analysis\n\n\n```stata\n\n```\n\n# Panel Data Analysis III\n\n| '\n html_str += g._repr_svg_()\n html_str += ' | '\n html_str += '
\nq_0: |0>\n\nq_1: |0>\n\n\n\n\n## Qiskit quantum operations summary: \n### https://qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html\n\n\n```python\n# Add a Hadamard gate on qubit 0, putting this in superposition.\nqc.h(0)\n# Add a CX (CNOT) gate on control qubit 0 \n# and target qubit 1 to create an entangled state.\nqc.cx(0, 1)\nqc.draw()\n```\n\n\n\n\n
┌───┐ \nq_0: |0>┤ H ├──■──\n └───┘┌─┴─┐\nq_1: |0>─────┤ X ├\n └───┘\n\n\n\n\n```python\n# Create a classical register with 2 bits\nc = ClassicalRegister(2,'c')\n\nmeas = QuantumCircuit(q,c,name=\"first_m\")\nmeas.barrier(q)\nmeas.measure(q, c)\n\nmeas.draw()\n```\n\n\n\n\n
░ ┌─┐ \nq_0: |0>─░─┤M├───\n ░ └╥┘┌─┐\nq_1: |0>─░──╫─┤M├\n ░ ║ └╥┘\n c_0: 0 ════╩══╬═\n ║ \n c_1: 0 ═══════╩═\n\n\n\n\n\n```python\n# Quantum circuits can be added with + operations\n# Add two pre-defined circuits\nqc_all=qc+meas\nqc_all.draw()\n```\n\n\n\n\n
┌───┐ ░ ┌─┐ \nq_0: |0>┤ H ├──■───░─┤M├───\n └───┘┌─┴─┐ ░ └╥┘┌─┐\nq_1: |0>─────┤ X ├─░──╫─┤M├\n └───┘ ░ ║ └╥┘\n c_0: 0 ══════════════╩══╬═\n ║ \n c_1: 0 ═════════════════╩═\n\n\n\n\n\n```python\n# Draw the quantum circuit in a different (slightly better) format\nqc_all.draw(output='mpl')\n```\n\n\n```python\n# Create the quantum circuit with the measurement in one go.\nqc_all = QuantumCircuit(q,c,name=\"2q_all\")\nqc_all.h(0)\nqc_all.cx(0,1)\nqc_all.barrier()\nqc_all.measure(0,0)\nqc_all.measure(1,1)\nqc_all.draw(output='mpl')\n```\n\n\n```python\n# Use Aer's qasm_simulator\nbackend_q = Aer.get_backend('qasm_simulator')\n\n# Execute the circuit on the qasm simulator.\njob_sim1 = execute(qc_all, backend_q, shots=4096)\n```\n\n\n```python\njob_sim1.status()\n```\n\n\n\n\n
| \n | no | \nyes | \nPr(Ai) | \n
|---|---|---|---|
| sex | \n\n | \n | \n |
| female | \n406 | \n91 | \n0.495513 | \n
| male | \n391 | \n115 | \n0.504487 | \n
| \n | smoker | \nsex | \ncount | \nExpected value | \n(O_ij - E_ij)^2/E_ij | \n
|---|---|---|---|---|---|
| 0 | \nno | \nmale | \n391 | \n402.075773 | \n0.305099 | \n
| 1 | \nyes | \nmale | \n115 | \n103.924227 | \n1.180406 | \n
| 2 | \nno | \nfemale | \n406 | \n394.924227 | \n0.310623 | \n
| 3 | \nyes | \nfemale | \n91 | \n102.075773 | \n1.201781 | \n
\n \n
\n\n\n```python\n# Example : Dot Product\n\nA = [1.0, 3.0, -5.0]\nB = [4.0, -2.0, -1.0]\n\n# Create a variable called dot_product with value, 0.0\ndot_product = 0.0\n\n# Update the value each time the code loops\nfor a , b in zip(A, B):\n dot_product += a * b\n\n# Print the solution\nprint(dot_product)\n```\n\n 3.0\n\n\n(Solution in 02_DataStructures_LibraryFunctions_SOLS.ipynb)\n\n__Check Your Solution:__ \n\nThe dot product $\\mathbf{A} \\cdot \\mathbf{B}$:\n| \n View on QuantumAI\n | \n\n Run in Google Colab\n | \n\n View source on GitHub\n | \n\n Download notebook\n | \n
| \n | train_precision@1 | \ntrain_recall@1 | \ntrain_f1@1 | \ntest_precision@1 | \ntest_recall@1 | \ntest_f1@1 | \ndsub | \nfile_size | \n
|---|---|---|---|---|---|---|---|---|
| 0 | \n0.638 | \n0.277 | \n0.386 | \n0.489 | \n0.211 | \n0.295 | \n-1 | \n5143093 | \n
| 1 | \n0.638 | \n0.277 | \n0.386 | \n0.487 | \n0.210 | \n0.294 | \n2 | \n1181690 | \n
| 2 | \n0.630 | \n0.274 | \n0.381 | \n0.483 | \n0.209 | \n0.291 | \n4 | \n891770 | \n
| 3 | \n0.587 | \n0.255 | \n0.355 | \n0.470 | \n0.203 | \n0.283 | \n8 | \n746810 | \n
| Planet | Mass in kg | Distance to sun in AU |
|---|---|---|
| Earth | $M_{\\mathrm{Earth}}=6\\times 10^{24}$ kg | 1AU |
| Jupiter | $M_{\\mathrm{Jupiter}}=1.9\\times 10^{27}$ kg | 5.20 AU |
| Mars | $M_{\\mathrm{Mars}}=6.6\\times 10^{23}$ kg | 1.52 AU |
| Venus | $M_{\\mathrm{Venus}}=4.9\\times 10^{24}$ kg | 0.72 AU |
| Saturn | $M_{\\mathrm{Saturn}}=5.5\\times 10^{26}$ kg | 9.54 AU |
| Mercury | $M_{\\mathrm{Mercury}}=3.3\\times 10^{23}$ kg | 0.39 AU |
| Uranus | $M_{\\mathrm{Uranus}}=8.8\\times 10^{25}$ kg | 19.19 AU |
| Neptun | $M_{\\mathrm{Neptun}}=1.03\\times 10^{26}$ kg | 30.06 AU |
| Pluto | $M_{\\mathrm{Pluto}}=1.31\\times 10^{22}$ kg | 39.53 AU |
| 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}$ |
| $M$ | $M_s$ | $\\alpha$ | State |
|---|---|---|---|
| -2 | 0 | 1 | $\\vert 3,2\\rangle$ |
| -1 | -1 | 3 | $\\vert 2,0\\rangle$ |
| -1 | 0 | 4 | $\\vert 3,0\\rangle$ |
| -1 | 0 | 4 | $\\vert 2,1\\rangle$ |
| -1 | 1 | 5 | $\\vert 3,1\\rangle$ |
| 0 | -1 | 6 | $\\vert 4,2\\rangle$ |
| 0 | 0 | 7 | $\\vert 1,0\\rangle$ |
| 0 | 0 | 7 | $\\vert 5,2\\rangle$ |
| 0 | 0 | 7 | $\\vert 4,3\\rangle$ |
| 0 | 1 | 8 | $\\vert 5,3\\rangle$ |
| 1 | -1 | 9 | $\\vert 4,0\\rangle$ |
| 1 | 0 | 10 | $\\vert 5,0\\rangle$ |
| 1 | 0 | 10 | $\\vert 4,1\\rangle$ |
| 1 | 1 | 11 | $\\vert 5,1\\rangle$ |
| 2 | 0 | 13 | $\\vert 5,4\\rangle$ |
| $R$ | $E_0^{HF}$ |
|---|---|
| 3 | 21.59320 |
| 4 | 20.76692 |
| 5 | 20.7484 |
| 6 | 20.72026 |
| 7 | 20.72013 |
| 8 | 20.71925 |
| 9 | 20.71925 |
| 10 | 20.71922 |
| 11 | 20.71922 |
| 12 | 20.71922 |
| 13 | 20.71922 |
| $R$ | $E_0^{HF}$ |
|---|---|
| 4 | 4.01979 |
| 5 | 3.96315 |
| 6 | 3.87062 |
| 7 | 3.86314 |
| 8 | 3.85288 |
| 9 | 3.85259 |
| 10 | 3.85239 |
| 11 | 3.85239 |
| 12 | 3.85238 |
| 13 | 3.85238 |
| type | test data | B_W | bilge keel | publish geom | publish test | |
|---|---|---|---|---|---|---|
| KVLCC2 | \ntanker | \nTrue | \nsmall | \nFalse | \nTrue | \nTrue | \n
| DTC | \ncontainer | \nTrue | \n? | \n? | \nTrue | \nTrue | \n
| Wallenius | \nPCTC | \nTrue | \nmedium | \nTrue | \nFalse | \nTrue | \n
| \n | account_age | \nage | \navg_hours | \ndays_visited | \nfriends_count | \nhas_membership | \nis_US | \nsongs_purchased | \nincome | \nprice | \ndemand | \n
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n3 | \n53 | \n1.834234 | \n2 | \n8 | \n1 | \n1 | \n4.903237 | \n0.960863 | \n1.0 | \n3.917117 | \n
| 1 | \n5 | \n54 | \n7.171411 | \n7 | \n9 | \n0 | \n1 | \n3.330161 | \n0.732487 | \n1.0 | \n11.585706 | \n
| 2 | \n3 | \n33 | \n5.351920 | \n6 | \n9 | \n0 | \n1 | \n3.036203 | \n1.130937 | \n1.0 | \n24.675960 | \n
| 3 | \n2 | \n34 | \n6.723551 | \n0 | \n8 | \n0 | \n1 | \n7.911926 | \n0.929197 | \n1.0 | \n6.361776 | \n
| 4 | \n4 | \n30 | \n2.448247 | \n5 | \n8 | \n1 | \n0 | \n7.148967 | \n0.533527 | \n0.8 | \n12.624123 | \n
| \n | project_number | \nseries_number | \nrun_number | \ntest_number | \nmodel_number | \nship_name | \nloading_condition_id | \nascii_name | \nship_speed | \ncomment | \nfile_path_ascii | \nfile_path_ascii_temp | \nfile_path_log | \nfile_path_hdf5 | \ndate | \ntest_type | \nfacility | \nangle1 | \nangle2 | \nKörfallstyp | \nname | \nlcg | \nkg | \ngm | \nCW | \nTF | \nTA | \nBWL | \nKXX | \nKZZ | \nBTT1 | \nCP | \nVolume | \nA0 | \nRH | \nscale_factor | \nlpp | \nbeam | \nABULB | \nBKX | \nTWIN | \nDCLR | \nVDES | \nRHBL | \nASKEG | \nPD | \nARH | \nCFP | \nAIX | \nPDTDES | \nRTYPE | \nSFP | \nBKL | \nBKB | \nPROT | \nD | \nLSKEG | \nRR | \nXSKEG | \nNDES | \nAR | \nBR | \nBRA | \nIRUD | \nPTYPE | \nXRUD | \nAI | \nHSKEG | \nRSKEG | \nLOA | \nship_type_id | \nrho | \ng | \n
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| id | \n\n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n | \n |
| 21337 | \n40178362 | \n1 | \n94 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n94.0 | \nNaN | \nRoll decay, 0 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-04-03 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n1000 | \n9.81 | \n
| 21338 | \n40178362 | \n1 | \n95 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n95.0 | \nNaN | \nRoll decay, 0 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-04-03 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n1000 | \n9.81 | \n
| 21339 | \n40178362 | \n1 | \n96 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n96.0 | \nNaN | \nRoll decay, 0 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-11-28 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n1000 | \n9.81 | \n
| 21340 | \n40178362 | \n1 | \n97 | \n1 | \nM5057-01-A | \nM5057-01-A | \n166 | \n97.0 | \n15.5 | \nRoll decay, 15.5 kn | \nNaN | \nNone | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00... | \n2018-04-04 | \nroll decay | \nMDL | \nNone | \nNone | \nNone | \n20.8 | \n11.2672 | \n18.6 | \n5.73 | \nNone | \n20.8 | \n20.8 | \nNone | \n23.2 | \n80.0 | \nNone | \nNone | \n312653.0 | \n0.99538 | \nNone | \n68.0 | \n320.0 | \n58.0 | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \nNone | \n1000 | \n9.81 | \n
| \n | x | \ny | \nz | \n
|---|---|---|---|
| count | \n7140.000000 | \n7140.000000 | \n7.140000e+03 | \n
| mean | \n157.454893 | \n17.750299 | \n7.740190e+00 | \n
| std | \n110.633263 | \n10.884987 | \n9.114148e+00 | \n
| min | \n-5.495000 | \n-0.000173 | \n-2.220446e-16 | \n
| 25% | \n48.179054 | \n6.451813 | \n8.789816e-01 | \n
| 50% | \n153.290740 | \n22.257320 | \n3.160564e+00 | \n
| 75% | \n264.429320 | \n27.889503 | \n1.273352e+01 | \n
| max | \n327.995000 | \n29.000004 | \n4.000111e+01 | \n
| \n | y | \nz | \nx | \nno | \n
|---|---|---|---|---|
| 0 | \n-9.001914e-15 | \n18.80 | \n-5.495 | \n0 | \n
| 1 | \n0.000000e+00 | \n20.80 | \n-5.495 | \n0 | \n
| 2 | \n5.819288e+00 | \n20.80 | \n-5.495 | \n0 | \n
| 3 | \n5.819288e+00 | \n20.75 | \n-5.495 | \n0 | \n
| 4 | \n5.198539e+00 | \n20.43 | \n-5.495 | \n0 | \n
| \n | area | \nx | \nt | \nb | \nr_b | \n
|---|---|---|---|---|---|
| no | \n\n | \n | \n | \n | \n |
| 0 | \n13.826612 | \n-5.495000 | \n2.00 | \n11.638577 | \n6.636080 | \n
| 1 | \n123.851306 | \n10.159932 | \n18.25 | \n27.893522 | \n42.367175 | \n
| 2 | \n428.211409 | \n28.051284 | \n20.80 | \n41.824284 | \n45.369454 | \n
| 3 | \n683.709165 | \n43.706216 | \n20.80 | \n50.282514 | \n41.080696 | \n
| 4 | \n917.895066 | \n61.597568 | \n20.80 | \n56.159232 | \n34.146143 | \n
| 5 | \n1056.860933 | \n77.252500 | \n20.80 | \n57.870498 | \n26.158540 | \n
| 6 | \n1139.503552 | \n92.907432 | \n20.80 | \n58.000008 | \n17.655717 | \n
| 7 | \n1186.852794 | \n110.798780 | \n20.80 | \n58.000008 | \n9.543935 | \n
| 8 | \n1203.217372 | \n126.453720 | \n20.80 | \n58.000008 | \n3.851125 | \n
| 9 | \n1203.929931 | \n144.345070 | \n20.80 | \n58.000008 | \n3.392755 | \n
| 10 | \n1203.929195 | \n160.000000 | \n20.80 | \n58.000008 | \n3.393260 | \n
| 11 | \n1203.928607 | \n175.891420 | \n20.80 | \n58.000008 | \n3.393664 | \n
| 12 | \n1203.929195 | \n194.053040 | \n20.80 | \n58.000008 | \n3.393260 | \n
| 13 | \n1203.929195 | \n209.944460 | \n20.80 | \n58.000008 | \n3.393260 | \n
| 14 | \n1203.906161 | \n225.835880 | \n20.80 | \n58.000008 | \n3.409039 | \n
| 15 | \n1195.569763 | \n243.997500 | \n20.80 | \n57.987376 | \n7.017342 | \n
| 16 | \n1159.988460 | \n259.888920 | \n20.80 | \n57.487792 | \n12.908255 | \n
| 17 | \n1077.577243 | \n275.780340 | \n20.80 | \n55.361310 | \n18.561674 | \n
| 18 | \n899.155097 | \n291.671760 | \n20.80 | \n48.130896 | \n21.797880 | \n
| 19 | \n502.526691 | \n309.833380 | \n20.80 | \n28.203708 | \n19.797403 | \n
| 20 | \n43.489245 | \n325.724800 | \n16.18 | \n5.709535 | \n15.093775 | \n
A measure that combines all thresholds is the **Area Under the ROC Curve (AUC)**
\n