{"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": "
Link Github
\n\n\n\n\n\n
\n

Resúmen Teórico de Medidas Electrónicas 1

\n

Incertidumbre

\n

Liaño, Lucas

\n
\n\n\n\n# Contenidos\n\n- **Introducción**\n- **Marco Teórico**\n - Conceptos Básicos Metrología\n - ¿Qué es la incertidumbre?\n - Modelo matemático de una medición ($Y$)\n - Evaluación incertidumbre Tipo A\n - Evaluación incertidumbre Tipo B\n - Incertidumbre Conjunta\n - Grado de Confianza\n - Caso de análisis: $u_{i}(x_{i}) \\gg u_{j}(X_{i})$\n - Caso de análisis: $u_{i}(x_{i}) \\ll u_{j}(X_{i})$\n - Correlación\n \n- **Experimentación**\n - Caso General\n - Caso Incertidumbre tipo A dominante\n - Caso Incertidumbre tipo B dominante\n - Ejemplo Correlación\n- **Bibliografía**\n***\n \n# Introducción \n\nEl objetivo del presente documento es de resumir, al mismo tiempo que simular, los contenidos teóricos correspondientes a la unidad N°1 de la materia medidas 1. Para ello, utilizaremos los recursos disponibles en el drive de la materia.\n\n
\n Link: https://drive.google.com/folderview?id=1p1eVB4UoS0C-5gyienup-XiewKsTpcNc\n
\n\n***\n\n\n# Marco Teórico\n\n## Conceptos Básicos Metrología\n\nLa de medición de una magnitud física, atributo de un cuerpo mensurable, consiste en el proceso mediante el cual se da a conocer el valor de dicha magnitud. A lo largo de la historia se han desarrollado diversos modelos de medición, todos ellos consisten en la comparación de la magnitud contra un patrón.\n\nA su vez, a medida que se fueron confeccionando mejores métodos de medición, se empezó a tener en consideración el error en la medida. Este error consiste en una indicación cuantitativa de la calidad del resultado. Valor que demuestra la confiabilidad del proceso.\n\nActualmente, definimos al **resultado de una medición** como al conjunto de valores de una magnitud, atribuidos a un mensurando. Se puede definir a partir de una función distribución densidad de probabilidad (también denomidada _pdf_, de la sígla inglesa _probability density function_). El resultado de una medición está caracterizado por la media de la muestra, la incertidumbre y el grado de confianza de la medida.\n\nDenominaremos **incertidumbre de una medición** al parámetro asociado con el resultado de la medición que caracteríza la dispersión de los valores atribuidos a un mensurando. Mientras que el **error de medida** será la diferencia entre el valor medido con un valor de referencia. [[1]](http://depa.fquim.unam.mx/amyd/archivero/CALCULODEINCERTIDUMBRESDR.JAVIERMIRANDA_26197.pdf)\n\n#### Tipos de errores\n\nExisten dos tipos:\n\n> **Error sistemático:** Componente del error que en repetidas mediciones permanece constante.\n\n> **Error aleatorio:** Componente del error que en repetidas mediciones varía de manera impredecible.\n\n***\n## ¿Qué es la incertidumbre?\n\nComo bien definimos anteriormente, la incertidumbre es un parámetro que caracteríza la dispersión de los valores atribuidos a un mensurando. Esto significa que, considerando al resultado de la medición como una función distribución densidad de probabilidad, la incertidumbre representa el desvío estándar de la misma. Se suele denominar **incertidumbre estándar** a dicha expresión de la incertidumbre.\n\n#### Componentes de la incertidumbre\n\n> **Tipo A:** Componente de la incertidumbre descripta únicamente a partir del estudio estadístico de las muestras.\n\n> **Tipo B:** Componente de la incertidumbre descripta a partir de las hojas de datos previstas por los fabricantes de los instrumentos de medición, junto con datos de calibración.\n\nEn las próximas secciones se describe en detalle como son los test efectuados para determinar cada una de las componentes. [[2]](https://es.wikipedia.org/wiki/Propagaci%C3%B3n_de_errores)\n\n***\n## Modelo matemático de una medición ($Y$)\n\nSupongamos una magnitud a mensurar ($Y$), la cual se va a estimar de forma indirecta a partir de una relación fundamental con otras $N$ magnitudes mensurables, de manera que se cumple:\n\n\\begin{equation}\n Y = f(x_{1},x_{2},...,x_{N})\n\\end{equation}\n\nComo definimos previamente, las variables $x_{i}$ son funciones distribución densidad de probabilidad por ser resultados de mediciones. Cada una de estas mediciones viene determinada, idealmente, por el valor de su media ($\\mu_{X_{i}}$), su desvío estándar ($\\sigma_{x_{i}}$) y el grado de confianza de la medición. Dado que en la vida real no es posible conseguir una estimación lo suficientemente buena de estos parámetros, se utilizarán sus estimadores en su lugar.\n\n\nPor tanto, si se tomaron $M$ muestras de cada una de estas variables, podemos utilizar la **media poblacional ($\\bar{Y}$)** como estimador de la media ($\\mu_{Y}$) de la distribución densidad de probabilidad de la medición como:\n\n\\begin{equation}\n \\hat{Y} = \\bar{Y} = \\frac{1}{M} \\sum_{k=0}^{M} f_{k}(x_{1},x_{2},...,x_{N}) = f(\\bar{X_{1}},\\bar{X_{2}},...,\\bar{X_{N}})\n\\end{equation}\n\n
\n Verificar que esto este bien. Sospecho que no porque estamos suponiendo que podes aplicar linealidad adentro de la función. Estoy leyendo el ejemplo del calculo de resistencia y hacemos \"resistencia= (media_V/media_I)\" en la línea 39 del documento compartido en el canal general de Slack. \n
\n\nAsimismo, para determinar el otro parámetro fundamental de la medición (la incertidumbre) utilizaremos como estimador a la **incertidumbre combinada ($u_{c}$)** definida a partir de la siguiente ecuación,\n\n\\begin{equation}\n u_{c}^{2}(Y) = \\sum_{i=1}^{N} (\\dfrac{\\partial f}{\\partial x_{i}})^{2} \\cdot u_{c}^{2}(x_{i}) + 2 \\sum_{i=1}^{N-1} \\sum_{j = i+1}^{N} \\dfrac{\\partial f}{\\partial x_{i}} \\dfrac{\\partial f}{\\partial x_{j}} u(x_{i},x_{j})\n\\end{equation}\n\ndonde $u(x_{i},x_{j})$ es la expresión de la covariancia entre las pdf de las $x_{i}$.\n\nEsta expresión, para permitir el uso de funciones $f_{k}$ no lineales, es la aproximación por serie de Taylor de primer orden de la expresión original para funciones que cumplen linealidad. [[2]](https://es.wikipedia.org/wiki/Propagaci%C3%B3n_de_errores)\n\nA su vez, a partir de la **ley de propagación de incertidumbres**, podemos decir que para la determinación de una variable unitaria mediante medición directa es posible reducir la expresión anterior a la siguiente:\n\n\\begin{equation}\n u_{c}^{2}(x_{i}) = u_{i}^{2}(x_{i}) + u_{j}^{2}(x_{i}) \n\\end{equation}\n\ndonde denominaremos $u_{i}(x_{i})$ a la incertidumbre tipo A, y $u_{j}(x_{i})$ a la incertidumbre tipo B.\n\n***\n## Evaluación incertidumbre Tipo A\n\nLa incertidumbre tipo A, recordando que se trata de una medida de dispersión y al ser tipo A se relaciona con la estadística de las muestras, se puede estimar con el desvío estándar experimental de la media ($S(\\bar{X_{i}})$). Para ello hace falta recordar algunos conceptos de estadística.\n\nSuponiendo que se toman $N$ muestras:\n\n> **Estimador media poblacional:**\n>> $\\hat{x_{i}}=\\bar{X_{i}}=\\dfrac{1}{N} \\sum_{k=1}^{N}x_{i,k}$\n\n> **Grados de libertad:**\n>> $\\nu = N-1$\n\n> **Varianza experimental de las observaciones:**\n>> $\\hat{\\sigma^{2}(X_{i})}=S^{2}(X_{i})=\\dfrac{1}{\\nu} \\sum_{k=1}^{N}(X_{i,k} - \\bar{X_{i}})^{2}$\n\n> **Varianza experimental de la media:**\n>> $\\hat{\\sigma^{2}(\\bar{X_{i}})}=S^{2}(\\bar{X_{i}})=\\dfrac{S^{2}(x_{i})}{N}$\n\n\n\n\n
\n Por ende, la componente de la incertidumbre tipo A nos queda:\n \n\\begin{equation}\n u_{i}(x_{i}) = \\sqrt{S^{2}(\\bar{X_{i}})}\n\\end{equation}\n
\n\n
\n Nota: Para calcular el std con un divisor de $\\nu = N-1$ es necesario modificar un argumento en la función de python. El comando correctamente utilizado es: 'myVars.std(ddof=1)'.\n \n
\n\n\n***\n## Evaluación incertidumbre Tipo B\n\nLa incertidumbre tipo B viene determinada por la información que proveen los fabricantes de los instrumentos de medición, asi como también por los datos resultantes por la calibración de los mismos.\n\nEn estos instrumentos de medición la incertidumbre viene descripta en forma de distribuciones densidad de probabilidad, no en forma estadística. Para ello utilizamos los siguientes estadísticos que caracterízan a las variables aleatorias, en caso de que su dominio fuera continuo:\n\n> **Esperanza:**\n>> $E(x)=\\int x.f(x)dx$\n\n> **Varianza:**\n>> $V(x)=\\int x^{2}.f(x)dx$\n\n\n
\n Por tanto, si la incertidumbre es un parámetro de dispersión, la misma vendrá descripta por la expresión:\n \n\\begin{equation}\n u_{j}(x_{i}) = \\sqrt{V(x)}\n\\end{equation}\n
\n\nPor simplicidad a la hora de trabajar, a continuación se presenta una tabla con los valores típicos del desvío estándar para el caso de distintas distribuciones. Se demuestra el caso de distribución uniforme.\n\n\n\nSuponiendo que la distribución esta centrada en $\\bar{X_{i}}$, nos quedaría que $a = \\bar{X_{i}} - \\Delta X$ y $b = \\bar{X_{i}} - \\Delta X$. \n\nPor tanto si la expresión de la varianza es $V(x_{i}) = \\frac{(b-a)^{2}}{12}$, finalmente quedaría:\n\n\\begin{equation}\n V(x_{i}) = \\frac{(b-a)^{2}}{12} = \\frac{(2 \\Delta X)^{2}}{12} = \\frac{4 \\Delta X^{2}}{12} = \\frac{\\Delta X^{2}}{3}\n\\end{equation}\n\n\\begin{equation}\n \\sigma_{x_{i}} = \\frac{\\Delta X}{\\sqrt{3}}\n\\end{equation}\n\nFinalmente la tabla queda,\n\n| Distribution | $u_{j}(x_{i}) = \\sigma_{x_{i}}$|\n| :----: | :----: |\n| Uniforme | $\\frac{\\Delta X}{\\sqrt{3}}$ |\n| Normal | $\\Delta X $ |\n| Normal ($K=2$) | $\\frac{\\Delta X}{2} $ |\n| Triangular | $\\frac{\\Delta X}{\\sqrt{6}}$ |\n| U | $\\frac{\\Delta X}{\\sqrt{2}}$ |\n\n
\n Verificar que esto este bien. Me genera dudas el término $\\Delta X$. Esto no creo que deba ser así porque en el caso de la distribución normal $\\sigma_{x_{i}} = \\sigma$. No creo que deba aparecer ningun error absoluto ahí.\n
\n\n***\n## Incertidumbre Conjunta\n\nComo definimos anteriormente, la incertidumbre conjunta queda definida como:\n\n\\begin{equation}\n u_{c}^{2}(x_{i}) = u_{i}^{2}(x_{i}) + u_{j}^{2}(x_{i}) \n\\end{equation}\n\n#### ¿Qué función distribución densidad de probabilidad tiene $u_{c}$?\n\nSi se conocen $x_{1},x_{2},...,x_{N}$ y $Y$ es una combinación lineal de $x_{i}$ (o en su defecto una aproximación lineal, como en el caso del polinomio de taylor de primer grado de la función), podemos conocer la función distribución densidad de probabilidad a partir de la convolución de las $x_{i}$, al igual que se hace para SLIT. [[3]](https://es.wikipedia.org/wiki/Convoluci%C3%B3n)\n\nDado que habitualmente no se conoce con precisión la función distribución densidad de probabilidad de $u_{i}(x_{i})$, se suele utilizar el **teorema central del límite** para conocer $u_{c}(x_{i})$. El mismo plantea que cuantas más funciones $x_{i}$ con función distribución densidad de probabilidad deconocida sumemos, más va a tender su resultado a una distribución normal.\n\n***\n## Grado de Confianza\n\nFinalmente, el último parámetro que nos interesa conocer para determinar el resultado de la medición es el grado de confianza.\n\n> **Grado de confianza:** Es la probabilidad de que al evaluar nuevamente la media poblacional ($\\bar{y}$) nos encontremos con un valor dentro del intervalo $[\\bar{Y} - K.\\sigma_{Y}(\\bar{Y}) \\le \\mu_{Y} \\le \\bar{Y} - K.\\sigma_{Y}(\\bar{Y})]$ para el caso de una distribución que cumpla el teorema central del límite, donde $K$ es el factor de cobertura.\n\nOtra forma de verlo es:\n\n\n\ndonde el grado de confianza viene representado por $(1-\\alpha)$. Recomiendo ver el ejemplo [[4]](https://es.wikipedia.org/wiki/Intervalo_de_confianza#Ejemplo_pr%C3%A1ctico) en caso de no entender lo que representa.\n\nDe esta forma, el factor de cobertura ($K$) nos permite modificar el grado de confianza. Agrandar $K$ aumentará el área bajo la curva de la gaussiana, lo que representará un mayor grado de confianza. \n\nSe definirá **incertidumbre expandida** a $U(x_{i}) = K \\cdot u_{c}(x_{i})$ si $u_{c}(x_{i})$ es la incertidumbre que nos proveé un grado de confianza de aproximadamente $ 68\\% $.\n\nPara una función que distribuye como normal podemos estimar el grado de confianza mediante la siguiente tabla,\n\n| Factor de cobertura | Grado de confianza|\n| :----: | :----: |\n| $K=1$ | $68.26\\% $ |\n| $K=2$ | $95.44\\% $ |\n| $K=3$ | $99.74\\% $ |\n\n\n#### ¿Qué sucede si $u_{c}$ no distribuye normalmente?\n\nEn este caso también se podrá utilizar la ecuación $U(x_{i}) = K \\cdot u_{c}(x_{i})$, pero el método mediante el cual obtendremos a $K$ será distinto.\n\n***\n## Caso de análisis: $u_{i}(x_{i}) \\gg u_{j}(X_{i})$\n\nCuando sucede que la incertidumbre que proveé la evaluación tipo A es muy significativa frente a la tipo B, esto querrá decir que no tenemos suficientes grados de libertad para que $u_{c}(x_{i})$ se aproxime a una gaussiana. En otras palabras, la muestra obtenida no es significativa.\n\nEn estos casos vamos a suponer que $u_{c}(x_{i})$ distribuye como t-Student. La distribución t-Student surge justamente del problema de estimar la media de una población normalmente distribuida cuando el tamaño de la muestra es pequeño.\n\nComo la distribución de t-Student tiene como parámetro los grados de libertad efectivos, debemos calcularlos. Para ello utilizaremos la fórmula de Welch-Satterthwaite:\n\n\\begin{equation}\n \\nu_{eff} = \\dfrac{u_{c}^{4}(y)}{\\sum_{i=1}^{N} \\dfrac{ c_{i}^{4} u^{4}(x_{i})} {\\nu_{i}} } \n\\end{equation}\n\n\ndonde $c_i = \\dfrac{\\partial f}{\\partial x_{i}}$ y $u_{i}(x_{i})$ es la incertidumbre tipo A.\n\n\n\nPara obtener el factor de cobertura que nos asegure un factor de cobertura del $95/%$ debemos recurrir a la tabla del t-Student. Para ello existe una función dentro del módulo _scipy.stats_ que nos integra la función hasta lograr un área del $95.4%$.\n\nA continuación presentamos la función que utilizaremos con dicho fin,\n\n~~~\ndef get_factor_Tstudent(V_eff, porcentaje_confianza_objetivo=95.4):\n \"\"\"\n Funcion de calculo de factor de expansión por T-student\n input:\n V_eff: Grados de libertad (float)\n porcentaje_confianza_objetivo: porcentaje_confianza_objetivo (float)\n returns: \n Factor de expansión (float)\n \"\"\"\n return np.abs( -(stats.t.ppf((1.0+(porcentaje_confianza_objetivo/100))/2.0,V_eff)) )\n~~~\n\n\n***\n## Caso de análisis: $u_{i}(x_{i}) \\ll u_{j}(X_{i})~$\n\nPara el caso en el que la incertidumbre del muestreo es muy inferior a la incertidumbre tipo B, nos encontramos frente al caso de incertidumbre B dominante. Esta situación es equivalente a tener la convolución entre una delta de dirac con una función de distribución cualquiera. \n\n\n\n\nComo observamos en la imagen, la función distribución densidad de probabilidad resultate se asemeja más a la distribución uniforme del tipo B. En este caso para encontrar el factor de cobertura utilizaremos otra tabla distinta. En esta tabla el parámetro de entrada es el cociente $\\dfrac{u_{i}}{u_{j}}$.\n\nA continuación presentamos la función que utilizaremos con dicho fin,\n\n~~~\ndef tabla_B(arg):\n tabla_tipoB = np.array([\n [0.0, 1.65],\n [0.1, 1.66],\n [0.15, 1.68],\n [0.20, 1.70],\n [0.25, 1.72],\n [0.30, 1.75],\n [0.35, 1.77],\n [0.40, 1.79],\n [0.45, 1.82],\n [0.50, 1.84],\n [0.55, 1.85],\n [0.60, 1.87],\n [0.65, 1.89],\n [0.70, 1.90],\n [0.75, 1.91],\n [0.80, 1.92],\n [0.85, 1.93],\n [0.90, 1.94],\n [0.95, 1.95],\n [1.00, 1.95],\n [1.10, 1.96],\n [1.20, 1.97],\n [1.40, 1.98],\n [1.80, 1.99],\n [1.90, 1.99]])\n if arg >= 2.0:\n K = 2.0\n else:\n pos_min = np.argmin(np.abs(tabla_tipoB[:,0]-arg)) \n K = tabla_tipoB[pos_min,1]\n\n return K\n~~~\n\n\n***\n## Correlación\n\nFinalmente nos encontramos con el caso mas general. En esta situación las variables se encuentran correlacionadas, por lo que la expresión de $u_{c}(Y)$ debe utilizarse en su totalidad.\n\nPor simplicidad de computo vamos a definir al coeficiente correlación como,\n\n\\begin{equation}\n r(q,w) = \\dfrac{ u(q,w) }{ u(q)u(w) }\n\\end{equation}\n\nDe esta forma podemos expresar a $u_{c}$ como:\n\n\\begin{equation}\n u_{c}^{2}(Y) = \\sum_{i=1}^{N} (\\dfrac{\\partial f}{\\partial x_{i}})^{2} \\cdot u_{c}^{2}(x_{i}) + 2 \\sum_{i=1}^{N-1} \\sum_{j = i+1}^{N} \\dfrac{\\partial f}{\\partial x_{i}} \\dfrac{\\partial f}{\\partial x_{j}} r(x_{i},x_{j})u(x_{i})u(x_{j})\n\\end{equation}\n\nEsta expresión debe utilizarse cada vez que $r(x_{i},x_{j}) \\ne 0$.\n\n# Experimentación\n**Comenzamos inicializando los módulos necesarios**\n\n\n```python\n# módulos genericos\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfrom scipy import signal\n\n# Módulos para Jupyter (mejores graficos!)\nimport warnings\nwarnings.filterwarnings('ignore')\nplt.rcParams['figure.figsize'] = [12, 4]\nplt.rcParams['figure.dpi'] = 150 # 200 e.g. is really fine, but slower\n\n\nfrom pandas import DataFrame\nfrom IPython.display import HTML\n```\n\n**Definimos las funciones previamente mencionadas**\n\n\n```python\nAhora# Tabla para el caso A dominante\ndef get_factor_Tstudent(V_eff, porcentaje_confianza_objetivo=95.4):\n \"\"\"\n Funcion de calculo de factor de expansión por T-student\n input:\n V_eff: Grados de libertad (float)\n porcentaje_confianza_objetivo: porcentaje_confianza_objetivo (float)\n returns: .libertad efectivosdenoted\n Factor de expansión (float)\n \"\"\"\n return np.abs( -(stats.t.ppf((1.0+(porcentaje_confianza_objetivo/100))/2.0,V_eff)) )\n\n# Tabla para el caso B dominante\ndef tabla_B(arg):\n tabla_tipoB = np.array([\n [0.0, 1.65],\n [0.1, 1.66],\n [0.15, 1.68],\n [0.20, 1.70],\n [0.25, 1.72],\n [0.30, 1.75],\n [0.35, 1.77],\n [0.40, 1.79],\n [0.45, 1.82],\n [0.50, 1.84],\n [0.55, 1.85],\n [0.60, 1.87],\n [0.65, 1.89],\n [0.70, 1.90],\n [0.75, 1.91],\n [0.80, 1.92],\n [0.85, 1.93],\n [0.90, 1.94],\n [0.95, 1.95],\n [1.00, 1.95],\n [1.10, 1.96],\n [1.20, 1.97],\n [1.40, 1.98],\n [1.80, 1.99],\n [1.90, 1.99]])\n if arg >= 2.0:\n K = 2.0\n else:\n pos_min = np.argmin(np.abs(tabla_tipoB[:,0]-arg)) \n K = tabla_tipoB[pos_min,1]\n\n return K\n```\n\n## Caso general\n**Definimos las constantes necesarias**\n\n\n```python\n# Constantes del instrumento\nCONST_ERROR_PORCENTUAL = 0.5 # Error porcentual del instrumento de medición\nCONST_ERROR_CUENTA = 3 # Error en cuentas del instrumento de medición\nCONST_DECIMALES = 2 # Cantidad de decimales que representa el instrumento\n\n# Constantes del muestro\nN = 10 # Cantidad de muestras tomadas\n\n# Señal a muestrear idealizada\nmu = 100 # Valor medio de la distribución normal de la población ideal\nstd = 2 # Desvío estándar de la distribución normal de la población ideal\n\n# Muestreo mi señal ideal (Normal)\nmuestra = np.random.randn(N) * std + mu\n```\n\n**Ahora solamente genero un gráfico que compare el histograma con la distribución normal de fondo**\n\n\n```python\nnum_bins = 50\nfig, ax = plt.subplots()\n# the histogram of the 1.1data\nn, bins, patches = ax.hist(muestra, num_bins, density=True)\n# add a 'best fit' line\ny = ((1 / (np.sqrt(2 * np.pi) * std)) *\n np.exp(-0.5 * (1 / std * (bins - mu))**2))\nax.plot(bins, y, '--')\nax.set_xlabel('Smarts')\nax.set_ylabel('Probability density')\nax.set_title('Histogram of IQ: $\\mu=$'+ str(mu) + ', $\\sigma=$' + str(std))\n# Tweak spacing to prevent clipping of ylabel\nfig.tight_layout()\nplt.show()\n```\n\n\n```python\nmedia = np.round(muestra.mean(), CONST_DECIMALES) # Redondeamos los decimales a los valores que puede ver el tester\ndesvio = muestra.std(ddof=1)\n\nprint(\"Mean:\",media )\nprint(\"STD:\" ,desvio)\n```\n\n Mean: 99.29\n STD: 1.6777655348895033\n\n\n**Calculamos el desvío estándar experimental de la media como:**\n\\begin{equation}\n u_{i}(x_{i}) = \\sqrt{S^{2}(\\bar{X_{i}})}\n\\end{equation}\n\n\n```python\n#Incertidumbre Tipo A\nui = desvio/np.sqrt(N)\nui\n```\n\n\n\n\n 0.5305560469981527\n\n\n\n**Calculamos el error porcentual total del dispositivo de medición como:**\n\\begin{equation}\n e_{\\%T} = e_{\\%} + \\dfrac{e_{cuenta}\\cdot 100\\%}{\\bar{X_{i}}(10^{cte_{Decimales}})}\n\\end{equation}\n\n\n```python\n#Incertidumbre Tipo B\nERROR_PORCENTUAL_CUENTA = (CONST_ERROR_CUENTA*100)/(media * (10**CONST_DECIMALES ))\n\nERROR_PORCENTUAL_TOTAL = CONST_ERROR_PORCENTUAL + ERROR_PORCENTUAL_CUENTA\n\nERROR_PORCENTUAL_CUENTA\n```\n\n\n\n\n 0.030214523114110183\n\n\n\n**Por tanto el error absoluto se representa como:**\n\\begin{equation}\n \\Delta X = e_{\\%T} \\dfrac{\\bar{X_{i}}}{100\\%}\n\\end{equation}\n\n\n```python\ndeltaX = ERROR_PORCENTUAL_TOTAL * media/100\ndeltaX\n```\n\n\n\n\n 0.5264500000000001\n\n\n\n**Finalmente la incertidumbre tipo B queda:**\n\\begin{equation}\n u_{j}(x_{i}) = \\sqrt{Var(x_{i})} = \\dfrac{\\Delta X}{\\sqrt{3}}\n\\end{equation}\n\ndonde recordamos que, al suponer una distribución uniforme en el dispositivo de medición, la varianza nos queda $Var(X_{uniforme}) = \\dfrac {(b-a)^{2}}{12}$.\n\n\n```python\nuj = deltaX / np.sqrt(3)\nuj\n```\n\n\n\n\n 0.30394604921487856\n\n\n\n**Calculamos la incertidumbre conjunta**\n\nComo este es el caso de una medición directa de una sola variable, la expresión apropiada es:\n\n\\begin{equation}\n u_{c}^{2}(x_{i}) = u_{i}^{2}(x_{i}) + u_{j}^{2}(x_{i}) \n\\end{equation}\n\n\n```python\n#incertidumbre combinada\nuc = np.sqrt(ui**2 + uj**2)\nuc\n```\n\n\n\n\n 0.61145148608834\n\n\n\n**Ahora debemos evaluar frente a que caso nos encontramos**\n\nEn primera instancia evaluamos que componente de la incertidumbre es mayoritaria y en que proporción.\n\nEntonces tenemos tres situaciones posibles:\n\n1. **Caso B dominante** $\\Rightarrow \\dfrac{u_{i}(x_{i})}{u_{j}(x_{i})} \\lt 1 \\Rightarrow$ Se utiliza la tabla de B dominante.\n1. **Caso Normal** $\\Rightarrow \\dfrac{u_{i}(x_{i})}{u_{j}(x_{i})} \\gt 1$ y $V_{eff} \\gt 30 \\Rightarrow$ Se toma $K=2$.\n1. **Caso A dominante** $\\Rightarrow \\dfrac{u_{i}(x_{i})}{u_{j}(x_{i})} \\gt 1$ y $V_{eff} \\lt 30 \\Rightarrow$ Se utiliza t-Student con los grados de libertad efectivos.\n\n\n\n```python\ndef evaluacion(uc,ui,uj,N):\n cte_prop = ui/uj\n print(\"Constante de proporcionalidad\", cte_prop)\n if cte_prop > 1:\n # Calculo los grados de libertad efectivos\n veff = int ((uc**4)/((ui**4)/(N-1)))\n print(\"Grados efectivos: \", veff)\n if veff > 30:\n # Caso Normal\n k = 2\n else:\n # Caso t-Student\n k = get_factor_Tstudent(veff)\n else:\n # Caso B Dominante\n k = tabla_B(cte_prop)\n print(\"Constante de expansión: \",k)\n return k\n```\n\n
\n Nota: La contribución de $u_{j}(x_{i})$ no se tiene en cuenta dado que, al ser una distribución continua, tiene infinitos grados de libertad.\n \n \n\\begin{equation}\n \\nu_{eff} = \\dfrac{u_{c}^{4}(y)}{\\sum_{i=1}^{N} \\dfrac{ c_{i}^{4} u^{4}(x_{i})} {\\nu_{i}} } \n\\end{equation}\n
\n\n\n\n\n```python\nk = evaluacion(uc,ui,uj,N)\n```\n\n Constante de proporcionalidad 1.7455599385766958\n Grados efectivos: 15\n Constante de expansión: 2.175422110927068\n\n\n**Análisis y presentación del resultado**\n\nComo el cociente $\\dfrac{u_{i}(x_{i})}{u_{j}(x_{i})} \\gt 2$, entonces suponemos que nos encontramos frente al caso de distribución normal o distribución t-Student. Para ello utilizamos el criterio de los grados de libertad efectivos.\n\nEn este caso los grado de libertad efectivos $V_{eff} \\gt 30$, por lo que suponemos distribución normal.\n\nFinalmente presentamos el resultado con 1 dígito significativo.\n\n\n```python\nU = uc*k\nprint(\"Resultado de la medición: (\",np.round(media,1),\"+-\",np.round(U,1),\")V con un grado de confianza del 95%\")\n```\n\n Resultado de la medición: ( 99.3 +- 1.3 )V con un grado de confianza del 95%\n\n\n# Bibliografía\n\n_Nota: Las citas **no** respetan el formato APA._\n\n1. [Evaluación de la Incertidumbre en Datos Experimentales, Javier Miranda Martín del Campo](http://depa.fquim.unam.mx/amyd/archivero/CALCULODEINCERTIDUMBRESDR.JAVIERMIRANDA_26197.pdf)\n\n1. [Propagación de erroes, Wikipedia](https://es.wikipedia.org/wiki/Propagaci%C3%B3n_de_errores)\n\n1. [Convolución, Wikipedia](https://es.wikipedia.org/wiki/Convoluci%C3%B3n)\n\n1. [Intervalo de Confianza, Wikipedia](https://es.wikipedia.org/wiki/Intervalo_de_confianza#Ejemplo_pr%C3%A1ctico)\n", "meta": {"hexsha": "f55d90f30564ce025901c9190cc1c31e2d8a58bc", "size": 75558, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Incertidumbre/Incertidumbre.ipynb", "max_stars_repo_name": "lucasliano/Medidas1", "max_stars_repo_head_hexsha": "349f1e3783b35782a445d7e34ab9827ee5117e31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-02T19:24:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T01:19:53.000Z", "max_issues_repo_path": "Incertidumbre/Incertidumbre.ipynb", "max_issues_repo_name": "lucasliano/Medidas1", "max_issues_repo_head_hexsha": "349f1e3783b35782a445d7e34ab9827ee5117e31", "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": "Incertidumbre/Incertidumbre.ipynb", "max_forks_repo_name": "lucasliano/Medidas1", "max_forks_repo_head_hexsha": "349f1e3783b35782a445d7e34ab9827ee5117e31", "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": 85.6666666667, "max_line_length": 40872, "alphanum_fraction": 0.7744778845, "converted": true, "num_tokens": 7976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.20689405126100327, "lm_q1q2_score": 0.09940818024586277}} {"text": "# Python for scientific computing\n\n> Marcos Duarte \n> Laboratory of Biomechanics and Motor Control [http://demotu.org](http://demotu.org) \n> Federal University of ABC, Brazil \n\n# This talk\n\n*The Python programming language with its ecosystem for scientific programming has features, maturity, and a community of developers and users that makes it the ideal environment for the scientific community.* \n\n*This talk will show some of these features and usage examples.* \n\n*If you are viewing this notebook online (served by [http://nbviewer.ipython.org](http://nbviewer.ipython.org)), you can click the button 'View as Slides' on the toolbar above to start the slide show.*\n\n## The lifecycle of a scientific idea\n\n\n```python\nfrom IPython.display import Image\nImage(filename='../images/lifecycle_FPerez.png') # From F. Perez\n```\n\n## About Python\n\n*Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs* [[python.org](http://python.org/)].\n\n*Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, well suited for Rapid Application Development and for scripting or glue language to connect existing components. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and standard libraries are available without charge for all major platforms, and can be freely distributed* [[Python documentation](http://www.python.org/doc/essays/blurb/)].\n\n## About me\n\nAs a scientist, what I do it's similar to this other fellow:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('9ZlBUglE6Hc', width=480, height=360, rel=0)\n```\n\n\n\n\n\n\n\n\n\n\n## Python ecosystem for scientific computing (main libraries)\n\n- [Numpy](http://numpy.scipy.org): fundamental package for scientific computing with a N-dimensional array package.\n- [Scipy](http://scipy.org/scipylib/index.html): numerical routines for scientific computing.\n- [Matplotlib](http://matplotlib.org): comprehensive 2D Plotting.\n- [Sympy](http://sympy.org): symbolic mathematics.\n- [Pandas](http://pandas.pydata.org/): data structures and data analysis tools.\n- [Jupyter Notebook](https://jupyter.org): web application for creating and sharing documents with live code, equations, visualizations and text. \n- [Statsmodels](http://statsmodels.sourceforge.net/): to explore data, estimate statistical models, and perform statistical tests.\n- [Scikit-learn](http://scikit-learn.org/stable/): tools for data mining and data analysis (including machine learning).\n- [Pillow](http://python-pillow.github.io/): Python Imaging Library.\n- [Spyder](https://code.google.com/p/spyderlib/): interactive development environment.\n\n## Why Python and not 'X' (put any other language here)\n\nPython is not the best programming language for all needs and for all people. There is no such language. But, if you are doing scientific computing, chances are that Python is perfect for you because:\n\n1. Python is free, open source, and cross-platform. \n2. Python is easy to learn, with readable code, well documented, and with a huge and friendly user community. \n3. Python is a real programming language, able to handle a variety of problems, easy to scale from small to huge problems, and easy to integrate with other systems (including other programming languages).\n4. Python code is not the fastest but Python is one the fastest languages for programming. It is not uncommon in science to care more about the time we spend programming than the time the program took to run. But if code speed is important, one can easily integrate in different ways a code written in other languages (such as C and Fortran) with Python.\n5. The Jupyter Notebook is a versatile tool for programming, data visualization, plotting, simulation, numeric and symbolic mathematics, and writing for daily use.\n\n## Popularity of Python for teaching\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-' +\n 'introductory-teaching-language-at-top-us-universities/fulltext',\n width='100%', height=450)\n```\n\n\n\n\n\n\n\n\n\n\n## The Jupyter Notebook\n\nThe Jupyter Notebook App is a server-client application that allows editing and running notebook documents via a web browser. The Jupyter Notebook App can be executed on a local desktop requiring no internet access (as described in this document) or installed on a remote server and accessed through the internet. \n\nNotebook documents (or “notebooks”, all lower case) are documents produced by the Jupyter Notebook App which contain both computer code (e.g. python) and rich text elements (paragraph, equations, figures, links, etc...). Notebook documents are both human-readable documents containing the analysis description and the results (figures, tables, etc..) as well as executable documents which can be run to perform data analysis.\n\n[Try Jupyter Notebook in your browser](https://try.jupyter.org/).\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://jupyter.org/', width='100%', height=450)\n```\n\n\n\n\n\n\n\n\n\n\n## Jupyter Notebook and IPython kernel architectures\n\n
\n\n## Python installation and tutorial\n\n- [Python for scientific computing](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/PythonForScientificComputing.ipynb)\n- [How to install Python for scientific computing](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/PythonInstallation.ipynb) \n- [Tutorial on Python for scientific computing](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/PythonTutorial.ipynb)\n\n## Installing the Python ecosystem\n\n**The easy way** \nThe easiest way to get Python and the most popular packages for scientific programming is to install them with a Python distribution such as [Anaconda](https://www.continuum.io/anaconda-overview). In fact, you don't even need to install Python in your computer, you can run Python for scientific programming in the cloud using [python.org](https://www.python.org/shell/), [SageMathCloud](https://cloud.sagemath.com), [Wakari](https://www.wakari.io/), [pythonanywhere](https://www.pythonanywhere.com/), or [repl.it](https://repl.it/languages/python3).\n\n**The hard way** \nYou can download Python and all individual packages you need and install them one by one. In general, it's not that difficult, but it can become challenging and painful for certain big packages heavily dependent on math, image visualization, and your operating system (i.e., Microsoft Windows).\n\n## Anaconda\n\nGo to the [*Anaconda* website](https://www.continuum.io/downloads) and download the appropriate version for your computer (but download Anaconda3! for Python 3.x). The file is big (about 350 MB). [From their website](https://www.continuum.io/downloads): \n**Linux Install** \nIn your terminal window type and follow the instructions: \n```\nbash Anaconda3-4.1.1-Linux-x86_64.sh \n```\n**OS X Install** \nFor the graphical installer, double-click the downloaded .pkg file and follow the instructions \nFor the command-line installer, in your terminal window type and follow the instructions: \n```\nbash Anaconda3-4.1.1-MacOSX-x86_64.sh \n```\n**Windows** \nDouble-click the .exe file to install Anaconda and follow the instructions on the screen \n\n## Miniconda\n\nA variation of *Anaconda* is [*Miniconda*](http://conda.pydata.org/miniconda.html) (Miniconda3 for Python 3.x), which contains only the *Conda* package manager and Python. \n\nOnce *Miniconda* is installed, you can use the `conda` command to install any other packages and create environments, etc.\n\n# My current installation\n\n\n```python\n# pip install version_information\n%load_ext version_information\n%version_information numpy, scipy, matplotlib, sympy, pandas, ipython, jupyter\n```\n\n\n\n\n
SoftwareVersion
Python3.5.2 64bit [MSC v.1900 64 bit (AMD64)]
IPython5.1.0
OSWindows 10 10.0.10586 SP0
numpy1.11.1
scipy0.18.0
matplotlib1.5.3
sympy1.0
pandas0.18.1
ipython5.1.0
jupyter1.0.0
Thu Sep 22 01:04:43 2016 E. South America Standard Time
\n\n\n\n## To learn more about Python\n\nThere is a lot of good material in the internet about Python for scientific computing, some of them are: \n\n - [How To Think Like A Computer Scientist](http://www.openbookproject.net/thinkcs/python/english2e/) or [the interactive edition](http://interactivepython.org/courselib/static/thinkcspy/index.html) (book)\n - [Python Scientific Lecture Notes](http://scipy-lectures.github.io/) (lecture notes)\n - [Lectures on scientific computing with Python](https://github.com/jrjohansson/scientific-python-lectures#lectures-on-scientific-computing-with-python) (lecture notes)\n - [A gallery of interesting IPython Notebooks](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks)\n\n# Brief tutorial on Python\n\n## Python as a calculator\n\nOnce in the IPython notebook, if you type a simple mathematical expression and press Shift+Enter it will give the result of the expression:\n\n\n```python\n1 + 2 - 5\n```\n\n\n\n\n -2\n\n\n\n\n```python\nimport math # use the import function to import the math library\nmath.sqrt(12)\n```\n\n\n\n\n 3.4641016151377544\n\n\n\n\n```python\nx = 1\ny = 1 + math.pi\ny\n```\n\n\n\n\n 4.141592653589793\n\n\n\n## Main built-in datatypes in Python\n\n- Bolleans: True, False\n- NoneType: None\n- Numbers: int, float, complex\n- Sequences: list, tuple, range\n- Text sequence: str\n- Binary sequence: bytes, bytearray, memoryview\n- Mapping: dict\n- Set: set, frozenset\n- Boolean operations: and, or, not\n- Comparisons: <, <=, >, >=, ==, !=, is, is not\n- Math operations: +, -, \\*, /, //, %, **\n- Bitwise operations: |, ^, &, <<, >>, ~\n\n## Example: strings\n\n\n```python\ns = 'P' + 'y' + 't' + 'h' + 'o' + 'n'\nprint(s)\nprint(s*5)\n```\n\n Python\n PythonPythonPythonPythonPython\n\n\nStrings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0:\n\n\n```python\nprint('s[0] = ', s[0], ' (s[index], start at 0)')\nprint('s[5] = ', s[5])\nprint('s[-1] = ', s[-1], ' (last element)')\nprint('s[:] = ', s[:], ' (all elements)')\nprint('s[1:] = ', s[1:], ' (from this index (inclusive) till the last (inclusive))')\nprint('s[2:4] = ', s[2:4], ' (from 1st index (inclusive) till 2nd index (exclusive))')\nprint('s[:2] = ', s[:2], ' (till this index, exclusive)')\nprint('s[:10] = ', s[:10], ' (Python handles the index if it''s larger than length)')\nprint('s[-10:] = ', s[-10:])\nprint('s[0:5:2] = ', s[0:5:2], ' (s[ini:end:step])')\nprint('s[::2] = ', s[::2], ' (s[::step], initial and final indexes can be omitted)')\nprint('s[0:5:-1] = ', s[::-1], ' (s[::-step] reverses the string)')\nprint('s[:2] + s[2:] = ', s[:2] + s[2:], ' (this sounds natural with Python indexing)')\n```\n\n s[0] = P (s[index], start at 0)\n s[5] = n\n s[-1] = n (last element)\n s[:] = Python (all elements)\n s[1:] = ython (from this index (inclusive) till the last (inclusive))\n s[2:4] = th (from 1st index (inclusive) till 2nd index (exclusive))\n s[:2] = Py (till this index, exclusive)\n s[:10] = Python (Python handles the index if its larger than length)\n s[-10:] = Python\n s[0:5:2] = Pto (s[ini:end:step])\n s[::2] = Pto (s[::step], initial and final indexes can be omitted)\n s[0:5:-1] = nohtyP (s[::-step] reverses the string)\n s[:2] + s[2:] = Python (this sounds natural with Python indexing)\n\n\n## Defining a function in Python\n\n\n```python\ndef fibo(N):\n \"\"\"Fibonacci series: the sum of two elements defines the next.\n \n The series is calculated till the input parameter N and\n returned as an ouput variable.\n \n \"\"\"\n \n a, b, c = 0, 1, []\n while b < N:\n c.append(b)\n a, b = b, a + b\n \n return c\n```\n\n\n```python\nfibo(9)\n```\n\n\n\n\n [1, 1, 2, 3, 5, 8]\n\n\n\n## Defining a function in Python II\n\n\n```python\ndef bmi(weight, height):\n \"\"\"Body mass index calculus and categorization.\n Enter the weight in kg and the height in m.\n See http://en.wikipedia.org/wiki/Body_mass_index\n \"\"\"\n bmi = weight / height**2\n if bmi < 15:\n c = 'very severely underweight'\n elif 15 <= bmi < 16:\n c = 'severely underweight'\n elif 16 <= bmi < 18.5:\n c = 'underweight'\n elif 18.5 <= bmi < 25:\n c = 'normal'\n elif 25 <= bmi < 30:\n c = 'overweight'\n elif 30 <= bmi < 35:\n c = 'moderately obese'\n elif 35 <= bmi < 40:\n c = 'severely obese'\n else:\n c = 'very severely obese'\n \n s = 'For a weight of {0:.1f} kg and a height of {1:.2f} m,\\n\\\n the body mass index (bmi) is {2:.1f} kg/m2,\\n\\\n which is considered {3:s}.'\\\n .format(weight, height, bmi, c)\n print(s)\n```\n\n\n```python\nbmi(70, 1.90);\n```\n\n For a weight of 70.0 kg and a height of 1.90 m,\n the body mass index (bmi) is 19.4 kg/m2,\n which is considered normal.\n\n\n## Numeric data manipulation with Numpy\n\nNumpy is the fundamental package for scientific computing in Python and has a N-dimensional array package convenient to work with numerical data. With Numpy it's much easier and faster to work with numbers grouped as 1-D arrays (a vector), 2-D arrays (like a table or matrix), or higher dimensions. \n\n\n```python\nimport numpy as np\n\nx = np.array([1, 2, 3, 4, 5, 6])\nprint(x)\nx = np.random.randn(2,4)\nprint(x)\n```\n\n [1 2 3 4 5 6]\n [[ 0.6504986 1.21639113 0.06680213 0.43133861]\n [ 0.35556254 0.43596075 1.17614962 1.0677548 ]]\n\n\n## Moving-average filter (Numpy use for performance)\n\n*A moving-average filter has the general formula:*\n\n$$ y[i] = \\sum_{j=0}^{m-1} x[i+j] \\;\\;\\;\\; for \\;\\;\\; i=1, \\; \\dots, \\; n-m+1 $$\n\nHere are two different versions of a function to implement the moving-average filter:\n\n\n```python\nimport numpy as np\ndef mav1(x, window):\n \"\"\"Moving average of 'x' with window size 'window'.\"\"\"\n y = np.empty(len(x)-window+1)\n for i in range(len(y)):\n y[i] = np.sum(x[i:i+window])/window\n return y\n\ndef mav2(x, window):\n \"\"\"Moving average of 'x' with window size 'window'.\"\"\"\n xsum = np.cumsum(x)\n xsum[window:] = xsum[window:] - xsum[:-window]\n return xsum[window-1:]/window\n```\n\n\n```python\nx = np.random.randn(300)/10\nx[100:200] += 1\nwindow = 10\n\nprint('Performance of mav1:')\n%timeit mav1(x, window)\nprint('Performance of mav2:')\n%timeit mav2(x, window)\n```\n\n Performance of mav1:\n 1000 loops, best of 3: 1.56 ms per loop\n Performance of mav2:\n The slowest run took 5.70 times longer than the fastest. This could mean that an intermediate result is being cached.\n 100000 loops, best of 3: 11.6 µs per loop\n\n\n## Ploting with matplotlib\n\nMatplotlib is the most-widely used packge for plotting data in Python. Let's see some examples of it.\n\n\n```python\nimport matplotlib.pyplot as plt\n#%matplotlib notebook\n%matplotlib inline\nimport numpy as np\n```\n\n\n```python\ny1 = mav1(x, window)\ny2 = mav2(x, window)\n# plot\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.plot(x, 'b-', linewidth=1, label = 'raw data')\nax.plot(y1, 'y-', linewidth=2, label = 'moving average 1')\nax.plot(y2, 'g--', linewidth=2, label = 'moving average 2')\nax.legend(frameon=False, loc='upper right', fontsize=12)\nax.set_xlabel(\"Data #\")\nax.set_ylabel(\"Amplitude\")\nax.grid();\n```\n\n\n```python\nplt.figure(figsize=(8, 4))\nplt.plot(x, 'b-', linewidth=1, label = 'raw data')\nplt.plot(y1, 'y-', linewidth=2, label = 'moving average 1')\nplt.plot(y2, 'g--', linewidth=2, label = 'moving average 2')\nplt.legend(frameon=False, loc='upper right', fontsize=12)\nplt.xlabel(\"Data #\")\nplt.ylabel(\"Amplitude\")\nplt.grid()\nplt.show()\n```\n\n## Ploting with matplotlib II\n\nPlot figure in an external window (outside the ipython notebook area):\n\n\n```python\n#%matplotlib qt\n```\n\n\n```python\nmu, sigma = 10, 2\nx = mu + sigma * np.random.randn(1000)\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))\nax1.plot(x, 'ro')\nax1.set_title('Data')\nax1.grid()\n\nn, bins, patches = ax2.hist(x, 25, normed=True, facecolor='r') # histogram\nax2.set_xlabel('Bins')\nax2.set_ylabel('Probability')\nax2.set_title('Histogram')\nfig.suptitle('Another example using matplotlib', fontsize=18, y=1.02)\nax2.grid()\n\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n# get back the inline plot\n#%matplotlib inline\n#%matplotlib notebook\n```\n\nInstead of \"`%matplotlib inline`\" you can use \"`%matplotlib notebook`\" which gives you a nice toolbar for zooming, panning, etc. The caveat is that once \"`%matplotlib notebook`\" is used you can't alternate between matplotlib backends as we just did.\n\n## Symbolic mathematics with Sympy\n\nSympy is a package to perform symbolic mathematics in Python. Let's see some of its features:\n\n\n```python\nfrom IPython.display import display\nimport sympy as sym\nfrom sympy.interactive import printing\nprinting.init_printing()\n```\n\nDefine some symbols and the create a second-order polynomial function (a.k.a., parabola), plot, and find the roots:\n\n\n```python\nx, y = sym.symbols('x y')\ny = -x**3 + 4*x\ny\n```\n\n\n```python\nfrom sympy.plotting import plot\n%matplotlib inline\nplot(y, (x, -3, 3));\n```\n\n\n```python\nsym.solve(y, x)\n```\n\n## More live examples\n\nLet's run stuff from:\n- [https://github.com/demotu/BMC](https://github.com/demotu/BMC)\n- [http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/Index.ipynb](http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/Index.ipynb)\n- [http://nbviewer.jupyter.org/](http://nbviewer.jupyter.org/)\n- ...\n\n## Questions?\n\n- http://mail.scipy.org/mailman/listinfo/ipython-dev\n- http://www.reddit.com/r/python\n- http://stackoverflow.com/\n\n> This entire document was written in the Jupyter Notebook (which can be statically viewed [here](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/PythonForScientificComputing.ipynb) or downloaded [here](https://raw.githubusercontent.com/demotu/BMC/master/notebooks/PythonForScientificComputing.ipynb)). If you are watching my presentation right now, these slides are just a visualization of the same notebook (probably using the [RISE: \"Live\" Reveal.js Jupyter/IPython Slideshow Extension](https://github.com/damianavila/live_reveal)).\n", "meta": {"hexsha": "7237255343d3751485edfb3f5a723e9715bb5d28", "size": 532338, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/PythonForScientificComputing.ipynb", "max_stars_repo_name": "jagar2/BMC", "max_stars_repo_head_hexsha": "884250645693ef828471fe1d132a093dc6df7593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-30T04:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T04:02:59.000Z", "max_issues_repo_path": "notebooks/PythonForScientificComputing.ipynb", "max_issues_repo_name": "jagar2/BMC", "max_issues_repo_head_hexsha": "884250645693ef828471fe1d132a093dc6df7593", "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": "notebooks/PythonForScientificComputing.ipynb", "max_forks_repo_name": "jagar2/BMC", "max_forks_repo_head_hexsha": "884250645693ef828471fe1d132a093dc6df7593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-30T04:03:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T04:03:02.000Z", "avg_line_length": 288.8431904504, "max_line_length": 168334, "alphanum_fraction": 0.9164553348, "converted": true, "num_tokens": 5194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.25091279808829703, "lm_q1q2_score": 0.09937857183352067}} {"text": "# Cass and Koopman's Model of Optimal Growth\n\n** This project sets out to investigate the optimal level of growth. **\n\nWe're interested analysing the theoretically optimal level of optimal growth. To do so, we will be using Cass and Koopman's model of exactly that. \n\nThe model can be interpreted as an extension of the Solow model but adapted to make the savings rate the outcome of an optimal choice. This is in contrast to that of the Solow model which assumed a constant savings rate determined outside the model. The model is based on the articles:\n\n* Tjalling C. Koopmans. On the concept of optimal economic growth. In Tjalling C. Koopmans, editor, The Economic Approach to Development Planning, page 225–287. Chicago, 1965.\n\n* David Cass. Optimum growth in an aggregative model of capital accumulation. Review of Economic Studies, 32(3):233–240, 1965.\n\n** Imports and set magics:**\n\n\n```python\nimport numpy as np\nfrom scipy import optimize\nimport sympy as sm\nimport matplotlib.pyplot as plt\n\n# autoreload modules when code is run\n%load_ext autoreload\n%autoreload 2\n\n# local modules\nimport modelproject\n```\n\n# Description of the model\n\nTime is discrete and takes the values t=0,1...,T. A single good is consumed or invested in physical capital. The consumption good is not durable and will depreciate if it is not consumed immediately. The capital good is durable but depreciates each period with the rate $\\gamma \\epsilon (0,1)$. \n\nWe consider the a model of Cass and Koopman's optimal growth where:\n\n* $C_t$ is a nondurable consumption good at time t.\n* $K_t$ is is the stock of physical capital at time t.\n* Let $C={C_0,...,C_T}$ and $K={K_1,...,K_{T+1}}$\n\nA representative household is endowed with one unit of labour $N_t$ at each t, such that $N_t=1$ for all $t \\epsilon [0,T]$. \n\nThe representative household has preferences over consumption bundles with the utility function given by: \n\n$$ U(C)=\\sum_{T=0}^{T}\\beta^t\\frac{C_t^{1-\\gamma}}{1-\\gamma} $$\n\nwhere $\\beta \\epsilon (0,1)$ is a discount factor and $\\gamma > 0$ decides the curvature of the one-period utility function. \n\nNote that\n\n$$u(C_t)=\\frac{C_t^{1-\\gamma}}{1-\\gamma}$$\n\nsatisfies $u'>0, u''<0$. \n\nWe also note that\n* $u'>0$ asserts the consumer prefers more to less\n* $u''<0$ asserts that marginal utility declines with increases in $C_t$\n\nWe assume that $K_0>0$ is a given exogenous level of intial capital. \n\nThere is an economy-wide production function: \n\n$$ F(K_t, N_t)=AK_t^\\alpha N_t^{1-\\alpha} $$\n\nwith 0 < \\alpha < 1, A>0. \n\nA feasible allocation C, K will satisfy\n$$ C_t+K_t+1 \\leq F(K_t,N_t)+(1-\\delta)K_t,$$ \n\nfor all $t \\epsilon[0,T]$\n\nwhere $\\delta \\epsilon(0,1)$ is the rate at which capital depreciates.\n\n\n## Planning Problem\n\nA planner chooses an allocation ${C,K}$, to maximise the utility function st the feasible allocation. Let $\\mu ={\\mu_0,...,\\mu_T}$ be a sequence of non-negative Lagrange multipliers. To find an optimal allocation, we use the Lagrangian\n\n$$ L(C, K, \\mu) = \\sum_{t=1}^{T}\\beta^t{\\mu(C_t)+\\mu_t(F(K_t, 1)+(1-\\delta)K_t-C_t-K_{t+1})} $$\n\nand then solve the following max problem\n\n$$ max L(C,K, \\mu) $$\n\n**Useful Properties of Linearly Homogenous Production Functions**\n\nNotice that \n\n$$ F(K_t, N_t)=AK^\\alpha_tN^{1-\\alpha}_t=N_tA(\\frac{K_t}{N_t})^\\alpha $$\n\nWe define the output per-capital production function \n\n$$f(\\frac{K_t}{N_t})=A(\\frac{K_t}{N_t})^\\alpha $$\n\nwhose argument is capital per-capita. \n\nThen we have that \n\n$$F(K_t,N_t)=N_tf(\\frac{K_t}{N_t}) $$\n\nTaking the derivate wrt K, yields\n\n$$ \\frac{\\delta F}{\\delta K} = \\frac{\\delta N_tf({\\frac{K_t}{N_t})}}{\\delta N_t} $$\n$$ = N_tf'(\\frac{K_t}{N_t}\\frac{1}{N_t}) $$\n$$ =f' (\\frac{K_t}{N_t} \\bigg\\rvert_{N_t=1} $$\n$$ f'(K_t) $$\n\nAlso\n\n$$ \\frac{\\delta F}{\\delta N} = \\frac{\\delta N_t f(\\frac{K_t}{N_t})}{\\delta N_t} $$\n$$ = f(\\frac{K_t}{N_t})+N_tf'(\\frac{K_t}{N_t})-\\frac{-K_t}{N_t^2}) $$\n$$ = f(\\frac{K_t}{N_t})- \\frac{K_t}{N_t}f'(\\frac{K_t}{N_t})\\bigg\\rvert_{N_t=1} $$\n$$ = f(K_t)-f'(K_t)K_t $$\n\n** Returning to solving the problem **\n\nWe compute first derivatives of Lagrangian and set them equal to 0, in order to solve the Lagrangian maximisation problem. \n\nOur objective function and constraints satisfy conditions that assure that the required SOCs are satisfied at an allocation satisfying the FOCs which that are derived below.\n\nThe FOC for maximisation with respet to C, K: \n\n$$ C_t: \\mu'(C_t)=\\mu_t = 0 for all t= 0,1,...,T $$\n$$ K_t: \\beta \\mu_t[(1-\\delta)+f'(K_t)]-\\mu–{t-1}=0 for all t=1,2,...,T $$\n$$ \\mu_t:F(K_t,1)+(1-\\delta)K_t-C_t-K_{t+1}=0 for all t=0,1,...,T $$ \n$$ K_{T+1}: -\\mu_T \t\\leq 0, \t\\leq if K_{T+1}=0; =0 if K_{T+1} > 0 $$\n\nIn the equation for $C_t$ we plugged in for $\\frac{\\delta F}{\\delta K}$ using the formula given above. As $N_t=1$ for all t=1,...,T, it is not necessary to differentiate with respect to those arguments. Note that the equation for $\\mu_t$ comes from the occurrence of $K_t$ in both the period t and period t-1 feasibility constraints. The equation for $K_{T+1}$ comes from differentiating with respect to $K_{T+1}$ in the last period and applying the following Karush-Kuhn-Tucker condition: \n\n$$ \\mu_tK_{T+1}=0 $$\n\nCombining equations for $C_t$ and $K_t$ yields\n\n$$ \\mu'(C_t)[(1-\\delta)+f'(K_t)]-\\mu'(C{t-1})=0 $$ for all t=1,2,...,T+1\n\nRewriting yields \n\n$$ u'(C_{t+1})[(1-\\delta)+f'(K_{t+1})]=\\mu'(C_t) $$ for all t=0,1,...,T \n\nTaking the inverse of the utility function on both sides of the above equation yields \n\n$$ C_{t+1}=u'^{-1}((\\frac{\\beta}{u'(C_t)}[f'(K_{t+1})+(1-\\delta)])^{-1}) $$ \n\nOr using the utility function.\n\n$$ C_{t+1}=(\\beta C^{\\gamma}_t[f'(K_{t+1})+(1-\\delta)])^{1/\\gamma} $$\n$$ =C_t(\\beta[f'(K_{t+1})+(1-\\delta)])^{1/\\gamma} $$\n\nThe above FOC for consumption is an Euler Equation. It descirbes how consumption in consecuitive periods are optimally related to each other and to capital in the following period. \n\nWe now apply the equations above to calculate variables and functions that we will need to solve the planning problem. \n\nFirst we define symbols\n\n\n```python\ngamma = sm.symbols('gamma')\nalpha = sm.symbols('alpha')\ndelta = sm.symbols('delta')\nbeta = sm.symbols('beta')\nA = sm.symbols('A')\n```\n\n\n```python\n# The utility function\ndef u(c, gamma): \n if y == 1: # if y = 1 we can with L'hopital's Rule show that the utility becomes log\n return np.log(c)\n else: \n return (c**(1-gamma))/(1-gamma)\n\n#The derivative of utility\ndef u_prime(c, gamma): \n if gamma == 1:\n return 1/c\n else: \n return c**(-gamma)\n\n#The inverse utility\ndef u_prime_inverse(c, gamma):\n if gamma == 1: \n return c\n else: \n return c**(-1/gamma)\n\n#The production function \ndef f(A, k, alpha):\n return A*k**alpha\n\n#The derivative of production function\ndef f_prime(A, k, alpha):\n return alpha*A*k**(alpha-1)\n\n#The inverse production function\ndef f_prime_inverse(A, k, alpha):\n return (k/(A*alpha))**(1/(alpha-1))\n```\n\nWe will be using an algorithmic method with a for loop, to derive an optimal allocation for C,K and an associated Lagrange multiplier sequence $\\mu$. The FOCs for the planning problem, form a system of difference equations with two boundary conditions\n\n* $K_0$ is a given initial condition for capital\n* $K_{T+1}=0$ is a terminal condition for capital\n\nThe parameters are: \n* c = Initial consumption \n* k = Initial capital\n* $\\gamma$ = Coefficient of relative risk aversion \n* $\\delta$ = Depreciation rate on capital \n* $\\beta$ = Discount factor\n* $\\alpha$ = return to capital per capital\n* A = technology\n\n** The model paramters are defined **\n\n\n```python\ngamma=2\ndelta=0.02\nbeta=0.95\nalpha=0.33\nA=1\n```\n\n** The algortihmic method to solve the problem **\n\n\n```python\nT=10\nc=np.zeros(T+1) #T periods of consumption initialised to 0\nk=np.zeros(T+2) #T periods of capital initialised to 0(T+2 to include t+1 variable)\nk[0]=0.3 #Initial k\nc[0]=0.2 # Initial guess of c_0\n\ndef algorithm(c, k, gamma, delta, beta, alpha, A):\n T = len(c)-1 \n for t in range(T): \n k[t+1]=f(A=A, k=k[t], alpha=alpha)+(1-delta)*k[t]-c[t] \n if k[t+1]<0: #Ensuring nonnegativity\n k[t+1]=0 \n if beta*(f_prime(A=A, k=k[t+1], alpha=alpha)+(1-delta))==np.inf: \n#Only occurs if k[t+1] is 0, at which point nothing will be produced next period, thus consumption go to 0\n c[t+1]=0\n else: c[t+1]=u_prime_inverse(u_prime(c=c[t], gamma=gamma)/(beta*(f_prime(A=A, k=k[t+1], alpha=alpha)+(1-delta))), gamma=gamma)\n\n#Terminal condition calculation\n k[T+1]=f(A=A, k=k[T], alpha=alpha)+(1-delta)*k[T]-c[T]\n return c, k\n\npaths = algorithm(c, k, gamma, delta, beta, alpha, A)\n\nfig, axes = plt.subplots(1, 2, figsize=(10, 4))\ncolors = ['orange', 'green']\ntitles = ['Consumption', 'Capital']\nylabels = ['$c_t$', '$k_t$']\n\nfor path, color, title, y, ax in zip(paths, colors, titles, ylabels, axes):\n ax.plot(path, c=color, alpha=0.7)\n ax.set(title=title, ylabel=y, xlabel='t')\n\nax.scatter(T+1, 0, s=80)\nax.axvline(T+1, color='k', ls='--', lw=1)\n\nplt.tight_layout()\nplt.show()\n```\n\nFrom the graphs above, it is evident that our guess for $\\mu_0$ is too high and makes initial consumption too low. This is evident because the $K_{T+1}=0$ target is missing on the high side. \n\n## Bisection Method\n\nIn the following section we will automate the above procedure with the derivative-free method, Bisection. Applying the method means searching for $\\mu_0$, stopping when we reach the target $K_{T+1}=0$. \n\n\nWe take an initial guess for $C_0$ ($\\mu_0$ can be eliminated because $C_0$ is an exact function of $\\mu_0$. We know that the lowest $C_0$ can ever be is 0 and the largest it can be is initial output $f(K_0)$. We will take a guess on $C_0$ towards T+1. If $K_{T+1}>0$, let it be our new lower bound on $C_0$. If $K_{T+1}<0$, let it be our new upper bound. We will make a new guess for $C_0$ exactly halfway between our new upper and lower bounds. When $K_{T+1}$ gets close enough to 0 (wihtin some error tolerance bounds), the procedure will stop and we will have our values for consumption and capital.\n\nMore specifically the bisection methods in our model works in the following steps: \n\n1. We set $c_{low}=0$ and $c_{high}=f(k=k[0], alpha=alpha, A=A)$ where $f(c_{low})$ and $f(c_{high})$ have opposite sign, $f(c_{low})f(c_{high})<0$\n\n2. We compute $C[0]$ where $C[0]=(c_{low}+c_{high})/2$ is the midpoint\n\n3. The next sub-interval $[c_{low+1},c_{high+1}]$:\n\n - If $f(c_{low})f(C[0])<0$ (different signs) then $c_{low+1}=c_{low}$ and $c_{high+1}=C[0]$ (i.e. focus on the range $[c_{low},C[0]$)\n\n - If $fC[0]c_{high}<0$ (different signs) then $c_{low+1}=C[0]$ and $c_{high+1}=c_{high}$ (i.e. focus on the range $[C[0], c_{high}]$)\n \n4. Steps 2 and 3 are then repeated until $f(C[0]_n)<\\epsilon$\n\n\n```python\ndef bisection(c, k, gamma, delta, beta, alpha, A, tol=1e-4, max_iter=1e4, terminal=0): # Terminal is the value we are estimating towards\n\n #Step 1: Initialise\n T = len(c) - 1\n i = 1 # Initial iteration\n c_high = f(k=k[0], alpha=alpha, A=A) # Initial high value of c\n c_low = 0 # Initial low value of c\n\n path_c, path_k = algorithm(c, k, gamma, delta, beta, alpha, A)\n\n #Step 2-4: Main\n while (np.abs((path_k[T+1] - terminal)) > tol or path_k[T] == terminal) and i < max_iter:\n\n # Step 2: Midpoint and associated value\n c[0] = (c_high + c_low) / 2 \n path_c, path_k = algorithm(c, k, gamma, delta, beta, alpha, A)\n \n # Step 3: Determine sub-interval\n if path_k[T+1] - terminal > tol:\n # If assets are too high the c[0] guess is lower bound on possible values of c[0]\n c_low = c[0]\n elif path_k[T+1] - terminal < -tol:\n # If assets fell too quickly, the c[0] guess is upper bound on possible values of c[0]\n c_high=c[0]\n elif path_k[T] == terminal:\n # If assets fell too quickly, the c[0] guess is now an uppernbound on possible values of c[0]\n c_high=c[0]\n\n i += 1 \n\n if np.abs(path_k[T+1] - terminal) < tol and path_k[T] != terminal:\n print('Bisection method successful. Converged on iteration', i-1)\n else:\n print('Bisection method failed')\n\n u = u_prime(c=path_c, gamma=gamma)\n return path_c, path_k, u\n```\n\n** Plots of the above defined algorithms **\n\n\n```python\nT = 10\nc = np.zeros(T+1)\nk = np.zeros(T+2)\n\nk[0] = 0.3 # Initial k\nc[0] = 0.3 # Initial guess of c_0\n\npaths = bisection(c, k, gamma, delta, beta, alpha, A)\n\ndef plot_paths(paths, axes=None, ss=None):\n\n T = len(paths[0])\n\n if axes is None:\n fix, axes = plt.subplots(1, 3, figsize=(13, 3))\n\n ylabels = ['$c_t$', '$k_t$', '$\\mu_t$']\n titles = ['Consumption Level', 'Capital Level', 'Lagrange Multiplier']\n\n for path, y, title, ax in zip(paths, ylabels, titles, axes):\n ax.plot(path)\n ax.set(ylabel=y, title=title, xlabel='t')\n\n #Plotting the steady state value of k\n if ss is not None:\n axes[1].axhline(ss, c='k', ls='--', lw=1)\n\n axes[1].axvline(T, c='k', ls='--', lw=1)\n axes[1].scatter(T, paths[1][-1], s=80)\n plt.tight_layout()\n\nplot_paths(paths)\n```\n\nEvidently now, when our initial guess of $\\mu_0$ is higher, we get a significantly different result. \n\n# Analysis of the Steady State\n\nWe now want to analyse the steady state of the model. We set the inital level of capital to its steady state. \n\nIf T $\\rightarrow+ \\infty$, the optimal allocation will converge to the steady state values of $C_t$ and $K_t$. \n\nWe can derive these values and set $K_0$ equal to its steady state value. In a steady state we have that $K_{t+1}=K_t=\\overline{K}$ for all very large ts, the feasibility constraint previously stated is $f(\\overline{K})-\\delta\\overline{K}=\\overline{C}$ Substituting $K_t=\\overline{K}$ and $C_t=\\overline{C}$ for all t into the previously obtained equation $$u'(C_{t+1})[(1-\\delta)+f'(K_{t+1})]= u'(C_t)$$ for all t=0,1,...,T, yields $$1=\\beta\\frac{u'(\\overline{C}}{u'(\\overline{C}}[f'(\\overline{K}+(1-\\delta)]$$. Defining $\\beta=\\frac{1}{1+\\rho}$, and rearranging yields $$1+\\rho=1[f'(\\overline{K})+(1- \\delta)]$$ Simplifying yields $$f'(\\overline{K})=\\rho+\\delta$$ and $$\\overline{K}=f'^{-1}(\\rho+\\delta)$$ Using our production function from earlier yields $$\\alpha\\overline{K}^{\\alpha-1}=\\rho+\\delta$$\n\nUsing the obtained values $\\alpha$=0.33, $\\rho=\\frac{1}{\\beta}-1=\\frac{1}{\\frac{19}{20}}-1=\\frac{1}{19}$ and $\\delta=\\frac{1}{50}$, we get $$\\overline{K}=(\\frac{\\frac{33}{100}}{\\frac{1}{50}+\\frac{1}{19}})^{\\frac{67}{100}}≈9.6$$\n\nIn the below we will verify this result and use this steady state $\\overline{K}$ as our initial capital stock $K_0$. \n\n\n```python\nrho = sm.symbols('rho')\nrho=1/beta-1\nk_ss=f_prime_inverse(k=rho+delta,A=A, alpha=alpha)\nprint(f'The steady state of capital, k, is: {k_ss}')\n```\n\n The steady state of capital, k, is: 9.57583816331462\n\n\n** We are now at a stage where we can plot given the obtained values for the steady state **\n\n\n```python\nT=150\nc=np.zeros(T+1)\nk=np.zeros(T+2)\nc[0]=0.3\nk[0]=k_ss\npaths = bisection(c, k, gamma, delta, beta, alpha, A)\n\nplot_paths(paths, ss=k_ss)\n```\n\nFrom the plots obtained above we see that in this economy with a large value of $T$, $K_t$ will stay near its initial value for as long as possible. We can from this deduct that the social planner likes the steady state capital stock and wants to stay there for as long as possible.\n\n# Changing the parameter values\n\nIn the below we examine what happens when the initial $K_0$ is pushed below $\\overline{K}$.\n\n\n```python\nk_initial = k_ss/3 #Value below steady state \nT=150\nc=np.zeros(T+1)\nk=np.zeros(T+2)\nc[0]=0.3\nk[0]=k_initial\npaths = bisection(c, k, gamma, delta, beta, alpha, A)\n\nplot_paths(paths, ss=k_ss)\n```\n\nWe now see that the planner pushes capital toward the steady state value then stays at this value for a substantial amount of time and subsequently pushes $K_t$ toward the terminal value $K_{T+1}=0$ as t gets close to T. \n\n## Changing the value of T\n\nWe are also interested in seeing how the trajectory of the paths will change, when altering the value for T. We're making a list with four differet values of T in order to see the difference when the time horizon is altered within the same graphs. The values of T are ranging from 30 to 180 to incapsule a large range of Ts.\n\n\n```python\nT_list = (180, 90, 60, 30)\nfix, axes =plt.subplots(1, 3, figsize=(13,3))\n\nfor T in T_list:\n c=np.zeros(T+1)\n k=np.zeros(T+2)\n c[0]=0.3\n k[0]=k_initial\n paths=bisection(c, k, gamma, delta, beta, alpha, A)\n plot_paths(paths, ss=k_ss, axes=axes)\n\n```\n\nThe different colours in the graphs above are tied to outcomes with different time horizons T. These are the values given in the T_list. \n\nWe see that as we increase the time horizon, the planner puts $K_{t}$ closer to the steady state value $\\overline{K}$ for longer. \n\n## Further changes to the value of T\n\n** In the following we are testing what happens when we set the value of T at a very high value. **\n\nWe expect the pllaner making the capital stockspend most of its time close to its steady state level. \n\n\n```python\nT_list = (260, 180, 60, 30)\nfix, axes = plt.subplots(1, 3, figsize=(13, 3))\n\nfor T in T_list:\n c = np.zeros(T+1)\n k = np.zeros(T+2)\n c[0] = 0.3\n k[0] = k_initial\n paths = bisection(c, k, gamma, delta, beta, alpha, A)\n plot_paths(paths, ss=k_ss, axes=axes)\n```\n\nEvidently the bisection method failed when the parameter for T is set to 260. It failed to converge and hit the maximum iteration.\n\nHowever, it is evident that the pattern from the previous analysis is repeated with the increased values of T. The pattern reflects a turnpike property of the steady state. \n\nWe can conclude that for any given initial value of $K_0$, $K_t$ is pushed toward the steady state and held at this level for as long as possible. \n\n# Further analysis\n\nIn the below we extend the Cass-Koopman's model of optimal growth by adding an environmental term with inspiration from a paper done by Luiz Fernando (Luiz Fernando Ohara Kamogawa & Ricardo Shirota, 2011. \"Economic growth, energyconsumption and emissions: an extension of Ramsey-Cass-Koopmans modelunder EKC hypothesis,\" Anais do XXXVII Encontro Nacional de Economia [Proceedings of the 37th Brazilian Economics Meeting] 187, ANPEC)\n\n## Description of the model extension\n\nThe production function remains unchanged, but new parameters changes the utility function. The parameters are:\n\n* $\\eta$ = relative $CO_2$-emission done by non-renewable energy compared to renewable energy\n* $\\Phi$ = means of the gloabl awareness of climate changes\n* $j$ = substitutability from non-renewable energy to renewable energy. \n\nThe utility function is then given by: \n\n$$U=c^{-\\gamma}-\\eta*\\Phi^j$$\n\n\n\n## Solving the model\n\nTo solve the extended model, we use the same bisection method as previous, but add the above mentioned alterations. \n\n**The new symbols are defined:**\n\n\n```python\nepsilon = sm.symbols('epsilon')\ntheta = sm.symbols('theta')\n```\n\n**The parameters are defined:**\n\nThe values of the added terms is based on empirical studies found in the literature.\n\n\n\n```python\nepsilon=0.5\ntheta=0.3\nj=0.5\n```\n\n**The model functions are defined:**\n\n\n```python\n#The derivative of environmental utility\ndef u_prime_2(c, gamma, epsilon, theta, j): \n if gamma == 1:\n return 1/c\n else: \n return c**(-gamma)-epsilon*(theta)**j\n\n#Inverse environmental utility\ndef u_prime_inverse_2(c, gamma, epsilon, theta, j):\n if gamma == 1: \n return c\n else: \n return c**(-1/gamma)-epsilon*(theta)**(1/j)\n```\n\n**The bisection method is now used to solve the model:**\n\n\n```python\ndef bisection(c, k, gamma, delta, beta, alpha, A, tol=1e-4, max_iter=1e4, terminal=0): # Terminal is the value we are estimating towards\n\n #Step 1: Initialise\n T = len(c) - 1\n i = 1 # Initial iteration\n c_high = f(k=k[0], alpha=alpha, A=A) # Initial high value of c\n c_low = 0 # Initial low value of c\n\n path_c, path_k = algorithm(c, k, gamma, delta, beta, alpha, A)\n\n #Step 2-4: Main\n while (np.abs((path_k[T+1] - terminal)) > tol or path_k[T] == terminal) and i < max_iter:\n\n # Step 2: Midpoint and associated value\n c[0] = (c_high + c_low) / 2 \n path_c, path_k = algorithm(c, k, gamma, delta, beta, alpha, A)\n \n # Step 3: Determine sub-interval\n if path_k[T+1] - terminal > tol:\n c_low = c[0]\n elif path_k[T+1] - terminal < -tol:\n c_high=c[0]\n elif path_k[T] == terminal:\n c_high=c[0]\n\n i += 1 \n\n if np.abs(path_k[T+1] - terminal) < tol and path_k[T] != terminal:\n print('Bisection method successful. Converged on iteration', i-1)\n else:\n print('Bisection method failed')\n\n u_2 = u_prime_2(c=path_c, gamma=gamma, theta=theta, j=j, epsilon=epsilon)\n return path_c, path_k, u_2\n\n T = 10\nc = np.zeros(T+1)\nk = np.zeros(T+2)\n\nk[0] = 0.3 # Initial k\nc[0] = 0.3 # Initial guess of c_0\n\npaths = bisection(c, k, gamma, delta, beta, alpha, A)\n\ndef plot_paths(paths, axes=None, ss=None):\n\n T = len(paths[0])\n\n if axes is None:\n fix, axes = plt.subplots(1, 3, figsize=(13, 3))\n\n ylabels = ['$c_t$', '$k_t$', '$\\mu_t$']\n titles = ['Consumption Level', 'Capital Level', 'Lagrange Multiplier']\n\n for path, y, title, ax in zip(paths, ylabels, titles, axes):\n ax.plot(path)\n ax.set(ylabel=y, title=title, xlabel='t')\n\n #Plotting the steady state value of k\n if ss is not None:\n axes[1].axhline(ss, c='k', ls='--', lw=1)\n\n axes[1].axvline(T, c='k', ls='--', lw=1)\n axes[1].scatter(T, paths[1][-1], s=80)\n plt.tight_layout()\n\nplot_paths(paths)\n```\n\nThe optimal consumption path has evidently changed to lower consumption in the fist 9 periods then a quite radical rise in the tenth period after having added the environmental terms. The optimal capital path has also changed to a bigger fall of capital in the last period.\n\n# Conclusion\n\nWe used a algorithmic and bisection method to solve cass-koopman model for optimal growth. The optimal growth path for consumption is found to be rise over the whole time period while the path for capital rise until steady state is achieved then fall to zero at the end of the time period. The steady state for capital is found to be 9.58. In the next step we did a graphically visualization of the optimal consumption and capital path with different time horizons, we found evidence that the time period has to be larger than 150 years to be in the steady state path. At last we analyzed an extension to the baseline model, we added an environmental term to the utility function. The new environmental growth model had different optimal consumption and capital path.\n", "meta": {"hexsha": "1860033a86e4d80153f1f50fb651978bfc6b4983", "size": 648125, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "modelproject/modelproject.ipynb", "max_stars_repo_name": "NumEconCopenhagen/projects-2020-marcus-christian-sigrid", "max_stars_repo_head_hexsha": "6529738d3ea1bb8309c2886e5fcb64cc0f122166", "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": "modelproject/modelproject.ipynb", "max_issues_repo_name": "NumEconCopenhagen/projects-2020-marcus-christian-sigrid", "max_issues_repo_head_hexsha": "6529738d3ea1bb8309c2886e5fcb64cc0f122166", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-04-13T15:55:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-13T16:51:47.000Z", "max_forks_repo_path": "modelproject/modelproject.ipynb", "max_forks_repo_name": "NumEconCopenhagen/projects-2020-marcus-christian-sigrid", "max_forks_repo_head_hexsha": "6529738d3ea1bb8309c2886e5fcb64cc0f122166", "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": 622.0009596929, "max_line_length": 77378, "alphanum_fraction": 0.736333269, "converted": true, "num_tokens": 6951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.20181322706107543, "lm_q1q2_score": 0.09933007599098834}} {"text": "
\n\n    \n## [mlcourse.ai](https://mlcourse.ai) - Open Machine Learning Course\n\n
\nAuteur: [Egor Polusmak](https://www.linkedin.com/in/egor-polusmak/). \nTraduit et édité par [Yuanyuan Pao](https://www.linkedin.com/in/yuanyuanpao/) et [Ousmane Cissé](https://fr.linkedin.com/in/ousmane-cisse). \nCe matériel est soumis aux termes et conditions de la licence [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/). \nL'utilisation gratuite est autorisée à des fins non commerciales.\n\n#
Topic 9. Analyse des séries temporelles en Python
\n##
Partie 2. Prédire l'avenir avec Facebook Prophet
\n\nLa prévision de séries chronologiques trouve une large application dans l'analyse de données. Ce ne sont que quelques-unes des prévisions imaginables des tendances futures qui pourraient être utiles:\n- Le nombre de serveurs dont un service en ligne aura besoin l'année prochaine.\n- La demande d'un produit d'épicerie dans un supermarché un jour donné.\n- Le cours de clôture de demain d'un actif financier négociable.\n\nPour un autre exemple, nous pouvons faire une prédiction des performances d'une équipe, puis l'utiliser comme référence: d'abord pour fixer des objectifs pour l'équipe, puis pour mesurer les performances réelles de l'équipe par rapport à la référence.\n\nIl existe plusieurs méthodes différentes pour prédire les tendances futures, par exemple, [ARIMA](https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average), [ARCH](https://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity), [modèles régressifs](https://en.wikipedia.org/wiki/Autoregressive_model), [réseaux de neurones](https://medium.com/machine-learning-world/neural-networks-for-algorithmic-trading-1-2-correct-time-series-forecasting-backtesting-9776bfd9e589).\n\nDans cet article, nous examinerons [Prophet](https://facebook.github.io/prophet/), une bibliothèque de prévisions de séries chronologiques publiée par Facebook et open source, le 23 février 2017. Nous l'essayerons également dans le problème de prédiction du nombre quotidien de publications sur Medium.\n\n## Plan de l'article\n\n1. Introduction\n2. Le modèle de prévision de Prophet\n3. Entraînez-vous avec le Prophet\n    * 3.1 Installation en Python\n * 3.2 Ensemble de données\n    * 3.3 Analyse visuelle exploratoire\n * 3.4 Faire une prévision\n    * 3.5 Évaluation de la qualité des prévisions\n * 3.6 Visualisation\n4. Transformation Box-Cox\n5. Résumé\n6. Références\n\n## 1. Introduction\n\nSelon [l'article](https://research.fb.com/prophet-forecasting-at-scale/) sur Facebook Research, Prophet a été initialement développé dans le but de créer des prévisions commerciales de haute qualité. Cette bibliothèque tente de résoudre les difficultés suivantes, communes à de nombreuses séries chronologiques commerciales:\n- Effets saisonniers causés par le comportement humain: cycles hebdomadaires, mensuels et annuels, creux et pics les jours fériés.\n- Changements de tendance dus aux nouveaux produits et aux événements du marché.\n- Valeurs aberrantes.\n\nLes auteurs affirment que, même avec les paramètres par défaut, dans de nombreux cas, leur bibliothèque produit des prévisions aussi précises que celles fournies par des analystes expérimentés.\n\nDe plus, Prophet dispose d'un certain nombre de personnalisations intuitives et facilement interprétables qui permettent d'améliorer progressivement la qualité du modèle de prévision. Ce qui est particulièrement important, ces paramètres sont tout à fait compréhensibles même pour les non-experts en analyse de séries chronologiques, qui est un domaine de la science des données nécessitant certaines compétences et expérience.\n\nSoit dit en passant, l'article d'origine s'intitule «Prévisions à grande échelle», mais il ne s'agit pas de l'échelle au sens «habituel», qui traite des problèmes de calcul et d'infrastructure d'un grand nombre de programmes de travail. Selon les auteurs, Prophet devrait bien évoluer dans les 3 domaines suivants:\n- Accessibilité à un large public d'analystes, éventuellement sans expertise approfondie des séries chronologiques.\n- Applicabilité à un large éventail de problèmes de prévision distincts.\n- Estimation automatisée des performances d'un grand nombre de prévisions, y compris la signalisation des problèmes potentiels pour leur inspection ultérieure par l'analyste.\n\n## 2. Le modèle de prévision Prophet\n\nMaintenant, regardons de plus près comment fonctionne Prophet. Dans son essence, cette bibliothèque utilise le [modèle de régression additive](https://en.wikipedia.org/wiki/Additive_model) $y(t)$ comprenant les composants suivants:\n\n$$y(t) = g(t) + s(t) + h(t) + \\epsilon_{t},$$\n\noù:\n* La tendance $g(t)$ modélise les changements non périodiques.\n* La saisonnalité $s(t)$ représente des changements périodiques.\n* La composante vacances $h(t)$ fournit des informations sur les vacances et les événements.\n\nCi-dessous, nous considérerons quelques propriétés importantes de ces composants de modèle.\n\n### Tendance\n\nLa bibliothèque Prophet implémente deux modèles de tendance possibles pour $g(t)$.\n\nLe premier est appelé *Croissance saturée non linéaire*. Il est représenté sous la forme du [modèle de croissance logistique](https://en.wikipedia.org/wiki/Fonction_logistique):\n\n$$g(t) = \\frac{C}{1+e^{-k(t - m)}},$$\n\noù:\n\n* $C$ est la capacité de charge (c'est-à-dire la valeur maximale de la courbe).\n\n* $k$ est le taux de croissance (qui représente \"la pente\" de la courbe).\n\n* $m$ est un paramètre de décalage.\n\nCette équation logistique permet de modéliser la croissance non linéaire avec saturation, c'est-à-dire lorsque le taux de croissance d'une valeur diminue avec sa croissance. Un des exemples typiques serait de représenter la croissance de l'audience d'une application ou d'un site Web.\n\nEn fait, $C$ et $k$ ne sont pas nécessairement des constantes et peuvent varier dans le temps. Prophet prend en charge le réglage automatique et manuel de leur variabilité. La bibliothèque peut elle-même choisir des points optimaux de changements de tendance en ajustant les données historiques fournies.\n\nEn outre, Prophet permet aux analystes de définir manuellement des points de changement du taux de croissance et des valeurs de capacité à différents moments. Par exemple, les analystes peuvent avoir des informations sur les dates des versions précédentes qui ont influencé de manière importante certains indicateurs clés de produit.\n\nLe deuxième modèle de tendance est un simple *modèle linéaire par morceaux* (Piecewise Linear Model) avec un taux de croissance constant. \nIl est le mieux adapté aux problèmes sans saturation de la croissance.\n\n### Saisonnalité\n\nLa composante saisonnière $s(t)$ fournit un modèle flexible de changements périodiques dus à la saisonnalité hebdomadaire et annuelle.\n\nLes données saisonnières hebdomadaires sont modélisées avec des variables factices. Six nouvelles variables sont ajoutées: «lundi», «mardi», «mercredi», «jeudi», «vendredi», «samedi», qui prennent des valeurs 0 ou 1 selon le jour de la semaine. La caractéristique «dimanche» n'est pas ajoutée car ce serait une combinaison linéaire des autres jours de la semaine, et ce fait aurait un effet négatif sur le modèle.\n\nLe modèle de saisonnalité annuelle dans Prophet repose sur la série de Fourier.\n\nDepuis la version 0.2, vous pouvez également utiliser des séries chronologiques infra-journalières et faire des prévisions infra-journalières, ainsi qu'utiliser la nouvelle caractéristique de saisonnalité quotidienne.\n\n### Vacances et événements\n\nLa composante $h(t)$ représente les jours anormaux prévisibles de l'année, y compris ceux dont les horaires sont irréguliers, par exemple les Black Fridays.\n\nPour utiliser cette caractéristique, l'analyste doit fournir une liste personnalisée d'événements.\n\n### Erreur\n\nLe terme d'erreur $\\epsilon(t)$ représente des informations qui n'étaient pas reflétées dans le modèle. Habituellement, il est modélisé comme un bruit normalement distribué.\n\n### Analyse comparative (benchmark) de Prophet\n\nPour une description détaillée du modèle et des algorithmes derrière Prophet, reportez-vous à l'article [\"Forecasting at scale\"](https://peerj.com/preprints/3190/) de Sean J. Taylor et Benjamin Letham.\n\nLes auteurs ont également comparé leur bibliothèque avec plusieurs autres méthodes de prévision de séries chronologiques. Ils ont utilisé l'[Erreur absolue moyenne en pourcentage (MAPE)](https://en.wikipedia.org/wiki/Mean _absolue_ pourcentage_erreur) comme mesure de la précision de la prédiction. Dans cette analyse, Prophet a montré une erreur de prévision considérablement plus faible que les autres modèles.\n\n\n\nRegardons de plus près comment la qualité de la prévision a été mesurée dans l'article. Pour ce faire, nous aurons besoin de la formule d'erreur moyenne absolue en pourcentage.\n\nSoit $y_{i}$ la *valeur réelle (historique)* et $\\hat{y}_{i}$ la *valeur prévue* donnée par notre modèle.\n\n$e_{i} = y_{i} - \\hat{y}_{i}$ est alors *l'erreur de prévision* et $p_{i} =\\frac{\\displaystyle e_{i}}{\\displaystyle y_{i}}$ est *l'erreur de prévision relative*.\n\nNous définissons\n\n$$MAPE = mean\\big(\\left |p_{i} \\right |\\big)$$\n\nMAPE est largement utilisé comme mesure de la précision des prédictions car il exprime l'erreur en pourcentage et peut donc être utilisé dans les évaluations de modèles sur différents ensembles de données.\n\nDe plus, lors de l'évaluation d'un algorithme de prévision, il peut s'avérer utile de calculer [MAE (Mean Absolute Error)](https://en.wikipedia.org/wiki/Mean _error_ absolue) afin d'avoir une image des erreurs en nombres absolus. En utilisant des composants précédemment définis, son équation sera\n\n$$MAE = mean\\big(\\left |e_{i}\\right |\\big)$$\n\nQuelques mots sur les algorithmes avec lesquels Prophet a été comparé. La plupart d'entre eux sont assez simples et sont souvent utilisés comme référence pour d'autres modèles:\n* `naive` est une approche de prévision simpliste dans laquelle nous prédisons toutes les valeurs futures en nous appuyant uniquement sur l'observation au dernier moment disponible.\n* `snaive` (saisonnier naïf) est un modèle qui fait des prédictions constantes en tenant compte des informations sur la saisonnalité. Par exemple, dans le cas de données saisonnières hebdomadaires pour chaque futur lundi, nous prédirions la valeur du dernier lundi et pour tous les futurs mardis, nous utiliserions la valeur du dernier mardi, etc.\n* `mean` utilise la valeur moyenne des données comme prévision.\n* `arima` signifie *Autoregressive Integrated Moving Average*, voir [Wikipedia](https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average) pour plus de détails.\n* `ets` signifie *Lissage exponentiel*, voir [Wikipedia](https://en.wikipedia.org/wiki/Exponential_smoothing) pour plus d'informations.\n\n## 3. Entraînez-vous avec Facebook Prophet\n\n### 3.1 Installation en Python\n\nTout d'abord, vous devez installer la bibliothèque. Prophet est disponible pour Python et R. Le choix dépendra de vos préférences personnelles et des exigences du projet. Plus loin dans cet article, nous utiliserons Python.\n\nEn Python, vous pouvez installer Prophet à l'aide de PyPI:\n```\n$ pip install fbprophet\n```\n\nDans R, vous trouverez le package CRAN correspondant. Reportez-vous à la [documentation](https://facebookincubator.github.io/prophet/docs/installation.html) pour plus de détails.\n\nImportons les modules dont nous aurons besoin et initialisons notre environnement:\n\n\n```python\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nfrom scipy import stats\n\n%matplotlib inline\n```\n\n### 3.2 Jeu de données\n\nNous prédirons le nombre quotidien de publications publiées sur [Medium](https://medium.com/).\n\nTout d'abord, nous chargeons notre jeu de données.\n\n\n```python\ndf = pd.read_csv(\"../../data/medium_posts.csv.zip\", sep=\"\\t\")\n```\n\nEnsuite, nous omettons toutes les colonnes à l'exception de `published` et `url`. Le premier correspond à la dimension temporelle tandis que le second identifie de manière unique un message par son URL. Par la suite, nous nous débarrassons des doublons possibles et des valeurs manquantes dans les données:\n\n\n```python\ndf = df[[\"published\", \"url\"]].dropna().drop_duplicates()\n```\n\nEnsuite, nous devons convertir `published` au format datetime car par défaut `pandas` traite ce champ comme une chaîne.\n\n\n```python\ndf[\"published\"] = pd.to_datetime(df[\"published\"])\n```\n\nTrions la trame de données par date et jetons un œil à ce que nous avons:\n\n\n```python\ndf.sort_values(by=[\"published\"]).head(n=3)\n```\n\nLa date de sortie publique de Medium était le 15 août 2012. Mais, comme vous pouvez le voir sur les données ci-dessus, il existe au moins plusieurs lignes avec des dates de publication beaucoup plus anciennes. Ils sont apparus d'une manière ou d'une autre dans notre ensemble de données, mais ils ne sont guère légitimes. Nous allons simplement couper notre série chronologique pour ne conserver que les lignes qui tombent sur la période du 15 août 2012 au 25 juin 2017:\n\n\n```python\ndf = df[\n (df[\"published\"] > \"2012-08-15\") & (df[\"published\"] < \"2017-06-26\")\n].sort_values(by=[\"published\"])\ndf.head(n=3)\n```\n\n\n```python\ndf.tail(n=3)\n```\n\nComme nous allons prédire le nombre de publications, nous allons agréger et compter les publications uniques à chaque moment donné. Nous nommerons la nouvelle colonne correspondante `posts`:\n\n\n```python\naggr_df = df.groupby(\"published\")[[\"url\"]].count()\naggr_df.columns = [\"posts\"]\n```\n\nDans cette pratique, nous sommes intéressés par le nombre de messages **par jour**. Mais en ce moment, toutes nos données sont divisées en intervalles de temps irréguliers qui sont inférieurs à une journée. C'est ce qu'on appelle une série chronologique infra-journalière (*sub-daily time series*). Pour le voir, affichons les 3 premières lignes:\n\n\n```python\naggr_df.head(n=3)\n```\n\nPour résoudre ce problème, nous devons agréger le nombre de messages par \"bins\" d'une taille de date. Dans l'analyse des séries chronologiques, ce processus est appelé *rééchantillonnage* (*resampling*). Et si l'on *réduit* le taux d'échantillonnage des données, il est souvent appelé *sous-échantillonnage* (*downsampling*).\n\nHeureusement, `pandas` a une fonctionnalité intégrée pour cette tâche. Nous allons rééchantillonner notre indice de date jusqu'à des \"bins\" d'un jour:\n\n\n```python\ndaily_df = aggr_df.resample(\"D\").apply(sum)\ndaily_df.head(n=3)\n```\n\n### 3.3 Analyse visuelle exploratoire\n\nComme toujours, il peut être utile et instructif de regarder une représentation graphique de vos données.\n\nNous allons créer un tracé de série chronologique pour toute la plage de temps. L'affichage de données sur une période aussi longue peut donner des indices sur la saisonnalité et les écarts anormaux visibles.\n\nTout d'abord, nous importons et initialisons la bibliothèque `Plotly`, qui permet de créer de superbes graphes interactifs:\n\n\n```python\nfrom plotly import graph_objs as go\nfrom plotly.offline import init_notebook_mode, iplot\n\n# Initialize plotly\ninit_notebook_mode(connected=True)\n```\n\nNous définissons également une fonction d'aide, qui tracera nos trames de données tout au long de l'article:\n\n\n```python\ndef plotly_df(df, title=\"\"):\n \"\"\"Visualize all the dataframe columns as line plots.\"\"\"\n common_kw = dict(x=df.index, mode=\"lines\")\n data = [go.Scatter(y=df[c], name=c, **common_kw) for c in df.columns]\n layout = dict(title=title)\n fig = dict(data=data, layout=layout)\n iplot(fig, show_link=False)\n```\n\nEssayons de tracer notre jeu de données *tel quel*:\n\n\n```python\nplotly_df(daily_df, title=\"Posts on Medium (daily)\")\n```\n\nLes données à haute fréquence peuvent être assez difficiles à analyser. Même avec la possibilité de zoomer fournie par `Plotly`, il est difficile d'inférer quoi que ce soit de significatif à partir de ce graphique, à l'exception de la tendance à la hausse et à l'accélération.\n\nPour réduire le bruit, nous allons rééchantillonner le compte à rebours des postes jusqu'à la semaine. Outre le *binning*, d'autres techniques possibles de réduction du bruit incluent [Moving-Average Smoothing](https://en.wikipedia.org/wiki/Moving_average) et [Exponential Smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing), entre autres.\n\nNous sauvegardons notre dataframe sous-échantillonné dans une variable distincte, car dans cette pratique, nous ne travaillerons qu'avec des séries journalières:\n\n\n```python\nweekly_df = daily_df.resample(\"W\").apply(sum)\n```\n\nEnfin, nous traçons le résultat:\n\n\n```python\nplotly_df(weekly_df, title=\"Posts on Medium (weekly)\")\n```\n\nCe graphique sous-échantillonné s'avère un peu meilleur pour la perception d'un analyste.\n\nL'une des fonctions les plus utiles fournies par `Plotly` est la possibilité de plonger rapidement dans différentes périodes de la chronologie afin de mieux comprendre les données et trouver des indices visuels sur les tendances possibles, les effets périodiques et irréguliers.\n\nPar exemple, un zoom avant sur quelques années consécutives nous montre des points temporels correspondant aux vacances de Noël, qui influencent grandement les comportements humains.\n\nMaintenant, nous allons omettre les premières années d'observations, jusqu'en 2015. Premièrement, elles ne contribueront pas beaucoup à la qualité des prévisions en 2017. Deuxièmement, ces premières années, ayant un nombre très faible de messages par jour, sont susceptible d'augmenter le bruit dans nos prévisions, car le modèle serait obligé d'ajuster ces données historiques anormales avec des données plus pertinentes et indicatives des dernières années.\n\n\n```python\ndaily_df = daily_df.loc[daily_df.index >= \"2015-01-01\"]\ndaily_df.head(n=3)\n```\n\nPour résumer, à partir de l'analyse visuelle, nous pouvons voir que notre ensemble de données n'est pas stationnaire avec une tendance croissante importante. Il montre également une saisonnalité hebdomadaire et annuelle et un certain nombre de jours anormaux chaque année.\n\n### 3.4 Faire une prévision\n\nL'API de Prophet est très similaire à celle que vous pouvez trouver dans `sklearn`. Nous créons d'abord un modèle, puis appelons la méthode `fit` et, enfin, faisons une prévision. L'entrée de la méthode `fit` est un` DataFrame` avec deux colonnes:\n* `ds` (datestamp ou horodatage) doit être de type` date` ou `datetime`.\n* `y` est une valeur numérique que nous voulons prédire.\n\nPour commencer, nous allons importer la bibliothèque et éliminer les messages de diagnostic sans importance:\n\n\n```python\nimport logging\n\nfrom fbprophet import Prophet\n\nlogging.getLogger().setLevel(logging.ERROR)\n```\n\nConvertissons notre dataframe de données au format requis par Prophet:\n\n\n```python\ndf = daily_df.reset_index()\ndf.columns = [\"ds\", \"y\"]\ndf.tail(n=3)\n```\n\nLes auteurs de la bibliothèque conseillent généralement de faire des prédictions basées sur au moins plusieurs mois, idéalement, plus d'un an de données historiques. Heureusement, dans notre cas, nous avons plus de quelques années de données pour s'adapter au modèle.\n\nPour mesurer la qualité de nos prévisions, nous devons diviser notre ensemble de données en une *partie historique*, qui est la première et la plus grande tranche de nos données, et une *partie prédiction*, qui sera située à la fin de la chronologie. Nous allons supprimer le dernier mois de l'ensemble de données afin de l'utiliser plus tard comme cible de prédiction:\n\n\n```python\nprediction_size = 30\ntrain_df = df[:-prediction_size]\ntrain_df.tail(n=3)\n```\n\nMaintenant, nous devons créer un nouvel objet `Prophet`. Ici, nous pouvons passer les paramètres du modèle dans le constructeur. Mais dans cet article, nous utiliserons les valeurs par défaut. Ensuite, nous formons notre modèle en invoquant sa méthode `fit` sur notre jeu de données de formation:\n\n\n```python\nm = Prophet()\nm.fit(train_df);\n```\n\nEn utilisant la méthode `Prophet.make_future_dataframe`, nous créons un dataframe qui contiendra toutes les dates de l'historique et s'étendra également dans le futur pour les 30 jours que nous avons omis auparavant.\n\n\n```python\nfuture = m.make_future_dataframe(periods=prediction_size)\nfuture.tail(n=3)\n```\n\nNous prédisons les valeurs avec `Prophet` en passant les dates pour lesquelles nous voulons créer une prévision. Si nous fournissons également les dates historiques (comme dans notre cas), en plus de la prédiction, nous obtiendrons un ajustement dans l'échantillon pour l'historique. Appelons la méthode `predict` du modèle avec notre dataframe `future` en entrée:\n\n\n```python\nforecast = m.predict(future)\nforecast.tail(n=3)\n```\n\nDans le dataframe résultant, vous pouvez voir de nombreuses colonnes caractérisant la prédiction, y compris les composants de tendance et de saisonnalité ainsi que leurs intervalles de confiance. La prévision elle-même est stockée dans la colonne `yhat`.\n\nLa bibliothèque Prophet possède ses propres outils de visualisation intégrés qui nous permettent d'évaluer rapidement le résultat.\n\nTout d'abord, il existe une méthode appelée `Prophet.plot` qui trace tous les points de la prévision:\n\n\n```python\nm.plot(forecast);\n```\n\nCe graphique n'a pas l'air très informatif. La seule conclusion définitive que nous pouvons tirer ici est que le modèle a traité de nombreux points de données comme des valeurs aberrantes.\n\nLa deuxième fonction `Prophet.plot_components` pourrait être beaucoup plus utile dans notre cas. Il nous permet d'observer différentes composantes du modèle séparément: tendance, saisonnalité annuelle et hebdomadaire. De plus, si vous fournissez des informations sur les vacances et les événements à votre modèle, elles seront également affichées dans ce graphique.\n\nEssayons-le:\n\n\n```python\nm.plot_components(forecast);\n```\n\nComme vous pouvez le voir sur le graphique des tendances, Prophet a fait du bon travail en adaptant la croissance accélérée des nouveaux messages à la fin de 2016. Le graphique de la saisonnalité hebdomadaire conduit à la conclusion qu'il y a généralement moins de nouveaux messages le samedi et le dimanche que le les autres jours de la semaine. Dans le graphique de saisonnalité annuelle, il y a une baisse importante le jour de Noël.\n\n### 3.5 Évaluation de la qualité des prévisions\n\nÉvaluons la qualité de l'algorithme en calculant les mesures d'erreur pour les 30 derniers jours que nous avons prédits. Pour cela, nous aurons besoin des observations $y_i$ et des valeurs prédites correspondantes $\\hat{y}_i$.\n\nExaminons l'objet `forecast` que la bibliothèque a créé pour nous:\n\n\n```python\nprint(\", \".join(forecast.columns))\n```\n\nNous pouvons voir que cette base de données contient toutes les informations dont nous avons besoin, à l'exception des valeurs historiques. Nous devons joindre l'objet `forecast` avec les valeurs réelles `y` de l'ensemble de données d'origine `df`. Pour cela nous allons définir une helper fonction que nous réutiliserons plus tard:\n\n\n```python\ndef make_comparison_dataframe(historical, forecast):\n \"\"\"Join the history with the forecast.\n \n The resulting dataset will contain columns 'yhat', 'yhat_lower', 'yhat_upper' and 'y'.\n \"\"\"\n return forecast.set_index(\"ds\")[[\"yhat\", \"yhat_lower\", \"yhat_upper\"]].join(\n historical.set_index(\"ds\")\n )\n```\n\nAppliquons cette fonction à notre dernière prévision:\n\n\n```python\ncmp_df = make_comparison_dataframe(df, forecast)\ncmp_df.tail(n=3)\n```\n\nNous allons également définir une helper fonction que nous utiliserons pour évaluer la qualité de nos prévisions avec les mesures d'erreur MAPE et MAE:\n\n\n```python\ndef calculate_forecast_errors(df, prediction_size):\n \"\"\"Calculate MAPE and MAE of the forecast.\n \n Args:\n df: joined dataset with 'y' and 'yhat' columns.\n prediction_size: number of days at the end to predict.\n \"\"\"\n\n # Make a copy\n df = df.copy()\n\n # Now we calculate the values of e_i and p_i according to the formulas given in the article above.\n df[\"e\"] = df[\"y\"] - df[\"yhat\"]\n df[\"p\"] = 100 * df[\"e\"] / df[\"y\"]\n\n # Recall that we held out the values of the last `prediction_size` days\n # in order to predict them and measure the quality of the model.\n\n # Now cut out the part of the data which we made our prediction for.\n predicted_part = df[-prediction_size:]\n\n # Define the function that averages absolute error values over the predicted part.\n error_mean = lambda error_name: np.mean(np.abs(predicted_part[error_name]))\n\n # Now we can calculate MAPE and MAE and return the resulting dictionary of errors.\n return {\"MAPE\": error_mean(\"p\"), \"MAE\": error_mean(\"e\")}\n```\n\nUtilisons notre fonction:\n\n\n```python\nfor err_name, err_value in calculate_forecast_errors(cmp_df, prediction_size).items():\n print(err_name, err_value)\n```\n\nEn conséquence, l'erreur relative de notre prévision (MAPE) est d'environ 22,72%, et en moyenne notre modèle est erroné de 70,45 posts (MAE).\n\n### 3.6 Visualisation\n\nCréons notre propre visualisation du modèle construit par Prophet. Il comprendra les valeurs réelles, les prévisions et les intervalles de confiance.\n\nPremièrement, nous allons tracer les données sur une période de temps plus courte pour rendre les points de données plus faciles à distinguer. Deuxièmement, nous ne montrerons les performances du modèle que pour la période que nous avons prévue, c'est-à-dire les 30 derniers jours. Il semble que ces deux mesures devraient nous donner un graphique plus lisible.\n\nTroisièmement, nous utiliserons `Plotly` pour rendre notre graphique interactif, ce qui est idéal pour l'exploration.\n\nNous définirons notre propre helper fonction `show_forecast` et l'appellerons (pour en savoir plus sur son fonctionnement, veuillez vous référer aux commentaires dans le code et la [documentation](https://plot.ly/python/)):\n\n\n```python\ndef show_forecast(cmp_df, num_predictions, num_values, title):\n \"\"\"Visualize the forecast.\"\"\"\n\n def create_go(name, column, num, **kwargs):\n points = cmp_df.tail(num)\n args = dict(name=name, x=points.index, y=points[column], mode=\"lines\")\n args.update(kwargs)\n return go.Scatter(**args)\n\n lower_bound = create_go(\n \"Lower Bound\",\n \"yhat_lower\",\n num_predictions,\n line=dict(width=0),\n marker=dict(color=\"444\"),\n )\n upper_bound = create_go(\n \"Upper Bound\",\n \"yhat_upper\",\n num_predictions,\n line=dict(width=0),\n marker=dict(color=\"444\"),\n fillcolor=\"rgba(68, 68, 68, 0.3)\",\n fill=\"tonexty\",\n )\n forecast = create_go(\n \"Forecast\", \"yhat\", num_predictions, line=dict(color=\"rgb(31, 119, 180)\")\n )\n actual = create_go(\"Actual\", \"y\", num_values, marker=dict(color=\"red\"))\n\n # In this case the order of the series is important because of the filling\n data = [lower_bound, upper_bound, forecast, actual]\n\n layout = go.Layout(yaxis=dict(title=\"Posts\"), title=title, showlegend=False)\n fig = go.Figure(data=data, layout=layout)\n iplot(fig, show_link=False)\n\n\nshow_forecast(cmp_df, prediction_size, 100, \"New posts on Medium\")\n```\n\nÀ première vue, la prédiction des valeurs moyennes par notre modèle semble raisonnable. La valeur élevée de MAPE que nous avons obtenue ci-dessus peut s'expliquer par le fait que le modèle n'a pas réussi à saisir l'amplitude croissante de pic-à-pic (peak-to-peak) d'une faible saisonnalité. \n\nEn outre, nous pouvons conclure du graphique ci-dessus que de nombreuses valeurs réelles se trouvent en dehors de l'intervalle de confiance. Prophet peut ne pas convenir aux séries chronologiques avec une variance instable, du moins lorsque les paramètres par défaut sont utilisés. Nous allons essayer de résoudre ce problème en appliquant une transformation à nos données.\n\n## 4. Transformation Box-Cox\n\nJusqu'à présent, nous avons utilisé Prophet avec les paramètres par défaut et les données d'origine. Nous laisserons les paramètres du modèle seuls. Mais malgré cela, nous avons encore des progrès à faire. Dans cette section, nous appliquerons la [Box–Cox transformation](http://onlinestatbook.com/2/transformations/box-cox.html) à notre série originale. Voyons où cela nous mènera.\n\nQuelques mots sur cette transformation. Il s'agit d'une transformation de données monotone qui peut être utilisée pour stabiliser la variance. Nous utiliserons la transformation Box-Cox à un paramètre, qui est définie par l'expression suivante:\n\n$$\n\\begin{equation}\n boxcox^{(\\lambda)}(y_{i}) = \\begin{cases}\n \\frac{\\displaystyle y_{i}^{\\lambda} - 1}{\\displaystyle \\lambda} &, \\text{if $\\lambda \\neq 0$}.\\\\\n ln(y_{i}) &, \\text{if $\\lambda = 0$}.\n \\end{cases}\n\\end{equation}\n$$\n\nNous devrons implémenter l'inverse de cette fonction afin de pouvoir restaurer l'échelle de données d'origine. Il est facile de voir que l'inverse est défini comme:\n\n$$\n\\begin{equation}\n invboxcox^{(\\lambda)}(y_{i}) = \\begin{cases}\n e^{\\left (\\frac{\\displaystyle ln(\\lambda y_{i} + 1)}{\\displaystyle \\lambda} \\right )} &, \\text{if $\\lambda \\neq 0$}.\\\\\n e^{y_{i}} &, \\text{if $\\lambda = 0$}.\n \\end{cases}\n\\end{equation}\n$$\n\nLa fonction correspondante en Python est implémentée comme suit:\n\n\n```python\ndef inverse_boxcox(y, lambda_):\n return np.exp(y) if lambda_ == 0 else np.exp(np.log(lambda_ * y + 1) / lambda_)\n```\n\nTout d'abord, nous préparons notre jeu de données en définissant son index:\n\n\n```python\ntrain_df2 = train_df.copy().set_index(\"ds\")\n```\n\nEnsuite, nous appliquons la fonction `stats.boxcox` de` Scipy`, qui applique la transformation Box – Cox. Dans notre cas, il renverra deux valeurs. La première est la série transformée et la seconde est la valeur trouvée de $\\lambda$ qui est optimale en termes de maximum de log-vraisemblance (maximum log-likelihood):\n\n\n```python\ntrain_df2[\"y\"], lambda_prophet = stats.boxcox(train_df2[\"y\"])\ntrain_df2.reset_index(inplace=True)\n```\n\nNous créons un nouveau modèle `Prophet` et répétons le cycle d'ajustement de prévision que nous avons déjà fait ci-dessus:\n\n\n```python\nm2 = Prophet()\nm2.fit(train_df2)\nfuture2 = m2.make_future_dataframe(periods=prediction_size)\nforecast2 = m2.predict(future2)\n```\n\nÀ ce stade, nous devons inverser la transformation de Box – Cox avec notre fonction inverse et la valeur connue de $\\lambda$:\n\n\n```python\nfor column in [\"yhat\", \"yhat_lower\", \"yhat_upper\"]:\n forecast2[column] = inverse_boxcox(forecast2[column], lambda_prophet)\n```\n\nIci, nous allons réutiliser nos outils pour faire le dataframe de comparaison et calculer les erreurs:\n\n\n```python\ncmp_df2 = make_comparison_dataframe(df, forecast2)\nfor err_name, err_value in calculate_forecast_errors(cmp_df2, prediction_size).items():\n print(err_name, err_value)\n```\n\nOn peut donc affirmer avec certitude que la qualité du modèle s'est améliorée. \n\nEnfin, tracons nos performances précédentes avec les derniers résultats côte à côte. Notez que nous utilisons `prediction_size` pour le troisième paramètre afin de zoomer sur l'intervalle prévu:\n\n\n```python\nshow_forecast(cmp_df, prediction_size, 100, \"No transformations\")\nshow_forecast(cmp_df2, prediction_size, 100, \"Box–Cox transformation\")\n```\n\nNous voyons que la prévision des changements hebdomadaires dans le deuxième graphique est beaucoup plus proche des valeurs réelles maintenant.\n\n## 5. Résumé\n\nNous avons jeté un coup d'œil à *Prophet*, une bibliothèque de prévisions open source spécifiquement destinée aux séries chronologiques commerciales. Nous avons également effectué des exercices pratiques de prévision des séries chronologiques.\n\nComme nous l'avons vu, la bibliothèque Prophet ne fait pas de merveilles et ses prédictions prêtes à l'emploi ne sont pas [idéales](https://en.wikipedia.org/wiki/No_free_lunch_in_search_and_optimization). Il appartient toujours au data scientist d'explorer les résultats des prévisions, d'ajuster les paramètres du modèle et de transformer les données si nécessaire.\n\nToutefois, cette bibliothèque est conviviale et facilement personnalisable. La seule possibilité de prendre en compte les jours anormaux connus de l'analyste à l'avance peut faire la différence dans certains cas\n\nDans l'ensemble, la bibliothèque Prophet vaut la peine de faire partie de votre boîte à outils analytiques.\n\n## 6. Références\n\n- Official [Prophet repository](https://github.com/facebookincubator/prophet) on GitHub.\n- Official [Prophet documentation](https://facebookincubator.github.io/prophet/docs/quick_start.html).\n- Sean J. Taylor, Benjamin Letham [\"Forecasting at scale\"](https://facebookincubator.github.io/prophet/static/prophet_paper_20170113.pdf) — scientific paper explaining the algorithm which lays the foundation of `Prophet`.\n- [Forecasting Website Traffic Using Facebook’s Prophet Library](http://pbpython.com/prophet-overview.html) — `Prophet` overview with an example of website traffic forecasting.\n- Rob J. Hyndman, George Athanasopoulos [\"Forecasting: principles and practice\"](https://www.otexts.org/fpp) – a very good online book about time series forecasting.\n", "meta": {"hexsha": "c4fb4055ac180c39e64294e3c12204880a1a963b", "size": 48233, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter_french/topic09_time_series/topic9_part2_facebook_prophet-fr_def.ipynb", "max_stars_repo_name": "salman394/AI-ml--course", "max_stars_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter_french/topic09_time_series/topic9_part2_facebook_prophet-fr_def.ipynb", "max_issues_repo_name": "salman394/AI-ml--course", "max_issues_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter_french/topic09_time_series/topic9_part2_facebook_prophet-fr_def.ipynb", "max_forks_repo_name": "salman394/AI-ml--course", "max_forks_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3031709203, "max_line_length": 505, "alphanum_fraction": 0.6396243236, "converted": true, "num_tokens": 8616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.2281565074091475, "lm_q1q2_score": 0.09901569194943782}} {"text": "Before you turn in your homework, make sure everything runs as expected.\n\nMake sure you execute every single code cell, in order, filling with your solutions in any place that says `# YOUR CODE HERE`, and always DELETE the line that says:\n\n```python\nraise NotImplementedError()\n```\n\nThe purpose of this line is to tell you if you forgot to answer a question (it will throw an error if the line is there)\n\n**IMPORTANT:**\n\n* **DO NOT DELETE ANY CELL** and do not change the title of the Notebook.\n\n* Use the same variable names as the ones written in the questions; otherwise, the tests will fail.\n\n* Before you turn in your homework, make sure everything runs as expected: restart the kernel (in the menubar, select Kernel $\\rightarrow$ Restart) and then run all cells (in the menubar, select Cell $\\rightarrow$ Run All).\n\nFill your name below:\n\n\n```python\nname = \"Yinfeng Ding\"\n```\n\n# Sod's test problems\n\nSod's test problems are standard benchmarks used to assess the accuracy of numerical solvers. The tests use a classic example of one-dimensional compressible flow: the shock-tube problem. Sod (1978) chose initial conditions and numerical discretization parameters for the shock-tube problem and used these to test several schemes, including Lax-Wendroff and MacCormack's. Since then, many others have followed Sod's example and used the same tests on new numerical methods.\n\nThe shock-tube problem is so useful for testing numerical methods because it is one of the few problems that allows an exact solution of the Euler equations for compressible flow.\n\nThis notebook complements the previous lessons of the course module [_\"Riding the wave: convection problems\"_](https://github.com/numerical-mooc/numerical-mooc/tree/master/lessons/03_wave) with Sod's test problems as an independent coding exercise. We'll lay out the problem for you, but leave important bits of code for you to write on your own. Good luck!\n\n## What's a shock tube?\n\nA shock tube is an idealized device that generates a one-dimensional shock wave in a compressible gas. The setting allows an analytical solution of the Euler equations, which is very useful for comparing with the numerical results to assess their accuracy. \n\nPicture a tube with two regions containing gas at different pressures, separated by an infinitely-thin, rigid diaphragm. The gas is initially at rest, and the left region is at a higher pressure than the region to the right of the diaphragm. At time $t = 0.0 s$, the diaphragm is ruptured instantaneously. \n\nWhat happens? \n\nYou get a shock wave. The gas at high pressure, no longer constrained by the diaphragm, rushes into the lower-pressure area and a one-dimensional unsteady flow is established, consisting of:\n\n* a shock wave traveling to the right\n* an expansion wave traveling to the left\n* a moving contact discontinuity\n\nThe shock-tube problem is an example of a *Riemann problem* and it has an analytical solution, as we said. The situation is illustrated in Figure 1.\n\n\n
Figure 1: The shock-tube problem.
\n\n## The Euler equations\n\nThe Euler equations govern the motion of an inviscid fluid (no viscosity). They consist of the conservation laws of mass and momentum, and often we also need to work with the energy equation. \n\nLet's consider a 1D flow with velocity $u$ in the $x$-direction. The Euler equations for a fluid with density $\\rho$ and pressure $p$ are:\n\n$$\n\\begin{cases}\n &\\frac{\\partial \\rho}{\\partial t} + \\frac{\\partial}{\\partial x}(\\rho u) = 0 \\\\\n &\\frac{\\partial}{\\partial t}(\\rho u) + \\frac{\\partial}{\\partial x} (\\rho u^2 + p)=0\n\\end{cases}\n$$\n\n... plus the energy equation, which we can write in this form:\n\n$$\n\\begin{equation}\n\\frac{\\partial}{\\partial t}(\\rho e_T) + \\frac{\\partial}{\\partial x} (\\rho u e_T +p u)=0\n\\end{equation}\n$$\n\nwhere $e_T=e+u^2/2$ is the total energy per unit mass, equal to the internal energy plus the kinetic energy (per unit mass).\n\nWritten in vector form, you can see that the Euler equations bear a strong resemblance to the traffic-density equation that has been the focus of this course module so far. Here is the vector representation of the Euler equation:\n\n$$\n\\begin{equation}\n\\frac{\\partial }{\\partial t} \\underline{\\mathbf{u}} + \\frac{\\partial }{\\partial x} \\underline{\\mathbf{f}} = 0\n\\end{equation}\n$$\n\nThe big difference with our previous work is that the variables $\\underline{\\mathbf{u}}$ and $\\underline{\\mathbf{f}}$ are *vectors*. If you review the [Phugoid Full Model](https://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb) lesson, you will recall that we can solve for several values at once using the vector form of an equation. In the Phugoid Module, it was an ODE—now we apply the same procedure to a PDE. \n\nLet's take a look at what $\\underline{\\mathbf{u}}$ and $\\underline{\\mathbf{f}}$ consist of.\n\n## The conservative form\n\nMany works in the early days of computational fluid dynamics in the 1960s showed that using the conservation form of the Euler equations is more accurate for situations with shock waves. And as you already saw, the shock-tube solutions do contain shocks.\n\nThe conserved variables $\\underline{\\mathbf{u}}$ for Euler's equations are\n\n$$\n\\begin{equation}\n\\underline{\\mathbf{u}} = \\left[\n\\begin{array}{c}\n\\rho \\\\\n\\rho u \\\\\n\\rho e_T \\\\ \n\\end{array}\n\\right]\n\\end{equation}\n$$\n\nwhere $\\rho$ is the density of the fluid, $u$ is the velocity of the fluid and $e_T = e + \\frac{u^2}{2}$ is the specific total energy; $\\underline{\\mathbf{f}}$ is the flux vector:\n\n$$\n\\begin{equation}\n\\underline{\\mathbf{f}} = \\left[\n\\begin{array}{c}\n\\rho u \\\\\n\\rho u^2 + p \\\\\n(\\rho e_T + p) u \\\\\n\\end{array}\n\\right]\n\\end{equation}\n$$\n\nwhere $p$ is the pressure of the fluid.\n\nIf we put together the conserved variables and the flux vector into our PDE, we get the following set of equations:\n\n$$\n\\begin{equation}\n \\frac{\\partial}{\\partial t}\n \\left[\n \\begin{array}{c}\n \\rho \\\\\n \\rho u \\\\\n \\rho e_T \\\\\n \\end{array}\n \\right] +\n \\frac{\\partial}{\\partial x}\n \\left[\n \\begin{array}{c}\n \\rho u \\\\\n \\rho u^2 + p \\\\\n (\\rho e_T + p) u \\\\\n \\end{array}\n \\right] =\n 0\n\\end{equation}\n$$\n\nThere's one major problem there. We have 3 equations and 4 unknowns. But there is a solution! We can use an equation of state to calculate the pressure—in this case, we'll use the ideal gas law.\n\n## Calculating the pressure\n\nFor an ideal gas, the equation of state is\n\n$$\ne = e(\\rho, p) = \\frac{p}{(\\gamma -1) \\rho}\n$$\n\nwhere $\\gamma = 1.4$ is a reasonable value to model air, \n\n$$\n\\therefore p = (\\gamma -1)\\rho e\n$$ \n\nRecall from above that\n\n$$\ne_T = e+\\frac{1}{2} u^2\n$$\n\n$$\n\\therefore e = e_T - \\frac{1}{2}u^2\n$$\n\nPutting it all together, we arrive at an equation for the pressure\n\n$$\np = (\\gamma -1)\\left(\\rho e_T - \\frac{\\rho u^2}{2}\\right)\n$$\n\n## Flux in terms of $\\underline{\\mathbf{u}}$\n\nWith the traffic model, the flux was a function of traffic density. For the Euler equations, the three equations we have are coupled and the flux *vector* is a function of $\\underline{\\mathbf{u}}$, the vector of conserved variables:\n\n$$\n\\underline{\\mathbf{f}} = f(\\underline{\\mathbf{u}})\n$$\n\nIn order to get everything squared away, we need to represent $\\underline{\\mathbf{f}}$ in terms of $\\underline{\\mathbf{u}}$.\nWe can introduce a little shorthand for the $\\underline{\\mathbf{u}}$ and $\\underline{\\mathbf{f}}$ vectors and define:\n\n$$\n\\underline{\\mathbf{u}} =\n\\left[\n \\begin{array}{c}\n u_1 \\\\\n u_2 \\\\\n u_3 \\\\\n \\end{array}\n\\right] =\n\\left[\n \\begin{array}{c}\n \\rho \\\\\n \\rho u \\\\\n \\rho e_T \\\\\n \\end{array}\n\\right]\n$$\n\n$$\n\\underline{\\mathbf{f}} =\n\\left[\n \\begin{array}{c}\n f_1 \\\\\n f_2 \\\\\n f_3 \\\\\n \\end{array}\n\\right] =\n\\left[\n \\begin{array}{c}\n \\rho u \\\\\n \\rho u^2 + p \\\\\n (\\rho e_T + p) u \\\\\n \\end{array}\n\\right]\n$$ \n\nWith a little algebraic trickery, we can represent the pressure vector using quantities from the $\\underline{\\mathbf{u}}$ vector.\n\n$$\np = (\\gamma -1)\\left(u_3 - \\frac{1}{2} \\frac{u^2_2}{u_1} \\right)\n$$\n\nNow that pressure can be represented in terms of $\\underline{\\mathbf{u}}$, the rest of $\\underline{\\mathbf{f}}$ isn't too difficult to resolve:\n\n$$\\underline{\\mathbf{f}} = \\left[ \\begin{array}{c}\nf_1 \\\\\nf_2 \\\\\nf_3 \\\\ \\end{array} \\right] =\n\\left[ \\begin{array}{c}\nu_2\\\\\n\\frac{u^2_2}{u_1} + (\\gamma -1)\\left(u_3 - \\frac{1}{2} \\frac{u^2_2}{u_1} \\right) \\\\\n\\left(u_3 + (\\gamma -1)\\left(u_3 - \\frac{1}{2} \\frac{u^2_2}{u_1}\\right) \\right) \\frac{u_2}{u_1}\\\\ \\end{array}\n\\right]$$\n\n## Test conditions\n\nThe first test proposed by Sod in his 1978 paper is as follows. \n\nIn a tube spanning from $x = -10 \\text{m}$ to $x = 10 \\text{m}$ with the rigid membrane at $x = 0 \\text{m}$, we have the following initial gas states:\n\n$$\n\\underline{IC}_L =\n\\left[\n \\begin{array}{c}\n \\rho_L \\\\\n u_L \\\\\n p_L \\\\\n \\end{array}\n\\right] =\n\\left[\n \\begin{array}{c}\n 1.0 \\, kg/m^3 \\\\\n 0 \\, m/s \\\\\n 100 \\, kN/m^2 \\\\\n \\end{array}\n\\right]\n$$\n\n$$\n\\underline{IC}_R =\n\\left[\n \\begin{array}{c}\n \\rho_R \\\\\n u_R \\\\\n p_R \\\\\n \\end{array}\n\\right] =\n\\left[\n \\begin{array}{c}\n 0.125 \\, kg/m^3 \\\\\n 0 \\, m/s \\\\\n 10 \\, kN/m^2 \\\\\n \\end{array}\n\\right]\n$$\n\nwhere $\\underline{IC}_L$ are the initial density, velocity and pressure on the left side of the tube membrane and $\\underline{IC}_R$ are the initial density, velocity and pressure on the right side of the tube membrane. \n\nThe analytical solution to this test for the velocity, pressure and density, looks like the plots in Figure 2.\n\n\n
Figure 2. Analytical solution for Sod's first test.
\n\n## The Richtmyer method\n\nFor this exercise, you will use the **Lax-Friedrichs** scheme that we implemented in [lesson 2](https://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/03_wave/03_02_convectionSchemes.ipynb).\nBut, we will also be using a new scheme called the **Richtmyer** method.\nLike the MacCormack method, Richtmyer is a *two-step method*, given by:\n\n$$\n\\begin{align}\n\\underline{\\mathbf{u}}^{n+\\frac{1}{2}}_{i+\\frac{1}{2}} &= \\frac{1}{2} \\left( \\underline{\\mathbf{u}}^n_{i+1} + \\underline{\\mathbf{u}}^n_i \\right) - \n\\frac{\\Delta t}{2 \\Delta x} \\left( \\underline{\\mathbf{f}}^n_{i+1} - \\underline{\\mathbf{f}}^n_i\\right) \\\\\n\\underline{\\mathbf{u}}^{n+1}_i &= \\underline{\\mathbf{u}}^n_i - \\frac{\\Delta t}{\\Delta x} \\left(\\underline{\\mathbf{f}}^{n+\\frac{1}{2}}_{i+\\frac{1}{2}} - \\underline{\\mathbf{f}}^{n+\\frac{1}{2}}_{i-\\frac{1}{2}} \\right)\n\\end{align}\n$$\n\nThe flux vectors used in the second step are obtained by evaluating the flux functions on the output of the first step:\n\n$$\n\\underline{\\mathbf{f}}^{n+\\frac{1}{2}}_{i+\\frac{1}{2}} = \\underline{\\mathbf{f}}\\left(\\underline{\\mathbf{u}}^{n+\\frac{1}{2}}_{i+\\frac{1}{2}}\\right)\n$$\n\nThe first step is like a *predictor* of the solution: if you look closely, you'll see that we are applying a Lax-Friedrichs scheme here. The second step is a *corrector* that applies a leapfrog update. Figure 3 gives a sketch of the stencil for Richtmyer method, where the \"intermediate time\" $n+1/2$ will require a temporary variable in your code, just like we had in the MacCormack scheme.\n\n\n
Figure 3. Stencil of Richtmyer scheme.
\n\n## Implement your solution (40 points)\n\n---\n\nYour mission, should you wish to accept it, is to calculate the pressure, density and velocity along the shock tube at time $t = 0.01 s$ using the Richtmyer method **and** the Lax-Friedrichs method. Good luck!\n\nCode parameters to use:\n\n* Number of discrete points along the 1D domain: `nx = 81` (which gives `dx = 0.25` for a domain of length 20).\n* Time-step size: `dt = 0.0002`.\n* Heat capacity ratio: `gamma = 1.4`.\n\nImplement your solution in this section.\nYou can use as many code cells as you want.\n\n\n```python\n# YOUR CODE HERE\nimport numpy\nimport sympy\nfrom matplotlib import pyplot\n%matplotlib inline\n```\n\n\n```python\n# Set the font family and size to use for Matplotlib figures.\npyplot.rcParams['font.family'] = 'serif'\npyplot.rcParams['font.size'] = 16\nsympy.init_printing()\n```\n\n\n```python\n# Set parameters.\nnx = 81\ndx = 0.25\ndt = 0.0002\ngamma = 1.4\nt = 0.01\nnt = int(t/dt)+1\n```\n\n\n```python\n# Get the grid point coordinates.\nx = numpy.linspace(-10,10,num = nx)\n\n# Set the initial conditions.\nrho0 = numpy.ones(nx)\nmask = numpy.where(x >= 0)\nrho0[mask] = 0.125\np0 = 100000*numpy.ones(nx)\np0[mask] = 10000\nv0 = numpy.zeros(nx)\ne0 = p0 / ((gamma-1) * rho0)\neT0 = e0 + 0.5 * v0**2\n\nu0 = numpy.array([rho0,\n rho0*v0,\n rho0*eT0])\nf0 = numpy.array([u0[1],\n u0[1]**2 / u0[0] + (gamma-1)*(u0[2] - 0.5*u0[1]**2 / u0[0]),\n (u0[2] + (gamma - 1) * (u0[2] - 0.5*u0[1]**2 / u0[0])) * u0[1] / u0[0]])\n```\n\n\n```python\n# Richtmyer scheme, two step method, R1, R2\nu_R2 = u0.copy()\nu_R1 = u_R2.copy()\nf_R2 = f0.copy()\n\nfor i in range(1, nt):\n u_R1 = 0.5 * (u_R2[:,1:] + u_R2[:,:-1]) - dt / (2 * dx) * (f_R2[:,1:] - f_R2[:,:-1])# first step is like a predictor of the solution\n f_R1 = numpy.array([u_R1[1],\n u_R1[1]**2 / u_R1[0] + (gamma - 1) * (u_R1[2] - 0.5 * u_R1[1]**2 / u_R1[0]),\n (u_R1[2] + (gamma -1) * (u_R1[2] - 0.5 * u_R1[1]**2 / u_R1[0])) * u_R1[1] / u_R1[0]])\n u_R2[:,1:-1] = u_R2[:,1:-1] - dt / dx * (f_R1[:,1:] - f_R1[:,:-1])# corrector that applies a leapfrog update, advance in time\n f_R2 = numpy.array([u_R2[1],\n u_R2[1]**2 / u_R2[0] + (gamma - 1) * (u_R2[2] - 0.5 * u_R2[1]**2 / u_R2[0]),\n (u_R2[2] + (gamma -1) * (u_R2[2] - 0.5 * u_R2[1]**2 / u_R2[0])) * u_R2[1] / u_R2[0]])\n\nrho_Richtmyer = u_R2[0]\nv_Richtmyer = u_R2[1] / u_R2[0]\np_Richtmyer = (gamma -1) * (u_R2[2] - 0.5 * u_R2[1]**2 / u_R2[0])\n```\n\n\n```python\n# Lax-Friedrichs scheme\nu_L = u0.copy()\nf_L = f0.copy()\nfor n in range(1, nt):\n # Advance in time using Lax-Friedrichs scheme.\n u_L[:,1:-1] = 0.5*(u_L[:,:-2] + u_L[:,2:]) - 0.5*dt/dx * (f_L[:,2:] - f_L[:,:-2])\n f_L = numpy.array([u_L[1],\n u_L[1]**2 / u_L[0] + (gamma - 1) * (u_L[2] - 0.5 * u_L[1]**2 / u_L[0]),\n (u_L[2] + (gamma -1) * (u_L[2] - 0.5 * u_L[1]**2 / u_L[0])) * u_L[1] / u_L[0]])\nrho_Lax = u_L[0]\nv_Lax = u_L[1] / u_L[0]\np_Lax = (gamma -1) * (u_L[2] - 0.5 * u_L[1]**2 / u_L[0])\n```\n\n## Assessment (80 points)\n\n---\n\nAnswer questions in this section.\n\nDo not try to delete or modify empty code cells that are already present.\nFor each question, provide your answer in the cell **just above** the empty cell.\n(This empty cell contains hidden tests to assert the correctness of your answer and cannot be deleted.)\nPay attention to the name of the variables we ask you to create to store computed values; if the name of the variable is misspelled, the test will fail.\n\n\n```python\ntry:\n import mooc37 as mooc\nexcept:\n import mooc36 as mooc\n```\n\n* **Q1 (10 points):** Plot the numerical solution of the density, velocity, and pressure at time $t = 0.01 s$ obtained with the Richtmyer scheme **and** with the Lax-Friedrichs scheme.\n\nYou should also plot the analytical solution.\nThe analytical solution can be obtained using the function `analytical_solution` from the Python file `sod.py` (located in the same folder than the Jupyter Notebook).\nTo import the function in your Notebook, use `from sod import analytical_solution`.\nYou can use `help(analytical_solution)` to see how you should call the function.\n\nCreate one figure per variable and make sure to label your axes.\n(For example, the first figure should contain the numerical solution of the density using both schemes, as well as the analytical solution for the density.)\nMake sure to add a legend to your plots.\n\n\n```python\n# YOUR CODE HERE\nfrom sod import analytical_solution\nhelp(analytical_solution)\n```\n\n Help on function analytical_solution in module sod:\n \n analytical_solution(t, x, left_state, right_state, diaphragm=0.0, gamma=1.4)\n Compute the analytical solution of the Sod's test at a given time.\n \n Parameters\n ----------\n t : float\n The time.\n x : numpy.ndarray\n Coordinates along the tube (as a 1D array of floats).\n left_state : tuple or list\n Initial density, velocity, and pressure values\n on left side of the diaphragm.\n The argument should be a tuple or list with 3 floats.\n right_state : tuple or list\n Initial density, velocity, and pressure values\n on right side of the diaphragm.\n The argument should be a tuple or list with 3 floats.\n diaphragm : float, optional\n Location of the diaphgram (membrane), by default 0.0.\n gamma : float, optional\n Heat capacity ratio, by default 1.4.\n \n Returns\n -------\n tuple of numpy.ndarray objects\n The density, velocity, and pressure along the tube at the given time.\n This is a tuple with 3 elements: (density, velocity, pressure).\n Each element is a 1D NumPy array of floats.\n \n\n\n\n```python\n# Analytical solution\n# Set the initial conditions.\nleft_state = [1.0, 0.0, 100000.0]\nright_state = [0.125, 0.0, 10000.0]\n\n# Analytical solution at t = 0.01\nA = analytical_solution(t, x, left_state, right_state, diaphragm=0.0, gamma=1.4)\nrho_analytical = A[0]\nv_analytical = A[1]\np_analytical = A[2]\n```\n\n\n```python\n# Plot rho\npyplot.figure(figsize=(6.0, 6.0))\npyplot.title('Density at time 0.01s')\npyplot.xlabel('x')\npyplot.ylabel('rho')\npyplot.grid()\npyplot.plot(x, rho_Richtmyer, label='Richtmyer', color='C0', linestyle='-', linewidth=2)\npyplot.plot(x, rho_Lax, label='Lax-Friedrich', color='C1', linestyle='-', linewidth=2)\npyplot.plot(x, rho_analytical, label='Analytical', color='C2', linestyle='-', linewidth=2)\npyplot.legend()\npyplot.xlim(-10.0, 10.0)\npyplot.ylim(0.0, 1.1)\n```\n\n\n```python\n# Plot velocity\npyplot.figure(figsize=(6.0, 6.0))\npyplot.title('Velocity at time 0.01s')\npyplot.xlabel('x')\npyplot.ylabel('velocity')\npyplot.grid()\npyplot.plot(x, v_Richtmyer, label='Richtmyer', color='C0', linestyle='-', linewidth=2)\npyplot.plot(x, v_Lax, label='Lax-Friedrich', color='C1', linestyle='-', linewidth=2)\npyplot.plot(x, v_analytical, label='Analytical', color='C2', linestyle='-', linewidth=2)\npyplot.legend()\npyplot.xlim(-10.0, 10.0)\npyplot.ylim(0.0, 400.0)\n```\n\n\n```python\n# Plot pressure\npyplot.figure(figsize=(6.0, 6.0))\npyplot.title('Pressure at time 0.01s')\npyplot.xlabel('x')\npyplot.ylabel('pressure')\npyplot.grid()\npyplot.plot(x, p_Richtmyer, label='Richtmyer', color='C0', linestyle='-', linewidth=2)\npyplot.plot(x, p_Lax, label='Lax-Friedrich', color='C1', linestyle='-', linewidth=2)\npyplot.plot(x, p_analytical, label='analytical', color='C2', linestyle='-', linewidth=2)\npyplot.legend()\npyplot.xlim(-10.0, 10.0)\npyplot.ylim(0.0, 110000.0)\n```\n\n* **Q2 (10 points):** At $t = 0.01 s$, what type of numerical errors to you observe in the numerical solution obtained with the Richtmyer scheme and with the Lax-Friedrichs scheme? (Diffusion errors? Dispersion errors? Explain why.)\n\nYou should write your answer in the following Markdown cell.\n\nYOUR ANSWER HERE\n\nThe Richtmyer scheme has dispersion errors. Observing the curve, we can find that the richtmyer scheme curve is closer to the analytical curve, and the curve oscillates, which is achieved through second-order accuracy. Numerical dispersion occurs when a higher order discretisation scheme is used to improve accuracy of the result. Numerical dispersion often takes the form of so-called 'spurious oscillations'. This is due to the truncation error of the discretisation. This is due to the truncation error of the discretisation. A second order upwind method, the leading truncation error is odd. And odd order derivatives contribute to numerical dispersion. \n\nThe Lax-Friedrichs scheme has diffusion errors. substituting 𝜌𝑛𝑖 by the average of its neighbors introduces a first-order error. Numerical diffusion occurs when 1st order discretisation are used. This is due to the truncation error of the discretisation. The truncation is an odd-order method, the leading truncation error is even. Even order derivatives in the truncation error contribute to numerical diffusion.\n\n* **Q3 (5 points):** At $t = 0.01 s$, what's the $L_2$-norm of the difference between the density obtained with the Richtmyer scheme and the analytical solution?\n\nStore your result in the variable `l2_norm1`; you can check your answer by calling the function `mooc.check('hw3_l2_norm1', l2_norm1)`.\n\n**WARNING:** the variable name `l2_norm1` is spelled with the number `1`, **not** the letter `l`.\n\n\n```python\n# YOUR CODE HERE\nDiff = rho_Richtmyer - rho_analytical\nhelp(numpy.linalg.norm)\nl2_norm1 = numpy.linalg.norm(Diff, ord=2, axis=0)\nprint(l2_norm1)\nmooc.check('hw3_l2_norm1', l2_norm1)\n```\n\n Help on function norm in module numpy.linalg:\n \n norm(x, ord=None, axis=None, keepdims=False)\n Matrix or vector norm.\n \n This function is able to return one of eight different matrix norms,\n or one of an infinite number of vector norms (described below), depending\n on the value of the ``ord`` parameter.\n \n Parameters\n ----------\n x : array_like\n Input array. If `axis` is None, `x` must be 1-D or 2-D, unless `ord`\n is None. If both `axis` and `ord` are None, the 2-norm of\n ``x.ravel`` will be returned.\n ord : {non-zero int, inf, -inf, 'fro', 'nuc'}, optional\n Order of the norm (see table under ``Notes``). inf means numpy's\n `inf` object. The default is None.\n axis : {None, int, 2-tuple of ints}, optional.\n If `axis` is an integer, it specifies the axis of `x` along which to\n compute the vector norms. If `axis` is a 2-tuple, it specifies the\n axes that hold 2-D matrices, and the matrix norms of these matrices\n are computed. If `axis` is None then either a vector norm (when `x`\n is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default\n is None.\n \n .. versionadded:: 1.8.0\n \n keepdims : bool, optional\n If this is set to True, the axes which are normed over are left in the\n result as dimensions with size one. With this option the result will\n broadcast correctly against the original `x`.\n \n .. versionadded:: 1.10.0\n \n Returns\n -------\n n : float or ndarray\n Norm of the matrix or vector(s).\n \n See Also\n --------\n scipy.linalg.norm : Similar function in SciPy.\n \n Notes\n -----\n For values of ``ord < 1``, the result is, strictly speaking, not a\n mathematical 'norm', but it may still be useful for various numerical\n purposes.\n \n The following norms can be calculated:\n \n ===== ============================ ==========================\n ord norm for matrices norm for vectors\n ===== ============================ ==========================\n None Frobenius norm 2-norm\n 'fro' Frobenius norm --\n 'nuc' nuclear norm --\n inf max(sum(abs(x), axis=1)) max(abs(x))\n -inf min(sum(abs(x), axis=1)) min(abs(x))\n 0 -- sum(x != 0)\n 1 max(sum(abs(x), axis=0)) as below\n -1 min(sum(abs(x), axis=0)) as below\n 2 2-norm (largest sing. value) as below\n -2 smallest singular value as below\n other -- sum(abs(x)**ord)**(1./ord)\n ===== ============================ ==========================\n \n The Frobenius norm is given by [1]_:\n \n :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`\n \n The nuclear norm is the sum of the singular values.\n \n Both the Frobenius and nuclear norm orders are only defined for\n matrices and raise a ValueError when ``x.ndim != 2``.\n \n References\n ----------\n .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,\n Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15\n \n Examples\n --------\n >>> from numpy import linalg as LA\n >>> a = np.arange(9) - 4\n >>> a\n array([-4, -3, -2, ..., 2, 3, 4])\n >>> b = a.reshape((3, 3))\n >>> b\n array([[-4, -3, -2],\n [-1, 0, 1],\n [ 2, 3, 4]])\n \n >>> LA.norm(a)\n 7.745966692414834\n >>> LA.norm(b)\n 7.745966692414834\n >>> LA.norm(b, 'fro')\n 7.745966692414834\n >>> LA.norm(a, np.inf)\n 4.0\n >>> LA.norm(b, np.inf)\n 9.0\n >>> LA.norm(a, -np.inf)\n 0.0\n >>> LA.norm(b, -np.inf)\n 2.0\n \n >>> LA.norm(a, 1)\n 20.0\n >>> LA.norm(b, 1)\n 7.0\n >>> LA.norm(a, -1)\n -4.6566128774142013e-010\n >>> LA.norm(b, -1)\n 6.0\n >>> LA.norm(a, 2)\n 7.745966692414834\n >>> LA.norm(b, 2)\n 7.3484692283495345\n \n >>> LA.norm(a, -2)\n 0.0\n >>> LA.norm(b, -2)\n 1.8570331885190563e-016 # may vary\n >>> LA.norm(a, 3)\n 5.8480354764257312 # may vary\n >>> LA.norm(a, -3)\n 0.0\n \n Using the `axis` argument to compute vector norms:\n \n >>> c = np.array([[ 1, 2, 3],\n ... [-1, 1, 4]])\n >>> LA.norm(c, axis=0)\n array([ 1.41421356, 2.23606798, 5. ])\n >>> LA.norm(c, axis=1)\n array([ 3.74165739, 4.24264069])\n >>> LA.norm(c, ord=1, axis=1)\n array([ 6., 6.])\n \n Using the `axis` argument to compute matrix norms:\n \n >>> m = np.arange(8).reshape(2,2,2)\n >>> LA.norm(m, axis=(1,2))\n array([ 3.74165739, 11.22497216])\n >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])\n (3.7416573867739413, 11.224972160321824)\n \n 0.2497209782456826\n [hw3_l2_norm1] Good job!\n\n\n\n```python\n\n```\n\n* **Q4 (5 points):** At $t = 0.01 s$, what's the $L_2$-norm of the difference between the density obtained with the Lax-Friedrichs scheme and the analytical solution?\n\nStore your result in the variable `l2_norm2`; you can check your answer by calling the function `mooc.check('hw3_l2_norm2', l2_norm2)`.\n\n\n```python\n# YOUR CODE HERE\nDiff_2 = rho_Lax - rho_analytical\nl2_norm2 = numpy.linalg.norm(Diff_2, ord=2, axis=0)\nprint(l2_norm2)\nmooc.check('hw3_l2_norm2', l2_norm2)\n```\n\n 0.4610293528265613\n [hw3_l2_norm2] Good job!\n\n\n\n```python\n\n```\n\n* **Q5 (5 points):** At $t = 0.01 s$, what's the value of the density, obtained with Richtmyer scheme, at location $x = 2.5 m$ (in $kg/m^3$)?\n\nStore your result in the variable `rho1`; you can check your answer by calling the function `mooc.check('hw3_rho1', rho1)`.\n\n**WARNING**: the variable name `rho1` is spelled with the number `1`, **not** the letter `l`.\n\n\n```python\n# YOUR CODE HERE\nrho1 = rho_Richtmyer[int((2.5+10)/dx)]\nprint(rho1)\nmooc.check('hw3_rho1', rho1)\n```\n\n 0.3746914026476011\n [hw3_rho1] Good job!\n\n\n\n```python\n\n```\n\n* **Q6 (5 points):** At $t = 0.01 s$, what's the value of the velocity, obtained with Lax-Friedrichs scheme, at location $x = 2.5 m$ (in $m/s$)?\n\nStore your result in the variable `v2`; you can check your answer by calling the function `mooc.check('hw3_v2', v2)`.\n\n\n```python\n# YOUR CODE HERE\nv2 = v_Lax[int((2.5+10)/dx)]\nprint(v2)\nmooc.check('hw3_v2', v2)\n```\n\n 281.8563023522752\n [hw3_v2] Good job!\n\n\n\n```python\n\n```\n\n* **Q7 (5 points):** At $t = 0.01 s$, what's the absolute difference in the pressure, between the analytical solution and the Richtmyer solution, at location $x = 2.5 m$ (in $N/m^2$)?\n\nStore your result in the variable `p_diff`; you can check your answer by calling the function `mooc.check('hw3_p_diff', p_diff)`.\n\n\n```python\n# YOUR CODE HERE\np_R = p_Richtmyer[int((2.5+10)/dx)]\np_A = p_analytical[int((2.5+10)/dx)]\np_diff = abs(p_R - p_A)\nprint(p_diff)\nmooc.check('hw3_p_diff', p_diff)\n```\n\n 64.17847424907086\n [hw3_p_diff] Good job!\n\n\n\n```python\n\n```\n\n* **Q8 (5 points):** At $t = 0.01 s$, what's the value of the entropy, obtained with Richtmyer scheme, at location $x = -1.5 m$ (in $J/kg/K$)?\n\nThe entropy $s$ is defined as:\n\n$$\ns = \\frac{p}{\\rho^\\gamma}\n$$\n\nStore your result in the variable `s1`; you can check your answer by calling the function `mooc.check('hw3_s1', s1)`.\n\n**WARNING**: the variable name `s1` is spelled with the number `1`, **not** the letter `l`.\n\n\n```python\n# YOUR CODE HERE\nrho_Rs = rho_Richtmyer[int((10-1.5)/dx)]\np_Rs = p_Richtmyer[int((10-1.5)/dx)]\ns1 = p_Rs / rho_Rs**gamma\nprint(s1)\nmooc.check('hw3_s1', s1)\n```\n\n 100697.043028669\n [hw3_s1] Good job!\n\n\n\n```python\n\n```\n\n* **Q9 (5 points):** At $t = 0.01 s$, what's the value of the speed of sound, obtained with Lax-Friedrichs scheme, at location $x = -1.5 m$ (in $m/s$)?\n\nThe speed of sound $a$ is defined as:\n\n$$\na = \\sqrt{\\frac{\\gamma p}{\\rho}}\n$$\n\nStore your result in the variable `a2`; you can check your answer by calling the function `mooc.check('hw3_a2', a2)`.\n\n\n```python\n# YOUR CODE HERE\nrho_La = rho_Lax[int((10-1.5)/dx)]\np_La = p_Lax[int((10-1.5)/dx)]\na2 = (gamma * p_La / rho_La)**0.5\nprint(a2)\nmooc.check('hw3_a2', a2)\n```\n\n 349.455377505974\n [hw3_a2] Good job!\n\n\n\n```python\n\n```\n\n* **Q10 (5 points):** At $t = 0.01 s$, what's the value of the Mach number, obtained with Richtmyer scheme, at location $x = -1.5 m$?\n\n**Hint:** the Mach number is the ratio between the velocity and the speed of sound.\n\nStore your result in the variable `M1`; you can check your answer by calling the function `mooc.check('hw3_M1', M1)`.\n\n**WARNING**: the variable name `M1` is spelled with the number `1`, **not** the letter `l`.\n\n\n```python\n# YOUR CODE HERE\n# Mach number = velocity / speed of sound\nrho_Ra = rho_Richtmyer[int((10-1.5)/dx)]\np_Ra = p_Richtmyer[int((10-1.5)/dx)]\naR = (gamma * p_Ra / rho_Ra)**0.5\nv_Ra = v_Richtmyer[int((10-1.5)/dx)]\nM1 = v_Ra/aR\nprint(M1)\nmooc.check('hw3_M1', M1)\n```\n\n 0.5483352954050432\n [hw3_M1] Good job!\n\n\n\n```python\n\n```\n\n## Reference\n\n---\n\n* Sod, Gary A. (1978), \"A survey of several finite difference methods for systems of nonlinear hyperbolic conservation laws,\" *J. Comput. Phys.*, Vol. 27, pp. 1–31 DOI: [10.1016/0021-9991(78)90023-2](http://dx.doi.org/10.1016%2F0021-9991%2878%2990023-2) // [PDF from unicamp.br](http://www.fem.unicamp.br/~phoenics/EM974/TG%20PHOENICS/BRUNO%20GALETTI%20TG%202013/a%20survey%20of%20several%20finite%20difference%20methods%20for%20systems%20of%20nonlinear%20hyperbolic%20conservation%20laws%20Sod%201978.pdf), checked Oct. 28, 2014.\n", "meta": {"hexsha": "157e134d3130964999e8a26561f437a30306d1d9", "size": 174252, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "hw3/hw3/Sods_Shock_Tube.ipynb", "max_stars_repo_name": "YinfengDing/MAE6286", "max_stars_repo_head_hexsha": "41dc302762fc54ed1c8c9ff0621bd5f3c8e5d7f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-21T15:19:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T15:19:08.000Z", "max_issues_repo_path": "hw3/hw3/Sods_Shock_Tube.ipynb", "max_issues_repo_name": "YinfengDing/MAE6286", "max_issues_repo_head_hexsha": "41dc302762fc54ed1c8c9ff0621bd5f3c8e5d7f0", "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": "hw3/hw3/Sods_Shock_Tube.ipynb", "max_forks_repo_name": "YinfengDing/MAE6286", "max_forks_repo_head_hexsha": "41dc302762fc54ed1c8c9ff0621bd5f3c8e5d7f0", "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": 104.844765343, "max_line_length": 42672, "alphanum_fraction": 0.8304696646, "converted": true, "num_tokens": 9487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.2146914140875998, "lm_q1q2_score": 0.09897634426867202}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n#####Version 0.1\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the projects [homepage](camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n###The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$.:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n###Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n####Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computational-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%pylab inline\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n#####Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n##Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n###Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n###Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\")\n```\n\n\n###But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```\nimport pymc as mc\n\nalpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = mc.Exponential(\"lambda_1\", alpha)\nlambda_2 = mc.Exponential(\"lambda_2\", alpha)\n\ntau = mc.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```\nprint \"Random output:\", tau.random(), tau.random(), tau.random()\n```\n\n Random output: 4 17 67\n\n\n\n```\n@mc.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@mc.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. \n\n\n```\nobservation = mc.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = mc.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo*, which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```\n### Mysterious code to be explained in Chapter 3.\nmcmc = mc.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n [****************100%******************] 40000 of 40000 complete\n\n\n\n```\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n###Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages recieved\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\")\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```\n#type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. .\n- [2] Norvig, Peter. 2009. [*The Unreasonable Effectiveness of Data*](http://www.csee.wvu.edu/~gidoretto/courses/2011-fall-cp/reading/TheUnreasonable EffectivenessofData_IEEE_IS2009.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "8b1e4578c2ee3b25efbdf105fb95f243e42c9df4", "size": 413578, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_stars_repo_name": "jaimebayes/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "cc2ab1a3905f1537b5891028fdf097be95267c3a", "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": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_issues_repo_name": "jaimebayes/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "cc2ab1a3905f1537b5891028fdf097be95267c3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_forks_repo_name": "jaimebayes/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "cc2ab1a3905f1537b5891028fdf097be95267c3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-26T01:29:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-26T01:29:57.000Z", "avg_line_length": 401.1425800194, "max_line_length": 110534, "alphanum_fraction": 0.9050964993, "converted": true, "num_tokens": 11111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.09873653894145347}} {"text": "```python\n%run ../../common/import_all.py\n\nfrom common.setup_notebook import *\nconfig_ipython()\nsetup_matplotlib()\nset_css_style()\n```\n\n\n\n\n\n\n\n\n\n\n#
Moments of a distribution and summary statistics\n\nIn the following, we will use $X$ to represent a random variable living in sample space (the space of all possible values it can assume) $\\Omega$.\n\nIn the discrete case, the probability of each value $x_i$ will be represented as $p_i$ (probability mass function); in the continuous case $p(x) = P(X=x)$ will be the probability density function. See [the note on probability functions](probfunctions.ipynb).\n\nLet's start with mean and variance and then we'll then give the general definitions. Also, we'll then switch to other quantities beyond moments which help drawing a comprehensive picture of how data is distributed.\n\n## Expected Value\n\nThe **expected value**, or **expectation**, or **mean value** is defined, in the *continuous* case as\n\n$$\n\\mathbb{E}[X] = \\int_\\Omega \\text{d} x \\ x p(x) \\ ,\n$$\n\nSimilarly, in the *discrete* case,\n\n$$\n\\mathbb{E}[X] = \\sum_i^N p_i x_i \\ ,\n$$\n\nThe expectation is the average of all the possible values the random variable can assume. It is the arithmetic mean in the case of discrete variables. This is easy to see if the distribution is uniform, that is, all $N$ values have the same probability $\\frac{1}{N}$: the expectation becomes $\\frac{1}{N}\\sum_i x_i$, which is the exact definition of arithmetic mean. When the distribution is not uniform, the probability is not the same for each value, but the end result is still the arithmetic mean as each different value will be weighted with its probability of occurrence, that is, the count of them over the total of values. \n\nThe expected value is typically indicated with $\\mu$. \n\n### Linearity of the expected value\n\nThe expected value is a linear operator:\n\n$$\n\\mathbb{E}[aX + bY] = a\\mathbb{E}[X] + b \\mathbb{E}[Y]\n$$\n\n*Proof*\n\nWe will prove this in the continuous case but it is clearly easily extensible.\n\n$$\n\\begin{align}\n\\mathbb{E}[aX + bY] &= \\int_{\\Omega_X}\\limits \\int_{\\Omega_Y}\\limits \\text{d} x \\ \\text{d} y \\ (ax + by) p(x, y) \\\\\n&= a \\int_{\\Omega_X}\\limits \\int_{\\Omega_Y}\\limits \\text{d} x \\ \\text{d} y \\ x p(x, y) + b \\int_{\\Omega_X}\\limits \\int_{\\Omega_Y}\\limits \\text{d} x \\ \\text{d} y \\ y p(x, y) \\\\\n&= a \\int_{\\Omega_X}\\limits \\text{d} x \\ x p(x) + b \\int_{\\Omega_Y}\\limits \\text{d} y \\ y p(y) \\\\\n&= a\\mathbb{E}[X] + b \\mathbb{E}[Y]\n\\end{align}\n$$\n\nThis is because $p(x) = \\int_{\\Omega_Y}\\limits\\text{d} y \\ x p(x, y)$ because we are effectively summing the PDFs over all the possible values of $Y$, hence eliminating the dependency from this random variable. Analogously the other one.\n\n### Expectation over two variables\n\nWe have\n\n$$\n\\mathbb{E}_{x, y}[A] = \\mathbb{E}_x[\\mathbb{E}_y[A | x]]\n$$\n\n*Proof*\n\nBy definition\n\n$$\n\\mathbb{E}_{x, y}[A] = \\int \\,dx \\,dy \\, p(x, y) \\, A\n$$\n\nand from the definition of [conditional and joint probability](joint-marg-conditional-prob.ipynb),\n\n$$\np(x, y) = p(y|x) p(x) \\ .\n$$\n\nSo, we can write\n\n$$\n\\mathbb{E}_{x, y}[A] = \\int \\, dx \\, dy A \\, p(y|x)p(x)\n$$\n\nwhich is exactly the second term in the statement.\n\n## Variance and standard deviation\n\nThe variance is the expected value of the squared difference from the expectation:\n\n$$\nVar[X] = \\mathbb{E}[(X - \\mathbb{E}[X])^2] = \\int_{\\Omega_X} \\text{d} x \\ (x - \\mathbb{E}[X])^2 p(x)\n$$\n\nThe variance is the second moment around the mean. It is typically indicated as $\\sigma^2$, $\\sigma$ being the **standard deviation**, which gives the measure of error of values from the mean.\n\n### Rewriting the variance\n\nWe can also write the variance as\n\n$$\nVar[X] = \\mathbb{E}[X^2] - \\big(\\mathbb{E}[X]\\big)^2\n$$\n\n*Proof*\n\n$$\n\\begin{align}\nVar[X] &= \\mathbb{E}[(X - \\mu)^2] \\\\\n&= \\int_{\\Omega_X} \\text{d}x \\ (x^2 - 2 \\mu x + \\mu^2) p(x) \\\\\n&= \\int_{\\Omega_X} \\text{d}x \\ x^2 p(x) -2 \\mu \\int_{\\Omega_X} \\text{d}x \\ x p(x) + \\mu^2 \\int_{\\Omega_X} \\text{d} x p(x) \\\\\n&= \\mathbb{E}[X^2] - 2 \\mu^2 + \\mu^2 \\\\\n&= \\mathbb{E}[X^2] - \\big(\\mathbb{E}[X]\\big)^2\n\\end{align}\n$$\n\n### The variance is not linear\n\nIn fact, using the linearity of the expectation\n\n$$\n\\begin{align}\nVar[aX] &= \\mathbb{E}[(aX)^2] - \\big( \\mathbb{E}[aX] \\big)^2 \\\\\n&= a^2 \\mathbb{E}[X^2] - (a^2 \\mu^2) \\\\\n&= a^2 (\\mathbb{E}[X^2] - \\mu^2) \\\\\n&= a^2 Var[X]\n\\end{align}\n$$\n\nand more in general, \n\n$$\n\\begin{align}\nVar[aX + bY] &= \\mathbb{E}[(aX + bY)^2] - \\big( \\mathbb{E}[aX+bY] \\big)^2 \\\\\n&= \\mathbb{E}[a^2 X^2 + b^2 Y^2 + 2ab XY] - \\big( a \\mathbb{E}[X] + b \\mathbb{E}[Y] \\big)^2 \\\\\n&= a^2\\mathbb{E}[X^2] + b^2\\mathbb{E}[Y^2] + 2ab\\mathbb{E}[XY] - a^2(\\mathbb{E}[X])^2 - b^2(\\mathbb{E}[Y])^2 - 2ab\\mathbb{E}[X]\\mathbb{E}[Y] \\\\\n&= a^2 Var[X] + b^2 Var[Y] + 2ab \\ \\text{cov}(X, Y)\n\\end{align}\n$$\n\n($\\text{cov}$ is the covariance).\n\n## The unbiased estimator of variance and standard deviation\n\n\n\nIf we have $n$ data points, extracted from a population (so we have a sample, refer to figure) and we want to calculate its variance (or standard deviation), using $n$ in the denominator would lead to a biased estimation. We would in fact use $n$ in the case we had the full population, in the case of a sample we have to use $n-1$ and this is because the degrees of freedom are $n-1$ as the mean is computed from $n$ data points so there is one less.\n\nFor the mean, if $\\mu$ is the one computed with the full population and $\\bar x$ the one computed with the sample, which is the estimator of $\\mu$, \n\n$$\n\\bar x = \\frac{\\sum_{i=1}^{i=n} x_i}{n}\n$$\n\nFor the variance, calling $\\sigma^2$ the one computed with the full population and $s^2$ the one computed with the sample, we have\n\n$$\ns_n^2 = \\frac{\\sum_{i=1}^{i=n} (x_i - \\bar x)^2}{n}\n$$\n\nand\n\n$$\ns_{n-1}^2 = \\frac{\\sum_{i=1}^{i=n} (x_i - \\bar x)^2}{n-1}\n$$\n\nwith subscript $n$ or $n-1$ indicating, respectively, with which denominator they are calculated. \n\n$s_n^2$ is a biased estimator of the population variance (it contains the mean, which itself eats one degree of freedom) and we have $s_n^2 < s_{n-1}^2$. This last one is the correct estimator of the population variance when you have a sample.\n\n## Standard deviation and standard error\n\nRefer again to the above about sample and population. The population follows a certain distribution, of which the distribution of the sample is an \"approximation\". This is why we have to use the sample mean (the mean of data points in the sample) as an estimate of the (unknown) population mean. The problem is now how to attribute the error to this value.\n\nIn general, following definition, what the standard deviation quantifies is the variability of individuals from the mean. Having the sample, the sample standard deviation tells how far away each sample point is from the sample mean. \n\nNow because we're using the sample mean to estimate the mean (expected value) of the population, and because if we had another sample extracted from the same population this sample mean would likely be different, in general this sample mean follows its distribution. The *standard error* (of the mean, as it can be related to other statistics), typically indicated by *SE*, is the standard deviation of these means. \n\nThe standard error is usually estimated by the sample standard deviation $s$ divided by the square root of the sample size $n$:\n\n$$\nSE = \\frac{s}{\\sqrt{n}} \\ ,\n$$\n\nunder the assumption of statistical independence of observations in the sample.\n\nIn fact, let $x_1, \\ldots, x_n$ be the sample points extracted from a population whose mean and standard deviation are, respectively, $\\mu$ and $\\sigma$, the sample mean is\n\n$$\nm = \\frac{x_1 + \\cdots + x_n}{n} \\ .\n$$\n\nThe variance of this sample mean $m$, telling how far away the sample mean is from the population mean, is\n\n$$\nVar[m] = Var \\left[\\frac{\\sum_i x_i}{n}\\right] = \n\\frac{1}{n^2} Var\\Big[\\sum_i x_i\\Big] = \\frac{1}{n^2} \\sum_i Var[x_i]\n= \\frac{1}{n^2} n Var[x_1]\n= \\frac{1}{n} \\sigma^2 \\ ,\n$$\n\nbecause each point has the same variance and the points are independent. See above for the non-linearity of the variance for the details on this calculation. Following this, the standard deviation of $m$ is then $\\frac{\\sigma}{\\sqrt{n}}$ and we will use $s$ as an estimate for $\\sigma$, which is, again, unknown.\n\n### When to use which\n\nThe Standard Error tells how far the sample mean is from the population mean so it is the error to attribute to a sample mean. The standard deviation again is about the individual data points and it tells how far away they are from the sample mean.\n\nWhile the standard error goes to 0 when $n \\to \\infty$, the standard deviation goes to $\\sigma$.\n\n## Moments: general definition\n\nThe $n$-th **raw moment** is the expected value of the $n$-th power of the random variable:\n\n$$\n\\boxed{\\mu_n' = \\int \\text{d} x \\ x^n p(x)}\n$$\n\nThe expected value is then the first raw moment.\n\n\nThe $n$-th **central moment** around the mean is defined as\n\n$$\n\\boxed{\\mu_n = \\int \\text{d} x (x-\\mu)^n p(x)}\n$$\n\nThe variance is the second central moment around the mean.\n\nMoments get standardises (normalised) by dividing for the appropriate power of the standard deviation. The $n$-th **standardised moment** is the central moment divided by standard deviation with the same order power:\n\n$$\n\\boxed{\\tilde \\mu_n = \\frac{\\mu_n}{\\sigma^n}}\n$$\n\n## Skeweness\n\nThe **skeweness** is the third standardised moment:\n\n$$\n\\gamma = \\frac{\\mathbb{E}[(X-\\mu)^3]}{\\sigma^3}\n$$\n\nThe skeweness quantifies how symmetrical a distribution is around the mean: it is zero in the case of a perfectly symmetrical shape. It is positive if the distribution is skewed on the right, that is, if the right tail is heavier than the left one; it is negative if it is skewed on the left, meaning the left tail is heavier than the right one.\n\n## Kurtosis\n\nThe **kurtosis** is the fourth standardised moment:\n\n$$\n\\kappa = \\frac{\\mu_4}{\\sigma^4}\n$$\n\nIt measures how heavy the tail of a distribution is with respect to a gaussian with the same $\\sigma$.\n\n## Further results\n\n### Variance of a matrix of constants times a random vector\n\nIn general, with a matrix of constants $\\mathbf{X}$ and a vector of observations (random variables) $\\mathbf{a}$, using the linearity of the expected value so that $\\mathbb{E}[\\mathbf{X a}] = \\mathbf{X} \\mathbb{E}[\\mathbf{a}]$, we have\n\n$$\n\\begin{align}\n Var[\\mathbf{X a}] &= \\mathbb{E}[(\\mathbf{X a} - \\mathbb{E}[\\mathbf{X a}])^2] \\\\\n &= \\mathbb{E}[(\\mathbf{X a} - \\mathbb{E}[\\mathbf{X a}])(\\mathbf{X a} - \\mathbb{E}[\\mathbf{X a}])^t] \\\\ \n &= \\mathbb{E}[(\\mathbf{X a} - \\mathbf{X}\\mathbb{E}[\\mathbf{a}])(\\mathbf{X a} - \\mathbf{X}\\mathbb{E}[\\mathbf{a}])^t] \\\\\n &= \\mathbb{E}[(\\mathbf{X a} - \\mathbf{X}\\mathbb{E}[\\mathbf{a}])((\\mathbf{X a})^t - (\\mathbf{X}\\mathbb{E}[\\mathbf{a}])^t)] \\\\\n &= \\mathbb{E}[\\mathbf{Xa}\\mathbf{a}^t\\mathbf{X}^t - \\mathbf{Xa} \\mathbb{E}[\\mathbf{a}]^t \\mathbf{X}^t - \\mathbf{X} \\mathbb{E}[\\mathbf{a}]\\mathbf{a}^t\\mathbf{X}^t + \\mathbf{X} \\mathbb{E}[\\mathbf{a}] \\mathbb{E}[\\mathbf{a}]^t\\mathbf{X}^t] \\\\\n &= \\mathbf{X} \\mathbb{E}[\\mathbf{a}\\mathbf{a}^t] \\mathbf{X}^t - \\mathbf{X} \\mathbb{E}[\\mathbf{a}] \\mathbb{E}[\\mathbf{a}]^t \\mathbf{X}^t - \\mathbf{X} \\mathbb{E}[\\mathbf{a}] \\mathbb{E}[\\mathbf{a}^t] \\mathbf{X}^t + \\mathbf{X} \\mathbb{E}[\\mathbf{a}] \\mathbb{E}[\\mathbf{a}^t] \\mathbf{X}^t \\\\\n &= \\mathbf{X} \\mathbb{E}[\\mathbf{a}\\mathbf{a}^t] \\mathbf{X}^t - 2 \\mathbf{X} \\mathbb{E}[\\mathbf{a}] \\mathbb{E}[\\mathbf{a}]^t \\mathbf{X}^t + \\mathbf{X} \\mathbb{E}[\\mathbf{a}] \\mathbb{E}[\\mathbf{a}^t] \\mathbf{X}^t = \\\\\n &= \\mathbf{X} (\\mathbb{E}[\\mathbf{a} \\mathbf{a}^t] - \\mathbb{E}[\\mathbf{a}] \\mathbb{E}[\\mathbf{a}^t]) \\mathbf{X}^t = \\\\\n &= \\mathbf{X} Var[\\mathbf{a}] \\mathbf{X}^t\n\\end{align}\n$$\n\n## Let's see all this on some known distributions!\n\nWe will extract $n$ values from several distributions, one at a time, and see what happens to the moments.\n\n\n```python\nn = 100000 # the number of points to extract\n\ng = np.random.normal(size=n) # gaussian\ne = np.random.exponential(size=n) # exponential\np = np.random.power(a=0.5, size=n) # power-law x^{0.5}, or a sqrt\nz = np.random.zipf(a=2, size=n) # Zipf (power-law) x^{-2}\n```\n\n### The gaussian \n\nThe gaussian will be the comparison distribution we refer to. Why? Because it's the queen of distributions!\n\n\n```python\n# Use 100 bins\nbins = 100 \n\nhist = np.histogram(g, bins=bins)\nhist_vals, bin_edges = hist[0], hist[1]\nbin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)] # middle point of bin\n \nplt.plot(bin_mids, hist_vals, marker='o')\n\nplt.title('Histogram $10^5$ normally distributed data')\nplt.xlabel('Bin mid')\nplt.ylabel('Count items')\nplt.show();\n```\n\n\n```python\n'The mean is %s, the std %s' % (np.mean(g), np.std(g))\n'The skeweness is %s, the kurtosis %s' % (stats.skew(g), stats.kurtosis(g))\n```\n\n\n\n\n 'The mean is -0.000640742485484, the std 0.999986499155'\n\n\n\n\n\n\n 'The skeweness is 0.01838211229141485, the kurtosis -0.025766042470362294'\n\n\n\nClearly, the mean is 0 (we've taken values this way!); the skeweness is also 0 as the data is normally distributed, hence symmetrical, and the kurtosis comes as 0 because Scipy gives, [by default](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html), the Fisher version of it, which subtracts 3 so that a normal distribution has 0 kurtosis.\n\n### The exponential\n\nSame plot as for the gaussian, except that we will also plot it in semilog scale (on the $y$), where the distribution appears linear.\n\n\n```python\n# Use 100 bins\nbins = 100 \n\nhist = np.histogram(e, bins=bins)\nhist_vals, bin_edges = hist[0], hist[1]\nbin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)] # middle point of bin\n\n# Main plot: in linear scale\nplt.plot(bin_mids, hist_vals)\nplt.xlabel('Bin mid')\nplt.ylabel('Count items')\nplt.title('Histogram $10^5$ exponentially distributed data')\n\n# Inset plot: in semilog (on y)\na = plt.axes([.4, .4, .4, .4], facecolor='y')\nplt.semilogy(bin_mids, hist_vals)\nplt.title('In semilog scale')\nplt.ylabel('Count items')\nplt.xlabel('Bin mid')\n\nplt.show();\n```\n\n\n```python\n'The mean is %s, the std %s' % (np.mean(e), np.std(e))\n'The skeweness is %s, the kurtosis %s' % (stats.skew(e), stats.kurtosis(e))\n```\n\n\n\n\n 'The mean is 1.00304878455, the std 0.996973171878'\n\n\n\n\n\n\n 'The skeweness is 1.9954113378643468, the kurtosis 6.02308754016868'\n\n\n\nThis time, the distribution is not symmetrical.\n\n### The power law\n\nWe chose to extract numbers from a [power law](power-law.ipynb) with exponent $-0.7$ (see the [docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.power.html#numpy.random.power)). Because of this, it is so much better to bin logarithmically, that is, with a bin width growing logarithmically. If we also choose a log-log scale, we get a line. Let's do it.\n\n\n```python\n# Use 100 bins\nbins = np.logspace(0, 4, num=100) \n\nhist = np.histogram(z, bins=bins)\nhist_vals, bin_edges = hist[0], hist[1]\nbin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)] # middle point of bin\n\n# Main plot: in linear scale\nplt.plot(bin_mids, hist_vals)\nplt.xlabel('Bin mid')\nplt.ylabel('Count items')\nplt.title('Histogram $10^5$ pow-law distributed data')\n\n# Inset plot: in semilog (on y)\na = plt.axes([.4, .4, .4, .4], facecolor='y')\nplt.loglog(bin_mids, hist_vals)\nplt.title('In log-log scale')\nplt.ylabel('Count items')\nplt.xlabel('Bin mid')\n\nplt.show();\n```\n\nClearly because it is a power law, a linear graph is really useless, can't really see anything. The inset shows the linear trend in log-log scale.\n\n\n```python\n'The mean is %s, the std %s' % (np.mean(z), np.std(z))\n'The skeweness is %s, the kurtosis %s' % (stats.skew(z), stats.kurtosis(z))\n```\n\n\n\n\n 'The mean is 37.28617, the std 7991.95971848'\n\n\n\n\n\n\n 'The skeweness is 299.37959397823863, the kurtosis 92083.86568826315'\n\n\n\nNow, this is a heavy-tail, and the kurtosis is quite verbal about it.\n\n## Mode\n\nThe mode of a distribution is simply its most frequent value. \n\n## Quantiles\n\nQuantiles are the values which divide a probability distribution into equally populated sets, how many, you decide. As special types of quantiles you got\n\n* *deciles*: 10 sets, so the first decile is the value such that 10% of the observations are smaller and the tenth decile is the value such that 90% of the observations are smaller \n* *quartiles*: 4 sets, so the first quartile is such that 25% of the observations are smaller\n* *percentile*: 100 sets, so the first percentile is such that 1% of the observations are smaller\n\nThe second quartile, corresponding to the fifth decile and to the fiftieth percentile, is kind of special and is called the *median*. Note that unlike the mean, the median is a measure of centrality in the data which is non-sensible to outliers. \n\nThis all means you can use the percentile everywhere as it's the most fine-grained one, and calculate the other splits from them. This is in fact what Numpy does, for this reason, and we'll see it below.\n\nQuartiles are conveniently displayed all together in a box plot, along with outliers. \n\n### Trying them out\n\nLet's extract 1000 numbers from a given distribution and let's compute the quartiles. We use `numpy.percentile(array, q=[0, 25, 50, 75, 100])`. Note that the quartile 0 and the quartile 100 correspond respectively to the minimum and maximum of the data.\n\n#### On a uniform distribution, between 0 and 1\n\n\n```python\nu = np.random.uniform(size=1000)\n\nnp.percentile(u, q=[0, 25 , 50, 75, 100])\nmin(u), max(u)\n```\n\n\n\n\n array([0.00205504, 0.27189483, 0.52432025, 0.75195201, 0.99904427])\n\n\n\n\n\n\n (0.0020550371300288583, 0.999044272466301)\n\n\n\n#### On a standard gaussian (mean 0, std 1)\n\nNote the median is the mean, that is, in this case, 0. It won't be precisely, because of finite size effect. A gaussian is such that median, mean and mode coincide, doesn't this make it great?\n\n\n```python\ng = np.random.normal(size=1000)\n\nnp.percentile(g, q=[0, 25 , 50, 75, 100])\n```\n\n\n\n\n array([-3.48444618, -0.61679718, 0.05202165, 0.68962899, 3.38339965])\n\n\n\n#### On a power law with exponent -0.3\n\nCan see that they span orders of magnitude.\n\n\n```python\np = np.random.power(0.7, size=1000)\n\nnp.percentile(p, q=[0, 25 , 50, 75, 100])\n```\n\n\n\n\n array([5.58878867e-05, 1.48743304e-01, 3.93775538e-01, 6.76276735e-01,\n 9.99854544e-01])\n\n\n\n### The inter-quartile range (IQR)\n\nIt is the difference between the third and first quartile and gives a measure of dispersion of the data. It is also sometimes called *midspread*. Note that it is a robust measure of dispersion specifically because it works on quartiles.\n\n$$\nIQR = Q_3 - Q-1\n$$\n\nThe IQR can be used to *test the normality of a distribution* at a simple level, because the quartiles of a normal (standardised) distribution are known so calculated ones can be compared to them. \n\nIt is also used in *spotting outliers*: the Tukey's range test defines outliers as those points that fall below $Q_1 - 1.5 IQR$ and above $Q_3 + 1.5 IQR$.\n\n\n```python\n\n```\n", "meta": {"hexsha": "9e0fed9c5a20f69aada9c2f616fb86e2d58bc37e", "size": 239449, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "prob-stats-data-analysis/foundational/moments-summarystats.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": "prob-stats-data-analysis/foundational/moments-summarystats.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": "prob-stats-data-analysis/foundational/moments-summarystats.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": 243.3424796748, "max_line_length": 81940, "alphanum_fraction": 0.8953889972, "converted": true, "num_tokens": 6584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660004, "lm_q2_score": 0.24220562872535942, "lm_q1q2_score": 0.09865843877378612}} {"text": "# Day 1. Introduction to the Notebook and NumPy\n\n* [Navigating the Notebook](#1)\n* [Python built-in functions](#2)\n* [Storage and manipulation of numerical arrays](#3)\n* [Repeated operations and universal functions](#4)\n\nThe answers to the exercises are encrypted. Feel free to ask the instructors for the decryption key whenever you need to view the solution.\n\n\n```python\nfrom IPython.display import IFrame\nfrom IPython.display import YouTubeVideo\n```\n\n\n```python\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\nfrom cryptography.fernet import Fernet\nimport base64\ndef encrypt(string, key):\n keygen = lambda x : base64.urlsafe_b64encode(x.encode() + b' '*(32 - len(x)))\n cipher = Fernet(keygen(key))\n return cipher.encrypt(string.encode())\ndef decrypt(string, key):\n keygen = lambda x : base64.urlsafe_b64encode(x.encode() + b' '*(32 - len(x)))\n cipher = Fernet(keygen(key))\n return print(cipher.decrypt(string.encode()).decode())\n```\n\n## Familiarize yourself with \n\n\n* create a new [environment](https://conda.io/docs/user-guide/concepts.html#conda-environments):\n - go to the terminal (or to the anaconda prompt on Windows) and [make sure](https://conda.io/docs/user-guide/tasks/manage-environments.html#determining-your-current-environment) that no environment is acrivated (else [deactivate](https://conda.io/docs/user-guide/tasks/manage-environments.html#deactivating-an-environment) it)\n - decide on the name of your new environment (_i.e._ `[env_name]`)\n - run `conda create -n [env_name]`\n* [activate](https://conda.io/docs/user-guide/tasks/manage-environments.html#activating-an-environment) the new environment\n* install the following packages in the new environment:\n - python=3.6\n - mdtraj=1.9 from the `conda-forge` channel (`conda install -c conda-forge mdtraj=1.9`)\n - R from the `r` channel (the package is called r-essentials)\n* list the packages installed in the environment (`conda list`)\n* deactivate the environment\n* [export](https://conda.io/docs/user-guide/tasks/manage-environments.html#sharing-an-environment) the environment to a yml file (be careful not to overwrite any yml file in your current directory)\n* [view a list](https://conda.io/docs/user-guide/tasks/manage-environments.html#viewing-a-list-of-your-environments) of all your conda environments\n* [remove](https://conda.io/docs/user-guide/tasks/manage-environments.html#removing-an-environment) the environment that you have just created\n\n## Use [Binder](https://mybinder.org/) to launch a GitHub repository\n\n\n* go to mybinder.org and launch a GitHub repository containing Jupyter Notebooks of your choice\n* navigate and run a Notebook in the executable environment\n* be aware that the repository has to contain a dependency file (_e.g._ the yml file containing the list of packages of a conda environment)\n* Binder uses the dependency file to build a Docker [container](https://www.docker.com/resources/what-container) image of the repository\n - \"A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings.\" (excerpt from docker.com)\n\n\n\n# Navigating the Notebook\n\n\n```python\nIFrame(src='https://api.kaltura.nordu.net/p/310/sp/31000/embedIframeJs/uiconf_id/23449977/partner_id/310?iframeembed=true&playerId=kaltura_player&entry_id=0_z85if4is&flashvars[streamerType]=auto&flashvars[localizationCode]=en&flashvars[leadWithHTML5]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true&&wid=0_l2d1egty', width=608, height=402)\n```\n\n### Tasks\n\n1. Find and try out the keyboard shortcuts (Help > Keyboard Shortcuts) for\n - Toggling line numbers\n - Setting the cell to _code_\n - Setting the cell to _markdown_\n - Merging two consecutive cells\n - Inserting a cell above\n - Inserting a cell below\n - Deleting a cell\n2. Export this notebook as HTML and open it in a web-browser\n3. Go back to the Home page (usually a browser tab) and check which notebooks that are currently running\n\n## Output\n\nThe result from running a code cell is shown as output directly below it. In particular, the output from the _last_ command will be printed, unless explicitly suppressed by a trailing `;`\n\nPrevious output can be retrieved by:\n- `_` last output\n- `__` last last output\n- `_x` where `x` is the cell number.\n\n### Tasks\n- Retrieve the output of the following cell\n- Suppress the output of the following cell\n\n\n```python\na = 3\na\n```\n\n## Getting help\n\n- `shift`-`tab`-`tab`: access information about python functions (place cursor between brackets)\n- `tab`: tab complete functions and objects\n- `?command` or `command?`\n- The help menu has links to detailed help on Python, Markdown, Matplotlib etc.\n\n### Task\n\nUse the above different ways to explore the arguments for the `print()` function.\nWhat is the `end` argument for?\n\n## Documentation using Markdown\n\nMarkdown is a _lightweight_ markup language that\n\n- is intended to be as easy-to-read and easy-to-write as possible\n- supports equations ($f(x)=x$), [links](http://), ~~text formatting~~, tables, images etc.\n\nFor more information see [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).\n\n### Task 1\n\nUse a Markdown cell to explain Pythagoras' theorem. Your answer should include\n\n- headers and text formatting\n- a link to an external web page\n- [LaTeX math](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html)\n\n_Hint:_ images need not be local, but can be linked via a URL.\n\n\n```python\nanswer = 'gAAAAABcAVG3y9adFC6juLwdCUxdFnKhUDK9gqLlTTrVNfiedLFxfKdZqWayixC54-Anq9BhGQZvoWBm-AzZMyDhmsfFKIWkrhe9KR-9bwwXho5axladf90oUcqO3gBRYcOHt1nixpfl4ExV2z7Fr-xsxLyIpCzz6K2e0BvagxTonkRQNApDU_qZ6PGTVzpjq9VvgIj_xIQkSt0GEvUI0vtOdZUPly8eszQorUXGbGqIgt5aeE4YVQrnwWRAkwErK9_SdSNNqzWUwnraM_GhnjeFDIMFEbrpSxGYZomAy8N5zqWQIYGbi7jJkPePqIGqYdoM2Anceb_9IrZHQEaap18pBwLU6-Mkwx6k1uCc26eQBdKsUbk36zVKcvt-FeHojYSXtCF3CsDb40nE_b7oBBh5we1fI9IWLSaaOv6NlQVUD0uM5qze7w8BegBmLtMbdwlX9lqx2UC1'\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 2\n\n1. Use a markdown cell to create a table with column labels **Element**, **Symbol**, **Atomic number**, and a single row with **Hydrogen**, **H**, and **1**.\n2. In a *code cell*, import the `Markdown` function from `IPython` using\n ```.py\n from IPython.display import Markdown\n ```\n and explore its documentation.\n3. Redo subquestion 1 using the `Markdown` command:\n - write the markdown table as a string (use triple quotation marks or write it on a single line using the line escape sequence \\n)\n - populate the table using a [formatted Python string](https://pyformat.info)\n\n\n```python\nanswer = 'gAAAAABcAVHzAOYjHRhWhK28NdM61aXfc9hOcExm9TdQPvYCRa50Es4vPadouW4usg3AIm5zdbuYycJMkJ8HvGHmp-AOZcKT0W6XrSXMO8yZz44rUNWMYvT-re4ZVFx-om_Vtsj6bcWLAupO2QHKxZdRh2bl5o4sy8s-0yposy8g4CIGMC0OZs18nBru06xRa9DeLQhxBENMu7FqdC4XU9Bs_fIYtR8WJP5U3suk8O8bXX4AQlkfSCWGsCo-0729C0h6K3k2CkVFoMlnZnXCjpxND9pj5okvZNIsAR2-4KU_T6_AyP_8ifI1w4Xloe_hWourVdpagznZ3I16KLjFI9HdAC6kPeV1ao3Pm9-uKWhjq7oZWLj-aOgfBJeq3GKjyNSJ_r2RBa9bWU2hM9az05h-KtazArxp7_zdq3RDijC5NMgL6_Cyhut5G4Q243K6YiGBlrIWPC7lFhmmgsowExlBKWQne5Z6AQgYfHWPnoEteS-grvqN0iwuRT2PS1hv36RG4a6-O65HL0oQ9oslKmzCJCmd9UNoTBp_oMHWxE2kc-2lnZlB7BwrcsHhVXtrkap8tce0tyj_N3RksSJ6XN-CNoRklAA8UwbFjzSGBr20Q6HdL3QJ5o1r6gxvG06bFNx-iJvc_ALTjyIc9ZKXZnsWOoMymG-L_4FCejCKrLqHFonT2lsrn_dOZ5qVu5KQr4MzDwcxhBFlRYpHUcOCtj2wSqEM0f-ycCUZMveuJueC7s2uOKDXQQy0ZjtiZaW0VUoV-tJlwoWzlSjJvtRSLINESXfi9e60Xw=='\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task: Embedded web content\n\nLund University Publications ([LUP](https://lup.lub.lu.se/search)) allows you to search for publications from specific LU departments or authors. They also provide the possibility to _embed_ the search result. Use `IPython.display.IFrame` to display a search of your choice.\n\n\n```python\n# Here's an example showing a protein - replace with something from LUP!\nfrom IPython.display import IFrame\nIFrame(src=\"http://www.ncbi.nlm.nih.gov/Structure/icn3d/full.html?pdbid=4lzt\", width=800, height=400)\n```\n\n## IPython Magic commands\n- Line magic (`%`): operates on a single line and can be mixed with other languages\n- Cell magic (`%%`): operates on the whole cell\n- [More info](http://ipython.readthedocs.io/en/stable/interactive/magics.html)\n\n\n```python\n%lsmagic\n```\n\nThis is an example of a LaTeX cell\n\n\n```latex\n%%latex\n\n\\begin{equation}\n G_O = \\int_0^\\infty \\mathrm{d}r\\; 4 \\pi r^2 \\left [ g_O(r) -1 \\right ]\n\\end{equation}\n```\n\nThis is an example of an [SVG](https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html) cell \n\n\n```python\n%%svg\n\n\n \n \n \n \n \n \n \n \n \n \n \n +\n -\n r\n \n \n```\n\n### [Shell commands](https://jakevdp.github.io/PythonDataScienceHandbook/01.05-ipython-and-shell-commands.html)\n\n* find the path of the current directory using `%pwd`\n* create a new directory using `%mkdir`\n* enter the new directory using `%cd`\n* find the path of the current directory using `%pwd`\n* get back to the parent directory using `%cd`\n* view a list of files and folders in the current directory with `%ls`\n* use `%cat` to view the environment.yml file of the course repository\n\nBesides the Magic commands, any command that works on your terminal can be run in the Notebook by prepending an exclamation mark! These commands are executed in a temporary subshell, _e.g._, compare the output of the following two cells.\n\nN.B. The command to remove a nonempty folder on Windows is `rmdir /Q /S `\n\n\n```python\n%mkdir new_dir\n%cd new_dir\n%pwd\n%ls\n%cd ..\n%pwd\n%rm -r new_dir\n```\n\n\n```python\n%mkdir new_dir\n!cd new_dir\n!ls\n!pwd\n!cd ..\n!pwd\n%rm -r new_dir\n```\n\n### Task 3\n - Write a script in a Python cell which creates and deletes this directory tree: \n ```bash\n .\n └── new_dir\n ├── dir_1\n ├── dir_2\n ├── dir_3\n └── dir_4\n ```\n - To write your script, translate the following bash shell.\n\n\n```bash\n%%bash\n\nmkdir new_dir\ncd new_dir\nfor i in {1..4}\ndo\nmkdir dir_$i\ndone\ncd ..\nrm -r new_dir\n```\n\n\n```python\nanswer = 'gAAAAABcASqXgQ5RM5983tgSRo4nD-XKkEiKOpq95dvnucHN62hTjGmSZ0IE5zbBooxiuMD72EmfXoY_3pLy89XMf9Wn-sxohva6A15UfPsfAydL7n3Qq628J4kam9LoBpinpVberru5ojcPui6p7VC9VXaE2HcqGTiCjn_GpPNineaXh8EgaMxWASEYpj2cGRfnmPV02nSK'\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 4\n - Search stackoverflow.com for different ways of saving a string to file in Python\n - Use one of those methods to write a file named dirtree.txt containing the bash script to create the directory tree of the previous task \n - Read the new file using `%cat`\n - Use the `%%writefile` Magic command to save the same string to file \n\n\n```python\nanswer = 'gAAAAABcATGAqC3y72nhYgn_E9BXBLx4ASSuSPcL4wLsn7BbprEwqVpW0GdDJfsDZYNMBbCvNjBOUrE1-AtJ4uTehitEyiU22VBerBYe5HGJoT58bBJhJOduZn5pMTQu4_UDf3Tp7TQSbceTB7d3IsGCFg92F1tiuNZkJsbELRJPcHU4NjrjcToYXAHkLRF-bC6jl312p91HpxbWnIflpUXesJqRdUmlzLwxkSYJ4DmRUiRru-BR1dEEio38ciQbs3coLJQY8edUiEyQoyRPEUzJIcxROM0PGrB9iYrsaD5eUs_NQOOaALpQDdiT_pMVmeUjSVlJpiI298l84ahqa5Io6mitG6YnZ0qj2C-BJlQUc55vK1SJvCIIGC4EoPQ9S83C-Q1VekR5ilUM5T0N1FPD4XiSurarcZRJGdMdsGPrK-24vX2Ok9l7QLCOvR03-gLMFnoKRXmBF0i8cQ-8Ms5UAGUHAYLv3AaiOmcLwbAzwwotHUmmTZw='\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n## Cross-language interaction\n\nIt is possible to integrate [multiple languages](https://blog.jupyter.org/i-python-you-r-we-julia-baf064ca1fb6) in the same Notebook. For example we can pass variables from Bash to Python and vice versa. We can also define and compile [Cython](https://cython.org/) or Fortran functions in the Notebook and run them in a Python cell (vide infra).\n\n### Task 5\n - Create a Python variable storing the path of the current directory\n - Create a Python variable storing the list of files and folders in the current directory (using `!ls` on Unix and `!dir` on Windows)\n\n\n```python\nanswer = 'gAAAAABcAGuDmNC7FPu2tRLRlcnuPGB0ZNGjMJW7dvPic723eZeqR2fueK25CFKrfgPFQ3HzAoludqrlQLAr8d1cWRW7JW-ZGS6DTBZNaRo1ejwWTnRXaexSypoZjH4YFVzwZ3t_CRRg'\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n\n\n# Python built-in functions\n\n\n```python\nYouTubeVideo('YpBUiEsTiEA')\n```\n\n### Task 6\nFind the type of the items of the arrays `np.arange(0,9,1)` and `np.arange(0.,9,1)`.\n\n\n```python\nanswer = 'gAAAAABcAXC6ubPFyqGJPj-A6Mf7CUH0yX6Q55wFMDx-WUSVnAd38Ysi4wrkkBGJJAotGDGZ452zkXKoVX1J8G-fFWnvNtPyovGhVxC6sK7yDRbTFo9LolHQ5b2w3cTfZ0m7kAu063tYE8-VmCIQBh6m6zEd5l9Evw=='\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 7\nUse a list comprehension to generate all possible 4-digit codes consisting of 2 alphabetical letters and 2 numbers (from 0 to 9). How many items does the list of contain? Turn the list into a NumPy array and count the number of unique items.\n\n\n```python\nanswer = 'gAAAAABcAXUFYR3d2T0gj4i2zvger7rLhjcdCpmHtMJ25cg0I-Cng6cC2w5ZTCvDHRpt1XOKds6fWztIMkMPoihsu-XDusbRCL7S4-BiWICQHyUqyKuHtrNen4TrJXv2UHP_pzPsCv2BM6xUXKocTsgtBuAuYCLSxX-4bnyXyLNVEsOmTt7jw-QeVmBqiGvqXqP-vv4G7ueg1f6vpRWBNaqayso5ZhVlRzUNc6fNcgWX7q3EvOs_RqY1avTku9V46ldfWSbwFxcCyX-N1aEaYGHuVCgpyZy2w6HDSbWzGfx_quF293TLAX94nJOAh2JYS6NGk9IlvQYWa4LUyGW_Xj1V01I_AlSXiA=='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 8\nGenerate the array [9 7 5 3] with `np.linspace(start=0,stop=10,num=11)` and indexing. Convert its elements to strings with 2 trailing zeros using [`format`](https://pyformat.info/).\n\n\n```python\nanswer = 'gAAAAABcAXWqJ3EkPOBOFbWCE8-SH72Mxtjk9Vupi0T6fBICvOOaJrbNMdr2prHQGeOfWflKEbtWxCODpVK5HY7Q1PEeg1r7-SVmSIWO9HSk_rdBitN-DnIL2XbfC9AaM2SSurG4O9PYa-7Mq1lVhm1oyV9vdzVbK0W6M5Wup08NvRZliVlkve1Y4OvcsqxoQdrM1VfuM-fDU3yd7Ytk0zNIAaIueLFCOOkOoEgLipGSDRWdCSqbXquMtsd-xQ9sH2emp0k-k5yE'\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 9\n- create a linear sequence of integers from 0 to 7 stepping by 1 with `arange` and `linspace`\n- create a linear sequence of floating-point numbers from 0 to 7 stepping by 0.25 with `arange` and `linspace`\n\n\n```python\nanswer = 'gAAAAABcAXacH2s6wH7Q02OEFFeRxe9NXtcuBKGUB4UffBOYJnUZVnv8XeoToWcoQ7FGYa3_elbyhsuFj1n7t6ywpNMqfGIHyuSZA80EnCUrhBv-4hRGUEeeH-FFo_Ca2hck89vkCb-rCTXdVB3oKY_Sj5Cl1BbHY3p3lCtvRTrVY47y_GaUaIlnL1ZB1liPGl6t1m0-ejLJQTu9Jir0_-6HSaoQikAmhzZP1qhKnTbFp4-jK-ddpgxpVLjFJs316OcrGMkkk5YCosZRzzRW9QZSzbufN3nuJj13G7qbl9skcdgM2uvGWcQY3UzEmJy-tbqtnD809YrqtO9I7tpkSwBs82oxJ32hJ9FsSwGhy05GaDRhcUve7CI='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 10\n- Create an uninitialized array of size 0 and populate it, in a for loop, with the 4-digit codes containing the letter \"a\" and selected from those generated in Task 7.
\nHint: use `empty` and `append`.\n- Create the same array in a single line using list comprehension.\n\n\n```python\nanswer = 'gAAAAABcAX7FytesghVv_mvr9wtxzVRr8OP5di6oAxZuVVELnr2VIbXR8xTdwX7kyt32y2JRd3UiOc1FKIc1IyLOlmFJma2XXQ72wPGOnqlFaPTceiASAQ8dv50fvtwCsd3CkKDPFsL6Qs2Bk7gnCR602ZmQJJJgLuuaIip0N3d_H88olMevcDyBnMUU9hUqruGTaSf3WR3cRtCInw_5ACJgYgZ9FP4FDU20Ba6bN9guR45P1ShCZOwbLf0NKeLv03sl1LWw2nQSAHEmkMvJgdNZ5_Qwupv3_JxscIBFpN8ho7gKCXbbzCF2OB5-RivPv2DulrOe8WfUl_nm-r-sHhuC0doAs2m6-g=='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n\n\n# Storage and manipulation of numerical arrays\n\n\n\n```python\nYouTubeVideo('2xJsNi3wk-s')\n```\n\n### Task 11\nGenerate a 3x3 zero matrix and turn it into a 3x3 identity matrix by modifying values one by one or by fancy indexing.\n\n\n```python\nanswer = 'gAAAAABcAYDE5-H_i0u-50j3_pcGQwGmrLyH-98v5F-kISABJWSIDDiQues0yc1-M6rIQ57o_neV8kpksWCgjJUR-k0N7u2SrqBgz1oxnwSzryRYsfJLWKSxzNhJM0588wVeXPowZ0wjEKTeURn0f9aDhS3rghxDFaYD30qyubR1qXOqY3644FKa1x4YWgaLpN8x9s_Hs7_6MuPgnx0eoP5oDx1IfL4Dmqb51rIsgiGbQbvWT7tnAjI8JL7LCxP6PIG7FITginHriuM1edJ1h__JbxCQq78mdSFZYgsqy2TGoupVvOqNfN23ox91vXHotjp2UE6y_b0rY6d7mydOt4GgvMgKnDl6QCybpV_Td-ySVCvNuqWTADKwsfntWb-wrJwhh8SsFBrH-35h70ruU1U-307PtfjWZUCirkhANhWh4c5tJpzBJVjsTYyQDwoRNYzVgeAcHkmYocODTwhswnirZOZDwCuAgQY4F6Ba_zB47n6gltOsPYy_DUNAQClAIOABK4Zt79_1bMDDLrnVaHT1TqF4CR42PUJ143SF86zuqDoz0H_E1szwUsz_95qyBvcf1ZzO99tDdAFBt-5P4r5EVoy-iQ35kA=='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 12\nComplete the following lines\n\n```.py\nx = \ny = \nnp.savetxt('',np.c_[],fmt='%',header='\\t',delimiter='',comments='')\n%cat ```\n\nThe cell should\n- write to file the following table as a tab-separated value file, specifying a header and the format of the numbers\n\nx | y | \n-------- | -------- | \n0 | 0 |\n1 | 1 |\n2 | 4 |\n3 | 9 |\n4 | 16 |\n5 | 25 |\n6 | 36 |\n7 | 49 |\n8 | 64 |\n9 | 81 |\n\n- read the file in the notebook to check that it look as it should.\n\n\n```python\nanswer = 'gAAAAABcAoobPB8I2ABv5t6VCQQteRUOEPicO0MQ2Auh8Jw_UjJ3I7zAFTfSmNIdWktMQP1_nGsVTe-aQRcqJXoFtyruJp4Lm23MKpKie_dS_AQEBHfWD0xjqJiQQSmsPNSgNfI2qfO-umzSR0QbkFP9a9SafpfluAwlHliBG3rJfQ_foe5O9JccdsbqzG903DsDyZASaEhQmu0bWiq_0xTI3QR2ORwc8DKrrNNYJqm6IV15G9u66yM9zapPx8dNlrpnNCf5HE6t'\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 13\n\nComplete the following lines\n\n```.py\nx,y = np.loadtxt(,dtype=str,delimiter=,skiprows=,unpack=)\nplt.plot(x,y)\nplt.show()\nx,y = np.loadtxt(,dtype=int,delimiter=,skiprows=,unpack=)\nplt.plot(x,y)\nplt.show()```\n\nThe cell should\n- load the text file created in the previous task so that the values are interpreted as strings (each column should be loaded into a separate array)\n- plot $y$ vs $x$\n- load the text file created in the previous task so that the values are interpreted as integers (each column should be loaded into a separate array)\n- plot $y$ vs $x$ and compare with the previous plot.\n\n\n```python\nanswer = 'gAAAAABcAos1k2OGaYibgW_3ODaNjTrbU92NNsxSDFCTirW3uEf7DLxBrxNwMln4ZDiMRff3N6ctjB1KZGIE4FsOpG3x2MbteJgrycQJLoiW2atBA_3oXeaE83LPOK7Qcca0cuJPrxxJXY1lbBQPw0tZXe3-0zcytax9eI37TovKhPpNGWq2vxr-f3j22_0QREjMiZGhU2T5g2dXNFO9R5OKHk6gEtDldPf196SkJT9lO_WVxe21bkMXY7ogm6a-Jaxz71eovm_iaGqDg904nCd1sccqvS-oZFxPKZxNA-xzAKNvRfFzCPVnEMfm3YnUoFS7B5gPMnb3BVGkxD5fAYVpIXeI-ByaLGvutV7HvC8-PtJKOtJg-eM='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n\n\n# Repeated operations and universal functions\n\n\n```python\nYouTubeVideo('469ukhzwEPg')\n```\n\n### Task 14\nCompute and plot the function $z=xy\\exp[-(x^2+y^2)]$ on a square grid 100x100 with side lengths ranging from -2 to 2. Complete the following lines:\n\n```.py\ny = x[:,np.]\nz = * * np.exp( - - ) \nplt.imshow(z, extent=, origin=)\nplt.colorbar(label=)\nplt.xlabel()\nplt.ylabel();```\n\n\n```python\nanswer = 'gAAAAABcAoMby1Rf-3JRj1ehvYtOVLeVNwYOuGoUFrmbarZifjvZwDnLzdox_J9dSAkRSacDW9DcP5WbF3nCbXp0ByN7u4LiRhIVCCAJAHvQCjgKLJuimG3X-PHcCuvlofloVxMpuaYGY5QtpoFSH3FJRb40kHwFxrlKIgBqFK_yFMCOwOSc5srYCeJVgRydPqalgSqIHK5DTtIvR_DfRRcrA-MDPMM_hPyuPNYC-QYoeXH-scxbW-22kSNG8p-pcVNoySgIPn4C1YFq_T6m-oB8AOKy6pwtFog84--3yS1g63eYy6diu34nMMUOEnZEk9VmdqyhEPym'\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n### Task 15\nUse boolean masking to set to 0.18 the $z$ values that are lower than 0.04 in the previous plot.\n\n\n```python\nanswer = 'gAAAAABcApILR-KMnBa3VT2u-pmDiqF_LKSym5bvRjZmMm6ndi03WhBvgQEr3oKlJo5rOgM2MbBwwyHoLPnb81YakQFtnsG6PNdX-SR1K9gMPH9L4st8ihBFolIzrRjiuJldtCbLUmrAEx_Dpn1cjRtTlHND2OizxVrzneguu8PuVk1e-GHSUjXROBlACkkIQ--fJA4ypHYADl-rZpJh5aSgLaTF3PzziT2vvXlQBAQIjU4aAMCLFDEfH-iGI_mbxTNd6BEqY-AUfUDRd29YUobAM-MjmN-W1T79sVAY4w16ZRGptj1waz9vhYjB2avawWvW8COMFXATK-LQUH6TwFi_a_8yreMmZg=='\n\n```\n\n\n```python\ndecrypt(answer,'Ystad')\n```\n\n### Task 16\n\nDefine 3 functions that estimate the limiting value of $\\sum_1^\\infty \\frac{\\sqrt{n}}{n^3}$:\n1. a Python funtion involving a for loop\n2. a Python function exploiting universal functions for repeated operations and aggregation functions\n3. a Cython function defined with `cpdef` involving a for loop\nCython is a mix of C and Python. With `cpdef` we can define a function as we would in Python (_i.e._ without declarying any types) but we obtain a function that is almost as fast as C generated code.\n\nHere are snippets of code to complete for each of the three subtasks:\n1. ```.py\ndef func1(n):\n result = 0\n for k in range():\n result += \n return result```\n2. ```.py\ndef func2(n):\n return ( ).sum()```\n3. ```.py\n%load_ext Cython\n%%cython\ncdef extern from \"math.h\":\n double sqrt(int)\ncpdef func3(n): # note the 'p' in 'cpdef'\n result = 0\n for k in range():\n result += \n return result```\n \nUse `%timeit` to compare the speed of `func1`, `func2`, and `func3`.\n\n\n```python\nanswer = 'gAAAAABcAqbaIiWIulQgcO267q_p8PFsH41h2jQuTOZt3vnqlEBt29xULPJTQYQTRjYyVqiEIRJXYfQe-4xJ5bUnd2PVD1YClavYu5Dbj8JjpG_Y_D6DZED4DJV6qfTotHSUX8lNn-8m51YRheaWqMrPxcMyRfAw9I8DGMLlr9064KXVpLlIPIO5q95WWnl5E127o_NhRisZp5GsolVTJw7kxoipgZyGMg=='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n\n```python\nanswer = 'gAAAAABcAqcJPTwdzkomK_6f-zDZ7wbvZnch14UFrHEHQTmKcHmobziYV7dkfnBMmjyddE10f9pR9N9ymzPL0xh1X6tYmVoI9EBj2v5ty0soSsMzttDw0f1-UCioiIFTkrKmEyVBjJlUdZWxY1ybiRDeElJuvLpr6VygSgfJYDMIuv1Ho3YQbQznXQrbAQ5EhP4o-fh2XnFI'\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n\n```python\nanswer = 'gAAAAABcAqcun5hh9C7geQYhS-uzCeB2-uRhI_9yc6HtVO-di2GNbcmnLVFWRP-vghmxLPT7vNDrI4BepkH1kxrneRCTaP45Js2od2NYvOLME7xc1cIy4xTNsbYl2hwtK0JLHUK2NyDI6X4-cE9vtc7lHXwZt8gX6h1GA81LWjUwmYlEU-bwv1s9iJytNRF4Cs0s4pl6RfyN2wzCovjeCqt4oXHccoenWnlvW2hjhpI6Zpb6MdcsAfhsaoo39oWaL1XYn-lnQLj71gfc48qP9x5paPSX-xXXATSPJoY8bcGaTyK0dbcyuN6Bg0Iipg3MYGmIcozPEeW_FY1YQhrfXm4Fx09YdkvqbA=='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n\n\n```python\nanswer = 'gAAAAABcAqdTNpsPmdHE8Jrn6mxQGyRjquTtBOOwub9M47tFjCRCWu2xFuj9jH2-86BPouk-L3tZ7z97FaD_7cxi81KtQjHRutnrf8gwusJY9dCwgypzqtMsitla1XoBqeGX7fMXLT_Pz6B8yj8RP2SJLwuCOlXjKQ=='\n\n```\n\n\n```python\ndecrypt(answer,)\n```\n", "meta": {"hexsha": "c619e60e3b6e6f880e14211f72da2b4182589510", "size": 35569, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exercises/day_1.ipynb", "max_stars_repo_name": "urania277/jupyter-course", "max_stars_repo_head_hexsha": "20060173e7355fc4726148f00b61404d2613b74b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:41:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T21:24:04.000Z", "max_issues_repo_path": "exercises/day_1.ipynb", "max_issues_repo_name": "urania277/jupyter-course", "max_issues_repo_head_hexsha": "20060173e7355fc4726148f00b61404d2613b74b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-12-08T20:12:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T09:28:07.000Z", "max_forks_repo_path": "exercises/day_1.ipynb", "max_forks_repo_name": "mlund/jupyter-course", "max_forks_repo_head_hexsha": "d2e12d153febc6848a1ed80a2f3f29973a3bea73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2017-12-11T13:18:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T14:18:33.000Z", "avg_line_length": 33.2110177404, "max_line_length": 821, "alphanum_fraction": 0.6322640502, "converted": true, "num_tokens": 9020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.310694383214554, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.09862255780286215}} {"text": "```\n# this mounts your Google Drive to the Colab VM.\nfrom google.colab import drive\ndrive.mount('/content/drive', force_remount=True)\n\n# enter the foldername in your Drive where you have saved the unzipped\n# assignment folder, e.g. 'cs231n/assignments/assignment3/'\nFOLDERNAME = 'cs231n/assignments/assignment2/'\nassert FOLDERNAME is not None, \"[!] Enter the foldername.\"\n\n# now that we've mounted your Drive, this ensures that\n# the Python interpreter of the Colab VM can load\n# python files from within it.\nimport sys\nsys.path.append('/content/drive/My Drive/{}'.format(FOLDERNAME))\n\n# this downloads the CIFAR-10 dataset to your Drive\n# if it doesn't already exist.\n%cd drive/My\\ Drive/$FOLDERNAME/cs231n/datasets/\n!bash get_datasets.sh\n%cd /content\n```\n\n Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n \n Enter your authorization code:\n ··········\n Mounted at /content/drive\n /content/drive/My Drive/cs231n/assignments/assignment2/cs231n/datasets\n /content\n\n\n# Batch Normalization\nOne way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. \nOne idea along these lines is batch normalization which was proposed by [1] in 2015.\n\nThe idea is relatively straightforward. Machine learning methods tend to work better when their input data consists of uncorrelated features with zero mean and unit variance. When training a neural network, we can preprocess the data before feeding it to the network to explicitly decorrelate its features; this will ensure that the first layer of the network sees data that follows a nice distribution. However, even if we preprocess the input data, the activations at deeper layers of the network will likely no longer be decorrelated and will no longer have zero mean or unit variance since they are output from earlier layers in the network. Even worse, during the training process the distribution of features at each layer of the network will shift as the weights of each layer are updated.\n\nThe authors of [1] hypothesize that the shifting distribution of features inside deep neural networks may make training deep networks more difficult. To overcome this problem, [1] proposes to insert batch normalization layers into the network. At training time, a batch normalization layer uses a minibatch of data to estimate the mean and standard deviation of each feature. These estimated means and standard deviations are then used to center and normalize the features of the minibatch. A running average of these means and standard deviations is kept during training, and at test time these running averages are used to center and normalize features.\n\nIt is possible that this normalization strategy could reduce the representational power of the network, since it may sometimes be optimal for certain layers to have features that are not zero-mean or unit variance. To this end, the batch normalization layer includes learnable shift and scale parameters for each feature dimension.\n\n[1] [Sergey Ioffe and Christian Szegedy, \"Batch Normalization: Accelerating Deep Network Training by Reducing\nInternal Covariate Shift\", ICML 2015.](https://arxiv.org/abs/1502.03167)\n\n\n```\n# As usual, a bit of setup\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.fc_net import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array\nfrom cs231n.solver import Solver\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# for auto-reloading external modules\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2\n\ndef rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\ndef print_mean_std(x,axis=0):\n print(' means: ', x.mean(axis=axis))\n print(' stds: ', x.std(axis=axis))\n print() \n```\n\n =========== You can safely ignore the message below if you are NOT working on ConvolutionalNetworks.ipynb ===========\n \tYou will need to compile a Cython extension for a portion of this assignment.\n \tThe instructions to do this will be given in a section of the notebook below.\n \tThere will be an option for Colab users and another for Jupyter (local) users.\n\n\n\n```\n# Load the (preprocessed) CIFAR10 data.\ndata = get_CIFAR10_data()\nfor k, v in data.items():\n print('%s: ' % k, v.shape)\n```\n\n X_train: (49000, 3, 32, 32)\n y_train: (49000,)\n X_val: (1000, 3, 32, 32)\n y_val: (1000,)\n X_test: (1000, 3, 32, 32)\n y_test: (1000,)\n\n\n## Batch normalization: forward\nIn the file `cs231n/layers.py`, implement the batch normalization forward pass in the function `batchnorm_forward`. Once you have done so, run the following to test your implementation.\n\nReferencing the paper linked to above in [1] may be helpful!\n\n\n```\n# Check the training-time forward pass by checking means and variances\n# of features both before and after batch normalization \n\n# Simulate the forward pass for a two-layer network\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before batch normalization:')\nprint_mean_std(a,axis=0)\n\ngamma = np.ones((D3,))\nbeta = np.zeros((D3,))\n# Means should be close to zero and stds close to one\nprint('After batch normalization (gamma=1, beta=0)')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n\ngamma = np.asarray([1.0, 2.0, 3.0])\nbeta = np.asarray([11.0, 12.0, 13.0])\n# Now means should be close to beta and stds close to gamma\nprint('After batch normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n```\n\n Before batch normalization:\n means: [ -2.3814598 -13.18038246 1.91780462]\n stds: [27.18502186 34.21455511 37.68611762]\n \n After batch normalization (gamma=1, beta=0)\n means: [5.32907052e-17 7.04991621e-17 1.85962357e-17]\n stds: [0.99999999 1. 1. ]\n \n After batch normalization (gamma= [1. 2. 3.] , beta= [11. 12. 13.] )\n means: [11. 12. 13.]\n stds: [0.99999999 1.99999999 2.99999999]\n \n\n\n\n```\n# Check the test-time forward pass by running the training-time\n# forward pass many times to warm up the running averages, and then\n# checking the means and variances of activations after a test-time\n# forward pass.\n\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\n\nbn_param = {'mode': 'train'}\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n\nfor t in range(50):\n X = np.random.randn(N, D1)\n a = np.maximum(0, X.dot(W1)).dot(W2)\n batchnorm_forward(a, gamma, beta, bn_param)\n\nbn_param['mode'] = 'test'\nX = np.random.randn(N, D1)\na = np.maximum(0, X.dot(W1)).dot(W2)\na_norm, _ = batchnorm_forward(a, gamma, beta, bn_param)\n\n# Means should be close to zero and stds close to one, but will be\n# noisier than training-time forward passes.\nprint('After batch normalization (test-time):')\nprint_mean_std(a_norm,axis=0)\n```\n\n After batch normalization (test-time):\n means: [-0.03927354 -0.04349152 -0.10452688]\n stds: [1.01531428 1.01238373 0.97819988]\n \n\n\n## Batch normalization: backward\nNow implement the backward pass for batch normalization in the function `batchnorm_backward`.\n\nTo derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing branches; make sure to sum gradients across these branches in the backward pass.\n\nOnce you have finished, run the following to numerically check your backward pass.\n\n\n```\n# Gradient check batchnorm backward pass\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nfx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]\nfg = lambda a: batchnorm_forward(x, a, beta, bn_param)[0]\nfb = lambda b: batchnorm_forward(x, gamma, b, bn_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = batchnorm_forward(x, gamma, beta, bn_param)\ndx, dgamma, dbeta = batchnorm_backward(dout, cache)\n#You should expect to see relative errors between 1e-13 and 1e-8\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.7029261167605239e-09\n dgamma error: 7.420414216247087e-13\n dbeta error: 2.8795057655839487e-12\n\n\n## Batch normalization: alternative backward\nIn class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For example, you can derive a very simple formula for the sigmoid function's backward pass by simplifying gradients on paper.\n\nSurprisingly, it turns out that you can do a similar simplification for the batch normalization backward pass too! \n\nIn the forward pass, given a set of inputs $X=\\begin{bmatrix}x_1\\\\x_2\\\\...\\\\x_N\\end{bmatrix}$, \n\nwe first calculate the mean $\\mu$ and variance $v$.\nWith $\\mu$ and $v$ calculated, we can calculate the standard deviation $\\sigma$ and normalized data $Y$.\nThe equations and graph illustration below describe the computation ($y_i$ is the i-th element of the vector $Y$).\n\n\\begin{align}\n& \\mu=\\frac{1}{N}\\sum_{k=1}^N x_k & v=\\frac{1}{N}\\sum_{k=1}^N (x_k-\\mu)^2 \\\\\n& \\sigma=\\sqrt{v+\\epsilon} & y_i=\\frac{x_i-\\mu}{\\sigma}\n\\end{align}\n\n\n\nThe meat of our problem during backpropagation is to compute $\\frac{\\partial L}{\\partial X}$, given the upstream gradient we receive, $\\frac{\\partial L}{\\partial Y}.$ To do this, recall the chain rule in calculus gives us $\\frac{\\partial L}{\\partial X} = \\frac{\\partial L}{\\partial Y} \\cdot \\frac{\\partial Y}{\\partial X}$.\n\nThe unknown/hart part is $\\frac{\\partial Y}{\\partial X}$. We can find this by first deriving step-by-step our local gradients at \n$\\frac{\\partial v}{\\partial X}$, $\\frac{\\partial \\mu}{\\partial X}$,\n$\\frac{\\partial \\sigma}{\\partial v}$, \n$\\frac{\\partial Y}{\\partial \\sigma}$, and $\\frac{\\partial Y}{\\partial \\mu}$,\nand then use the chain rule to compose these gradients (which appear in the form of vectors!) appropriately to compute $\\frac{\\partial Y}{\\partial X}$.\n\nIf it's challenging to directly reason about the gradients over $X$ and $Y$ which require matrix multiplication, try reasoning about the gradients in terms of individual elements $x_i$ and $y_i$ first: in that case, you will need to come up with the derivations for $\\frac{\\partial L}{\\partial x_i}$, by relying on the Chain Rule to first calculate the intermediate $\\frac{\\partial \\mu}{\\partial x_i}, \\frac{\\partial v}{\\partial x_i}, \\frac{\\partial \\sigma}{\\partial x_i},$ then assemble these pieces to calculate $\\frac{\\partial y_i}{\\partial x_i}$. \n\nYou should make sure each of the intermediary gradient derivations are all as simplified as possible, for ease of implementation. \n\nAfter doing so, implement the simplified batch normalization backward pass in the function `batchnorm_backward_alt` and compare the two implementations by running the following. Your two implementations should compute nearly identical results, but the alternative implementation should be a bit faster.\n\n\n```\nnp.random.seed(231)\nN, D = 100, 500\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nout, cache = batchnorm_forward(x, gamma, beta, bn_param)\n\nt1 = time.time()\ndx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache)\nt2 = time.time()\ndx2, dgamma2, dbeta2 = batchnorm_backward_alt(dout, cache)\nt3 = time.time()\n\nprint('dx difference: ', rel_error(dx1, dx2))\nprint('dgamma difference: ', rel_error(dgamma1, dgamma2))\nprint('dbeta difference: ', rel_error(dbeta1, dbeta2))\nprint('speedup: %.2fx' % ((t2 - t1) / (t3 - t2)))\n```\n\n dx difference: 6.284600172572596e-13\n dgamma difference: 0.0\n dbeta difference: 0.0\n speedup: 2.10x\n\n\n## Fully Connected Nets with Batch Normalization\nNow that you have a working implementation for batch normalization, go back to your `FullyConnectedNet` in the file `cs231n/classifiers/fc_net.py`. Modify your implementation to add batch normalization.\n\nConcretely, when the `normalization` flag is set to `\"batchnorm\"` in the constructor, you should insert a batch normalization layer before each ReLU nonlinearity. The outputs from the last layer of the network should not be normalized. Once you are done, run the following to gradient-check your implementation.\n\nHINT: You might find it useful to define an additional helper layer similar to those in the file `cs231n/layer_utils.py`. If you decide to do so, do it in the file `cs231n/classifiers/fc_net.py`.\n\n\n```\nnp.random.seed(231)\nN, D, H1, H2, C = 2, 15, 20, 30, 10\nX = np.random.randn(N, D)\ny = np.random.randint(C, size=(N,))\n\n# You should expect losses between 1e-4~1e-10 for W, \n# losses between 1e-08~1e-10 for b,\n# and losses between 1e-08~1e-09 for beta and gammas.\nfor reg in [0, 3.14]:\n print('Running check with reg = ', reg)\n model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,\n reg=reg, weight_scale=5e-2, dtype=np.float64,\n normalization='batchnorm')\n\n loss, grads = model.loss(X, y)\n print('Initial loss: ', loss)\n\n for name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)\n print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))\n if reg == 0: print()\n```\n\n Running check with reg = 0\n Initial loss: 2.3004790897684924\n W1 relative error: 1.48e-07\n W2 relative error: 2.21e-05\n W3 relative error: 3.53e-07\n b1 relative error: 5.38e-09\n b2 relative error: 2.09e-09\n b3 relative error: 5.80e-11\n \n Running check with reg = 3.14\n Initial loss: 7.052114776533016\n W1 relative error: 3.90e-09\n W2 relative error: 6.87e-08\n W3 relative error: 2.13e-08\n b1 relative error: 1.48e-08\n b2 relative error: 1.72e-09\n b3 relative error: 1.57e-10\n\n\n# Batchnorm for deep networks\nRun the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization.\n\n\n```\nnp.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [100, 100, 100, 100, 100]\n\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nweight_scale = 2e-2\nbn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\nmodel = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\nprint('Solver with batch norm:')\nbn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True,print_every=20)\nbn_solver.train()\n\nprint('\\nSolver without batch norm:')\nsolver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=20)\nsolver.train()\n```\n\n Solver with batch norm:\n (Iteration 1 / 200) loss: 2.302838\n (Epoch 0 / 10) train acc: 0.131000; val_acc: 0.119000\n (Epoch 1 / 10) train acc: 0.227000; val_acc: 0.188000\n (Iteration 21 / 200) loss: 2.066770\n (Epoch 2 / 10) train acc: 0.274000; val_acc: 0.231000\n (Iteration 41 / 200) loss: 2.026292\n (Epoch 3 / 10) train acc: 0.301000; val_acc: 0.255000\n (Iteration 61 / 200) loss: 2.081528\n (Epoch 4 / 10) train acc: 0.368000; val_acc: 0.278000\n (Iteration 81 / 200) loss: 1.743705\n (Epoch 5 / 10) train acc: 0.405000; val_acc: 0.285000\n (Iteration 101 / 200) loss: 1.511911\n (Epoch 6 / 10) train acc: 0.479000; val_acc: 0.308000\n (Iteration 121 / 200) loss: 1.679106\n (Epoch 7 / 10) train acc: 0.501000; val_acc: 0.266000\n (Iteration 141 / 200) loss: 1.635350\n (Epoch 8 / 10) train acc: 0.508000; val_acc: 0.286000\n (Iteration 161 / 200) loss: 1.190941\n (Epoch 9 / 10) train acc: 0.594000; val_acc: 0.311000\n (Iteration 181 / 200) loss: 1.270953\n (Epoch 10 / 10) train acc: 0.650000; val_acc: 0.332000\n \n Solver without batch norm:\n (Iteration 1 / 200) loss: 2.302332\n (Epoch 0 / 10) train acc: 0.129000; val_acc: 0.131000\n (Epoch 1 / 10) train acc: 0.283000; val_acc: 0.250000\n (Iteration 21 / 200) loss: 2.041970\n (Epoch 2 / 10) train acc: 0.316000; val_acc: 0.277000\n (Iteration 41 / 200) loss: 1.900473\n (Epoch 3 / 10) train acc: 0.373000; val_acc: 0.282000\n (Iteration 61 / 200) loss: 1.713156\n (Epoch 4 / 10) train acc: 0.390000; val_acc: 0.310000\n (Iteration 81 / 200) loss: 1.662209\n (Epoch 5 / 10) train acc: 0.434000; val_acc: 0.300000\n (Iteration 101 / 200) loss: 1.696059\n (Epoch 6 / 10) train acc: 0.535000; val_acc: 0.345000\n (Iteration 121 / 200) loss: 1.557987\n (Epoch 7 / 10) train acc: 0.530000; val_acc: 0.304000\n (Iteration 141 / 200) loss: 1.432189\n (Epoch 8 / 10) train acc: 0.628000; val_acc: 0.339000\n (Iteration 161 / 200) loss: 1.033931\n (Epoch 9 / 10) train acc: 0.661000; val_acc: 0.340000\n (Iteration 181 / 200) loss: 0.901034\n (Epoch 10 / 10) train acc: 0.726000; val_acc: 0.318000\n\n\nRun the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster.\n\n\n```\ndef plot_training_history(title, label, baseline, bn_solvers, plot_fn, bl_marker='.', bn_marker='.', labels=None):\n \"\"\"utility function for plotting training history\"\"\"\n plt.title(title)\n plt.xlabel(label)\n bn_plots = [plot_fn(bn_solver) for bn_solver in bn_solvers]\n bl_plot = plot_fn(baseline)\n num_bn = len(bn_plots)\n for i in range(num_bn):\n label='with_norm'\n if labels is not None:\n label += str(labels[i])\n plt.plot(bn_plots[i], bn_marker, label=label)\n label='baseline'\n if labels is not None:\n label += str(labels[0])\n plt.plot(bl_plot, bl_marker, label=label)\n plt.legend(loc='lower center', ncol=num_bn+1) \n\n \nplt.subplot(3, 1, 1)\nplot_training_history('Training loss','Iteration', solver, [bn_solver], \\\n lambda x: x.loss_history, bl_marker='o', bn_marker='o')\nplt.subplot(3, 1, 2)\nplot_training_history('Training accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.train_acc_history, bl_marker='-o', bn_marker='-o')\nplt.subplot(3, 1, 3)\nplot_training_history('Validation accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.val_acc_history, bl_marker='-o', bn_marker='-o')\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n# Batch normalization and initialization\nWe will now run a small experiment to study the interaction of batch normalization and weight initialization.\n\nThe first cell will train 8-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training accuracy, validation set accuracy, and training loss as a function of the weight initialization scale.\n\n\n```\nnp.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [50, 50, 50, 50, 50, 50, 50]\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nbn_solvers_ws = {}\nsolvers_ws = {}\nweight_scales = np.logspace(-4, 0, num=20)\nfor i, weight_scale in enumerate(weight_scales):\n print('Running weight scale %d / %d' % (i + 1, len(weight_scales)))\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\n bn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n bn_solver.train()\n bn_solvers_ws[weight_scale] = bn_solver\n\n solver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n solver.train()\n solvers_ws[weight_scale] = solver\n```\n\n Running weight scale 1 / 20\n Running weight scale 2 / 20\n Running weight scale 3 / 20\n Running weight scale 4 / 20\n Running weight scale 5 / 20\n Running weight scale 6 / 20\n Running weight scale 7 / 20\n Running weight scale 8 / 20\n Running weight scale 9 / 20\n Running weight scale 10 / 20\n Running weight scale 11 / 20\n Running weight scale 12 / 20\n Running weight scale 13 / 20\n Running weight scale 14 / 20\n Running weight scale 15 / 20\n Running weight scale 16 / 20\n Running weight scale 17 / 20\n Running weight scale 18 / 20\n Running weight scale 19 / 20\n Running weight scale 20 / 20\n\n\n\n```\n# Plot results of weight scale experiment\nbest_train_accs, bn_best_train_accs = [], []\nbest_val_accs, bn_best_val_accs = [], []\nfinal_train_loss, bn_final_train_loss = [], []\n\nfor ws in weight_scales:\n best_train_accs.append(max(solvers_ws[ws].train_acc_history))\n bn_best_train_accs.append(max(bn_solvers_ws[ws].train_acc_history))\n \n best_val_accs.append(max(solvers_ws[ws].val_acc_history))\n bn_best_val_accs.append(max(bn_solvers_ws[ws].val_acc_history))\n \n final_train_loss.append(np.mean(solvers_ws[ws].loss_history[-100:]))\n bn_final_train_loss.append(np.mean(bn_solvers_ws[ws].loss_history[-100:]))\n \nplt.subplot(3, 1, 1)\nplt.title('Best val accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best val accuracy')\nplt.semilogx(weight_scales, best_val_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm')\nplt.legend(ncol=2, loc='lower right')\n\nplt.subplot(3, 1, 2)\nplt.title('Best train accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best training accuracy')\nplt.semilogx(weight_scales, best_train_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm')\nplt.legend()\n\nplt.subplot(3, 1, 3)\nplt.title('Final training loss vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Final training loss')\nplt.semilogx(weight_scales, final_train_loss, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_final_train_loss, '-o', label='batchnorm')\nplt.legend()\nplt.gca().set_ylim(1.0, 3.5)\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n## Inline Question 1:\nDescribe the results of this experiment. How does the scale of weight initialization affect models with/without batch normalization differently, and why?\n\n## Answer:\nThe second plot shows the problem of vanishing gradients (small initial weights). The baseline model is very sensitive to this problem (the accuracy is very low), therefore finding the correct weight scale is difficult. For this example, the baseline obtains the best result with a weight scale equal to 1e-1. On the other hand, we can see that the batchnorm model is less sensitive to weight initialization because its accuracy is around 30% for all the different weight scales.\n\nThe behaviour of the first plot is very similar to that of the second plot. The main difference is that the first plot shows that we are overfitting our model, besides that we can see that with the batchnorm model we obtained better results than the baseline model and that occurs because batch normalization has regularization properties.\n\nThe third plot depicts the problem of exploding gradients and it is very evident in the baseline model for weight scale values greater than 1e-1. However, the batchnorm model does not suffer from this problem.\n\nIn general with batch normalization we can avoid the problem of vanishing and exploding gradients because it normalizes every affine layer (xW+b), avoiding very large/small values. Moreover, its regularization properties allow to decrease overfitting.\n\n\n# Batch normalization and batch size\nWe will now run a small experiment to study the interaction of batch normalization and batch size.\n\nThe first cell will train 6-layer networks both with and without batch normalization using different batch sizes. The second layer will plot training accuracy and validation set accuracy over time.\n\n\n```\ndef run_batchsize_experiments(normalization_mode):\n np.random.seed(231)\n # Try training a very deep net with batchnorm\n hidden_dims = [100, 100, 100, 100, 100]\n num_train = 1000\n small_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n }\n n_epochs=10\n weight_scale = 2e-2\n batch_sizes = [5,10,50]\n lr = 10**(-3.5)\n solver_bsize = batch_sizes[0]\n\n print('No normalization: batch size = ',solver_bsize)\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n solver = Solver(model, small_data,\n num_epochs=n_epochs, batch_size=solver_bsize,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n solver.train()\n \n bn_solvers = []\n for i in range(len(batch_sizes)):\n b_size=batch_sizes[i]\n print('Normalization: batch size = ',b_size)\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=normalization_mode)\n bn_solver = Solver(bn_model, small_data,\n num_epochs=n_epochs, batch_size=b_size,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n bn_solver.train()\n bn_solvers.append(bn_solver)\n \n return bn_solvers, solver, batch_sizes\n\nbatch_sizes = [5,10,50]\nbn_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('batchnorm')\n```\n\n No normalization: batch size = 5\n Normalization: batch size = 5\n Normalization: batch size = 10\n Normalization: batch size = 50\n\n\n\n```\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 2:\nDescribe the results of this experiment. What does this imply about the relationship between batch normalization and batch size? Why is this relationship observed?\n\n## Answer:\nAccording to the results, we can see that the batch size affects directly the performance of batch normalization (the smaller the batch size the worse). Even the baseline model outperforms the batchnorm model when using a very small batch size. This problem occurs because when we calculate the statistics of a batch, i.e., mean and variance, we try to find an approximation of the statistics of the entire dataset. Therefore with a small batch size, these statistics can be very noisy. On the other hand, with a large batch size we can obtain a better approximation.\n\n\n# Layer Normalization\nBatch normalization has proved to be effective in making networks easier to train, but the dependency on batch size makes it less useful in complex networks which have a cap on the input batch size due to hardware limitations. \n\nSeveral alternatives to batch normalization have been proposed to mitigate this problem; one such technique is Layer Normalization [2]. Instead of normalizing over the batch, we normalize over the features. In other words, when using Layer Normalization, each feature vector corresponding to a single datapoint is normalized based on the sum of all terms within that feature vector.\n\n[2] [Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. \"Layer Normalization.\" stat 1050 (2016): 21.](https://arxiv.org/pdf/1607.06450.pdf)\n\n## Inline Question 3:\nWhich of these data preprocessing steps is analogous to batch normalization, and which is analogous to layer normalization?\n\n1. Scaling each image in the dataset, so that the RGB channels for each row of pixels within an image sums up to 1.\n2. Scaling each image in the dataset, so that the RGB channels for all pixels within an image sums up to 1. \n3. Subtracting the mean image of the dataset from each image in the dataset.\n4. Setting all RGB values to either 0 or 1 depending on a given threshold.\n\n## Answer:\nNumber 2 is analogous to layer normalization when we consider: mean = 0, beta parameter = 0 (at this point we have gamma*x/std where std=sqrt(sum(x^2))) and gamma=x/std. Thus the result of layer normalization will be x^2/sum(x^2).\n\nNumber 3 is analogous to batch normalization when we consider: batch size = size of the dataset, gamma parameter = standard deviation and beta parameter = 0. Thus the result of batch normalization will be std*(x-mean)/std + 0 = x-mean.\n\n\n# Layer Normalization: Implementation\n\nNow you'll implement layer normalization. This step should be relatively straightforward, as conceptually the implementation is almost identical to that of batch normalization. One significant difference though is that for layer normalization, we do not keep track of the moving moments, and the testing phase is identical to the training phase, where the mean and variance are directly calculated per datapoint.\n\nHere's what you need to do:\n\n* In `cs231n/layers.py`, implement the forward pass for layer normalization in the function `layernorm_forward`. \n\nRun the cell below to check your results.\n* In `cs231n/layers.py`, implement the backward pass for layer normalization in the function `layernorm_backward`. \n\nRun the second cell below to check your results.\n* Modify `cs231n/classifiers/fc_net.py` to add layer normalization to the `FullyConnectedNet`. When the `normalization` flag is set to `\"layernorm\"` in the constructor, you should insert a layer normalization layer before each ReLU nonlinearity. \n\nRun the third cell below to run the batch size experiment on layer normalization.\n\n\n```\n# Check the training-time forward pass by checking means and variances\n# of features both before and after layer normalization \n\n# Simulate the forward pass for a two-layer network\nnp.random.seed(231)\nN, D1, D2, D3 =4, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before layer normalization:')\nprint_mean_std(a,axis=1)\n\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n# Means should be close to zero and stds close to one\nprint('After layer normalization (gamma=1, beta=0)')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n\ngamma = np.asarray([3.0,3.0,3.0])\nbeta = np.asarray([5.0,5.0,5.0])\n# Now means should be close to beta and stds close to gamma\nprint('After layer normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n```\n\n Before layer normalization:\n means: [-59.06673243 -47.60782686 -43.31137368 -26.40991744]\n stds: [10.07429373 28.39478981 35.28360729 4.01831507]\n \n After layer normalization (gamma=1, beta=0)\n means: [ 4.81096644e-16 -7.40148683e-17 2.22044605e-16 -5.92118946e-16]\n stds: [0.99999995 0.99999999 1. 0.99999969]\n \n After layer normalization (gamma= [3. 3. 3.] , beta= [5. 5. 5.] )\n means: [5. 5. 5. 5.]\n stds: [2.99999985 2.99999998 2.99999999 2.99999907]\n \n\n\n\n```\n# Gradient check batchnorm backward pass\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nln_param = {}\nfx = lambda x: layernorm_forward(x, gamma, beta, ln_param)[0]\nfg = lambda a: layernorm_forward(x, a, beta, ln_param)[0]\nfb = lambda b: layernorm_forward(x, gamma, b, ln_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = layernorm_forward(x, gamma, beta, ln_param)\ndx, dgamma, dbeta = layernorm_backward(dout, cache)\n\n#You should expect to see relative errors between 1e-12 and 1e-8\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.4336158494902849e-09\n dgamma error: 4.519489546032799e-12\n dbeta error: 2.276445013433725e-12\n\n\n# Layer Normalization and batch size\n\nWe will now run the previous batch size experiment with layer normalization instead of batch normalization. Compared to the previous experiment, you should see a markedly smaller influence of batch size on the training history!\n\n\n```\nln_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('layernorm')\n\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 4:\nWhen is layer normalization likely to not work well, and why?\n\n1. Using it in a very deep network\n2. Having a very small dimension of features\n3. Having a high regularization term\n\n\n## Answer:\n1. [INCORRECT] In the previous example, the network had five layers and it can be considered as a deep network. Thus, using layer normalization in deep networks works correctly.\n\n2. [CORRECT] Having a small dimension of features affects the performance of layer normalization. The problem is very similar to that of batch normalization with small batch size because in layer normalization we calculate the statistics according to the number of hidden units, which represent the features that the network is learning. Thus, the smaller the hidden size the noisier the statistics used in layer normalization.\n\n3. [CORRECT] Having a high regularization term affects the performance of layer normalization. In general, when the regularization term is very high, the model learns very simple functions (underfitting).\n\n", "meta": {"hexsha": "355e8057e688a71c222953a7c17e2994e813f606", "size": 462511, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignment2/BatchNormalization.ipynb", "max_stars_repo_name": "BatyrM/Stanford-CS231n-Spring-2020", "max_stars_repo_head_hexsha": "112ec761589296ae1007165ea7032a3d441b2307", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-10T09:13:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T09:13:55.000Z", "max_issues_repo_path": "assignment2/BatchNormalization.ipynb", "max_issues_repo_name": "BatyrM/CS231n-Spring-2020", "max_issues_repo_head_hexsha": "112ec761589296ae1007165ea7032a3d441b2307", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-06-08T21:51:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:37:43.000Z", "max_forks_repo_path": "assignment2/BatchNormalization.ipynb", "max_forks_repo_name": "BatyrM/CS231n-Spring-2020", "max_forks_repo_head_hexsha": "112ec761589296ae1007165ea7032a3d441b2307", "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": 462511.0, "max_line_length": 462511, "alphanum_fraction": 0.9364944834, "converted": true, "num_tokens": 9956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208213008246071, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.09860699675410632}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\n# Write your imports here\nimport sympy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n```\n\n# High-School Maths Exercise\n## Getting to Know Jupyter Notebook. Python Libraries and Best Practices. Basic Workflow\n\n### Problem 1. Markdown\nJupyter Notebook is a very light, beautiful and convenient way to organize your research and display your results. Let's play with it for a while.\n\nFirst, you can double-click each cell and edit its content. If you want to run a cell (that is, execute the code inside it), use Cell > Run Cells in the top menu or press Ctrl + Enter.\n\nSecond, each cell has a type. There are two main types: Markdown (which is for any kind of free text, explanations, formulas, results... you get the idea), and code (which is, well... for code :D).\n\nLet me give you a...\n#### Quick Introduction to Markdown\n##### Text and Paragraphs\nThere are several things that you can do. As you already saw, you can write paragraph text just by typing it. In order to create a new paragraph, just leave a blank line. See how this works below:\n```\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n```\n**Result:**\n\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n\n##### Headings\nThere are six levels of headings. Level one is the highest (largest and most important), and level 6 is the smallest. You can create headings of several types by prefixing the header line with one to six \"#\" symbols (this is called a pound sign if you are ancient, or a sharp sign if you're a musician... or a hashtag if you're too young :D). Have a look:\n```\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n```\n\n**Result:**\n\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n\nIt is recommended that you have **only one** H1 heading - this should be the header of your notebook (or scientific paper). Below that, you can add your name or just jump to the explanations directly.\n\n##### Emphasis\nYou can create emphasized (stonger) text by using a **bold** or _italic_ font. You can do this in several ways (using asterisks (\\*) or underscores (\\_)). In order to \"escape\" a symbol, prefix it with a backslash (\\). You can also strike thorugh your text in order to signify a correction.\n```\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not \\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n```\n\n**Result:**\n\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not\\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n\n##### Lists\nYou can add two types of lists: ordered and unordered. Lists can also be nested inside one another. To do this, press Tab once (it will be converted to 4 spaces).\n\nTo create an ordered list, just type the numbers. Don't worry if your numbers are wrong - Jupyter Notebook will create them properly for you. Well, it's better to have them properly numbered anyway...\n```\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n```\n\n**Result:**\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n \nTo create an unordered list, type an asterisk, plus or minus at the beginning:\n```\n* This is\n* An\n + Unordered\n - list\n```\n\n**Result:**\n* This is\n* An\n + Unordered\n - list\n \n##### Links\nThere are many ways to create links but we mostly use one of them: we present links with some explanatory text. See how it works:\n```\nThis is [a link](http://google.com) to Google.\n```\n\n**Result:**\n\nThis is [a link](http://google.com) to Google.\n\n##### Images\nThey are very similar to links. Just prefix the image with an exclamation mark. The alt(ernative) text will be displayed if the image is not available. Have a look (hover over the image to see the title text):\n```\n Do you know that \"taco cat\" is a palindrome? Thanks to The Oatmeal :)\n```\n\n**Result:**\n\n Do you know that \"taco cat\" is a palindrome? Thanks to The Oatmeal :)\n\nIf you want to resize images or do some more advanced stuff, just use HTML. \n\nDid I mention these cells support HTML, CSS and JavaScript? Now I did.\n\n##### Tables\nThese are a pain because they need to be formatted (somewhat) properly. Here's a good [table generator](http://www.tablesgenerator.com/markdown_tables). Just select File > Paste table data... and provide a tab-separated list of values. It will generate a good-looking ASCII-art table for you.\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**Result:**\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##### Code\nJust use triple backtick symbols. If you provide a language, it will be syntax-highlighted. You can also use inline code with single backticks.\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___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\n

This 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
\n

Histogram 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

\nSupervised Learning can be further divided into the two tasks as below:\n
\n> a. Classifcation - where you predict that the data belongs to a specific class. Eg.: Classfying a cat or a dog.\n
\n> b. Regression - where a real number value is predicted. Eg: Predicting the price of a house given it's dimensions.\n
\n\n>>In the below example, you can see that images are trained against their labels. You test the model by inputting an image and predicting it's class... like a cat.\n>>>>> \n\n> - When your data is unlabelled, the only option would be to let your model figure out by itself the patterns in the data. This is called **Unsupervised Learning**.

In the example shown below, you only provide the datapoints and the number of clusters(classes) that has to be formed and let the algorithm find out the best set of clusters.\n>>>>>>> \n\n> 2\\. When you don't have data but instead have the environment itself to learn!\n\n>Here, a learning agent is put in a predefined environment and made to learn by the actions it takes. It is either rewarded or punished based on its actions. This is the most interesting kind of learning and is also where a lot of exploration and research is happenning.It is called **Reinforcement Learning**.

As it can clearly be seen from the below image that the agent which is modelled as a person, learns to climb the wall through trial and error.\n>>>>>>> \n\n

This tutorial focuses on Neural Networks which is a part of Supervised Learning.\n\n## A little bit into the history of how Neural Networks evolved\n\nThe evolution of AI dates to back to 1950 when Alan Turing, the computer genius, came out with the Turing Test to distinguish between a Human and a Robot. He describes that when a machine performs so well, that we humans are not able to distinguish between the response given by a human and a machine, it has passed the Turing Test. Apparently this feat was achieved only in 2012, when a company named Vicarious cracked the captchas. Check out this video below on how Vicarious broke the captchas.\n\n\n```python\n#@title Vicarious Video\n%%HTML\n\n\n```\n\n\n\n\n\n\nIt must be noted that most of the Algorithms that were developed during that period(1950-2000) and now existing, are highly inspired by the working of our brain, the neurons and their structure with how they learn and transfer data. The most popular works include the Perceptron and the Neocognitron $-$(not covered in this article, but in a future article) based on which the Neural Networks have been developed. \n\nNow, before you dive into what a perceptron is, let's make sure you know a bit of all these... Although not necessarily required!\n\n## Prerequisites\n\nWhat you’ll need to know for the course:\n1. A little bit of Python &\n2. The eagerness to learn Neural Networks.\n\nIf you are unsure of which environment to use for implementing this, I recommend [Google Colab](https://colab.research.google.com/). The environment comes with many important packages already installed. Installing new packages and also importing and exporting the data is quite simple. Most of all, it also comes with GPU support. So go ahead and get coding with the platform!\n\nLastly, this article is directed for those who want to learn about Neural Networks or just Linear Regression. However, there would be an inclination towards Neural Networks!\n\n## A biological Neuron\n\n>>>>> \n\nThe figure above shows a biological neuron. It has *dendrites* that recieve information from neurons. The recieved information is passed on to the *cell body or the nucleus* of the neuron. The *nucleus* is where the information is processed. The processed information is passed on to the next layer of neurons through the *axons*.\n\nOur brain consists of about 100 billion such neurons which communicate through electrochemical signals. Each neuron is connected to 100s and 1000s of other neurons which constantly transmit and recieve signals. When the sum of the signals recieved by a neuron exceeds a set threshold value, the cell is activated (although, it has been speculated that neurons use very complex activations to process the input data) and the signal is further transmitted to other neurons. You'll see that the artificial neuron or the perceptron adopts the same ideology to perform computation and transmit data in the next section.\n\nYou know that different regions of our brain are activated (/receptive) for different actions like seeing, hearing, creative thinking and so on. This is because the neurons belonging to a specific region in the brain are trained to process a certain kind of information better and hence get activated when only certain kinds of information is being sent.The figure below gives us a better understanding of the different receptive regions of the brain.\n\n>>>> \n\nIt has also been shown through the concept of Neuroplasticity that the different regions of the brain can be rewired to perform totally different tasks. Such as the neurons responsible for touch sensing can be rewired to become sensitive to smell. Check out this great TEDx video below to know more about neuroplasticity.\n\nSimilarly, an artificial neuron/perceptron can be trained to recognize some of the most comlplex pattern. Hence, they can be called Universal Function Approximators.\n\nIn the next section, we'll explore the working of a perceptron and also gain a mathematical intuition.\n\n\n```python\n#@title Neuroplasticity\n%%HTML\n\n''\n```\n\n\n\n''\n\n\n## Perceptron/Artificial Neuron\n\n>>>>>> \n\n\nFrom the figure, you can observe that the perceptron is a reflection of the biological neuron. The inputs combined with the weights($w_i$) are analogous to dendrties. These values are summed and passed through an activation function (like the thresholding function as shown in fig.). This is analogous to the nucleus. Finally, the activated value is transmitted to the next neuron/perceptron which is analogous to the axons.\n\nThe latent weights($w_i$) multiplied with each input($x_i$) depicts the significance of the respective input/feature. Larger the value of a weight, more important is the feature. Hence, the weights are what is learned in a perceptron so as to arrive at the required result. An additional bias($b$, here $w_0$) is also learned.\n\nHence, when there are multiple inputs (say n), the equation can be generalized as follows: \n\\begin{equation}\nz=w_0+w_1.x_1+w_2.x_2+w_3.x_3+......+w_n.x_n \\\\\n\\therefore z=\\sum_{i=0}^{n}w_i.x_i \\qquad \\text{where } x_0 = 1\n\\end{equation}\n\nFinally, the output of summation (assume as $z$) is fed to the *thresholding activation function*, where the function outputs $ -1 \\space \\text{if } z < 0 \\space \\& \\space 1 \\space \\text{if } z \\geq 0$.\n\n### An Example\n\nLet us consider our perceptron to perform as *logic gates* to gain more intuition.\n\nLet's choose an $AND \\space gate$. The Truth Table for the $AND \\space gate$ is shown below:\n\n>>>>>>>>> \n\nThe perceptron for the $AND \\space gate$ can be formed as shown in the figure. It is clear that the perceptron has two inputs (here $x1=A$ and $x2=B$)\n\n>>>>>>>>> \n\n\\begin{equation}\n\\text{Threshold Function,} \\qquad y = f(z) = \\begin{cases}\n1,& \\text{if }z \\geq 0.5\\\\\n0,& \\text{if } z< 0.5\\\\\n\\end{cases}\n\\end{equation}\n\nWe can see that for inputs $x1$, $x2$ & $x_0=1$, setting their weights as \n\\begin{equation}\nw_0=-0.5, \\\\\nw_1=0.6, \\space \\&\\\\\nw_2=0.6\n\\end{equation}\nrespectively and keeping the *Threshold function* as the activation function we can arrive at the $AND \\space Gate$.\n\nNow, let's get our hands dirty and codify this and test it out!\n\n\n```python\ndef and_perceptron(x1, x2):\n \n w0 = -0.5\n w1 = 0.6\n w2 = 0.6\n \n z = w0 + w1 * x1 + w2 * x2\n \n thresh = lambda x: 1 if x>= 0.5 else 0\n\n r = thresh(z)\n print(r)\n```\n\n\n```python\nand_perceptron(1, 1)\n```\n\n 1\n\n\nSimilarly for $NOR \\space Gate$ the Truth Table is,\n\n>>>>>>>>> \n\nThe perceptron for $NOR \\space Gate$ will be as below:\n\n>>>>>>>>> \n\n\nYou can set the weights as\n\\begin{equation}\nw_0 = 0.5 \\\\\nw_1 = -0.6 \\\\\nw_2 = -0.6\n\\end{equation}\nso that you obtain a $NOR \\space Gate$.\n\nYou can go ahead and implement this in code.\n\n\n```python\ndef nor_perceptron(x1, x2):\n \n w0 = 0.5\n w1 = -0.6\n w2 = -0.6\n \n z = w0 + w1 * x1 + w2 * x2\n \n thresh = lambda x: 1 if x>= 0.5 else 0\n\n r = thresh(z)\n print(r)\n```\n\n\n```python\nnor_perceptron(1, 1)\n```\n\n 0\n\n\nHere, is the Truth Table for $NAND \\space Gate$. Go ahead and guess the weights that fits the function and also implement in code.\n\n>>>>>>>>> \n\n## What you are actually calculating...\n\nIf you analyse what you were trying to do in the above examples, you will realize that you were actually trying to adjust the values of the weights to obtain the required output.\n\nLets consider the NOR Gate example and break it down to very miniscule steps to gain more understanding. \n\nWhat you would usually do first is to simply set some values to the weights and observe the result, say\n\n\\begin{equation}\nw_0 = 0.4 \\\\\nw_1 = 0.7 \\\\\nw_2 = -0.2\n\\end{equation}\n\nThen the output will be as shown in below table:\n>>>>> \n\nSo how can you fix the values of weights so that you get the right output?\n\nBy intuition, you can easily observe that $w_0$ must be increased and $w_1$ and $w_2$ must be reduced or rather made negative so that you obtain the actual output. But if you breakdown this intuition, you will observe that you are actually finding the difference between the actual output and the predicted output and finally reflecting that on the weights...\n\nThis is a very important concept that you will be digging deeper and will be the core to formulate the ideas behind *gradient descent* and also *backward propagation*.\n\n## Conclusion\n\nIn this tutorial you were introduced to the field of AI and went through an overview of perceptron. In the next tutorial, you'll learn to train a perceptron and do some predictions!!\n", "meta": {"hexsha": "75378f2458af2d0e22f3c13698ef612cac355308", "size": 21718, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NN with Numpy 1/Neural_Networks_for_Absolute_beginners_Part_1_Introduction.ipynb", "max_stars_repo_name": "SurajDonthi/Article-Tutorials", "max_stars_repo_head_hexsha": "994a9bba02611cb79d708ae6abc32db7f03f03f1", "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": "NN with Numpy 1/Neural_Networks_for_Absolute_beginners_Part_1_Introduction.ipynb", "max_issues_repo_name": "SurajDonthi/Article-Tutorials", "max_issues_repo_head_hexsha": "994a9bba02611cb79d708ae6abc32db7f03f03f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-03-10T04:17:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-10T04:43:28.000Z", "max_forks_repo_path": "NN with Numpy 1/Neural_Networks_for_Absolute_beginners_Part_1_Introduction.ipynb", "max_forks_repo_name": "SurajDonthi/Article-Tutorials", "max_forks_repo_head_hexsha": "994a9bba02611cb79d708ae6abc32db7f03f03f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-01-26T16:59:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T13:27:17.000Z", "avg_line_length": 40.5943925234, "max_line_length": 623, "alphanum_fraction": 0.6345427756, "converted": true, "num_tokens": 2804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.19682619657611938, "lm_q1q2_score": 0.09764426159964305}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\n# Write your imports here\nimport sympy\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n### Problem 1. Markdown\nJupyter Notebook is a very light, beautiful and convenient way to organize your research and display your results. Let's play with it for a while.\n\nFirst, you can double-click each cell and edit its content. If you want to run a cell (that is, execute the code inside it), use Cell > Run Cells in the top menu or press Ctrl + Enter.\n\nSecond, each cell has a type. There are two main types: Markdown (which is for any kind of free text, explanations, formulas, results... you get the idea), and code (which is, well... for code :D).\n\nLet me give you a...\n#### Quick Introduction to Markdown\n##### Text and Paragraphs\nThere are several things that you can do. As you already saw, you can write paragraph text just by typing it. In order to create a new paragraph, just leave a blank line. See how this works below:\n```\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n```\n**Result:**\n\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n\n##### Headings\nThere are six levels of headings. Level one is the highest (largest and most important), and level 6 is the smallest. You can create headings of several types by prefixing the header line with one to six \"#\" symbols (this is called a pound sign if you are ancient, or a sharp sign if you're a musician... or a hashtag if you're too young :D). Have a look:\n```\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n```\n\n**Result:**\n\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n\nIt is recommended that you have **only one** H1 heading - this should be the header of your notebook (or scientific paper). Below that, you can add your name or just jump to the explanations directly.\n\n##### Emphasis\nYou can create emphasized (stronger) text by using a **bold** or _italic_ font. You can do this in several ways (using asterisks (\\*) or underscores (\\_)). In order to \"escape\" a symbol, prefix it with a backslash (\\). You can also strike through your text in order to signify a correction.\n```\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not \\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n```\n\n**Result:**\n\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not\\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n\n##### Lists\nYou can add two types of lists: ordered and unordered. Lists can also be nested inside one another. To do this, press Tab once (it will be converted to 4 spaces).\n\nTo create an ordered list, just type the numbers. Don't worry if your numbers are wrong - Jupyter Notebook will create them properly for you. Well, it's better to have them properly numbered anyway...\n```\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n```\n\n**Result:**\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n \nTo create an unordered list, type an asterisk, plus or minus at the beginning:\n```\n* This is\n* An\n + Unordered\n - list\n```\n\n**Result:**\n* This is\n* An\n + Unordered\n - list\n \n##### Links\nThere are many ways to create links but we mostly use one of them: we present links with some explanatory text. See how it works:\n```\nThis is [a link](http://google.com) to Google.\n```\n\n**Result:**\n\nThis is [a link](http://google.com) to Google.\n\n##### Images\nThey are very similar to links. Just prefix the image with an exclamation mark. The alt(ernative) text will be displayed if the image is not available. Have a look (hover over the image to see the title text):\n```\n Do you know that \"taco cat\" is a palindrome? Thanks to The Oatmeal :)\n```\n\n**Result:**\n\n Do you know that \"taco cat\" is a palindrome? Thanks to The Oatmeal :)\n\nIf you want to resize images or do some more advanced stuff, just use HTML. \n\nDid I mention these cells support HTML, CSS and JavaScript? Now I did.\n\n##### Tables\nThese are a pain because they need to be formatted (somewhat) properly. Here's a good [table generator](http://www.tablesgenerator.com/markdown_tables). Just select File > Paste table data... and provide a tab-separated list of values. It will generate a good-looking ASCII-art table for you.\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**Result:**\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##### Code\nJust use triple backtick symbols. If you provide a language, it will be syntax-highlighted. You can also use inline code with single backticks.\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
\nFor more playing arround, please check out the attached notebook\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

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\n

Write 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\\begin{align}\n\\frac{\\partial \\text{NLL}}{\\partial {\\bf w}} & = \\frac{\\partial \\text{NLL}}{\\partial {\\hat y}} \\cdot \\frac{\\partial \\hat y}{\\partial o} \\cdot \\frac{\\partial o}{\\partial {\\bf w}} \\\\\n& = \\sum_{k=0}^{K-1} \\left[\\frac{1 - y_k}{1 - \\hat y_k} - \\frac{y_k}{\\hat y_k}\\right]\\hat y_k (1-\\hat y_k) {\\bf x}_k \\\\\n& = \\sum_{k=0}^{K-1} \\left[(1 - y_k) \\hat y_k - y_k (1 - \\hat y_k) \\right] {\\bf x}_k \\\\\n\\frac{\\partial \\text{NLL}}{\\partial b} & = \\sum_{k=0}^{K-1} \\left[(1 - y_k) \\hat y_k - y_k (1 - \\hat y_k) \\right]\n\\end{align}\n\n* Gradient Descent Optimization\n\n
\n$${\\bf w}_{n+1} = {\\bf w}_n + \\rho_n \\sum_{k=0}^{K-1} \\left[y_k (1 - \\hat y_k) - (1 - y_k) \\hat y_k \\right] {\\bf x}_k = {\\bf w}_n + \\rho_n \\sum_{k=0}^{K-1} (y_k - \\hat y_k){\\bf x}_k$$\n$$b_{n+1} = b_n + \\rho_n \\sum_{k=0}^{K-1} \\left[y_k (1 - \\hat y_k) - (1 - y_k) \\hat y_k \\right] = b_n + \\rho_n \\sum_{k=0}^{K-1} (y_k - \\hat y_k)$$\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\n#dataset = 'DogsCats'\ndataset = 'digits'\n\nif dataset=='DogsCats':\n X = DogsCatsX_flatten\n y = DogsCatsY\n \nelse:\n #Zero and Ones are one hot encoded in columns 1 and 4\n X0 = digitsX_flatten[np.argmax(digitsY, axis=1)==1,]\n X1 = digitsX_flatten[np.argmax(digitsY, axis=1)==4,]\n X = np.vstack((X0, X1))\n y = np.zeros(X.shape[0])\n y[X0.shape[0]:] = 1\n \n#Joint normalization of all data. For images [-.5, .5] scaling is frequent\nmin_max_scaler = MinMaxScaler(feature_range=(-.5, .5))\nX = min_max_scaler.fit_transform(X)\n\n#Generate train and validation data, shuffle\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42, shuffle=True)\n```\n\n\n```python\n# Define some useful functions\ndef logistic(t):\n return 1.0 / (1 + np.exp(-t))\n\ndef forward(w,b,x):\n #Calcula la salida de la red\n return logistic(x.dot(w)+b)\n\ndef backward(y,y_hat,x):\n #Calcula los gradientes\n #w_grad = x.T.dot((1-y)*y_hat - y*(1-y_hat))/len(y)\n #b_grad = np.sum((1-y)*y_hat - y*(1-y_hat))/len(y)\n w_grad = x.T.dot(y_hat-y)/len(y)\n b_grad = np.sum(y_hat-y)/len(y)\n return w_grad, b_grad\n \ndef accuracy(y, y_hat):\n return np.mean(y == (y_hat>=0.5))\n\ndef loss(y, y_hat):\n return -np.sum(y*np.log(y_hat)+(1-y)*np.log(1-y_hat))/len(y)\n```\n\n\n```python\n#Neural Network Training\n\nepochs = 50\nrho = .05 #Use this setting for Sign Digits Dataset\n\n#Parameter initialization\nw = .1 * np.random.randn(X.shape[1])\nb = .1 * np.random.randn(1)\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in np.arange(epochs):\n y_hat_train = forward(w, b, X_train)\n y_hat_val = forward(w, b, X_val)\n w_grad, b_grad = backward(y_train, y_hat_train, X_train)\n w = w - rho * w_grad\n b = b - rho * b_grad\n \n loss_train[epoch] = loss(y_train, y_hat_train)\n loss_val[epoch] = loss(y_val, y_hat_val)\n acc_train[epoch] = accuracy(y_train, y_hat_train)\n acc_val[epoch] = accuracy(y_val, y_hat_val)\n```\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n### Exercise\n\n* Study the behavior of the algorithm changing the number of epochs and the learning rate\n\n* Repeat the analysis for the other dataset, trying to obtain as large an accuracy value as possible\n\n* What do you believe are the reasons for the very different performance for both datasets?\n\nLinear logistic regression allowed us to review a few concepts that are key for Neural Networks:\n\n* Network topology (In this case, a linear network with one layer)\n* Activation functions\n* Parametric approach ($\\bf w$/$b$)\n* Parameter initialization\n* Obtaining the network prediction using *forward* computation\n* Loss function\n* Parameter gradient calculus using *backward* computation\n* Optimization method for parameters update (here, GD)\n\n### 2.2. (Multiclass) SoftMax Regression \n\n* One hot encoding output, e.g., $[0, 1, 0, 0]$, $[0, 0, 0, 1]$\n* Used to encode categorial variables without predefined order\n* Similar to logistic regression, network tries to predict class probability\n$$\\hat y_{k,j} = \\hat P(y_k=j|{\\bf x}_k)$$\n* Network output should satisfy \"probability constraints\"\n$$\\hat y_{k,j} \\in [0,1]\\qquad \\text{and} \\qquad \\sum_j \\hat y_{k,j} = 1$$\n\n* Softmax regression network topology:\n\n\n### Notation\n\nIn this section, it is important to pay attention to subindexes:\n\n|Notation/ Variable Name|Definition|\n|-----------------------|---------------------------------|\n|$y_k \\in [0,\\dots,M-1]$|The label of pattern $k$|\n|${\\bf y}_k$|One hot encoding of the label of pattern $k$|\n|$y_{k,m}$|$m$-th component of vector ${\\bf y}_k$|\n|$y_{m}$|$m$-th component of generic vector ${\\bf y}$ (i.e., for an undefined pattern)|\n|$\\hat {\\bf y}_k$|Network output for pattern $k$|\n|$\\hat y_{k,m}$|$m$-th network output for pattern $k$|\n|$\\hat y_{m}$|$m$-th network output for an undefined pattern)|\n|$k$|Index used for pattern enumeration|\n|$m$|Index used for network output enumeration|\n|$j$|Secondary index for selected network output|\n\n\n\n\n\n### The softmax function\n\n* It is to multiclass problems as the logistic function for binary classification\n* Invented in 1959 by the social scientist R. Duncan Luce\n* Transforms a set of $M$ real numbers to satisfy \"probability\" constraints\n\n
\n$${\\bf \\hat y} = \\text{softmax}({\\bf o}) \\qquad \\text{where} \\qquad \\hat y_j = \\frac{\\exp(o_j)}{\\sum_m \\exp(o_m)} $$\n\n* Continuous and **differentiable** function\n\n
\n$$\\frac{\\partial \\hat y_j}{\\partial o_j} = \\hat y_j (1 - \\hat y_j) \\qquad \\text{and} \\qquad \\frac{\\partial \\hat y_j}{\\partial o_m} = - \\hat y_j \\hat y_m$$\n\n\n\n* The classifier is still linear, since\n\n
\n$$\\arg\\max \\hat {\\bf y} = \\arg\\max \\hat {\\bf o} = \\arg\\max {\\bf W} {\\bf x} + {\\bf b}$$\n\n### Cross-entropy loss for multiclass problems\n\n* Similarly to logistic regression, minimization of the log-likelihood can be stated to obtain ${\\bf W}$ and ${\\bf b}$\n\n
\n$$\\text{Binary}: \\text{NLL}({\\bf w}, b) = - \\sum_{k=0}^{K-1} \\log \\hat P(y_k|{\\bf x}_k)$$\n$$\\text{Multiclass}: \\text{NLL}({\\bf W}, {\\bf b}) = - \\sum_{k=0}^{K-1} \\log \\hat P(y_k|{\\bf x}_k)$$\n\n* Using one hot encoding for the label vector of each sample, e.g., $y_k = 2 \\rightarrow {\\bf y}_k = [0, 0, 1, 0]$\n\n$$\\text{NLL}({\\bf W}, {\\bf b}) = - \\sum_{k=0}^{K-1} \\sum_{m=0}^{M-1} y_{k,m} \\log \\hat P(m|{\\bf x}_k)= - \\sum_{k=0}^{K-1} \\sum_{m=0}^{M-1} y_{k,m} \\log \\hat y_{k,m} = \\sum_{k=0}^{K-1} l({\\bf y}_k, \\hat {\\bf y}_k)$$\n\n* Note that for each pattern, only one element in the inner sum (the one indexed with $m$) is non-zero\n\n* In the context of Neural Networks, this cost is referred to as the cross-entropy loss\n\n
\n$$l({\\bf y}, \\hat {\\bf y}) = - \\sum_{m=0}^{M-1} y_{m} \\log \\hat y_{m}$$\n\n### Network optimization\n\n* Gradient Descent Optimization\n\n
\n$${\\bf W}_{n+1} = {\\bf W}_n - \\rho_n \\sum_{k=0}^{K-1} \\frac{\\partial l({\\bf y}_k,{\\hat {\\bf y}_k})}{\\partial {\\bf W}}$$\n$${\\bf b}_{n+1} = {\\bf b}_n - \\rho_n \\sum_{k=0}^{K-1} \\frac{\\partial l({\\bf y}_k,{\\hat {\\bf y}_k})}{\\partial {\\bf b}}$$\n\n* We compute derivatives using the chain rule (we ignore dimension mismatchs, and rearrange at the end)\n\n
\n\\begin{align}\n\\frac{\\partial l({\\bf y},{\\hat {\\bf y}})}{\\partial {\\bf W}} &= \\frac{\\partial l({\\bf y},{\\hat {\\bf y}})}{\\partial \\hat {\\bf y}} \\cdot \\frac{\\partial \\hat {\\bf y}}{\\partial {\\bf o}} \\cdot \\frac{\\partial {\\bf o}}{\\partial {\\bf W}} \\\\ & = \\left[\\begin{array}{c} 0 \\\\ 0 \\\\ \\vdots \\\\ - 1/\\hat y_j \\\\ \\vdots \\end{array}\\right] \\left[ \\begin{array}{ccccc} \\hat y_1 (1 - \\hat y_1) & -\\hat y_1 \\hat y_2 & \\dots & -\\hat y_1 \\hat y_j & \\dots \\\\ -\\hat y_2 \\hat y_1 & \\hat y_2 (1 - \\hat y_2) & \\dots & -\\hat y_2 \\hat y_j & \\dots \\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\ - \\hat y_j \\hat y_1 & -\\hat y_j \\hat y_2 & \\dots & \\hat y_j (1-\\hat y_j) & \\dots \\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\end{array}\\right] {\\bf x}^\\top \\\\\n& = \\left[\\begin{array}{c}\\hat y_1 \\\\ \\hat y_2 \\\\ \\vdots \\\\ \\hat y_j - 1 \\\\ \\vdots \\end{array} \\right] {\\bf x}^\\top \\\\\n& = (\\hat {\\bf y} - {\\bf y}){\\bf x}^\\top \\\\\n\\\\\n\\frac{\\partial l({\\bf y},{\\hat {\\bf y}})}{\\partial {\\bf b}} & = (\\hat {\\bf y} - {\\bf y}){\\bf 1}^\\top\n\\end{align}\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\ndataset = 'digits'\n\n#Joint normalization of all data. For images [-.5, .5] scaling is frequent\nmin_max_scaler = MinMaxScaler(feature_range=(-.5, .5))\nX = min_max_scaler.fit_transform(digitsX_flatten)\n\n#Generate train and validation data, shuffle\nX_train, X_val, y_train, y_val = train_test_split(X, digitsY, test_size=0.2, random_state=42, shuffle=True)\n```\n\n\n```python\n# Define some useful functions\ndef softmax(t):\n \"\"\"Compute softmax values for each sets of scores in t.\"\"\"\n e_t = np.exp(t)\n return e_t / e_t.sum(axis=1)[:,np.newaxis]\n\ndef forward(w,b,x):\n #Calcula la salida de la red\n return softmax(x.dot(w.T)+b.T)\n\ndef backward(y,y_hat,x):\n #Calcula los gradientes\n W_grad = (y_hat-y).T.dot(x)/len(y)\n b_grad = ((y_hat-y).sum(axis=0)[:,np.newaxis])/len(y)\n return W_grad, b_grad\n \ndef accuracy(y, y_hat):\n return np.mean(np.argmax(y, axis=1) == np.argmax(y_hat, axis=1))\n\ndef loss(y, y_hat):\n return -np.sum(y * np.log(y_hat))/len(y)\n```\n\n\n```python\n#Neural Network Training\n\nepochs = 300\nrho = .1\n\n#Parameter initialization\nW = .1 * np.random.randn(y_train.shape[1], X_train.shape[1])\nb = .1 * np.random.randn(y_train.shape[1],1)\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in np.arange(epochs):\n y_hat_train = forward(W, b, X_train)\n y_hat_val = forward(W, b, X_val)\n W_grad, b_grad = backward(y_train, y_hat_train, X_train)\n W = W - rho * W_grad\n b = b - rho * b_grad\n \n loss_train[epoch] = loss(y_train, y_hat_train)\n loss_val[epoch] = loss(y_val, y_hat_val)\n acc_train[epoch] = accuracy(y_train, y_hat_train)\n acc_val[epoch] = accuracy(y_val, y_hat_val)\n```\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n### Exercise\n\n* Study the behavior of the algorithm changing the number of iterations and the learning rate\n\n* Obtain the confusion matrix, and study which classes are more difficult to classify\n\n* Think about the differences between using this 10-class network, vs training 10 binary classifiers, one for each class\n\nAs in linear logistic regression note that we covered the following aspects of neural network design, implementation, and training:\n\n* Network topology (In this case, a linear network with one layer and $M$ ouptuts)\n* Activation functions (softmax activation)\n* Parameter initialization ($\\bf W$/$b$)\n* Obtaining the network prediction using *forward* computation\n* Loss function\n* Parameter gradient calculus using *backward* computation\n* Optimization method for parameters update (here, GD)\n\n### 2.3. Multi Layer Networks (Deep Networks) \n\nPrevious networks are constrained in the sense that they can only implement linear classifiers. In this section we analyze how we can extend them to implement non-linear classification:\n* Fixed non-linear transformations of inputs: ${\\bf z} = {\\bf{f}}({\\bf x})$\n\n* Parametrize the transformation using additional non-linear layers\n\n\n* When counting layers, we normally ignore the input layer, since there is no computation involved\n* Intermediate layers are normally referred to as \"hidden\" layers\n* Non-linear activations result in an overall non-linear classifier\n* We can still use Gradient Descent Optimization as long as the network loss derivatives with respect to all parameters exist and are continuous\n* This is already deep learning. We can have two layers or more, each with different numbers of neurons. But as long as derivatives with respect to parameters can be calculated, the network can be optimized\n* Finding an appropriate number of layers for a particular problem, as well as the number of neurons per layer, requires exploration\n* The more data we have for training the network, the more parameters we can afford, making feasible the use of more complex topologies\n\n### Example: 2-layer network for binary classification\n\n* Network topology\n * Hidden layer with $n_h$ neurons\n * Hyperbolic tangent activation function for the hidden layer\n $${\\bf h} = \\text{tanh}({\\bf o}^{(1)})= \\text{tanh}\\left({\\bf W}^{(1)} {\\bf x} + {\\bf b}^{(1)}\\right)$$\n * Output layer is linear with logistic activation (as in logistic regression)\n $$\\hat y = \\text{logistic}(o) = \\text{logistic}\\left({{\\bf w}^{(2)}}^\\top {\\bf h} + b^{(2)}\\right)$$\n \n* Cross-entropy loss\n\n$$l(y,\\hat y) = -\\left[ y \\log(\\hat y) + (1 - y ) \\log(1 - \\hat y) \\right], \\qquad \\text{with } y\\in [0,1]$$\n\n* Update of output layer weights as in logistic regression (use ${\\bf h}$ instead of ${\\bf x}$)\n\n$${\\bf w}_{n+1}^{(2)} = {\\bf w}_n^{(2)} + \\rho_n \\sum_{k=0}^{K-1} (y_k - \\hat y_k){\\bf h}_k$$\n$$b_{n+1}^{(2)} = b_n^{(2)} + \\rho_n \\sum_{k=0}^{K-1} (y_k - \\hat y_k)$$\n\n\n\n* For updating the input layer parameters we need to use the chain rule (we ignore dimensions and rearrange at the end)\n\n\\begin{align}\\frac{\\partial l(y, \\hat y)}{\\partial {\\bf W}^{(1)}} & = \\frac{\\partial l(y, \\hat y)}{\\partial o} \\cdot \\frac{\\partial o}{\\partial {\\bf h}} \\cdot \\frac{\\partial {\\bf h}}{\\partial {\\bf o}^{(1)}} \\cdot \\frac{\\partial {\\bf o}^{(1)}}{\\partial {\\bf W}^{(1)}} \\\\\n& = (\\hat y - y) [{\\bf w}^{(2)} .\\ast ({\\bf 1}-{\\bf h})^2] {\\bf x}^{\\top}\n\\end{align}\n\n\\begin{align}\\frac{\\partial l(y, \\hat y)}{\\partial {\\bf b}^{(1)}} & = \\frac{\\partial l(y, \\hat y)}{\\partial o} \\cdot \\frac{\\partial o}{\\partial {\\bf h}} \\cdot \\frac{\\partial {\\bf h}}{\\partial {\\bf o}^{(1)}} \\cdot \\frac{\\partial {\\bf o}^{(1)}}{\\partial {\\bf b}^{(1)}} \\\\\n& = (\\hat y - y) [{\\bf w}^{(2)} .\\ast ({\\bf 1}-{\\bf h})^2]\n\\end{align}\n\n* GD update rules become\n$${\\bf W}_{n+1}^{(1)} = {\\bf W}_n^{(1)} + \\rho_n \\sum_{k=0}^{K-1} (y_k - \\hat y_k)[{\\bf w}^{(2)} .\\ast ({\\bf 1}-{\\bf h}_k)^2] {\\bf x}_k^{\\top}$$\n$${\\bf b}_{n+1}^{(1)} = {\\bf b}_n^{(1)} + \\rho_n \\sum_{k=0}^{K-1} (y_k - \\hat y_k)[{\\bf w}^{(2)} .\\ast ({\\bf 1}-{\\bf h}_k)^2]$$\n\n\n\n\n* The process can be implemented as long as the derivatives of the network overall loss with respect to parameters can be computed\n\n* Forward computation graphs represent how the network output can be computed\n\n* We can then reverse the graph to compute derivatives with respect to parameters\n\n* Deep Learning libraries implement automatic gradient camputation\n * We just define network topology\n * Computation of gradients is carried out automatically\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\n#dataset = 'DogsCats'\ndataset = 'digits'\n\nif dataset=='DogsCats':\n X = DogsCatsX_flatten\n y = DogsCatsY\n \nelse:\n #Zero and Ones are one hot encoded in columns 1 and 4\n X0 = digitsX_flatten[np.argmax(digitsY, axis=1)==1,]\n X1 = digitsX_flatten[np.argmax(digitsY, axis=1)==4,]\n X = np.vstack((X0, X1))\n y = np.zeros(X.shape[0])\n y[X0.shape[0]:] = 1\n \n#Joint normalization of all data. For images [-.5, .5] scaling is frequent\nmin_max_scaler = MinMaxScaler(feature_range=(-.5, .5))\nX = min_max_scaler.fit_transform(X)\n\n#Generate train and validation data, shuffle\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42, shuffle=True)\n```\n\n\n```python\n# Define some useful functions\ndef logistic(t):\n return 1.0 / (1 + np.exp(-t))\n\ndef forward(W1,b1,w2,b2,x):\n #Calcula la salida de la red\n h = x.dot(W1.T)+b1\n y_hat = logistic(h.dot(w2)+b2)\n #Provide also hidden units value for backward gradient step\n return h, y_hat\n\ndef backward(y,y_hat,h,x,w2):\n #Calcula los gradientes\n w2_grad = h.T.dot(y_hat-y)/len(y)\n b2_grad = np.sum(y_hat-y)/len(y)\n W1_grad = ((w2[np.newaxis,]*((1-h)**2)*(y_hat - y)[:,np.newaxis]).T.dot(x))/len(y)\n b1_grad = ((w2[np.newaxis,]*((1-h)**2)*(y_hat - y)[:,np.newaxis]).sum(axis=0))/len(y)\n return w2_grad, b2_grad, W1_grad, b1_grad\n \ndef accuracy(y, y_hat):\n return np.mean(y == (y_hat>=0.5))\n\ndef loss(y, y_hat):\n return -np.sum(y*np.log(y_hat)+(1-y)*np.log(1-y_hat))/len(y)\n```\n\n\n```python\n#Neural Network Training\nepochs = 1000\nrho = .05\n\n#Parameter initialization\nn_h = 5\nW1 = .01 * np.random.randn(n_h, X_train.shape[1])\nb1 = .01 * np.random.randn(n_h)\nw2 = .01 * np.random.randn(n_h)\nb2 = .01 * np.random.randn(1)\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in np.arange(epochs):\n h, y_hat_train = forward(W1, b1, w2, b2, X_train)\n dum, y_hat_val = forward(W1, b1, w2, b2, X_val)\n w2_grad, b2_grad, W1_grad, b1_grad = backward(y_train, y_hat_train, h, X_train, w2)\n W1 = W1 - rho/10 * W1_grad\n b1 = b1 - rho/10 * b1_grad\n w2 = w2 - rho * w2_grad\n b2 = b2 - rho * b2_grad\n \n loss_train[epoch] = loss(y_train, y_hat_train)\n loss_val[epoch] = loss(y_val, y_hat_val)\n acc_train[epoch] = accuracy(y_train, y_hat_train)\n acc_val[epoch] = accuracy(y_val, y_hat_val)\n \n if not ((epoch+1)%(epochs/5)):\n print('Número de iteraciones:', epoch+1)\n```\n\n### Results in Dogs vs Cats dataset ($epochs = 1000$ and $\\rho = 0.05$)\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n### Results in Binary Sign Digits Dataset ($epochs = 10000$ and $\\rho = 0.001$)\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n### Exercises\n\n* Train the network using other settings for:\n * The number of iterations\n * The learning step\n * The number of neurons in the hidden layer\n \n* You may find divergence issues for some settings\n * Related to the use of the hyperbolic tangent function in the hidden layer (numerical issues)\n * This is also why learning step was selected smaller for the hidden layer\n * Optimized libraries rely on certain modifications to obtain more robust implementations\n \n* Try to solve both problems using scikit-learn implementation\n * You can also explore other activation functions\n * You can also explore other solvers to speed up convergence\n * You can also adjust the size of minibatches\n * Take a look at the *early_stopping* parameter\n\n### 2.4. Multi Layer Networks for Regression \n\n* Deep Learning networks can be used to solve regression problems with the following common adjustments\n\n * Linear activation for the output unit\n \n * Square loss: \n $$l(y, \\hat y) = (y - \\hat y)^2, \\qquad \\text{where} \\qquad y, \\hat y \\in \\Re$$\n\n### 2.5. Activation Functions\n\nYou can refer to the Dive into Deep Learning book for a more detailed discussion on common actiation functions for the hidden units. \n\nWe extract some information about the very important **ReLU** function\n\n> *The most popular choice, due to both simplicity of implementation and its good performance on a variety of predictive tasks, is the rectified linear unit (ReLU). ReLU provides a very simple nonlinear transformation. Given an element $x$, the function is defined as the maximum of that element and 0.*\n\n> *When the input is negative, the derivative of the ReLU function is 0, and when the input is positive, the derivative of the ReLU function is 1. When the input takes value precisely equal to 0, we say that the derivative is 0 when the input is 0.*\n\n> *The reason for using ReLU is that its derivatives are particularly well behaved: either they vanish or they just let the argument through. This makes optimization better behaved and it mitigated the well-documented problem of vanishing gradients that plagued previous versions of neural networks.*\n\n\n```python\nx_array = np.linspace(-6,6,100)\ny_array = np.clip(x_array, 0, a_max=None)\nplt.plot(x_array, y_array)\nplt.title('ReLU activation function')\nplt.show()\n```\n\n## 3. Implementing Deep Networks with PyTorch \n\n* Pytorch is a Python library that provides different levels of abstraction for implementing deep neural networks\n\n* The main features of PyTorch are:\n\n * Definition of numpy-like n-dimensional *tensors*. They can be stored in / moved to GPU for parallel execution of operations\n * Automatic calculation of gradients, making *backward gradient calculation* transparent to the user\n * Definition of common loss functions, NN layers of different types, optimization methods, data loaders, etc, simplifying NN implementation and training\n * Provides different levels of abstraction, thus a good balance between flexibility and simplicity\n \n* This notebook provides just a basic review of the main concepts necessary to train NNs with PyTorch taking materials from:\n * Learning PyTorch with Examples, by Justin Johnson\n * What is *torch.nn* really?, by Jeremy Howard\n * Pytorch Tutorial for Deep Learning Lovers, by Kaggle user kanncaa1\n\n### 3.0. Installation and PyTorch introduction\n\n* PyTorch can be installed with or without GPU support\n * If you have an Anaconda installation, you can install from the command line, using the instructions of the project website\n \n* PyTorch is also preinstalled in Google Collab with free GPU access\n * Follow RunTime -> Change runtime type, and select GPU for HW acceleration\n \n* Please, refer to Pytorch getting started tutorial for a quick introduction regarding tensor definition, GPU vs CPU storage of tensors, operations, and bridge to Numpy\n\n### 3.1. Torch tensors (very) general overview\n\n* We can create tensors with different construction methods provided by the library, either to create new tensors from scratch or from a Numpy array\n\n\n```python\nimport torch\n\nx = torch.rand((100,200))\ndigitsX_flatten_tensor = torch.from_numpy(digitsX_flatten)\n\nprint(x.type())\nprint(digitsX_flatten_tensor.size())\n```\n\n torch.FloatTensor\n torch.Size([2062, 4096])\n\n\n* Tensors can be converted back to numpy arrays\n\n* Note that in this case, a tensor and its corresponding numpy array **will share memory**\n\n* Operations and slicing use a syntax similar to numpy\n\n\n```python\nprint('Size of tensor x:', x.size())\nprint('Tranpose of vector has size', x.t().size()) #Transpose and compute size\nprint('Extracting upper left matrix of size 3 x 3:', x[:3,:3])\nprint(x.mm(x.t()).size()) #mm for matrix multiplications\nxpx = x.add(x)\nxpx2 = torch.add(x,x)\nprint((xpx!=xpx2).sum()) #Since all are equal, count of different terms is zero\n```\n\n Size of tensor x: torch.Size([100, 200])\n Tranpose of vector has size torch.Size([200, 100])\n Extracting upper left matrix of size 3 x 3: tensor([[0.6252, 0.0318, 0.4039],\n [0.0704, 0.7540, 0.4963],\n [0.1201, 0.1661, 0.0053]])\n torch.Size([100, 100])\n tensor(0)\n\n\n* Adding underscore performs operations \"*in place*\", e.g., ```x.add_(y)```\n\n* If a GPU is available, tensors can be moved to and from the GPU device\n\n* Operations on tensors stored in a GPU will be carried out using GPU resources and will typically be highly parallelized\n\n\n```python\nif torch.cuda.is_available():\n device = torch.device('cuda')\n x = x.to(device)\n y = x.add(x)\n y = y.to('cpu')\nelse:\n print('No GPU card is available')\n```\n\n No GPU card is available\n\n\n### 3.2. Automatic gradient calculation \n\n* PyTorch tensors have a property ```requires_grad```. When true, PyTorch automatic gradient calculation will be activated for that variable\n\n* In order to compute these derivatives numerically, PyTorch keeps track of all operations carried out on these variables, organizing them in a forward computation graph.\n\n* When executing the ```backward()``` method, derivatives will be calculated\n\n* However, this should only be activated when necessary, to save computation\n\n\n```python\nx.requires_grad = True\ny = (3 * torch.log(x)).sum()\ny.backward()\nprint(x.grad[:2,:2])\nprint(3/x[:2,:2])\n\nx.requires_grad = False\nx.grad.zero_()\nprint('Automatic gradient calculation is deactivated, and gradients set to zero')\n```\n\n tensor([[ 4.7981, 94.4270],\n [42.5862, 3.9788]])\n tensor([[ 4.7981, 94.4270],\n [42.5862, 3.9788]], grad_fn=)\n Automatic gradient calculation is deactivated, and gradients set to zero\n\n\nExercise\n\n* Initialize a tensor ```x``` with the upper right $5 \\times 10$ submatrix of flattened digits\n* Compute output vector ```y``` applying a function of your choice to ```x```\n* Compute scalar value ```z``` as the sum of all elements in ```y``` squared\n* Check that ```x.grad``` calculation is correct using the ```backward``` method\n* Try to run your cell multiple times to see if the calculation is still correct. If not, implement the necessary mnodifications so that you can run the cell multiple times, but the gradient does not change from run to run\n\n**Note:** The backward method can only be run on scalar variables\n\n### 3.2. Feed Forward Network using PyTorch \n\n* In this section we will change our code for a neural network to use tensors instead of numpy arrays. We will work with the sign digits datasets.\n\n* We will introduce all concepts using a single layer perceptron (softmax regression), and then implement networks with additional hidden layers\n\n\n### 3.2.1. Using Automatic differentiation \n\n* We start by loading the data, and converting to tensors.\n\n* As a first step, we refactor our code to use tensor operations\n\n* We do not need to pay too much attention to particular details regarding tensor operations, since these will not be necessary when moving to higher PyTorch abstraction levels\n\n* We do not need to implement gradient calculation. PyTorch will take care of that\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\ndataset = 'digits'\n\n#Joint normalization of all data. For images [-.5, .5] scaling is frequent\nmin_max_scaler = MinMaxScaler(feature_range=(-.5, .5))\nX = min_max_scaler.fit_transform(digitsX_flatten)\n\n#Generate train and validation data, shuffle\nX_train, X_val, y_train, y_val = train_test_split(X, digitsY, test_size=0.2, random_state=42, shuffle=True)\n\n#Convert to Torch tensors\nX_train_torch = torch.from_numpy(X_train)\nX_val_torch = torch.from_numpy(X_val)\ny_train_torch = torch.from_numpy(y_train)\ny_val_torch = torch.from_numpy(y_val)\n```\n\n\n```python\n# Define some useful functions\ndef softmax(t):\n \"\"\"Compute softmax values for each sets of scores in t\"\"\"\n return t.exp() / t.exp().sum(-1).unsqueeze(-1)\n\ndef model(w,b,x):\n #Calcula la salida de la red\n return softmax(x.mm(w) + b)\n \ndef accuracy(y, y_hat):\n return (y.argmax(axis=-1) == y_hat.argmax(axis=-1)).float().mean()\n\ndef nll(y, y_hat):\n return -(y * y_hat.log()).mean()\n```\n\n* Syntaxis is a bit different because input variables are tensors, not arrays\n\n* This time we did not need to implement the backward function\n\n\n```python\n#Parameter initialization\nW = .1 * torch.randn(X_train_torch.size()[1], y_train_torch.size()[1])\nW.requires_grad_()\nb = torch.zeros(y_train_torch.size()[1], requires_grad=True)\n\nepochs = 500\nrho = .5\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n```\n\n\n```python\n# Network training\n\nfor epoch in range(epochs):\n \n if not ((epoch+1)%(epochs/5)):\n print('Current epoch:', epoch+1)\n \n #Compute network output and cross-entropy loss\n pred = model(W,b,X_train_torch)\n loss = nll(y_train_torch, pred)\n \n #Compute gradients\n loss.backward()\n \n #Deactivate gradient automatic updates\n with torch.no_grad():\n #Computing network performance after iteration\n loss_train[epoch] = loss.item()\n acc_train[epoch] = accuracy(y_train_torch, pred).item()\n pred_val = model(W, b, X_val_torch)\n loss_val[epoch] = nll(y_val_torch, pred_val).item()\n acc_val[epoch] = accuracy(y_val_torch, pred_val).item()\n\n #Weight update\n W -= rho * W.grad\n b -= rho * b.grad\n #Reset gradients\n W.grad.zero_()\n b.grad.zero_()\n```\n\nIt is important to deactivate gradient updates after the network has been evaluated on training data, and gradients of the loss function have been computed\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n### 3.2.2. Using torch *nn* module \n\n* PyTorch *nn* module provides many attributes and methods that make the implementation and training of Neural Networks simpler\n\n* ```nn.Module``` and ```nn.Parameter``` allow to implement a more concise training loop\n\n* ```nn.Module``` is a PyTorch class that will be used to encapsulate and design a specific neural network, thus, it is central to the implementation of deep neural nets using PyTorch\n\n* ```nn.Parameter``` allow the definition of trainable network parameters. In this way, we will simplify the implementation of the training loop.\n\n* All parameters defined with ```nn.Parameter``` will have ```requires_grad = True```\n\n\n```python\nfrom torch import nn\n\nclass my_multiclass_net(nn.Module):\n def __init__(self, nin, nout):\n \"\"\"This method initializes the network parameters\n Parameters nin and nout stand for the number of input parameters (features in X)\n and output parameters (number of classes)\"\"\"\n super().__init__()\n self.W = nn.Parameter(.1 * torch.randn(nin, nout))\n self.b = nn.Parameter(torch.zeros(nout))\n \n def forward(self, x):\n return softmax(x.mm(self.W) + self.b)\n \n def softmax(t):\n \"\"\"Compute softmax values for each sets of scores in t\"\"\"\n return t.exp() / t.exp().sum(-1).unsqueeze(-1)\n```\n\n\n```python\nmy_net = my_multiclass_net(X_train_torch.size()[1], y_train_torch.size()[1])\n\nepochs = 500\nrho = .5\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in range(epochs):\n \n if not ((epoch+1)%(epochs/5)):\n print('Current epoch:', epoch+1)\n \n #Compute network output and cross-entropy loss\n pred = my_net(X_train_torch)\n loss = nll(y_train_torch, pred)\n \n #Compute gradients\n loss.backward()\n \n #Deactivate gradient automatic updates\n with torch.no_grad():\n #Computing network performance after iteration\n loss_train[epoch] = loss.item()\n acc_train[epoch] = accuracy(y_train_torch, pred).item()\n pred_val = my_net(X_val_torch)\n loss_val[epoch] = nll(y_val_torch, pred_val).item()\n acc_val[epoch] = accuracy(y_val_torch, pred_val).item()\n\n #Weight update\n for p in my_net.parameters():\n p -= p.grad * rho\n #Reset gradients\n my_net.zero_grad()\n```\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n* ```nn.Module``` comes with several kinds of pre-defined layers, thus making it even simpler to implement neural networks\n\n* We can also import the Cross Entropy Loss from ```nn.Module```. When doing so:\n - We do not have to compute the softmax, since the ```nn.CrossEntropyLoss``` already does so\n - ```nn.CrossEntropyLoss``` receives two input arguments, the first is the output of the network, and the second is the true label as a 1-D tensor (i.e., an array of integers, one-hot encoding should not be used)\n\n\n```python\nfrom torch import nn\n\nclass my_multiclass_net(nn.Module):\n def __init__(self, nin, nout):\n \"\"\"Note that now, we do not even need to initialize network parameters ourselves\"\"\"\n super().__init__()\n self.lin = nn.Linear(nin, nout)\n \n def forward(self, x):\n return self.lin(x)\n \nloss_func = nn.CrossEntropyLoss()\n```\n\n\n```python\nmy_net = my_multiclass_net(X_train_torch.size()[1], y_train_torch.size()[1])\n\nepochs = 500\nrho = .1\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in range(epochs):\n \n if not ((epoch+1)%(epochs/5)):\n print('Current epoch:', epoch+1)\n \n #Compute network output and cross-entropy loss\n pred = my_net(X_train_torch)\n loss = loss_func(pred, y_train_torch.argmax(axis=-1))\n \n #Compute gradients\n loss.backward()\n \n #Deactivate gradient automatic updates\n with torch.no_grad():\n #Computing network performance after iteration\n loss_train[epoch] = loss.item()\n acc_train[epoch] = accuracy(y_train_torch, pred).item()\n pred_val = my_net(X_val_torch)\n loss_val[epoch] = loss_func(pred_val, y_val_torch.argmax(axis=-1)).item()\n acc_val[epoch] = accuracy(y_val_torch, pred_val).item()\n\n #Weight update\n for p in my_net.parameters():\n p -= p.grad * rho\n #Reset gradients\n my_net.zero_grad()\n```\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\nNote faster convergence is observed in this case. It is actually due to a more convenient initialization of the hidden layer\n\n### 3.2.3. Network Optimization \n\n* We cover in this subsection two different aspects about network training using PyTorch:\n\n + Using ```torch.optim``` allows an easier and more interpretable encoding of neural network training, and opens the door to more sophisticated training algorithms\n \n + Using minibatches can speed up network convergence\n\n \n* ```torch.optim``` provides two convenient methods for neural network training:\n - ```opt.step()``` updates all network parameters using current gradients\n - ```opt.zero_grad()``` resets all network parameters\n\n\n```python\nfrom torch import optim\n\nmy_net = my_multiclass_net(X_train_torch.size()[1], y_train_torch.size()[1])\nopt = optim.SGD(my_net.parameters(), lr=0.1)\n\nepochs = 500\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in range(epochs):\n \n if not ((epoch+1)%(epochs/5)):\n print('Current epoch:', epoch+1)\n \n #Compute network output and cross-entropy loss\n pred = my_net(X_train_torch)\n loss = loss_func(pred, y_train_torch.argmax(axis=-1))\n \n #Compute gradients\n loss.backward()\n \n #Deactivate gradient automatic updates\n with torch.no_grad():\n #Computing network performance after iteration\n loss_train[epoch] = loss.item()\n acc_train[epoch] = accuracy(y_train_torch, pred).item()\n pred_val = my_net(X_val_torch)\n loss_val[epoch] = loss_func(pred_val, y_val_torch.argmax(axis=-1)).item()\n acc_val[epoch] = accuracy(y_val_torch, pred_val).item()\n\n opt.step()\n opt.zero_grad()\n```\n\nNote network optimization is carried out outside ```torch.no_grad()``` but network evaluation (other than forward output calculation for the training patterns) still need to deactivate gradient updates\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n### Exercise \n\nImplement network training with other optimization methods. You can refer to the official documentation and select a couple of methods. You can also try to implement adaptive learning rates using ```torch.optim.lr_scheduler```\n\n \n* Each epoch of the previous implementation of network training was actually implementing Gradient Descent\n\n* In SGD only a *minibatch* of training patterns are used at every iteration\n\n* In each epoch we iterate over all training patterns sequentially selecting non-overlapping *minibatches*\n\n* Overall, convergence is usually faster than when using Gradient Descent\n\n* Torch provides methods that simplify the implementation of this strategy\n\n\n```python\nfrom torch.utils.data import TensorDataset, DataLoader\n\ntrain_ds = TensorDataset(X_train_torch, y_train_torch)\ntrain_dl = DataLoader(train_ds, batch_size=64)\n```\n\n\n```python\nfrom torch import optim\n\nmy_net = my_multiclass_net(X_train_torch.size()[1], y_train_torch.size()[1])\nopt = optim.SGD(my_net.parameters(), lr=0.1)\n\nepochs = 200\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in range(epochs):\n \n if not ((epoch+1)%(epochs/5)):\n print('Current epoch:', epoch+1)\n \n for xb, yb in train_dl:\n \n #Compute network output and cross-entropy loss for current minibatch\n pred = my_net(xb)\n loss = loss_func(pred, yb.argmax(axis=-1))\n \n #Compute gradients and optimize parameters\n loss.backward()\n opt.step()\n opt.zero_grad()\n \n #At the end of each epoch, evaluate overall network performance\n with torch.no_grad():\n #Computing network performance after iteration\n pred = my_net(X_train_torch)\n loss_train[epoch] = loss_func(pred, y_train_torch.argmax(axis=-1)).item()\n acc_train[epoch] = accuracy(y_train_torch, pred).item()\n pred_val = my_net(X_val_torch)\n loss_val[epoch] = loss_func(pred_val, y_val_torch.argmax(axis=-1)).item()\n acc_val[epoch] = accuracy(y_val_torch, pred_val).item()\n```\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n### 3.2.4. Multi Layer networks using ```nn.Sequential``` \n\n* PyTorch simplifies considerably the implementation of neural network training, since we do not need to implement derivatives ourselves\n\n* We can also make a simpler implementation of multilayer networks using ```nn.Sequential``` function\n\n* It returns directly a network with the requested topology, including parameters **and forward evaluation method**\n\n\n```python\nmy_net = nn.Sequential(\n nn.Linear(X_train_torch.size()[1], 200),\n nn.ReLU(),\n nn.Linear(200,50),\n nn.ReLU(),\n nn.Linear(50,20),\n nn.ReLU(),\n nn.Linear(20,y_train_torch.size()[1])\n)\n\nopt = optim.SGD(my_net.parameters(), lr=0.1)\n```\n\n\n```python\nepochs = 200\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in range(epochs):\n \n if not ((epoch+1)%(epochs/5)):\n print('Número de épocas:', epoch+1)\n \n for xb, yb in train_dl:\n \n #Compute network output and cross-entropy loss for current minibatch\n pred = my_net(xb)\n loss = loss_func(pred, yb.argmax(axis=-1))\n \n #Compute gradients and optimize parameters\n loss.backward()\n opt.step()\n opt.zero_grad()\n \n #At the end of each epoch, evaluate overall network performance\n with torch.no_grad():\n #Computing network performance after iteration\n pred = my_net(X_train_torch)\n loss_train[epoch] = loss_func(pred, y_train_torch.argmax(axis=-1)).item()\n acc_train[epoch] = accuracy(y_train_torch, pred).item()\n pred_val = my_net(X_val_torch)\n loss_val[epoch] = loss_func(pred_val, y_val_torch.argmax(axis=-1)).item()\n acc_val[epoch] = accuracy(y_val_torch, pred_val).item()\n```\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n\n```python\nprint('Validation accuracy with this net:', acc_val[-1])\n```\n\n Validation accuracy with this net: 0.8692494034767151\n\n\n### 3.3. Generalization\n\n* For complex network topologies (i.e., many parameters), network training can incur in over-fitting issues\n\n* Some common strategies to avoid this are:\n\n - Early stopping\n - Dropout regularization\n \n
Image Source
\n\n* Data augmentation can also be used to avoid overfitting, as well as to achieve improved accuracy by providing the network some a priori expert knowledge\n - E.g., if image rotations and scalings do not affect the correct class, we could enlarge the dataset by creating artificial images with these transformations\n\n\n### 3.5. Convolutional Networks for Image Processing \n\n* PyTorch implements other layers that are better suited for different applications\n\n* In image processing, we normally recur to Convolutional Neural Networks, since they are able to capture the true spatial information of the image\n\n
Image Source
\n\n\n```python\ndataset = 'digits'\n\n#Generate train and validation data, shuffle\nX_train, X_val, y_train, y_val = train_test_split(digitsX[:,np.newaxis,:,:], digitsY, test_size=0.2, random_state=42, shuffle=True)\n\n#Convert to Torch tensors\nX_train_torch = torch.from_numpy(X_train)\nX_val_torch = torch.from_numpy(X_val)\ny_train_torch = torch.from_numpy(y_train)\ny_val_torch = torch.from_numpy(y_val)\n\ntrain_ds = TensorDataset(X_train_torch, y_train_torch)\ntrain_dl = DataLoader(train_ds, batch_size=64)\n```\n\n\n```python\nclass Lambda(nn.Module):\n def __init__(self, func):\n super().__init__()\n self.func = func\n\n def forward(self, x):\n return self.func(x)\n\nmy_net = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.AvgPool2d(4),\n Lambda(lambda x: x.view(x.size(0), -1)),\n)\n\nopt = optim.SGD(my_net.parameters(), lr=0.1)\n```\n\n\n```python\nepochs = 2500\n\nloss_train = np.zeros(epochs)\nloss_val = np.zeros(epochs)\nacc_train = np.zeros(epochs)\nacc_val = np.zeros(epochs)\n\nfor epoch in range(epochs):\n \n if not ((epoch+1)%(epochs/5)):\n print('Número de épocas:', epoch+1)\n \n for xb, yb in train_dl:\n \n #Compute network output and cross-entropy loss for current minibatch\n pred = my_net(xb)\n loss = loss_func(pred, yb.argmax(axis=-1))\n \n #Compute gradients and optimize parameters\n loss.backward()\n opt.step()\n opt.zero_grad()\n \n #At the end of each epoch, evaluate overall network performance\n with torch.no_grad():\n #Computing network performance after iteration\n pred = my_net(X_train_torch)\n loss_train[epoch] = loss_func(pred, y_train_torch.argmax(axis=-1)).item()\n acc_train[epoch] = accuracy(y_train_torch, pred).item()\n pred_val = my_net(X_val_torch)\n loss_val[epoch] = loss_func(pred_val, y_val_torch.argmax(axis=-1)).item()\n acc_val[epoch] = accuracy(y_val_torch, pred_val).item()\n```\n\n Número de épocas: 500\n Número de épocas: 1000\n Número de épocas: 1500\n Número de épocas: 2000\n Número de épocas: 2500\n\n\n\n```python\nplt.figure(figsize=(14,5))\nplt.subplot(1, 2, 1), plt.plot(loss_train, 'b'), plt.plot(loss_val, 'r'), plt.legend(['train', 'val']), plt.title('Cross-entropy loss')\nplt.subplot(1, 2, 2), plt.plot(acc_train, 'b'), plt.plot(acc_val, 'r'), plt.legend(['train', 'val']), plt.title('Accuracy')\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "d5f0afe67bec9057b4851160021ebe74e99422fd", "size": 656922, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "C5.Classification_NN/NeuralNetworks_professor.ipynb", "max_stars_repo_name": "ML4DS/ML4all", "max_stars_repo_head_hexsha": "7336489dcb87d2412ad62b5b972d69c98c361752", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2016-11-30T17:34:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T23:11:48.000Z", "max_issues_repo_path": "C5.Classification_NN/NeuralNetworks_professor.ipynb", "max_issues_repo_name": "ML4DS/ML4all", "max_issues_repo_head_hexsha": "7336489dcb87d2412ad62b5b972d69c98c361752", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-08-12T18:28:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-26T11:01:39.000Z", "max_forks_repo_path": "C5.Classification_NN/NeuralNetworks_professor.ipynb", "max_forks_repo_name": "ML4DS/ML4all", "max_forks_repo_head_hexsha": "7336489dcb87d2412ad62b5b972d69c98c361752", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2016-11-30T17:34:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T09:53:32.000Z", "avg_line_length": 245.3032113518, "max_line_length": 77468, "alphanum_fraction": 0.9101887286, "converted": true, "num_tokens": 15258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.20181322706107538, "lm_q1q2_score": 0.0969669525508876}} {"text": "# Heteroskedasticity\n## Consequences of Heteroskedasticity for OLS\n\n$\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\plim}{plim}\n\\newcommand{\\using}[1]{\\stackrel{\\mathrm{#1}}{=}}\n\\newcommand{\\ffrac}{\\displaystyle \\frac}\n\\newcommand{\\asim}{\\overset{\\text{a}}{\\sim}}\n\\newcommand{\\space}{\\text{ }}\n\\newcommand{\\bspace}{\\;\\;\\;\\;}\n\\newcommand{\\QQQ}{\\boxed{?\\:}}\n\\newcommand{\\void}{\\left.\\right.}\n\\newcommand{\\Tran}[1]{{#1}^{\\mathrm{T}}}\n\\newcommand{\\d}[1]{\\displaystyle{#1}}\n\\newcommand{\\CB}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\SB}[1]{\\left[ #1 \\right]}\n\\newcommand{\\P}[1]{\\left( #1 \\right)}\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\n\\newcommand{\\norm}[1]{\\left\\| #1 \\right\\|}\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\Exp}{\\mathrm{E}}\n\\newcommand{\\RR}{\\mathbb{R}}\n\\newcommand{\\EE}{\\mathbb{E}}\n\\newcommand{\\II}{\\mathbb{I}}\n\\newcommand{\\NN}{\\mathbb{N}}\n\\newcommand{\\ZZ}{\\mathbb{Z}}\n\\newcommand{\\QQ}{\\mathbb{Q}}\n\\newcommand{\\PP}{\\mathbb{P}}\n\\newcommand{\\AcA}{\\mathcal{A}}\n\\newcommand{\\FcF}{\\mathcal{F}}\n\\newcommand{\\AsA}{\\mathscr{A}}\n\\newcommand{\\FsF}{\\mathscr{F}}\n\\newcommand{\\Var}[2][\\,\\!]{\\mathrm{Var}_{#1}\\left[#2\\right]}\n\\newcommand{\\Avar}[2][\\,\\!]{\\mathrm{Avar}_{#1}\\left[#2\\right]}\n\\newcommand{\\Cov}[2][\\,\\!]{\\mathrm{Cov}_{#1}\\left(#2\\right)}\n\\newcommand{\\Corr}[2][\\,\\!]{\\mathrm{Corr}_{#1}\\left(#2\\right)}\n\\newcommand{\\I}[1]{\\mathrm{I}\\left( #1 \\right)}\n\\newcommand{\\N}[1]{\\mathcal{N} \\left( #1 \\right)}\n\\newcommand{\\ow}{\\text{otherwise}}\n\\newcommand{\\FSD}{\\text{FSD}}Review$\n\n>Homoskedasticity assumption $\\text{MLR}.5$, that $\\Var{u\\mid x_1,x_2,\\dots, x_k} = \\sigma^2$, plays no role in showing whether OLS was unbiased or consistent. Only something like omitting an important variable would have this effect.\n>\n>Also, $R^2$ and $\\bar R^2$ are unaffected by the presence of heteroskedasticity. They are the estimators of population $R^2 = 1 - \\sigma_u^2/\\sigma_y^2$ where the two variances are *un*conditional while heteroskedasticity is under conditioning on $\\mathbf{x}$. \n\nUnder $\\text{MLR}.1$ to $\\text{MLR}.4$, $\\text{SSR}/n$ consistently estimates $\\sigma_u^2$ and $\\text{SST}/n$ consistently estimates $\\sigma_y^2$. Therefore, $R^2$ and $\\bar R^2$ are both consistant estimators of the population $R^2$, whether or not the homoskedasticity assumption holds.\n\nBut to do the inference by $t$ statistic and $F$ statistic, we still need that assumption. Besides, if $\\Var{u\\mid\\mathbf{x}}$ is no longer constant, OLS is no longer BLUE.\n\n## Heteroskedasticity-Robust Inference after OLS Estimation\n\nConsider the simple linear regression, the estimator of slope parameter is\n\n$$\\hat\\beta_1 = \\beta_1 + \\ffrac{\\d{\\sum_{i=1}^{n} \\P{x_i - \\bar x}} u_i}{\\d{\\sum_{i=1}^{n} \\P{x_i - \\bar x}^2}}$$\n\n$$\\Var{u_i\\mid x_i} = \\sigma_i^2\\;{\\Longrightarrow}\\;\\Var{\\hat\\beta_1} = \\ffrac{\\sum \\P{x_i - \\bar x}^2\\sigma_i^2}{\\text{SST}_x^2}$$\n\nNow we give a valid estimator for general MLR\n\n$$\\widehat{\\Var{\\hat \\beta_j}} = \\ffrac{\\d{\\sum_{i=1}^{n}\\hat r_{ij}^2 \\hat u_i^2}}{\\text{SSR}_j^2}$$\n\nwhere $\\hat r_{ij}$ denotes the $i$th residual from regressing $x_j$ on all other independent variables, and $\\text{SSR}_j$ is the sum of squared residuals from this regression. More than that, we have the ***heteroskedasticity-robust standard error*** for $\\hat\\beta_j$:\n\n$$\\sqrt{\\widehat{\\Var{\\hat \\beta_j}}}= \\ffrac{\\d{\\sqrt{\\sum_{i=1}^{n}\\hat r_{ij}^2 \\hat u_i^2}}}{\\text{SSR}_j^2}$$\n\nHere the $\\text{SSR}_j^2$ can be replaced by $\\text{SST}_j^2\\P{1-R_j^2}$, where $\\text{SST}_j^2$ is the total sum of squares of $x_j$, and $R_j^2$ is the usual $R^2$ from regressing $x_j$ on all other explanatory variables.\n\nThen the ***heteroskedasticity-robust $t$ statistic***.\n\n$$t = \\ffrac{\\text{estimate} - \\text{hypothesized value}}{\\textbf{heteroskedasticity-robust} \\text{ standard error}}$$\n\nUsing these formulas, the usual $t$ test is valid asymptotically; but the usual $F$-statistic does not work under heteroskedasticity.\n\n### Computing Heteroskedasticity-Robust LM Tests\n\nSkipped, however. OK, the usual LM statistic:\n\n1. Estimate the restricted model to obtain the residual $\\tilde u$\n2. regress $\\tilde u$ on all of the independent variables\n3. $\\text{LM} = n \\cdot R_{\\tilde u}^2$, where $R_{\\tilde u}^2$ is the $R^2$ from this regression\n\nThen the HR LM statistic in the general case\n\n1. The same: estimate the restricted model to obtain the residuals $\\tilde u$\n2. Regress each of the independent variables which are excluded under the null hypothesis, on all of the included variables; say there're $q$ excluded variables (restricted model for them: $x_j = \\beta_0 + \\beta_1 x_1 + \\cdots + \\beta_{k-q} x_{k-q} + u$, $j = k-q+1,\\dots,k$)\n3. Obtain $q$ sets of residuals $\\P{\\tilde r_1,\\tilde r_2,\\dots, \\tilde r_q}$, then find the element-wise production of $\\tilde r_j$ and $\\tilde u$\n4. Regress $y\\equiv 1$ on $\\beta = 0, \\tilde r_1 \\tilde u, \\tilde r_2 \\tilde u,\\dots,\\tilde r_q \\tilde u$\n5. The **Heteroskedasticity-Robust LM Statistic** is now $n-\\text{SSR}_1$ (I bet this is a minus sign, it could be some other signs though...), where $\\text{SSR}_1$ is just the usual sum of squared residuals from the regression in the final step.\n\nBy the way, under $H_0$, $\\text{LM}$ is distributed approximately as $\\chi_q^2$\n\n## Testing for Heteroskedasticity\n\nModel: $y = \\beta_0 + \\beta_1 x_1 + \\cdots + \\beta_k x_k + u$; assumption: $\\text{MLR}.1$ through $\\text{MLR}.4$, so that the OLS estimators are still unbiased and consistent.\n\nTo test the heteroskedasticity, we have $H_0: \\Var{u\\mid x_1,x_2,\\dots,x_k} = \\sigma^2$. Since $u$ has a zero conditional expectation, this is equivalent to\n\n$$H_0: \\Exp\\SB{u^2\\mid x_1,\\dots,x_k} = \\Exp\\SB{u^2} = \\sigma^2$$\n\nSo we are actually testing weather $u^2$ is related (in expected value) to one or more of the explanatory variables. Then we assume the linear function\n\n$$u^2 = \\delta_0 + \\delta_1 x_1 + \\delta_2 x_2 + \\cdots + \\delta_k x_k + v$$\n\nwhere $v$ is an error term with mean zero given the $x_j$. Then we rewrite the null hypothesis of homoskedasticity as $H_0: \\delta_1 = \\delta_2 = \\cdots = \\delta_k = 0$.\n\nThen we can use $F$ statistic or $\\text{LM}$ to test this. And to do so, we first need to estimate the left side, the residual and since it's unable to obtain, we will use its estimation $\\hat u_i$ so actually the equation to be process is actually\n\n$$\\hat u^2 = \\delta_0 + \\delta_1 x_1 + \\delta_2 x_2 + \\cdots + \\delta_k x_k + \\text{error}$$\n\nThen apply the $F$ test or $\\text{LM}$ test. And to distinguish two different $R$-square, we denote the $F$ statistic in this regression\n\n$$F = \\ffrac{\\ffrac{R_{\\hat u^2}^2}{k}}{\\ffrac{1-R_{\\hat u^2}^2}{n-k-1}}$$\n\nAnd the $\\text{LM}$ statistic is $\\text{LM} = n\\cdot R_{\\hat u^2}^2$. Under $H_0$, it's distributed asymptotically as $\\chi_k^2$. The $\\text{LM}$ version of the test is typically called the ***Breusch-Pagan test for heteroskedasticity (BP test)***.\n\n$Remark$\n\n>Larger $R_{\\hat u^2}^2$ could be the evidence against the null hypothesis.\n\n**Steps for BP test**:\n\n1. Estimate the model $y = \\beta_0 + \\beta_1 x_1 + \\cdots + \\beta_k x_k + u$ by OLS, as usual. And for each observation, find the residual $\\hat u^2$\n2. Regression the equation $\\hat u^2 = \\delta_0 + \\delta_1 x_1 + \\delta_2 x_2 + \\cdots + \\delta_k x_k + \\text{error}$, with the $R$-squared $R_{\\hat u^2}^2$.\n3. Form either the $F$ statistic or the $\\text{LM}$ statistic and compute the $p$-value. Use $F_{k,n-k-1}$ distribution for $F$ statistic and $\\chi_k^2$ distribution for the otherone. If the $p$-value is below the chosen significance level, meaning that it's sufficiently small, we reject the null hypothesis and admit the heteroskedasticity.\n\n$Remark$\n\n> If we suspect that heteroskedasticity depends only upon certain independent variables, we can simple modify the BP test that we regress $\\hat u^2$ only on the chosen variables and then carry out the appropriate $F$ or $\\text{LM}$ test.\n\n### The White Test for Heteroskedasticity\n\nThe ***White test for heteroskedasticity*** is the $\\text{LM}$ statistic for testing that all of the $\\delta_j$ where $j=1,2,\\dots$ (no $0$ here), defined by\n\n$$\\begin{align}\n\\hat u^2 &= \\P{y - \\hat\\beta_0 - \\hat\\beta_1 x_1 - \\cdots - \\hat\\beta_k x_k}^2 \\\\\n&\\equiv \\delta_0 + \\sum_{i=1}^k \\delta_i x_i + \\sum_{i=1}^k \\delta_{k+i} x_i^2 + \\sum_{jFeasible GLS is consistent and asymptotically more efficient than OLS.
\n***\n\n### What if the Assumed Heteroskedasticity Function is Wrong?\n\n- WLS is still consistent under $\\text{MLR}.1$ through $\\text{MLR}.4$\n- robust standard errors should be computed\n- WLS is consistent under $\\text{MLR}.4$ but not necessarily under $\\text{MLR}.4'$\n\n### Prediction and Prediction Intervals with Heteroskedasticity\n\n## The Linear Probability Model Revisited\n\n$$\\Var{y\\mid \\mathbf x} = p\\P{\\mathbf x} \\P{1-p\\P{\\mathbf x}}\\Rightarrow \\hat h_i = \\hat y_i \\P{1-\\hat y_i}$$\n\n***\n", "meta": {"hexsha": "3e1475e3bdecb406ed5592a7d1493eb6e2270e1a", "size": 18305, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FinMath/Econometrics/Chap_08.ipynb", "max_stars_repo_name": "XavierOwen/Notes", "max_stars_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-27T10:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T03:11:58.000Z", "max_issues_repo_path": "FinMath/Econometrics/Chap_08.ipynb", "max_issues_repo_name": "XavierOwen/Notes", "max_issues_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "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": "FinMath/Econometrics/Chap_08.ipynb", "max_forks_repo_name": "XavierOwen/Notes", "max_forks_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:57:23.000Z", "avg_line_length": 52.7521613833, "max_line_length": 354, "alphanum_fraction": 0.5816989893, "converted": true, "num_tokens": 4882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.21206881182686205, "lm_q1q2_score": 0.09694444038003952}} {"text": "# MAE 3120 Methods of Engineering Experiments\n\n>__Philippe M Bardet__\n\n>__Mechanical and Aerospace Engineering__\n\n>__The George Washington University__\n\n\n\n# Module 01: Introduction to measurement system\n\nThis class will be focused mainly on experiments, but many of the concepts seen here are also applied in many other fields where analytical thinking is needed. In fact, with the advancement of computers one talks more and more of numerical experiments. The stock market could also be considered as a huge real time experiment...\n\nThis is an introductory lecture and we need to establish a common (rigorous) language for the rest of the class (and your career). We are going to introduce a lot of definitions that we will use for the rest of the semester. Many definitions and notions introduced here should only be reviews at this point (I hope). \n\nAlong with the common language, we will also adopt a notation convention that is consistent throughout the class. Depending on the textbook you choose to follow, the convention might be slightly different than the one adopted here.\n\n\n## DIKW pyramid\n\nIn engineering, knowledge could be defined as a model that describes and (ideally) predicts the behavior of a complex system. The context of data acquisition, analysis, and model development can be put in the context of the wisdom pyramid (or DIKW pyramyd). This concept has been developed over the years by the information theory field.\n\n\n\nhttps://en.wikipedia.org/wiki/DIKW_pyramid\n\nStarting from the bottom of the pyramid:\n\n__data__: Signal reading from sensor/transducer\n\n__information__: \"organized or structured data, which has been processed in such a way that the information now has relevance for a specific purpose or context, and is therefore meaningful, valuable, useful and relevant.\" information + data: \"know what\". \n\n__knowledge__: \"organization and processing to convey understanding, experience, and accumulated learning\". It can be seen as having an engineering model that describes a phenomena or system. \"Why is\".\n\n__wisdom__: \"Why do\". Applicability of model to predict new behaviors.\n\nUse example of taking data at 3 points, to extract mean values, from mean values, trend line, and then knowing when to use the trendline.\n\nHere is another representation of the pyramid:\n\n\n\n## Goals of experiments\n\nExperiments serve two main purposes: \n\n>__1- Engineering/scientific experimentation__:\n>The goal is to seek new information. For example when developing a new product one needs to know: how hot does it get? When will it fail? Another example would be to determine a model that describes the behavior of a system.\n \n>__2- Operational system__:\n>The goal is to monitor and control processes. In other words to create a reliable operational sysem. This is generally applied to existing equipment (or equipment under design), rather than used to design a new equipment (first application of measurement). For example, this could be the A/C control system of a room: one needs to measure temperature and regulate the heating/cooling based on a set point.\n \nIt is convenient to think of the measurement process with a block diagram.\n\n\n\n\n## A brief history of measurement (length)\n\nIn Ancient Egypt, (~3,000 BC) people used a measure called a CUBIT. This word comes from a Latin word “cubitum” which meant elbow and it was the length of a person’s outstretched forearm - from the elbow to the tip of the middle finger. It was based on the Pharaoh’s body: the ROYAL CUBIT. A stick was marked with this distance and copies were distributed to merchants throughout the land. When the Pharaoh died, a new Pharaoh took the throne, a new Royal Cubit came into being, and a new stick and it’s copies had to be made and sent across the land. Plus, there were OTHER problems: The lengths that people wanted to measure were sometimes shorter or longer than a cubit. So other lengths like the PALM, DIGIT, and FOOT were used. 7 PALMS was the same as 1 CUBIT. The ROYAL FOOT was equal to about 18 fingers or ⅔ of a Royal Cubit.\n\n\n\n\nAlongside the Ancient Egyptians, people throughout the Mediterranean used parts of their bodies to create units of measurement. Mediterranean sailors used Fathoms to measure depth. The Hebrew people of long ago used a measurement called a SPAN. Hand spans are still a unit used to measure horses! The people of Ancient Greece adapted the Egyptian-Hebrew measurements and added more measurements based upon multiples of fingers. Ancient Romans created a measurement meant based on the width of the thumb or “uncia” in Latin. That’s where the word for INCH comes from. Roman armies measured the distance from one step to another using PACES. A PACE was equal to 2 Egyptian cubits and is still used to describe speed in foot races. The word MILE comes from the Latin word “milliare,” a distance of 1,000 paces covered by the Roman army at a forced march.\n\n\n\nAs the Roman empire spread, the Roman measuring units became the accepted system of measurement throughout Europe. A Roman FOOT was equal to 12 UNCIA. These uncia came to England and over time became INCHES. Like the Pharaohs of Ancient Egypt, the King of England at the time also wanted to STANDARDIZE (or make the same) the units of measurement across the land based on his own body. A royal decree went out: a YARD was to be the distance from the nose to the tip of the middle finger of the outstretched arm...or about 3 FEET. From this time, all units were derived from the King’s foot and yard. The English Mile was derived from that. This English or Customary system spread back down through Europe and across the ocean to North America with the English who arrived here. As trade and communication increased again, once again a more uniform or regulated system was needed. It took several hundred years for the Customary system to become more and more dependable and standardized. In 1855, a new distance for a yard was formalized. This was still about the size of the original Roman yard. Since then all of the other units of measurement for length have been derived from multiplications and divisions of the Yard. 1 Inch was 1/36 of a yard. 1 Foot was ⅓ yard. \n\n\n\nWhile the English or Customary system came to be widely used in Europe, and is still used here in the United States, today there is another widely used system of measurement that is not based on the measurements of the human body. It’s beginnings can be found in the 1600s in Europe, when people began to talk about finding better STANDARDS for measurement. In the 1790s, a group of French scientists decided to create a new standard of measurement that would be unchangeable. The name for the unit of measure chosen was the METER; it was based upon a measurement of the Earth. The system they developed is called the METRIC SYSTEM and it is still in use today, throughout France, Europe and almost every nation in the world. All scientists use the Metric system because it is the most precise. The length of the meter was taken to be one ten-millionth of the distance from the North Pole to the equator along a line of longitude near Paris, France. The word meters comes from the Greek word “metron” which means to measure. The metric system is based on multiples of 10.\n\n\n\n\n\n## Dimensions and Units\nFor measured data to be useful, one needs to have a common language: i.e. a unique definition of dimensions (length, time, etc.) with associated dimensional units (meter, second, etc.).\n\nThere are two types of dimensions: \n\n>__1- Primary or base.__ 7 in total.\n\n\\begin{array}{l l l}\n\\hline\n\\mathrm{primary\\, dimension} & \\mathrm{symbol} & \\mathrm{unit} \\\\\n\\hline\n\\text{mass} & m & \\mathrm{kg}\\\\\n\\mathrm{length} & L & \\mathrm{m}\\\\\n\\mathrm{time} & t & \\mathrm{s}\\\\\n\\mathrm{thermodynamic\\,temperature} & T& \\mathrm{K}\\\\\n\\mathrm{electrical \\,current} & I & \\mathrm{A}\\\\\n\\mathrm{amount\\,of\\,light} & C& \\mathrm{Cd,\\,Candela}\\\\\n\\mathrm{amount\\,of\\,matter} & mol & \\mathrm{mole}\\\\\n\\hline\n\\end{array}\n\n\n\n\n>__2- Secondary or derived.__ They are made of a combination of primary/base dimensions\n\n\\begin{equation}\n\\mathrm{force} = \\frac{ m \\times L}{t^2} \n\\end{equation}\n\nAll other dimensions and units can be derived as combinations of the primaries. Here is a table with examples.\n\n\\begin{array}{l l l l}\n\\hline\n\\mathrm{secondary\\, dimension} & \\mathrm{Symbol} & \\mathrm{unit} & \\text{unit name}\\\\\n\\hline\n\\mathrm{force} & F & \\mathrm{N= kg \\cdot m/s^2} & \\text{Newton}\\\\\n\\mathrm{pressure} & P \\,(p) & \\mathrm{Pa = N/m^2} & \\text{Pascal}\\\\\n\\mathrm{energy} & E & \\mathrm{J = N \\cdot m = kg \\cdot m^2 / s^2} & \\text{Joule} \\\\\n\\mathrm{power} & \\dot{W} \\, (P) & \\mathrm{W = N \\cdot m / s = kg \\cdot m^2 / s^3} & \\text{Watt}\\\\\n\\hline\n\\end{array}\n\n\nTo avoid confusions we will use the SI (International Standard) system of units. \n\nPlease also note the notation in how we report the units and symbols. We will use the same notation throughout the class and you will also throughtout your career. In scientific notation:\n> - mathematical symbols are reported as italic (e.g. temperature $T$, pressure $P$, velocity $U$), \n> - while units are reported in roman fonts and with a space in front of the value it characterizes (e.g. $P$ = 100 Pa, $U$ = 5 m/s, $T$ = 400 K). \n\n\nAnecdote: the Mars Climate Orbiter crashed in 1990's due to a problem of unit conversion. Source of the failure (from official report): ''failure using metric units''.\n\nWhile we will use the SI system in the class it is useful to know how to convert dimensions from one unit system to another (i.e. imperial to SI). Here are some useful quantities to keep handy.\n\n### Unit conversion\n\n\n\\begin{array}{l l l}\n\\hline\n\\mathrm{length} & & \\\\\n\\hline\n1 \\,\\mathrm{in} & = & 25.4 \\times 10^{-3}\\,\\mathrm{m}\\\\\n1 \\,\\mathrm{ft} & = & 0.3048 \\,\\mathrm{m} \\\\\n & = & 12 \\,\\mathrm{in}\\\\\n1\\, \\AA & = & 10^{-10}\\,\\mathrm{m} \\\\\n1\\,\\mathrm{mile \\,(statute)} & = & 1,609 \\,\\mathrm{m}\\\\\n1 \\,\\mathrm{mile \\,(nautical)} & = & 1,852 \\,\\mathrm{m} \\\\\n%\n\\hline\n\\mathrm{volume} & & \\\\\n\\hline\n1 \\,\\mathrm{l\\, (liter)} & = & 10^{-3}\\,\\mathrm{m}^3 \\\\ \n1\\,\\mathrm{ in}^3 & = & 16.387 \\,\\mathrm{cm}^3\\\\\n1 \\,\\mathrm{gal\\, (U.S.\\, liq.)} & = & 3.785\\,\\mathrm{l} \\\\\n1 \\,\\mathrm{gal\\, (U.S.\\, dry)} & = & 1.164\\,\\mathrm{ U.S.-liq.\\, gal}\\\\\n1 \\,\\mathrm{gal \\,(British)} & = & 1.201\\,\\mathrm{ U.S.-liq.\\, gal}\\\\\n%\n\\hline\n\\mathrm{mass} & &\\\\\n\\hline\n1 \\,\\mathrm{lb \\,(mass)} & = & 0.454\\,\\mathrm{ kg}\\\\\n%\n\\hline\n\\mathrm{force}& &\\\\\n\\hline\n1 \\,\\mathrm{N }& = & 1\\,\\mathrm{ kg\\cdot m/s}^2\\\\\n1\\,\\mathrm{ dynes} & = & 10^{-5}\\,\\mathrm{ N}\\\\\n1 \\,\\mathrm{lb \\,(force)} & = & 4.448 \\,\\mathrm{N}\\\\\n%\n\\hline\n\\mathrm{energy} & & \\\\\n\\hline\n1 \\,\\mathrm{J }& = & 1\\, \\mathrm{kg \\cdot m}^2/\\mathrm{s}^2\\\\\n1 \\,\\mathrm{BTU} & = & 1,055.1\\,\\mathrm{ J}\\\\\n1 \\,\\mathrm{cal} & \\equiv & 4.184\\,\\mathrm{ J}\\\\\n1 \\,\\mathrm{kg-TNT} & \\equiv & 4.184\\,\\mathrm{ MJ}\\\\\n%\n\\hline\n\\mathrm{power} & & \\\\\n\\hline\n1 \\,\\mathrm{W} & \\equiv & 1 \\,\\mathrm{J/s}\\\\\n1 \\,\\mathrm{HP\\, (imperial)} & \\equiv & 745.7 \\,\\mathrm{W}\\\\\n1 \\,\\mathrm{HP\\, (metric)} & \\equiv & 735.5 \\,\\mathrm{W}\\\\\n\\hline\n\\end{array}\n\n### Dimensionless numbers\n\n\\begin{array}{l l l}\n\\mathrm{Reynolds\\, number} & Re & U L / \\nu \\\\\n\\mathrm{Mach\\, number} & M & U/a \\\\\n\\mathrm{Prandtl\\, number} & Pr & \\mu c_p / k = \\nu / \\kappa \\\\\n\\mathrm{Strouhal\\, number} & St & L/U \\tau \\\\\n\\mathrm{Knudsen\\, number} & Kn & \\Lambda / L \\\\\n\\mathrm{Peclet\\, number} & Pe & U L / \\kappa = Pr \\cdot Re \\\\\n\\mathrm{Schmidt\\, number} & Sc & \\nu / D \\\\\n\\mathrm{Lewis\\, number} & Le & D / \\kappa \\\\\n\\end{array}\n\n### Useful constants\n\nAvogadro's number: \n\\begin{align*}\nN_A & = 6.022\\, 1367 \\times 10^{23} \\mathrm{\\, molecules/(mol)} %\\nolabel\n\\end{align*}\n\nBoltzman constant:\n\\begin{align*}\nk_B & = 1.380\\, 69 \\times 10^{-23} \\mathrm{\\, J/K} \\\\\nk_B T & = 2.585 \\times 10^{-2} \\mathrm{\\,eV} \\sim \\frac{1}{40} \\mathrm{\\, eV, at \\,} T = 300 \\mathrm{K} \n\\end{align*}\n\nUniversal gas constant:\n\\begin{align*}\nR_u & = 8.314\\, 510 \\mathrm{\\, J/(mol} \\cdot \\mathrm{K)}\n\\end{align*}\n\nEarth radius (at equator):\n\\begin{align*}\nr_{earth} & = 6\\,378.1370 \\mathrm{\\, km} \n\\end{align*}\n\n\n## Dimensional analysis\n\nNow that we know the primary dimensionns, we can make use of it to reduce the number of experimental runs one needs to perform. This is the foundation of dimensional analysis, which you have seen in MAE 3126 (Fluid Mechanics). To reduce the number of experimental runs will see other techniques, such as Taguchi arrays in a few weeks when we treat design of experiments. The benefit of dimensional analysis is best seen through the graph below:\n\n\n\nPlease review your notes of Fluid Mechanics on dimensional analysis and the method of repeating variables (also called Buckingham $\\Pi$ theorem)\n\n## Errors and Uncertainties\n\nAn __error__ is defined as:\n\n\\begin{align*}\n\\epsilon = x_m - x_{true}\n\\end{align*}\n\nwhere $x_m$ is the measured value and $x_{true}$ the true value. The problem is that we do not always (rarely in fact) know the true value. This will lead to the concept of uncertainty.\n\nErrors can be categorized into two types:\n\n>__1- Systematic or bias error__: Those are errors that are consistent or repeatable. For example, I use a ruler with the first 3 mm missing, all the measurements will be short by 3 mm.\n\n>__2- Random or precision error__: errors that are inconsistent or unrepeatable. This will be seen as scatter in the measured data. For examl]ple, this could be caused by electo-magnetic noise in a voltmeter (with implication on grounding and shielding of the instrument).\n\nSystematic vs random errors can be best seen visually:\n\n\n\n\nIn light of the two types of errors defined above, one would like to define mathematical formulas to quantify them.\n\n__systematic/bias error__\n\n\\begin{align*}\n\\epsilon_b = x_m - x_{true}\n\\end{align*}\n\n_Question_: What are sources of bias errors?\nHow can we reduce bias errors?\n\n__relative mean bias error__: non-dimensional (normalized) form of the mean bias error.\n\n\\begin{align*}\n\\frac{ - x_{true}}{x_{true}}\n\\end{align*}\n\n__random/precision error__\n\n\\begin{align*}\n\\epsilon_p = x_m - \n\\end{align*}\n\n_example_: We have five temperature measurements: Can you find the maximum precision error?\n\nThe __overal precision error or standard error__ is found by computing the standard deviation, $S$, divided by the square root of the number of samples, $n$.\n\n\\begin{align*}\n\\epsilon_{op} = \\frac{S}{\\sqrt{n}}\n\\end{align*}\n\n\n\n```python\nimport numpy\n\nT=[372.80, 373.00, 372.90, 373.30, 373.10]\n\nTm = numpy.mean(T)\nprint(Tm)\nep_max = 373.30-Tm\nprint(ep_max)\n```\n\n 373.02\n 0.28000000000002956\n\n\n_Question_: Are five measurement enough to quantify the precision error? We also need a statistics that represents the __mean__ precision error. We will see this soon.\n\nNow that we have described the two types of errors and hinted at how to estimate them, let's look at instruments specifically.\n\n### Calibration\n\nCalibration aims to determine and imrove its accuracy. Calibration can be accomplished in 3 manners: 1- comparison with a primary standard (such as developed by NIST, like the mass or meter defined earlier), 2- a secondary standard, such as another instrument of known and higher accuracy, 3- a known input source.\n\nHere are examples of primary standards for temperature that are ''easy'' to implement in any labs: \n\\begin{array}{l l}\n\\hline\n\\mathrm{definition} & \\text{temperature (K)}\\\\\n\\hline\n\\mathrm{triple\\, point\\, of\\, hydrogen} & 13.8033 \\\\\n\\mathrm{triple\\, point\\, of\\, oxygen} & 54.3584\\\\\n\\mathrm{triple\\, point\\, of\\, water} & 273.16 \\\\\n\\mathrm{Ice\\, point} & 273.15 \\\\\n\\mathrm{normal\\, boiling\\, point\\, of\\, water} & 373.15 \\\\\n\\hline\n\\end{array}\n\nCalibration can be done in a static and/or dynamic manner. It is a very important step to verify the accuracy of an instrument or sensor. In most laboratories, calibration has to be performed regularly. Some commercial entities are specialised in doing so. \n\nBefore each important test campaign or after a company recertify instrument, the results have be to be documented for traceability. Here is an example for load balance.\n\n\n\n\n\n### Uncertainty\n\nThe concept of __uncertainty__ needs to be taken into account when we conduct experiments. Uncertainty can be defined as (S.J. Kline) ''What we think the error would be if we could and did measure it by calibration''. Taking data is a very small part of doing an experiment and we are going to spend a lot of time doing uncertainty analysis. \n\nAn error, $\\epsilon$ has a particular sign and magnitude (see the equations above). If it is known, then if can be removed from the measurments (through calibration for example). Any remaining error that does not have a sign and mangitude cannot be removed. We will define an uncertainty $\\pm u$ as the range that contains the remaining (unknown) errors. \n\nBecause we are doing measurement in an uncertain world, we need to be able to express our __confidence level__ in our results. This wil require set of sophisticated statistical tools.\n\n__Uncertainty analysis__ is an extremely important tool and step in experiments and we are going to spend a significant amount of time on it during the class. This analysis is performed typically in the experimental planning phase (to help in determining the appropriate components to use in our instrumentation chain see in the first figure). An extensive analysis is also performed after the campaign to characterize the actual uncertainties in the measurement.\n\n### Instrument rating\n\nWhen selecting an instrument for a measurement, one has many options. Ideally, one would like to select a system that will meet our requirements for the measurement (such as expected range, but also for uncertainty) while not breaking the bank... Luckily manufacturers report a lot of data with their sensor/transducer that can help us in making an educated guess of the expected performance without having to characterize it ourselves. Here is an example from Omega Scientific for a pressure transducer:\n\n\n\n\nLet's define a few of the terms used.\n\n__Accuracy__ is difference between true and measured value. \n\n\\begin{align*}\nu_a = x_m - x_{true}\n\\end{align*}\n\nA small difference between true and measured value leads to a high accuracy and vice-versa. It can be expressed as a percentage of reading, of full-scale, or an absolute value. Accuracy can be assessed and minimized by calibrating the system.\n\n__Precision__ of an instrument is the reading minus the average of readings. It characterizes random error of instrument output or the reproducibility of an instrument.\n\n\\begin{align*}\nu_p = x_m - \n\\end{align*}\n\n_Questions_: \n\n>Can we improve precision by calibrating the system?\n\n> Is there a limit up to which we can improve the accuracy of a system?\n\nIf we recall our previous definitions for errors, you will remark that they are the same than the two terms introduced above and imply that we compare the instrument readings to the true, known, value. However, in most cases, we do not know the true value and instead we are only confident that we are within a certain range ($\\pm$) of the true value. Therefore to be consistent with the definitions introduced so far, we should use the term uncertainty and not error, when describing experimental results (except for a few cases).\n\nAccuracy and precision are the two main categories of uncertainties in our measurements; however, they are each comprised of elemental components. A non-exhaustive list includes:\n\n__resolution__: smallest change or increment in the measurand that the instrumente can detect. Note for digital instrument, resolution is associated with the number of digits on display, ie a 5 digit Digital Multi-Meter (DMM) has better resolution than a 4 digit DMM. The values reported by the DMM will be at $\\pm$ the last digit.\n\n__sensitivity__: it is defined \n\nOther sources of errors are zero, linearity, sensitivity, hysteresis, etc.\n\n\n\n## Experiment planning\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "54acba237adf094fc649af291c536f9348c7ffb8", "size": 26217, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures/00_Introduction.ipynb", "max_stars_repo_name": "eiriniflorou/GWU-MAE3120_2022", "max_stars_repo_head_hexsha": "52cd589c4cfcb0dda357c326cc60c2951cedca3b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/00_Introduction.ipynb", "max_issues_repo_name": "eiriniflorou/GWU-MAE3120_2022", "max_issues_repo_head_hexsha": "52cd589c4cfcb0dda357c326cc60c2951cedca3b", "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": "Lectures/00_Introduction.ipynb", "max_forks_repo_name": "eiriniflorou/GWU-MAE3120_2022", "max_forks_repo_head_hexsha": "52cd589c4cfcb0dda357c326cc60c2951cedca3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.7233606557, "max_line_length": 1293, "alphanum_fraction": 0.6296677728, "converted": true, "num_tokens": 5259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.0969011731900004}} {"text": "\n\n##### Copyright 2020 The TensorFlow Authors.\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# MNIST classification\n\n\n \n \n \n \n
\n View on TensorFlow.org\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\nThis tutorial builds a quantum neural network (QNN) to classify a simplified version of MNIST, similar to the approach used in Farhi et al. The performance of the quantum neural network on this classical data problem is compared with a classical neural network.\n\n## Setup\n\n\n```\n!pip install tensorflow==2.3.1\n```\n\n Collecting tensorflow==2.3.1\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/eb/18/374af421dfbe74379a458e58ab40cf46b35c3206ce8e183e28c1c627494d/tensorflow-2.3.1-cp37-cp37m-manylinux2010_x86_64.whl (320.4MB)\n \u001b[K |████████████████████████████████| 320.4MB 50kB/s \n \u001b[?25hRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (0.12.0)\n Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.1.2)\n Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (0.3.3)\n Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.15.0)\n Collecting numpy<1.19.0,>=1.16.0\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/d6/c6/58e517e8b1fb192725cfa23c01c2e60e4e6699314ee9684a1c5f5c9b27e1/numpy-1.18.5-cp37-cp37m-manylinux1_x86_64.whl (20.1MB)\n \u001b[K |████████████████████████████████| 20.1MB 1.3MB/s \n \u001b[?25hRequirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (3.3.0)\n Collecting tensorflow-estimator<2.4.0,>=2.3.0\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/e9/ed/5853ec0ae380cba4588eab1524e18ece1583b65f7ae0e97321f5ff9dfd60/tensorflow_estimator-2.3.0-py2.py3-none-any.whl (459kB)\n \u001b[K |████████████████████████████████| 460kB 47.3MB/s \n \u001b[?25hRequirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.12.1)\n Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (0.36.2)\n Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (0.2.0)\n Requirement already satisfied: tensorboard<3,>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (2.4.1)\n Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (2.10.0)\n Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.32.0)\n Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.6.3)\n Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (3.12.4)\n Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.1.0)\n Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (0.4.4)\n Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.3.4)\n Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (2.23.0)\n Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.28.1)\n Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.0.1)\n Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (56.0.0)\n Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.8.0)\n Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.3.0)\n Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.10.1)\n Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.24.3)\n Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (2020.12.5)\n Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (2.10)\n Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.0.4)\n Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (0.2.8)\n Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3.6\" in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (4.7.2)\n Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (4.2.1)\n Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.1.0)\n Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.4.1)\n Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.7.4.3)\n Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (0.4.8)\n \u001b[31mERROR: datascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.\u001b[0m\n \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n Installing collected packages: numpy, tensorflow-estimator, tensorflow\n Found existing installation: numpy 1.19.5\n Uninstalling numpy-1.19.5:\n Successfully uninstalled numpy-1.19.5\n Found existing installation: tensorflow-estimator 2.4.0\n Uninstalling tensorflow-estimator-2.4.0:\n Successfully uninstalled tensorflow-estimator-2.4.0\n Found existing installation: tensorflow 2.4.1\n Uninstalling tensorflow-2.4.1:\n Successfully uninstalled tensorflow-2.4.1\n Successfully installed numpy-1.18.5 tensorflow-2.3.1 tensorflow-estimator-2.3.0\n\n\n\n\nInstall TensorFlow Quantum:\n\n\n```\n!pip install tensorflow-quantum\n```\n\n Collecting tensorflow-quantum\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/53/02/878b2d4e7711f5c7f8dff9ff838e8ed84d218a359154ce06c7c01178a125/tensorflow_quantum-0.4.0-cp37-cp37m-manylinux2010_x86_64.whl (5.9MB)\n \u001b[K |████████████████████████████████| 5.9MB 4.2MB/s \n \u001b[?25hCollecting sympy==1.5\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/4d/a7/25d5d6b3295537ab90bdbcd21e464633fb4a0684dd9a065da404487625bb/sympy-1.5-py2.py3-none-any.whl (5.6MB)\n \u001b[K |████████████████████████████████| 5.6MB 26.4MB/s \n \u001b[?25hCollecting cirq==0.9.1\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/18/05/39c24828744b91f658fd1e5d105a9d168da43698cfaec006179c7646c71c/cirq-0.9.1-py3-none-any.whl (1.6MB)\n \u001b[K |████████████████████████████████| 1.6MB 45.9MB/s \n \u001b[?25hRequirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy==1.5->tensorflow-quantum) (1.2.1)\n Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (3.7.4.3)\n Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (1.1.5)\n Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (2.5.1)\n Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (1.4.1)\n Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (1.26.3)\n Requirement already satisfied: protobuf~=3.12.0 in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (3.12.4)\n Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (1.18.5)\n Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (2.3.0)\n Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (3.2.2)\n Collecting freezegun~=0.3.15\n Downloading https://files.pythonhosted.org/packages/17/5d/1b9d6d3c7995fff473f35861d674e0113a5f0bd5a72fe0199c3f254665c7/freezegun-0.3.15-py2.py3-none-any.whl\n Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.7/dist-packages (from cirq==0.9.1->tensorflow-quantum) (2.23.0)\n Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->cirq==0.9.1->tensorflow-quantum) (2.8.1)\n Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->cirq==0.9.1->tensorflow-quantum) (2018.9)\n Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx~=2.4->cirq==0.9.1->tensorflow-quantum) (4.4.2)\n Requirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (1.28.1)\n Requirement already satisfied: setuptools>=40.3.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (56.0.0)\n Requirement already satisfied: six>=1.13.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (1.15.0)\n Requirement already satisfied: packaging>=14.3 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (20.9)\n Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (1.53.0)\n Requirement already satisfied: grpcio<2.0dev,>=1.29.0; extra == \"grpc\" in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (1.32.0)\n Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq==0.9.1->tensorflow-quantum) (2.4.7)\n Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq==0.9.1->tensorflow-quantum) (0.10.0)\n Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq==0.9.1->tensorflow-quantum) (1.3.1)\n Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq==0.9.1->tensorflow-quantum) (2020.12.5)\n Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq==0.9.1->tensorflow-quantum) (1.24.3)\n Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq==0.9.1->tensorflow-quantum) (3.0.4)\n Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq==0.9.1->tensorflow-quantum) (2.10)\n Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3.6\" in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (4.7.2)\n Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (0.2.8)\n Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (4.2.1)\n Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.7/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3.6\"->google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq==0.9.1->tensorflow-quantum) (0.4.8)\n Installing collected packages: sympy, freezegun, cirq, tensorflow-quantum\n Found existing installation: sympy 1.7.1\n Uninstalling sympy-1.7.1:\n Successfully uninstalled sympy-1.7.1\n Successfully installed cirq-0.9.1 freezegun-0.3.15 sympy-1.5 tensorflow-quantum-0.4.0\n\n\nNow import TensorFlow and the module dependencies:\n\n\n```\nimport tensorflow as tf\nimport tensorflow_quantum as tfq\n\nimport cirq\nimport sympy\nimport numpy as np\nimport seaborn as sns\nimport collections\n\n# visualization tools\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom cirq.contrib.svg import SVGCircuit\n```\n\n## 1. Load the data\n\nIn this tutorial you will build a binary classifier to distinguish between the digits 3 and 6, following Farhi et al. This section covers the data handling that:\n\n- Loads the raw data from Keras.\n- Filters the dataset to only 3s and 6s.\n- Downscales the images so they fit can fit in a quantum computer.\n- Removes any contradictory examples.\n- Converts the binary images to Cirq circuits.\n- Converts the Cirq circuits to TensorFlow Quantum circuits. \n\n### 1.1 Load the raw data\n\nLoad the MNIST dataset distributed with Keras. \n\n\n```\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n\n# Rescale the images from [0,255] to the [0.0,1.0] range.\nx_train, x_test = x_train[..., np.newaxis]/255.0, x_test[..., np.newaxis]/255.0\n\nprint(\"Number of original training examples:\", len(x_train))\nprint(\"Number of original test examples:\", len(x_test))\n```\n\n Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n 11493376/11490434 [==============================] - 0s 0us/step\n Number of original training examples: 60000\n Number of original test examples: 10000\n\n\nFilter the dataset to keep just the 3s and 6s, remove the other classes. At the same time convert the label, `y`, to boolean: `True` for `3` and `False` for 6. \n\n\n```\ndef filter_36(x, y):\n keep = (y == 3) | (y == 6)\n x, y = x[keep], y[keep]\n y = y == 3\n return x,y\n```\n\n\n```\nx_train, y_train = filter_36(x_train, y_train)\nx_test, y_test = filter_36(x_test, y_test)\n\nprint(\"Number of filtered training examples:\", len(x_train))\nprint(\"Number of filtered test examples:\", len(x_test))\n```\n\n Number of filtered training examples: 12049\n Number of filtered test examples: 1968\n\n\nShow the first example:\n\n\n```\nprint(y_train[0])\n\nplt.imshow(x_train[0, :, :, 0])\nplt.colorbar()\n```\n\n### 1.2 Downscale the images\n\nAn image size of 28x28 is much too large for current quantum computers. Resize the image down to 4x4:\n\n\n```\nx_train_small = tf.image.resize(x_train, (4,4)).numpy()\nx_test_small = tf.image.resize(x_test, (4,4)).numpy()\n```\n\nAgain, display the first training example—after resize: \n\n\n```\nprint(y_train[0])\n\nplt.imshow(x_train_small[0,:,:,0], vmin=0, vmax=1)\nplt.colorbar()\n```\n\n### 1.3 Remove contradictory examples\n\nFrom section *3.3 Learning to Distinguish Digits* of Farhi et al., filter the dataset to remove images that are labeled as belonging to both classes.\n\nThis is not a standard machine-learning procedure, but is included in the interest of following the paper.\n\n\n```\ndef remove_contradicting(xs, ys):\n mapping = collections.defaultdict(set)\n orig_x = {}\n # Determine the set of labels for each unique image:\n for x,y in zip(xs,ys):\n orig_x[tuple(x.flatten())] = x\n mapping[tuple(x.flatten())].add(y)\n \n new_x = []\n new_y = []\n for flatten_x in mapping:\n x = orig_x[flatten_x]\n labels = mapping[flatten_x]\n if len(labels) == 1:\n new_x.append(x)\n new_y.append(next(iter(labels)))\n else:\n # Throw out images that match more than one label.\n pass\n \n num_uniq_3 = sum(1 for value in mapping.values() if len(value) == 1 and True in value)\n num_uniq_6 = sum(1 for value in mapping.values() if len(value) == 1 and False in value)\n num_uniq_both = sum(1 for value in mapping.values() if len(value) == 2)\n\n print(\"Number of unique images:\", len(mapping.values()))\n print(\"Number of unique 3s: \", num_uniq_3)\n print(\"Number of unique 6s: \", num_uniq_6)\n print(\"Number of unique contradicting labels (both 3 and 6): \", num_uniq_both)\n print()\n print(\"Initial number of images: \", len(xs))\n print(\"Remaining non-contradicting unique images: \", len(new_x))\n \n return np.array(new_x), np.array(new_y)\n```\n\nThe resulting counts do not closely match the reported values, but the exact procedure is not specified.\n\nIt is also worth noting here that applying filtering contradictory examples at this point does not totally prevent the model from receiving contradictory training examples: the next step binarizes the data which will cause more collisions. \n\n\n```\nx_train_nocon, y_train_nocon = remove_contradicting(x_train_small, y_train)\n```\n\n Number of unique images: 10387\n Number of unique 3s: 4912\n Number of unique 6s: 5426\n Number of unique contradicting labels (both 3 and 6): 49\n \n Initial number of images: 12049\n Remaining non-contradicting unique images: 10338\n\n\n### 1.4 Encode the data as quantum circuits\n\nTo process images using a quantum computer, Farhi et al. proposed representing each pixel with a qubit, with the state depending on the value of the pixel. The first step is to convert to a binary encoding.\n\n\n```\nTHRESHOLD = 0.5\n\nx_train_bin = np.array(x_train_nocon > THRESHOLD, dtype=np.float32)\nx_test_bin = np.array(x_test_small > THRESHOLD, dtype=np.float32)\n```\n\nIf you were to remove contradictory images at this point you would be left with only 193, likely not enough for effective training.\n\n\n```\n_ = remove_contradicting(x_train_bin, y_train_nocon)\n```\n\n Number of unique images: 193\n Number of unique 3s: 80\n Number of unique 6s: 69\n Number of unique contradicting labels (both 3 and 6): 44\n \n Initial number of images: 10338\n Remaining non-contradicting unique images: 149\n\n\nThe qubits at pixel indices with values that exceed a threshold, are rotated through an $X$ gate.\n\n\n```\ndef convert_to_circuit(image):\n \"\"\"Encode truncated classical image into quantum datapoint.\"\"\"\n values = np.ndarray.flatten(image)\n qubits = cirq.GridQubit.rect(4, 4)\n circuit = cirq.Circuit()\n for i, value in enumerate(values):\n if value:\n circuit.append(cirq.X(qubits[i]))\n return circuit\n\n\nx_train_circ = [convert_to_circuit(x) for x in x_train_bin]\nx_test_circ = [convert_to_circuit(x) for x in x_test_bin]\n```\n\nHere is the circuit created for the first example (circuit diagrams do not show qubits with zero gates):\n\n\n```\nSVGCircuit(x_train_circ[0])\n```\n\n findfont: Font family ['Arial'] not found. Falling back to DejaVu Sans.\n\n\n\n\n\n \n\n \n\n\n\nCompare this circuit to the indices where the image value exceeds the threshold:\n\n\n```\nbin_img = x_train_bin[0,:,:,0]\nindices = np.array(np.where(bin_img)).T\nindices\n```\n\n\n\n\n array([[2, 2],\n [3, 1]])\n\n\n\nConvert these `Cirq` circuits to tensors for `tfq`:\n\n\n```\nx_train_tfcirc = tfq.convert_to_tensor(x_train_circ)\nx_test_tfcirc = tfq.convert_to_tensor(x_test_circ)\n```\n\n## 2. Quantum neural network\n\nThere is little guidance for a quantum circuit structure that classifies images. Since the classification is based on the expectation of the readout qubit, Farhi et al. propose using two qubit gates, with the readout qubit always acted upon. This is similar in some ways to running small a Unitary RNN across the pixels.\n\n### 2.1 Build the model circuit\n\nThis following example shows this layered approach. Each layer uses *n* instances of the same gate, with each of the data qubits acting on the readout qubit.\n\nStart with a simple class that will add a layer of these gates to a circuit:\n\n\n```\nclass CircuitLayerBuilder():\n def __init__(self, data_qubits, readout):\n self.data_qubits = data_qubits\n self.readout = readout\n \n def add_layer(self, circuit, gate, prefix):\n for i, qubit in enumerate(self.data_qubits):\n symbol = sympy.Symbol(prefix + '-' + str(i))\n circuit.append(gate(qubit, self.readout)**symbol)\n```\n\nBuild an example circuit layer to see how it looks:\n\n\n```\ndemo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1),\n readout=cirq.GridQubit(-1,-1))\n\ncircuit = cirq.Circuit()\ndemo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx')\nSVGCircuit(circuit)\n```\n\n\n\n\n \n\n \n\n\n\nNow build a two-layered model, matching the data-circuit size, and include the preparation and readout operations.\n\n\n```\ndef create_quantum_model():\n \"\"\"Create a QNN model circuit and readout operation to go along with it.\"\"\"\n data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.\n readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]\n circuit = cirq.Circuit()\n \n # Prepare the readout qubit.\n circuit.append(cirq.X(readout))\n circuit.append(cirq.H(readout))\n \n builder = CircuitLayerBuilder(\n data_qubits = data_qubits,\n readout=readout)\n\n # Then add layers (experiment by adding more).\n builder.add_layer(circuit, cirq.XX, \"xx1\")\n builder.add_layer(circuit, cirq.ZZ, \"zz1\")\n\n # Finally, prepare the readout qubit.\n circuit.append(cirq.H(readout))\n\n return circuit, cirq.Z(readout)\n```\n\n\n```\nmodel_circuit, model_readout = create_quantum_model()\n```\n\n### 2.2 Wrap the model-circuit in a tfq-keras model\n\nBuild the Keras model with the quantum components. This model is fed the \"quantum data\", from `x_train_circ`, that encodes the classical data. It uses a *Parametrized Quantum Circuit* layer, `tfq.layers.PQC`, to train the model circuit, on the quantum data.\n\nTo classify these images, Farhi et al. proposed taking the expectation of a readout qubit in a parameterized circuit. The expectation returns a value between 1 and -1.\n\n\n```\n# Build the Keras model.\nmodel = tf.keras.Sequential([\n # The input is the data-circuit, encoded as a tf.string\n tf.keras.layers.Input(shape=(), dtype=tf.string),\n # The PQC layer returns the expected value of the readout gate, range [-1,1].\n tfq.layers.PQC(model_circuit, model_readout),\n])\n```\n\nNext, describe the training procedure to the model, using the `compile` method.\n\nSince the the expected readout is in the range `[-1,1]`, optimizing the hinge loss is a somewhat natural fit. \n\nNote: Another valid approach would be to shift the output range to `[0,1]`, and treat it as the probability the model assigns to class `3`. This could be used with a standard a `tf.losses.BinaryCrossentropy` loss.\n\nTo use the hinge loss here you need to make two small adjustments. First convert the labels, `y_train_nocon`, from boolean to `[-1,1]`, as expected by the hinge loss.\n\n\n```\ny_train_hinge = 2.0*y_train_nocon-1.0\ny_test_hinge = 2.0*y_test-1.0\n```\n\nSecond, use a custiom `hinge_accuracy` metric that correctly handles `[-1, 1]` as the `y_true` labels argument. \n`tf.losses.BinaryAccuracy(threshold=0.0)` expects `y_true` to be a boolean, and so can't be used with hinge loss).\n\n\n```\ndef hinge_accuracy(y_true, y_pred):\n y_true = tf.squeeze(y_true) > 0.0\n y_pred = tf.squeeze(y_pred) > 0.0\n result = tf.cast(y_true == y_pred, tf.float32)\n\n return tf.reduce_mean(result)\n```\n\n\n```\nmodel.compile(\n loss=tf.keras.losses.Hinge(),\n optimizer=tf.keras.optimizers.Adam(),\n metrics=[hinge_accuracy])\n```\n\n\n```\nprint(model.summary())\n```\n\n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n pqc (PQC) (None, 1) 32 \n =================================================================\n Total params: 32\n Trainable params: 32\n Non-trainable params: 0\n _________________________________________________________________\n None\n\n\n### Train the quantum model\n\nNow train the model—this takes about 45 min. If you don't want to wait that long, use a small subset of the data (set `NUM_EXAMPLES=500`, below). This doesn't really affect the model's progress during training (it only has 32 parameters, and doesn't need much data to constrain these). Using fewer examples just ends training earlier (5min), but runs long enough to show that it is making progress in the validation logs.\n\n\n```\nEPOCHS = 3\nBATCH_SIZE = 32\n\nNUM_EXAMPLES = len(x_train_tfcirc)\n```\n\n\n```\nx_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES]\ny_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES]\n```\n\nTraining this model to convergence should achieve >85% accuracy on the test set.\n\n\n```\nqnn_history = model.fit(\n x_train_tfcirc_sub, y_train_hinge_sub,\n batch_size=32,\n epochs=EPOCHS,\n verbose=1,\n validation_data=(x_test_tfcirc, y_test_hinge))\n\nqnn_results = model.evaluate(x_test_tfcirc, y_test)\n```\n\n Epoch 1/3\n 206/324 [==================>...........] - ETA: 3:31 - loss: 0.7359 - hinge_accuracy: 0.8359\n\nNote: The training accuracy reports the average over the epoch. The validation accuracy is evaluated at the end of each epoch.\n\n## 3. Classical neural network\n\nWhile the quantum neural network works for this simplified MNIST problem, a basic classical neural network can easily outperform a QNN on this task. After a single epoch, a classical neural network can achieve >98% accuracy on the holdout set.\n\nIn the following example, a classical neural network is used for for the 3-6 classification problem using the entire 28x28 image instead of subsampling the image. This easily converges to nearly 100% accuracy of the test set.\n\n\n```\ndef create_classical_model():\n # A simple model based off LeNet from https://keras.io/examples/mnist_cnn/\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Conv2D(32, [3, 3], activation='relu', input_shape=(28,28,1)))\n model.add(tf.keras.layers.Conv2D(64, [3, 3], activation='relu'))\n model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(tf.keras.layers.Dropout(0.25))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dense(128, activation='relu'))\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(1))\n return model\n\n\nmodel = create_classical_model()\nmodel.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['accuracy'])\n\nmodel.summary()\n```\n\n\n```\nmodel.fit(x_train,\n y_train,\n batch_size=128,\n epochs=1,\n verbose=1,\n validation_data=(x_test, y_test))\n\ncnn_results = model.evaluate(x_test, y_test)\n```\n\nThe above model has nearly 1.2M parameters. For a more fair comparison, try a 37-parameter model, on the subsampled images:\n\n\n```\ndef create_fair_classical_model():\n # A simple model based off LeNet from https://keras.io/examples/mnist_cnn/\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Flatten(input_shape=(4,4,1)))\n model.add(tf.keras.layers.Dense(2, activation='relu'))\n model.add(tf.keras.layers.Dense(1))\n return model\n\n\nmodel = create_fair_classical_model()\nmodel.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['accuracy'])\n\nmodel.summary()\n```\n\n\n```\nmodel.fit(x_train_bin,\n y_train_nocon,\n batch_size=128,\n epochs=20,\n verbose=2,\n validation_data=(x_test_bin, y_test))\n\nfair_nn_results = model.evaluate(x_test_bin, y_test)\n```\n\n## 4. Comparison\n\nHigher resolution input and a more powerful model make this problem easy for the CNN. While a classical model of similar power (~32 parameters) trains to a similar accuracy in a fraction of the time. One way or the other, the classical neural network easily outperforms the quantum neural network. For classical data, it is difficult to beat a classical neural network.\n\n\n```\nqnn_accuracy = qnn_results[1]\ncnn_accuracy = cnn_results[1]\nfair_nn_accuracy = fair_nn_results[1]\n\nsns.barplot([\"Quantum\", \"Classical, full\", \"Classical, fair\"],\n [qnn_accuracy, cnn_accuracy, fair_nn_accuracy])\n```\n", "meta": {"hexsha": "a619a3534b76e2ef26daedafc066c079119ce68e", "size": 76644, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Copy_of_mnist.ipynb", "max_stars_repo_name": "QDaria/QDaria.github.io", "max_stars_repo_head_hexsha": "f60d00270a651cceff47629edcee22c70d747185", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Copy_of_mnist.ipynb", "max_issues_repo_name": "QDaria/QDaria.github.io", "max_issues_repo_head_hexsha": "f60d00270a651cceff47629edcee22c70d747185", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Copy_of_mnist.ipynb", "max_forks_repo_name": "QDaria/QDaria.github.io", "max_forks_repo_head_hexsha": "f60d00270a651cceff47629edcee22c70d747185", "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": 55.0999281093, "max_line_length": 7930, "alphanum_fraction": 0.6299906059, "converted": true, "num_tokens": 9681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881506183194, "lm_q2_score": 0.19682620128743877, "lm_q1q2_score": 0.09687552400489356}} {"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\n%matplotlib notebook\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\nimport sympy as sym\n\nfrom ipywidgets import widgets, Layout\nfrom ipywidgets import interact\n\nfrom IPython.display import Latex, display, Markdown # For displaying Markdown and LaTeX code\n\nfrom matplotlib import patches\n```\n\n## Sistema di controllo dell'azimut di una antenna\n\nUn esempio di un sistema di controllo dell'azimut di una antenna è mostrato schematicamente nella figura in basso a sinistra. L'obiettivo di questo sistema di controllo è mantenere la posizione desiderata dell'antenna impostando l'angolo desiderato $\\theta_{ref}$ con il potenziometro di riferimento (RP). Lo schema a blocchi di questo sistema (mostrato nella figura in basso a destra) inizia quindi con il segnale $\\theta_{ref}$, che viene convertito in tensione $U_1$. La tensione $U_2$ viene quindi sottratta da $U_1$. $U_2$ è l'uscita dal potenziometro di misurazione (MP), che fornisce le informazioni sull'angolo effettivo. La differenza di tensione $U_1-U_2$ rappresenta l'errore che ci dice quanto l'angolo effettivo differisce da quello desiderato. In base a questo errore il controller agisce sull'elettromotore che (tramite ingranaggi) fa ruotare l'antenna in modo da ridurre l'errore. $d_w$ è un disturbo dovuto al vento che fa ruotare l'antenna in modo casuale.\n\n
\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
Rappresentazione schematica del sistema di controllo dell'azimut di una antenna Diagramma a blocchi del sistema di controllo dell'azimut di una antenna
Legenda: RP = potenziometro di riferimento, MP = potenziometro di misurazione, dw = disturbo dovuto al vento.
\n\n---\n\n### Come usare questo notebook?\n\n- Spostare i cursori per modificare i valori dell'angolo azimutale dell'antenna desiderato ($\\theta_{ref}$), del disturbo dovuto al vento ($d_w$) e dei coefficienti di controllo proporzionale ($K_p$), integrale ($K_i$) e derivativo ($K_d$).\n\n- Premere i pulsanti per alternare tra il tipo di controller proporzionale (P), proporzionale-integrale (PI) e proporzionale-integrale-derivativo (PID).\n\n---\n\n### Note\n\n- La dimensione della freccia rossa sulla rappresentazione schematica dell'antenna è proporzionale all'entità del disturbo dovuto al vento ($d_w$), mentre la direzione della freccia indica la direzione del disturbo.\n- La linea blu tratteggiata sulla rappresentazione schematica dell'antenna indica l'angolo effettivo.\n- La linea verde tratteggiata sulla rappresentazione schematica dell'antenna indica l'angolo desiderato.\n- La linea rossa tratteggiata sulla rappresentazione schematica dell'antenna indica l'angolo effettivo precedente.\n\nÈ possibile selezionare tra due diverse opzioni per la visualizzazione dei risultati:\n1. Resettare la rappresentazione schematica quando si modifica il tipo di controller.\n2. Resettare il grafico quando viene modificato il tipo di controller.\n\n\n```python\n# define system constants\n_Kpot = 0.318\n\n_K1 = 100\n_a = 100\n_Km = 2.083\n_am = 1.71\n_Kg = 0.1\n_R = 8\n_Kt = 0.5\n_Tv = 200 #in milliseconds\n\n#set current theta and theta reference:\nth = [0,0,0,0,0,0]\nthref = [0,0,0,0,0,0]\n# disturbance:\nm = [0,0,0,0,0,0]\n#joined together (first theta reference, second disturbance, then theta measured):\nvariables = [thref, m, th]\n\n# variables of controller:\n_K = 1\n_taui = 1\n_taud = 1\n\n```\n\n\n```python\n# symbolic calculus:\ntaui, taud, K, s, z = sym.symbols('taui, taud, K, s, z')\n\n_alpha=0.1\n#controller:\nP = K\nI = K/(taui*s)\nD = K*taud*s/(_alpha*taud*s+1)\n\ndef make_model(controller):\n if controller == 'P':\n C = P\n elif controller == 'PI':\n C = P+I\n elif controller == 'PID':\n C = P+I+D\n else:\n print('Sistema di controllo non modellato')\n \n tf_s = C*_K1*_Km*_Kg*_Kpot/(s*(s+_a)*(s+_am)+C*_K1*_Km*_Kg*_Kpot)\n tf_s = tf_s.simplify()\n\n tf_z = tf_s.subs(s,2/(_Tv/1000)*(z-1)/(z+1))\n tf_z = tf_z.simplify()\n \n num = [sym.fraction(tf_z.factor())[0].expand().coeff(z, i) for i in reversed(range(1+sym.degree(sym.fraction(tf_z.factor())[0], gen=z)))]\n den = [sym.fraction(tf_z.factor())[1].expand().coeff(z, i) for i in reversed(range(1+sym.degree(sym.fraction(tf_z.factor())[1], gen=z)))]\n #print(num)\n #print(den)\n\n tf_sM = _Km*_Kg*_R*(s+_a)/(s*(s+_a)*(s+_am)*_Kt+C*_K1*_Km*_Kg*_Kpot*_Kt)\n \n tf_zM = tf_sM.subs(s,2/(_Tv/1000)*(z-1)/(z+1))\n tf_zM = tf_zM.simplify()\n num_M = [sym.fraction(tf_zM.factor())[0].expand().coeff(z, i) for i in reversed(range(1+sym.degree(sym.fraction(tf_zM.factor())[0], gen=z)))]\n #print(num_M)\n #print(den_M)\n \n #print('\\n........finished........')\n return sym.lambdify((K, taui, taud), [np.array(num), -np.array(num_M), -np.array(den)])\n\nz_transform_p = make_model('P')\nz_transform_pi = make_model('PI')\nz_transform_pid = make_model('PID')\n```\n\n\n```python\ndef calculate_next(z_transform):\n variables[-1][0] = 0 # set current to zero\n z_transform = z_transform(_K, _taui, _taud)\n \n temp = 0\n for i in range(len(z_transform)): # for every polynomial\n for j in range(len(z_transform[i])): # for every term in polynomial\n temp += z_transform[i][j] * variables[i][j]\n\n return temp / z_transform[-1][0]*(-1)\n```\n\n\n```python\nfig = plt.figure(figsize=(9.8, 4),num='Sistema di controllo dell\\'azimut di una antenna')\n# add axes\nax = fig.add_subplot(121)\ngraph = fig.add_subplot(122)\n \n#set current theta and theta reference:\nth = [0,0,0,0,0,0]\nthref = [1,0,0,0,0,0]\n# disturbance:\nm = [.1,0,0,0,0,0]\n#joined together (first theta reference, second disturbance, then theta measured):\nvariables = [thref, m, th]\n\n# variables of controller:\n_K = 20\n_taui = 10\n_taud = 1\n\nnew_flag_value = [True, 0] # flag for displaying old value of th, before th_ref was changed [flag, angle]\n\n#slider widgets:\nth_ref_widget = widgets.FloatSlider(value=variables[0][0],min=0.0,max=2*np.pi,step=.01,description=r'\\(\\theta_{ref} \\) [rad]',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\nm_widget = widgets.FloatSlider(value=variables[1][0],min=-.3,max=.3,step=.01,description=r'\\(d_{w} \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\nK_widget = widgets.FloatSlider(value=_K,min=0.0,max=40,step=.1,description=r'\\(K_p \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.1f')\ntaui_widget = widgets.FloatSlider(value=_taui,min=0.01,max=60,step=.01,description=r'\\(K_i \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\ntaud_widget = widgets.FloatSlider(value=_taud,min=0.0,max=5,step=.1,description=r'\\(K_d \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\n#interact(set_coefficients, setK=K_widget, setthref=th_ref_widget, setm=m_widget, settaui=taui_widget, settaud=taud_widget)\n\n#checkboxes\n#checkbox_reset_antenna = widgets.Checkbox(value=False, description='Reset schematic representation of antenna when type of controller is changed', disabled=False)\n#checkbox_reset_graph = widgets.Checkbox(value=False, description='Reset graph when type of controller is changed', disabled=False)\n\ncheckbox_reset_antenna = widgets.Checkbox(value=False, disabled=False, layout=Layout(width='100px'))\nlabel_scheme = widgets.Label('Resetta la rappresentazione schematica dell\\'antenna quando viene cambiato il tipo di controller', layout=Layout(width='600px'))\nbox1 = widgets.HBox([checkbox_reset_antenna, label_scheme])\n \ncheckbox_reset_graph = widgets.Checkbox(value=False, disabled=False, layout=Layout(width='100px'))\nlabel_graph = widgets.Label('Resetta il grafico temporale quando viene cambiato il tipo di controller', layout=Layout(width='500px'))\nbox2 = widgets.HBox([checkbox_reset_graph, label_graph])\n\nstyle = {'description_width': 'initial'}\n\n#buttons:\ndef buttons_clicked(event):\n global controller_type, equation, list_th, list_th_ref, list_time\n controller_type = buttons.options[buttons.index]\n if controller_type =='P':\n taui_widget.disabled=True\n taud_widget.disabled=True\n equation = '$Kp$'\n if controller_type =='PI':\n taui_widget.disabled=False\n taud_widget.disabled=True\n equation = '$Kp\\,(1+\\dfrac{1}{T_{i}\\,s})$'\n if controller_type =='PID':\n taui_widget.disabled=False\n taud_widget.disabled=False\n equation = '$Kp\\,(1+\\dfrac{1}{T_{i}\\,s}+\\dfrac{T_{d}\\,s}{a\\,T_{d}\\,s+1})$'\n if checkbox_reset_antenna.value:\n #reset values to zero:\n for i in range(len(variables)):\n for j in range(1, len(variables[i])):\n variables[i][j] = 0\n variables[-1][0] = 0\n if checkbox_reset_graph.value:\n list_th = []\n list_th_ref = []\n list_time = []\n \nbuttons = widgets.ToggleButtons(\n options=['P', 'PI', 'PID'],\n description='Seleziona il tipo di controller:',\n disabled=False,\n style=style)\nbuttons.observe(buttons_clicked)\n\n\n#updating values\ndef set_values(event):\n global _K, _taui, _taud\n if event['name'] != 'value':\n return\n if th_ref_widget.value != variables[0][0] and not new_flag_value[0]:\n new_flag_value[0] = True\n new_flag_value[1] = variables[-1][0]\n \n variables[0][0] = th_ref_widget.value\n variables[1][0] = m_widget.value\n _K = K_widget.value\n _taui = taui_widget.value\n _taud = taud_widget.value\nth_ref_widget.observe(set_values)\nm_widget.observe(set_values)\nK_widget.observe(set_values)\ntaui_widget.observe(set_values)\ntaud_widget.observe(set_values)\n\n#displaying widgets:\ndisplay(buttons)\nvbox1 = widgets.VBox([th_ref_widget, m_widget, K_widget, taui_widget, taud_widget])\nvbox2 = widgets.VBox([box1, box2])\nhbox = widgets.HBox([vbox1, vbox2])\ndisplay(hbox)\n\n#setting at start:\ncontroller_type = 'P'\ntaui_widget.disabled=True\ntaud_widget.disabled=True\nequation = '$Kp$'\nset_values({'name':'value'})\n\n#lists for graph in time:\nlist_time = []\nlist_th = []\nlist_th_ref = []\n\n#previous th before change of th_ref:\nprev_th = 0\n\ncycles_flag = True\n\ndef update_figure(i_time):\n global cycles_flag, variables, _K, controller_type, equation\n \n if cycles_flag == True:\n cycles_flag = False\n return\n \n if controller_type == 'P':\n th = calculate_next(z_transform_p)\n elif controller_type == 'PI':\n th = calculate_next(z_transform_pi)\n elif controller_type == 'PID':\n th = calculate_next(z_transform_pid)\n variables[-1][0] = th\n \n # save variables for next time step:\n for i in range(len(variables)):\n for j in reversed(range(len(variables[i])-1)):\n variables[i][j+1] = variables[i][j]\n\n list_time.append((i_time+1)*_Tv/1000)\n list_th.append(th)\n list_th_ref.append(variables[0][0])\n \n #plot:\n ax.clear()\n ax.plot([-1.5, 1.5, 1.5, -1.5], [-1.5, -1.5, 1.5, 1.5], ',', color='b')\n \n #plot line:\n ax.plot([np.cos(th)*-.5, np.cos(th)*1.5], [np.sin(th)*-.5, np.sin(th)*1.5], 'b--', linewidth=.7, alpha=.7)\n \n #plot antenna:\n center1 = 1\n center2 = 3\n d1 = 2.2\n d2 = 5.5\n x1 = center1*np.cos(th)\n y1 = center1*np.sin(th)\n x2 = center2*np.cos(th)\n y2 = center2*np.sin(th)\n arc1 = patches.Arc((x1, y1), d1, d1,\n angle=th/np.pi*180+180, theta1=-58, theta2=58, linewidth=2, color='black', alpha=.7)\n arc2 = patches.Arc((x2, y2), d2, d2,\n angle=th/np.pi*180+180, theta1=-20, theta2=20, linewidth=2, color='black', alpha=.7)\n ax.add_patch(arc1)\n ax.add_patch(arc2)\n if m_widget.value > 0:\n ax.plot(0, 0, 'r', alpha=.1, marker=r'$\\circlearrowright$',ms=150*m_widget.value)\n elif m_widget.value < 0:\n ax.plot(0, 0, 'r', alpha=.1, marker=r'$\\circlearrowleft$',ms=-150*m_widget.value)\n ax.set_title('Rappresentazione schematica dell\\'antenna')\n\n \n #plot direction of antenna before thref change\n if abs(variables[0][0] - th) < 0.03:\n new_flag_value[0] = False\n if new_flag_value[0]:\n ax.plot([0,np.cos(new_flag_value[1])], [0, np.sin(new_flag_value[1])], 'r-.', alpha=.3, linewidth=0.5)\n #plot desired direction of antenna\n ax.plot([0,np.cos(variables[0][0])], [0, np.sin(variables[0][0])], 'g-.', alpha=.7, linewidth=0.7)\n \n ax.text(-1, 1.3, 'angolo attuale: %.2f rad' %th)\n ax.text(-1, -1.3, 'Tipo di controller:')\n ax.text(-1, -1.6, equation)\n \n ax.set_aspect('equal', adjustable='datalim')\n ax.set_xlim(-1.5,1.5)\n ax.set_ylim(-1.5,1.5)\n ax.axis('off')\n \n graph.clear()\n graph.plot(list_time, list_th_ref, 'g', label='angolo desiderato')\n graph.plot(list_time, list_th, 'b', label='angolo attuale') \n graph.set_xlabel('$t$ [s]')\n graph.set_ylabel('$\\\\theta$ [rad]')\n graph.legend(loc=4, fontsize=8)\n graph.set_title('Azimut vs. tempo')\n \n plt.show()\n\nani = animation.FuncAnimation(fig, update_figure, interval=_Tv)\n```\n\n\n \n\n\n\n\n\n\n\n ToggleButtons(description='Seleziona il tipo di controller:', options=('P', 'PI', 'PID'), style=ToggleButtonsS…\n\n\n\n HBox(children=(VBox(children=(FloatSlider(value=1.0, description='\\\\(\\\\theta_{ref} \\\\) [rad]', max=6.283185307…\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7cc0a913d0b5c33ba15998ef5376d0a9b4bbadcd", "size": 132087, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/02/.ipynb_checkpoints/TD-02-Sistema-di-controllo-della-posizione-azimutale-di-una-antenna-checkpoint.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_it/examples/02/.ipynb_checkpoints/TD-02-Sistema-di-controllo-della-posizione-azimutale-di-una-antenna-checkpoint.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_it/examples/02/.ipynb_checkpoints/TD-02-Sistema-di-controllo-della-posizione-azimutale-di-una-antenna-checkpoint.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": 99.388261851, "max_line_length": 76723, "alphanum_fraction": 0.7737778888, "converted": true, "num_tokens": 4183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.22815650216092534, "lm_q1q2_score": 0.09639717630785785}} {"text": "```javascript\n%%javascript\n MathJax.Hub.Config({\n TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n });\n```\n\n\n \n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n
''')\n```\n\n\n\n\n\n
\n\n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n\n\n\n''')\n```\n\n\n\n\n\n\n\n\n\n\n\n\n# Benchmark Problem 7: MMS Allen-Cahn\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''{% include jupyter_benchmark_table.html num=\"[7]\" revision=0 %}''')\n```\n\n\n\n\n{% include jupyter_benchmark_table.html num=\"[7]\" revision=0 %}\n\n\n\n

Table of Contents

\n\n\n\nSee the journal publication entitled [\"Benchmark problems for numerical implementations of phase field models\"][benchmark_paper] for more details about the benchmark problems. Furthermore, read [the extended essay][benchmarks] for a discussion about the need for benchmark problems.\n\n[benchmarks]: ../\n[benchmark_paper]: http://dx.doi.org/10.1016/j.commatsci.2016.09.022\n\n# Overview\n\nThe Method of Manufactured Solutions (MMS) is a powerful technique for verifying the accuracy of a simulation code. In the MMS, one picks a desired solution to the problem at the outset, the \"manufactured solution\", and then determines the governing equation that will result in that solution. With the exact analytical form of the solution in hand, when the governing equation is solved using a particular simulation code, the deviation from the expected solution can be determined exactly. This deviation can be converted into an error metric to rigously quantify the error for a calculation. This error can be used to determine the order of accuracy of the simulation results to verify simulation codes. It can also be used to compare the computational efficiency of different codes or different approaches for a particular code at a certain level of error. Furthermore, the spatial/temporal distribution can give insight into the conditions resulting in the largest error (high gradients, changes in mesh resolution, etc.).\n\nAfter choosing a manufactured solution, the governing equation must be modified to force the solution to equal the manufactured solution. This is accomplished by taking the nominal equation that is to be solved (e.g. Allen-Cahn equation, Cahn-Hilliard equation, Fick's second law, Laplace equation) and adding a source term. This source term is determined by plugging the manufactured solution into the nominal governing equation and setting the source term equal to the residual. Thus, the manufactured solution satisfies the MMS governing equation (the nominal governing equation plus the source term). A more detailed discussion of MMS can be found in [the report by Salari and Knupp][mms_report].\n\nIn this benchmark problem, the objective is to use the MMS to rigorously verify phase field simulation codes and then provide a basis of comparison for the computational performance between codes and for various settings for a single code, as discussed above. To this end, the benchmark problem was chosen as a balance between two factors: simplicity, to minimize the development effort required to solve the benchmark, and transferability to a real phase field system of physical interest. \n\n[mms_report]: http://prod.sandia.gov/techlib/access-control.cgi/2000/001444.pdf\n\n# Governing equation and manufactured solution\nFor this benchmark problem, we use a simple Allen-Cahn equation as the governing equation\n\n$$\\begin{equation}\n\\frac{\\partial \\eta}{\\partial t} = - \\left[ 4 \\eta \\left(\\eta - 1 \\right) \\left(\\eta-\\frac{1}{2} \\right) - \\kappa \\nabla^2 \\eta \\right] + S(x,y,t) \n\\end{equation}$$\n\nwhere $S(x,y,t)$ is the MMS source term and $\\kappa$ is a constant parameter (the gradient energy coefficient). \n\nThe manufactured solution, $\\eta_{sol}$ is a hyperbolic tangent function, shifted to vary between 0 and 1, with the $x$ position of the middle of the interface ($\\eta_{sol}=0.5$) given by the function $\\alpha(x,t)$:\n\n$$\\begin{equation}\n\\eta_{sol}(x,y,t) = \\frac{1}{2}\\left[ 1 - \\tanh\\left( \\frac{y-\\alpha(x,t)}{\\sqrt{2 \\kappa}} \\right) \\right] \n\\end{equation}$$\n\n$$\\begin{equation}\n\\alpha(x,t) = \\frac{1}{4} + A_1 t \\sin\\left(B_1 x \\right) + A_2 \\sin \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\nwhere $A_1$, $B_1$, $A_2$, $B_2$, and $C_2$ are constant parameters. \n\nThis manufactured solution is an equilbrium solution of the governing equation, when $S(x,y,t)=0$ and $\\alpha(x,t)$ is constant. The closeness of this manufactured solution to a solution of the nominal governing equation increases the likihood that the behavior of simulation codes when solving this benchmark problem is representive of the solution of the regular Allen-Cahn equation (i.e. without the source term). The form of $\\alpha(x,t)$ was chosen to yield complex behavior while still retaining a (somewhat) simple functional form. The two spatial sinusoidal terms introduce two controllable length scales to the interfacial shape. Summing them gives a \"beat\" pattern with a period longer than the period of either individual term, permitting a domain size that is larger than the wavelength of the sinusoids without a repeating pattern. The temporal sinusoidal term introduces a controllable time scale to the interfacial shape in addition to the phase transformation time scale, while the linear temporal dependence of the other term ensures that the sinusoidal term can go through multiple periods without $\\eta_{sol}$ repeating itself.\n\nInserting the manufactured solution into the governing equation and solving for $S(x,y,t)$ yields:\n\n$$\\begin{equation}\nS(x,y,t) = \\frac{\\text{sech}^2 \\left[ \\frac{y-\\alpha(x,t)}{\\sqrt{2 \\kappa}} \\right]}{4 \\sqrt{\\kappa}} \\left[-2\\sqrt{\\kappa} \\tanh \\left[\\frac{y-\\alpha(x,t)}{\\sqrt{2 \\kappa}} \\right] \\left(\\frac{\\partial \\alpha(x,t)}{\\partial x} \\right)^2+\\sqrt{2} \\left[ \\frac{\\partial \\alpha(x,t)}{\\partial t}-\\kappa \\frac{\\partial^2 \\alpha(x,t)}{\\partial x^2} \\right] \\right]\n\\end{equation}$$\n\nwhere $\\alpha(x,t)$ is given above and where:\n\n$$\\begin{equation}\n\\frac{\\partial \\alpha(x,t)}{\\partial x} = A_1 B_1 t \\cos\\left(B_1 x\\right) + A_2 B_2 \\cos \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\n$$\\begin{equation}\n\\frac{\\partial^2 \\alpha(x,t)}{\\partial x^2} = -A_1 B_1^2 t \\sin\\left(B_1 x\\right) - A_2 B_2^2 \\sin \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\n$$\\begin{equation}\n\\frac{\\partial \\alpha(x,t)}{\\partial t} = A_1 \\sin\\left(B_1 x\\right) + A_2 C_2 \\cos \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\n** *N.B.*: Don't transcribe these equations. Please download the appropriate files from the [Appendix](#Appendix) **.\n\n# Domain geometry, boundary conditions, initial conditions, and stopping condition\nThe domain geometry is a rectangle that spans [0, 1] in $x$ and [0, 0.5] in $y$. This elongated domain was chosen to allow multiple peaks and valleys in $\\eta_{sol}$ without stretching the interface too much in the $y$ direction (which causes the thickness of the interface to change) or having large regions where $\\eta_{sol}$ never deviates from 0 or 1. Periodic boundary conditions are applied along the $x = 0$ and the $x = 1$ boundaries to accomodate the periodicity of $\\alpha(x,t)$. Dirichlet boundary conditions of $\\eta$ = 1 and $\\eta$ = 0 are applied along the $y = 0$ and the $y = 0.5$ boundaries, respectively. These boundary conditions are chosen to be consistent with $\\eta_{sol}(x,y,t)$. The initial condition is the manufactured solution at $t = 0$:\n\n$$\n\\begin{equation}\n\\eta_{sol}(x,y,0) = \\frac{1}{2}\\left[ 1 - \\tanh\\left( \\frac{y-\\left(\\frac{1}{4}+A_2 \\sin(B_2 x) \\right)}{\\sqrt{2 \\kappa}} \\right) \\right] \n\\end{equation}\n$$\n\nThe stopping condition for all calculations is when t = 8 time units, which was chosen to let $\\alpha(x,t)$ evolve substantially, while still being slower than the characteristic time for the phase evolution (determined by the CFL condition for a uniform mesh with a reasonable level of resolution of $\\eta_{sol}$).\n\n# Parameter values\nThe nominal parameter values for the governing equation and manufactured solution are given below. The value of $\\kappa$ will change in Part (b) in the following section and the values of $\\kappa$ and $C_2$ will change in Part (c).\n\n| Parameter | Value |\n|-----------|-------|\n| $\\kappa$ | 0.0004|\n| $A_1$ | 0.0075|\n| $B_1$ | $8.0 \\pi$ |\n| $A_2$ | 0.03 |\n| $B_2$ | $22.0 \\pi$ |\n| $C_2$ | $0.0625 \\pi$|\n\n# Benchmark simulation instructions\nThis section describes three sets of tests to conduct using the MMS problem specified above. The primary purpose of the first test is provide a computationally inexpensive problem to verify a simulation code. The second and third tests are more computationally demanding and are primarily designed to serve as a basis for performance comparisons.\n\n## Part (a)\nThe objective of this test is to verify the accuracy of your simulation code in both time and space. Here, we make use of convergence tests, where either the mesh size (or grid point spacing) or the time step size is systematically changed to determine the response of the error to these quantities. Once a convergence test is completed the order of accuracy can be calculated from the result. The order of accuracy can be compared to the theoretical order of accuracy for the numerical method employed in the simulation. If the two match (to a reasonable degree), then one can be confident that the simulation code is working as expected. The remainder of this subsection will give instructions for convergence tests for this MMS problem.\n\nImplement the MMS problem specified above using the simulation code of your choice. Perform a spatial convergence test by running the simulation for a variety of mesh sizes. For each simulation, determine the discrete $L_2$ norm of the error at $t=8$:\n\n$$\\begin{equation}\n L_2 = \\sqrt{\\sum\\limits_{x,y}\\left(\\eta^{t=8}_{x,y} - \\eta_{sol}(x,y,8)\\right)^2 \\Delta x \\Delta y}\n\\end{equation}$$\n\nFor all of these simulations, verify that the time step is small enough that any temporal error is much smaller that the total error. This can be accomplished by decreasing the time step until it has minimal effect on the error. Ensure that at least three simulation results have $L_2$ errors in the range $[5\\times10^{-3}, 1\\times10^{-4}]$, attempting to cover as much of that range as possible/practical. This maximum and minimum errors in the range roughly represent a poorly resolved simulation and a very well-resolved simulation.\n\nSave the effective element size, $h$, and the $L_2$ error for each simulation.\n[Archive this data](https://github.com/usnistgov/pfhub/issues/491) in a\nCSV or JSON file, using one column (or key) each for $h$ and $L_2$. \nCalculate the effective element size as the square root of the area of\nthe finest part of the mesh for nonuniform meshes. For irregular meshes\nwith continuous distributions of element sizes, approximate the effective\nelement size as the average of the square root of the area of the smallest\n5% of the elements. Then [submit your results on the PFHub website](https://pages.nist.gov/pfhub/simulations/upload_form/) as a 2D data set with the effective mesh size as the x-axis column and the $L_2$ error as the y-axis column.\n\nNext, confirm that the observed order of accuracy is approximately equal to the expected value. Calculate the order of accuracy, $p$, with a least squares fit of the following function:\n\n$$\\begin{equation}\n \\log(E)=p \\log(R) + b\n\\end{equation}$$\n\nwhere $E$ is the $L_2$ error, $R$ is the effective element size, and b is an intercept. Deviations of ±0.2 or more from the theoretical value are to be expected (depending on the range of errors considered and other factors).\n\nFinally, perform a similar convergence test, but for the time step, systematically changing the time step and recording the $L_2$ error. Use a time step that does not vary over the course of any single simulation. Verify that the spatial discretization error is small enough that it does not substantially contribute to the total error. Once again, ensure that at least three simulations have $L_2$ errors in the range $[5\\times10^{-3}, 1\\times10^{-4}]$, attempting to cover as much of that range as possible/practical. [Archive the effective mesh size and $L_2$ error](https://github.com/usnistgov/pfhub/issues/491) for each individual simulation in a CSV or JSON file. [Submit your results to the PFHub website](https://pages.nist.gov/pfhub/simulations/upload_form/) as a 2D data set with the time step size as the x-axis column and the $L_2$ error as the y-axis column. Confirm that the observed order of accuracy is approximately equal to the expected value.\n\n## Part (b)\nNow that your code has been verified in (a), the objective of this part is to determine the computational performance of your code at various levels of error. These results can then be used to objectively compare the performance between codes or settings within the same code. To make the problem more computationally demanding and stress solvers more than in (a), decrease $\\kappa$ by a factor of $256$ to $1.5625\\times10^{-6}$. This change will reduce the interfacial thickness by a factor of $16$.\n\nRun a series of simulations, attempting to optimize solver parameters (mesh, time step, tolerances, etc.) to minimize the required computational resources for at least three levels of $L_2$ error in range $[5\\times10^{-3}, 1\\times10^{-5}]$. Use the same CPU and processor type for all simulations. For the best of these simulations, save the wall time (in seconds), number of computing cores, normalized computing cost (wall time in seconds $\\times$ number of cores $\\times$ nominal core speed $/$ 2 GHz), maximum memory usage, and $L_2$ error at $t=8$ for each individual simulation. [Archive this data](https://github.com/usnistgov/pfhub/issues/491) in a\nCSV or JSON file with one column (or key) for each of the quantities mentioned above. [Submit your results to the PFHub website](https://pages.nist.gov/pfhub/simulations/upload_form/) as two 2D data sets. For the first data set use the $L_2$ error as the x-axis column and the normalized computational cost as the y-axis column. For the second data set, use the $L_2$ error as the x-axis column and the wall time as the y-axis column.\n\n## Part (c)\nThis final part is designed to stress time integrators even further by increasing the rate of change of $\\alpha(x,t)$. Increase $C_2$ to $0.5$. Keep $\\kappa= 1.5625\\times10^{-6}$ from (b).\n\nRepeat the process from (b), uploading the wall time, number of computing cores, processor speed, normalized computing cost, maximum memory usage, and $L_2$ error at $t=8$ to the PFHub website.\n\n# Submission Guidelines\n\n## Part (a) Guidelines\n\nTwo data items are required in the \"Data Files\" section of the [upload form]. The data items should be labeled as `spatial` and `temporal` in the `Short name of data` box. The 2D radio button should be checked and the columns corresponding to the x-axis (either $\\Delta t$ or $\\Delta x$) and the y-axis ($e_{L2}$) should be labeled correctly for each CSV file. The CSV file for the spatial data should have the form\n\n```\nmesh_size,L2_error\n0.002604167,2.55E-06\n0.00390625,6.26E-06\n...\n```\n\nand the CSV file for the temporal data should have the form\n\n```\ntime_step,L2_error\n5.00E-04,5.80162E-06\n4.00E-04,4.69709E-06\n...\n\n```\n\n\n## Parts (b) and (c) Guidelines\n\nTwo data items are required in the \"Data Files\" section of the [upload form]. The data items should be labeled as `cost` and `time` in the `Short name of data` box. The 2D radio button should be checked and the columns corresponding to the x-axis ($e_{L2}$) and the y-axis (either $F_{\\text{cost}}$ or $t_{\\text{wall}}$) should be labeled correctly for each CSV file. The CSV file for the cost data should have the form\n\n```\ncores,wall_time,memory,error,cost\n1,1.35,25800,0.024275131,1.755\n1,4.57,39400,0.010521502,5.941\n...\n```\n\nOnly one CSV file is required with the same link in both data sections.\n\n[upload form]: ../../simulations/upload_form/\n\n# Results\nResults from this benchmark problem are displayed on the [simulation result page]({{ site.baseurl }}/simulations) for different codes.\n\n# Feedback\nFeedback on this benchmark problem is appreciated. If you have questions, comments, or seek clarification, please contact the [CHiMaD phase field community]({{ site.baseurl }}/community/) through the [Gitter chat channel]({{ site.links.chat }}) or by [email]({{ site.baseurl }}/mailing_list/). If you found an error, please file an [issue on GitHub]({{ site.links.github }}/issues/new).\n\n# Appendix\n\n## Computer algebra systems\nRigorous verification of software frameworks using MMS requires posing the equation and manufacturing the solution with as much complexity as possible. This can be straight-forward, but interesting equations produce complicated source terms. To streamline the MMS workflow, it is strongly recommended that you use a CAS such as SymPy, Maple, or Mathematica to generate source equations and turn it into executable code automatically. For accessibility, we will use [SymPy](http://www.sympy.org/), but so long as vector calculus is supported, CAS will do.\n\n## Source term\n\n\n```python\n# Sympy code to generate expressions for PFHub Problem 7 (MMS)\n\nfrom sympy import symbols, simplify\nfrom sympy import sin, cos, cosh, tanh, sqrt\nfrom sympy.physics.vector import divergence, gradient, ReferenceFrame, time_derivative\nfrom sympy.utilities.codegen import codegen\nfrom sympy.abc import kappa, S, x, y, t\n\n# Spatial coordinates: x=R[0], y=R[1], z=R[2]\nR = ReferenceFrame('R')\n\n# sinusoid amplitudes\nA1, A2 = symbols('A1 A2')\nB1, B2 = symbols('B1 B2')\nC2 = symbols('C2')\n\n# Define interface offset (alpha)\nalpha = 0.25 + A1 * t * sin(B1 * R[0]) \\\n + A2 * sin(B2 * R[0] + C2 * t)\n\n# Define the solution equation (eta)\neta = 0.5 * (1 - tanh((R[1] - alpha) / sqrt(2*kappa)))\n\n# Compute the source term from the equation of motion\nsource = simplify(time_derivative(eta, R)\n + 4 * eta * (eta - 1) * (eta - 1/2)\n - kappa * divergence(gradient(eta, R), R))\n\n# Replace R[i] with (x, y)\nalpha = alpha.subs({R[0]: x, R[1]: y})\neta = eta.subs({R[0]: x, R[1]: y})\neta0 = eta.subs(t, 0)\nsource = source.subs({R[0]: x, R[1]: y})\n\nprint(\"alpha =\", alpha, \"\\n\")\nprint(\"eta =\", eta, \"\\n\")\nprint(\"eta0 =\", eta0, \"\\n\")\nprint(\"S =\", source)\n```\n\n alpha = A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) + 0.25 \n \n eta = -0.5*tanh(sqrt(2)*(-A1*t*sin(B1*x) - A2*sin(B2*x + C2*t) + y - 0.25)/(2*sqrt(kappa))) + 0.5 \n \n eta0 = -0.5*tanh(sqrt(2)*(-A2*sin(B2*x) + y - 0.25)/(2*sqrt(kappa))) + 0.5 \n \n S = -(tanh(sqrt(2)*(A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25)/(2*sqrt(kappa)))**2 - 1)*(0.5*sqrt(kappa)*((A1*B1*t*cos(B1*x) + A2*B2*cos(B2*x + C2*t))**2 + 1)*tanh(sqrt(2)*(A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25)/(2*sqrt(kappa))) - 0.5*sqrt(kappa)*tanh(sqrt(2)*(A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25)/(2*sqrt(kappa))) + 0.25*sqrt(2)*kappa*(A1*B1**2*t*sin(B1*x) + A2*B2**2*sin(B2*x + C2*t)) + 0.25*sqrt(2)*(A1*sin(B1*x) + A2*C2*cos(B2*x + C2*t)))/sqrt(kappa)\n\n\n## Code\n\n### Python\n\nCopy the first cell under Source Term directly into your program.\nFor a performance boost, convert the expressions into lambda functions:\n\n```python\nfrom sympy.utilities.lambdify import lambdify\n\napy = lambdify([x, y], alpha, modules='sympy')\nepy = lambdify([x, y], eta, modules='sympy')\nipy = lambdify([x, y], eta0, modules='sympy')\nSpy = lambdify([x, y], S, modules='sympy')\n```\n\n> Note: Click \"Code Toggle\" at the top of the page to see the Python expressions.\n\n### C\n\n\n```python\n[(c_name, code), (h_name, header)] = \\\ncodegen([(\"alpha\", alpha),\n (\"eta\", eta),\n (\"eta0\", eta),\n (\"S\", S)],\n language=\"C\",\n prefix=\"manufactured\",\n project=\"PFHub\")\nprint(\"manufactured.h:\\n\")\nprint(header)\nprint(\"\\nmanufactured.c:\\n\")\nprint(code)\n```\n\n manufactured.h:\n \n /******************************************************************************\n * Code generated with sympy 1.2 *\n * *\n * See http://www.sympy.org/ for more information. *\n * *\n * This file is part of 'PFHub' *\n ******************************************************************************/\n \n \n #ifndef PFHUB__MANUFACTURED__H\n #define PFHUB__MANUFACTURED__H\n \n double alpha(double A1, double A2, double B1, double B2, double C2, double t, double x);\n double eta(double A1, double A2, double B1, double B2, double C2, double kappa, double t, double x, double y);\n double eta0(double A1, double A2, double B1, double B2, double C2, double kappa, double t, double x, double y);\n double S(double S);\n \n #endif\n \n \n \n manufactured.c:\n \n /******************************************************************************\n * Code generated with sympy 1.2 *\n * *\n * See http://www.sympy.org/ for more information. *\n * *\n * This file is part of 'PFHub' *\n ******************************************************************************/\n #include \"manufactured.h\"\n #include \n \n double alpha(double A1, double A2, double B1, double B2, double C2, double t, double x) {\n \n double alpha_result;\n alpha_result = A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) + 0.25;\n return alpha_result;\n \n }\n \n double eta(double A1, double A2, double B1, double B2, double C2, double kappa, double t, double x, double y) {\n \n double eta_result;\n eta_result = -0.5*tanh((1.0/2.0)*M_SQRT2*(-A1*t*sin(B1*x) - A2*sin(B2*x + C2*t) + y - 0.25)/sqrt(kappa)) + 0.5;\n return eta_result;\n \n }\n \n double eta0(double A1, double A2, double B1, double B2, double C2, double kappa, double t, double x, double y) {\n \n double eta0_result;\n eta0_result = -0.5*tanh((1.0/2.0)*M_SQRT2*(-A1*t*sin(B1*x) - A2*sin(B2*x + C2*t) + y - 0.25)/sqrt(kappa)) + 0.5;\n return eta0_result;\n \n }\n \n double S(double S) {\n \n double S_result;\n S_result = S;\n return S_result;\n \n }\n \n\n\n### Fortran\n\n\n```python\n[(f_name, code), (f_name, header)] = \\\ncodegen([(\"alpha\", alpha),\n (\"eta\", eta),\n (\"eta0\", eta),\n (\"S\", S)],\n language=\"f95\",\n prefix=\"manufactured\",\n project=\"PFHub\")\n\nprint(\"manufactured.f:\\n\")\nprint(code)\n```\n\n manufactured.f:\n \n !******************************************************************************\n !* Code generated with sympy 1.2 *\n !* *\n !* See http://www.sympy.org/ for more information. *\n !* *\n !* This file is part of 'PFHub' *\n !******************************************************************************\n \n REAL*8 function alpha(A1, A2, B1, B2, C2, t, x)\n implicit none\n REAL*8, intent(in) :: A1\n REAL*8, intent(in) :: A2\n REAL*8, intent(in) :: B1\n REAL*8, intent(in) :: B2\n REAL*8, intent(in) :: C2\n REAL*8, intent(in) :: t\n REAL*8, intent(in) :: x\n \n alpha = A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) + 0.25d0\n \n end function\n \n REAL*8 function eta(A1, A2, B1, B2, C2, kappa, t, x, y)\n implicit none\n REAL*8, intent(in) :: A1\n REAL*8, intent(in) :: A2\n REAL*8, intent(in) :: B1\n REAL*8, intent(in) :: B2\n REAL*8, intent(in) :: C2\n REAL*8, intent(in) :: kappa\n REAL*8, intent(in) :: t\n REAL*8, intent(in) :: x\n REAL*8, intent(in) :: y\n \n eta = -0.5d0*tanh(0.70710678118654752d0*kappa**(-0.5d0)*(-A1*t*sin(B1*x &\n ) - A2*sin(B2*x + C2*t) + y - 0.25d0)) + 0.5d0\n \n end function\n \n REAL*8 function eta0(A1, A2, B1, B2, C2, kappa, t, x, y)\n implicit none\n REAL*8, intent(in) :: A1\n REAL*8, intent(in) :: A2\n REAL*8, intent(in) :: B1\n REAL*8, intent(in) :: B2\n REAL*8, intent(in) :: C2\n REAL*8, intent(in) :: kappa\n REAL*8, intent(in) :: t\n REAL*8, intent(in) :: x\n REAL*8, intent(in) :: y\n \n eta0 = -0.5d0*tanh(0.70710678118654752d0*kappa**(-0.5d0)*(-A1*t*sin(B1*x &\n ) - A2*sin(B2*x + C2*t) + y - 0.25d0)) + 0.5d0\n \n end function\n \n REAL*8 function S(S)\n implicit none\n REAL*8, intent(in) :: S\n \n S = S\n \n end function\n \n\n\n### Julia\n\n\n```python\n[(f_name, code)] = \\\ncodegen([(\"alpha\", alpha),\n (\"eta\", eta),\n (\"eta0\", eta),\n (\"S\", S)],\n language=\"julia\",\n prefix=\"manufactured\",\n project=\"PFHub\")\n\nprint(\"manufactured.jl:\\n\")\nprint(code)\n```\n\n manufactured.jl:\n \n # Code generated with sympy 1.2\n #\n # See http://www.sympy.org/ for more information.\n #\n # This file is part of 'PFHub'\n \n function alpha(A1, A2, B1, B2, C2, t, x)\n \n out1 = A1.*t.*sin(B1.*x) + A2.*sin(B2.*x + C2.*t) + 0.25\n \n return out1\n end\n \n function eta(A1, A2, B1, B2, C2, kappa, t, x, y)\n \n out1 = -0.5*tanh(sqrt(2)*(-A1.*t.*sin(B1.*x) - A2.*sin(B2.*x + C2.*t) + y - 0.25)./(2*sqrt(kappa))) + 0.5\n \n return out1\n end\n \n function eta0(A1, A2, B1, B2, C2, kappa, t, x, y)\n \n out1 = -0.5*tanh(sqrt(2)*(-A1.*t.*sin(B1.*x) - A2.*sin(B2.*x + C2.*t) + y - 0.25)./(2*sqrt(kappa))) + 0.5\n \n return out1\n end\n \n function S(S)\n \n out1 = S\n \n return out1\n end\n \n\n\n### Mathematica\n\n\n```python\nfrom sympy.printing import mathematica_code\n\nprint(\"alpha =\", mathematica_code(alpha), \"\\n\")\nprint(\"eta =\", mathematica_code(eta), \"\\n\")\nprint(\"eta0 =\", mathematica_code(eta0), \"\\n\")\nprint(\"S =\", mathematica_code(source), \"\\n\")\n```\n\n alpha = A1*t*Sin[B1*x] + A2*Sin[B2*x + C2*t] + 0.25 \n \n eta = -0.5*Tanh[(1/2)*2^(1/2)*(-A1*t*Sin[B1*x] - A2*Sin[B2*x + C2*t] + y - 0.25)/kappa^(1/2)] + 0.5 \n \n eta0 = -0.5*Tanh[(1/2)*2^(1/2)*(-A2*Sin[B2*x] + y - 0.25)/kappa^(1/2)] + 0.5 \n \n S = -(Tanh[(1/2)*2^(1/2)*(A1*t*Sin[B1*x] + A2*Sin[B2*x + C2*t] - y + 0.25)/kappa^(1/2)]^2 - 1)*(0.5*kappa^(1/2)*((A1*B1*t*Cos[B1*x] + A2*B2*Cos[B2*x + C2*t])^2 + 1)*Tanh[(1/2)*2^(1/2)*(A1*t*Sin[B1*x] + A2*Sin[B2*x + C2*t] - y + 0.25)/kappa^(1/2)] - 0.5*kappa^(1/2)*Tanh[(1/2)*2^(1/2)*(A1*t*Sin[B1*x] + A2*Sin[B2*x + C2*t] - y + 0.25)/kappa^(1/2)] + 0.25*2^(1/2)*kappa*(A1*B1^2*t*Sin[B1*x] + A2*B2^2*Sin[B2*x + C2*t]) + 0.25*2^(1/2)*(A1*Sin[B1*x] + A2*C2*Cos[B2*x + C2*t]))/kappa^(1/2) \n \n\n\n### Matlab\n\n\n```python\ncode = \\\ncodegen([(\"alpha\", alpha),\n (\"eta\", eta),\n (\"eta0\", eta),\n (\"S\", S)],\n language=\"octave\",\n project=\"PFHub\")\n\nprint(\"manufactured.nb:\\n\")\nfor f in code[0]:\n print(f)\n```\n\n manufactured.nb:\n \n alpha.m\n function out1 = alpha(A1, A2, B1, B2, C2, t, x)\n %ALPHA Autogenerated by sympy\n % Code generated with sympy 1.2\n %\n % See http://www.sympy.org/ for more information.\n %\n % This file is part of 'PFHub'\n \n out1 = A1.*t.*sin(B1.*x) + A2.*sin(B2.*x + C2.*t) + 0.25;\n \n end\n \n function out1 = eta(A1, A2, B1, B2, C2, kappa, t, x, y)\n \n out1 = -0.5*tanh(sqrt(2)*(-A1.*t.*sin(B1.*x) - A2.*sin(B2.*x + C2.*t) + y - 0.25)./(2*sqrt(kappa))) + 0.5;\n \n end\n \n function out1 = eta0(A1, A2, B1, B2, C2, kappa, t, x, y)\n \n out1 = -0.5*tanh(sqrt(2)*(-A1.*t.*sin(B1.*x) - A2.*sin(B2.*x + C2.*t) + y - 0.25)./(2*sqrt(kappa))) + 0.5;\n \n end\n \n function out1 = S(S)\n \n out1 = S;\n \n end\n \n\n", "meta": {"hexsha": "56be1dc2a24c40ef013d280bc05d7cd39e8809db", "size": 43490, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "benchmarks/benchmark7.ipynb", "max_stars_repo_name": "wd15/chimad-phase-field", "max_stars_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "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": "benchmarks/benchmark7.ipynb", "max_issues_repo_name": "wd15/chimad-phase-field", "max_issues_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-02-06T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-12T17:39:56.000Z", "max_forks_repo_path": "benchmarks/benchmark7.ipynb", "max_forks_repo_name": "wd15/chimad-phase-field", "max_forks_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "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": 47.4263904035, "max_line_length": 4297, "alphanum_fraction": 0.5609105542, "converted": true, "num_tokens": 9591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.22000709974589316, "lm_q1q2_score": 0.0963242782407142}} {"text": "# 10 Gauss積分, ガンマ函数, ベータ函数\n\n黒木玄\n\n2018-06-21\n\n* Copyright 2018 Gen Kuroki\n* License: MIT https://opensource.org/licenses/MIT\n* Repository: https://github.com/genkuroki/Calculus\n\nこのファイルは次の場所できれいに閲覧できる:\n\n* http://nbviewer.jupyter.org/github/genkuroki/Calculus/blob/master/10%20Gauss%2C%20Gamma%2C%20Beta.ipynb\n\n* https://genkuroki.github.io/documents/Calculus/10%20Gauss%2C%20Gamma%2C%20Beta.pdf\n\nこのファイルは Julia Box で利用できる.\n\n自分のパソコンにJulia言語をインストールしたい場合には\n\n* WindowsへのJulia言語のインストール\n\nを参照せよ.\n\n論理的に完璧な説明をするつもりはない. 細部のいい加減な部分は自分で訂正・修正せよ.\n\n$\n\\newcommand\\eps{\\varepsilon}\n\\newcommand\\ds{\\displaystyle}\n\\newcommand\\Z{{\\mathbb Z}}\n\\newcommand\\R{{\\mathbb R}}\n\\newcommand\\C{{\\mathbb C}}\n\\newcommand\\QED{\\text{□}}\n\\newcommand\\root{\\sqrt}\n\\newcommand\\bra{\\langle}\n\\newcommand\\ket{\\rangle}\n\\newcommand\\d{\\partial}\n\\newcommand\\sech{\\operatorname{sech}}\n\\newcommand\\cosec{\\operatorname{cosec}}\n\\newcommand\\sign{\\operatorname{sign}}\n\\newcommand\\sinc{\\operatorname{sinc}}\n\\newcommand\\real{\\operatorname{Re}}\n\\newcommand\\imag{\\operatorname{Im}}\n\\newcommand\\Li{\\operatorname{Li}}\n\\newcommand\\PROD{\\mathop{\\coprod\\kern-1.35em\\prod}}\n$\n\n

Table of Contents

\n
\n\n\n```julia\nusing Plots\ngr(); ENV[\"PLOTS_TEST\"] = \"true\"\n#clibrary(:colorcet)\nclibrary(:misc)\n\nfunction pngplot(P...; kwargs...)\n sleep(0.1)\n pngfile = tempname() * \".png\"\n savefig(plot(P...; kwargs...), pngfile)\n showimg(\"image/png\", pngfile)\nend\npngplot(; kwargs...) = pngplot(plot!(; kwargs...))\n\nshowimg(mime, fn) = open(fn) do f\n base64 = base64encode(f)\n display(\"text/html\", \"\"\"\"\"\")\nend\n\nusing SymPy\n#sympy[:init_printing](order=\"lex\") # default\n#sympy[:init_printing](order=\"rev-lex\")\n\nusing SpecialFunctions\nusing QuadGK\n```\n\n## Gauss積分\n\n### Gauss積分の公式\n\n$$\n\\int_{-\\infty}^\\infty e^{-x^2}\\,dx = \\sqrt{\\pi}\n$$\n\nを**Gauss積分の公式**と呼ぶことにする. 証明は後で行う.\n\nこのノートの筆者は大学新入生が習う積分の公式の中でこれが**最も重要**であると考えている. ガウス積分が重要だと考える理由は以下の通り.\n\n(1) この公式自体が非常に面白い形をしている. 左辺を見てもどこにも円周率は見えないが, 右辺には円周率が出て来る. しかも円周率がそのまま出て来るのではなく, その平方根が出て来る.\n\n(2) 様々な方法を使ってGauss積分の公式を証明できる.\n\n(3) Gauss積分の公式は確率論や統計学で正規分布を扱うときには必須である. 正規分布は中心極限定理によって特別に重要な役目を果たす確率分布である. \n\n(4) Gauss積分はガンマ函数に一般化される. \n\n(5) Gauss積分はLaplaceの方法の基礎である. Laplaceの方法はある種の積分の漸近挙動を調べるための最も基本的な方法であり, 解析学の応用において基本的かつ重要である.\n\n(6) 特にGauss積分で階乗に等しい積分を近似することによって, Stirlingの公式が得られる. (Stirlingの公式 $n!\\sim n^n e^{-n}\\sqrt{2\\pi n}$ の平行根の因子はGauss積分を経由して得られる.)\n\n以上のようにGauss積分は純粋数学的にも応用数学的にも基本的かつ重要である.\n\n### Gauss積分を使う簡単な計算例\n\n**問題:** 上の公式を使って, $a>0$ のとき,\n\n$$\n\\int_{-\\infty}^\\infty e^{-y^2/a}\\,dy = \\sqrt{a\\pi}\n$$\n\nとなることを示せ. \n\n**注意:** $a$ を $1/a$ で置き換えれば\n\n$$\n\\int_{-\\infty}^\\infty e^{-ay^2}\\,dy = \\sqrt{\\frac{\\pi}{a}}\n$$\n\nも得られる.\n\n**解答例:** Gauss積分の公式で $\\ds x=\\frac{y}{\\sqrt{a}}$ と置換積分すると\n\n$$\n\\sqrt{\\pi} = \\int_{-\\infty}^\\infty e^{-x^2}\\,dx =\n\\frac{1}{\\sqrt{a}}\\int_{-\\infty}^\\infty e^{-y^2/a}\\,dy\n$$\n\nなので, 両辺に $\\sqrt{a}$ をかければ示したい公式が得られる. $\\QED$\n\n**問題:** 分散 $\\sigma^2>0$, 平均 $\\mu$ の正規分布の確率密度函数 $p(x)$ が\n\n$$\np(x) = \\frac{1}{\\sqrt{2\\pi\\sigma^2}} e^{-(x-\\mu)^2/(2\\sigma^2)}\n$$\n\nで定義される. このとき\n\n$$\n\\int_{-\\infty}^\\infty p(x)\\,dx = 1\n$$\n\nとなることを示せ. (この問題より, 確率統計学においてGauss積分の公式は必須であることがわかる.)\n\n**解答例:** $x=y+\\mu$ と置換し, 上の問題の結果を使うと, \n\n$$\n\\begin{aligned}\n\\int_{-\\infty}^\\infty p(x)\\,dx &=\n\\frac{1}{\\sqrt{2\\pi\\sigma^2}} \\int_{-\\infty}^\\infty e^{-(x-\\mu)^2/(2\\sigma^2)}\\,dx =\n\\frac{1}{\\sqrt{2\\pi\\sigma^2}} \\int_{-\\infty}^\\infty e^{-y^2/(2\\sigma^2)}\\,dy \n\\\\ &=\n\\frac{1}{\\sqrt{2\\pi\\sigma^2}} \\sqrt{2\\sigma^2\\pi} = 1.\n\\qquad \\QED\n\\end{aligned}\n$$\n\n**問題(Lebesgueの収束定理の結論が成立しない場合2):** 函数列 $f_n(x)$ を\n\n$$\nf_n(x)=\\frac{1}{\\sqrt{n\\pi}}e^{-x^2/n}\n$$\n\nと定める. 以下を示せ.\n\n(1) $\\ds\\int_{-\\infty}^\\infty f_n(x)\\,dx = 1$.\n\n(2) 各 $x\\in\\R$ ごとに $\\ds\\lim_{n\\to\\infty}f_n(x)= 0$.\n\n(3) したがって $\\ds\\lim_{n\\to\\infty}\\int_{-\\infty}^\\infty f_n(x)\\,dx \\ne \\int_{-\\infty}^\\infty \\lim_{n\\to\\infty}f_n(x)\\,dx$.\n\n**解答例:** (1)はGauss積分の公式から得られる(詳細は自分で計算して確認せよ). (3)は(1)と(2)からただちに得られるので, あとは(2)のみを示せば十分である. $x\\in\\R$ を任意に取って固定する. このとき $n\\to\\infty$ で $\\dfrac{x^2}{n}\\to 0$, $\\dfrac{1}{\\sqrt{n\\pi}}\\to 0$ となるので, $f_n(x)\\to 0$ となることもわかる. $\\QED$\n\n**問題:** すぐ上の問題の函数 $f_n(x)$ のグラフを描いてみよ. \n\n**解答例:** 以下のセルのようになる. \n\n$n$ が大きくなると, $f_n(x)$ の「分布」は広く拡がる. $\\QED$\n\n\n```julia\nf(n,x) = exp(-x^2/n)/√(n*π)\nx = -10.0:0.05:10.0\nP = plot(size=(400,250))\nfor n in [1,2,3,4,5,10, 30, 100]\n plot!(x, f.(n,x), label=\"n = $n\")\nend\nP\n```\n\n\n\n\n \n\n \n\n\n\n**問題:** 次を示せ: $a>0$ と $k=0,1,2,\\ldots$ について\n\n$$\n\\int_{-\\infty}^\\infty e^{-ax^2}x^{2k}\\,dx = \n\\sqrt{\\pi}\\; \\frac{1\\cdot3\\cdots(2k-1)}{2^k} a^{-(2k+1)/2} =\n\\sqrt{\\pi}\\; \\frac{(2k)!}{2^{2k}k!} a^{-(2k+1)/2}.\n\\tag{1}\n$$\n\n**注意:** $a$ を $1/a$ で置き換えれば次も得られる:\n\n$$\n\\int_{-\\infty}^\\infty e^{-x^2/a}x^{2k}\\,dx = \n\\frac{1\\cdot3\\cdots(2k-1)}{2^k} \\sqrt{a^{2k+1}\\pi} =\n\\frac{(2k)!}{2^{2k}k!} \\sqrt{a^{2k+1}\\pi}.\n\\tag{2}\n$$\n\n**解答例:** Gauss積分の公式から得られる公式\n\n$$\n\\int_{-\\infty}^\\infty e^{-ax^2}\\,dx = \\sqrt{\\pi}\\;a^{-1/2}\n$$\n\nの両辺を $a$ で微分して $-1$ 倍する操作を繰り返すと((K)を使う),\n\n$$\n\\begin{aligned}\n&\n\\int_{-\\infty}^\\infty e^{-ax^2}x^2\\,dx = \\sqrt{\\pi}\\;\\frac{1}{2}a^{-3/2},\n\\\\ &\n\\int_{-\\infty}^\\infty e^{-ax^2}x^4\\,dx = \\sqrt{\\pi}\\;\\frac{1}{2}\\frac{3}{2}a^{-5/2},\n\\\\ &\n\\int_{-\\infty}^\\infty e^{-ax^2}x^6\\,dx = \\sqrt{\\pi}\\;\\frac{1}{2}\\frac{3}{2}\\frac{5}{2}a^{-7/2}.\n\\end{aligned}\n$$\n\n$k$ 回その操作を繰り返すと, \n\n$$\n\\int_{-\\infty}^\\infty e^{-ax^2}x^{2k}\\,dx = \n\\sqrt{\\pi}\\;\\frac{1}{2}\\frac{3}{2}\\cdots\\frac{2k-1}{2}a^{-(2k+1)/2}.\n$$\n\nこれより, (1)の前半が成立することがわかる. 後半の成立は\n\n$$\n\\frac{1\\cdot3\\cdots(2k-1)}{2^k} =\n\\frac{1\\cdot3\\cdots(2k-1)}{2^k} \\frac{2\\cdot4\\cdots(2k)}{2^k k!} =\n\\frac{(2k)!}{2^{2k}k!}\n\\tag{3}\n$$\n\nによって確認できる. $\\QED$\n\n**注意:** 奇数の積 $1\\cdot3\\cdots(2k-1)$ について(3)の計算法はよく使われる:\n\n$$\n1\\cdot3\\cdots(2k-1) = \n1\\cdot3\\cdots(2k-1) \\frac{2\\cdot4\\cdots(2k)}{2^k k!} =\n\\frac{(2k)!}{2^k k!}.\n$$\n\n例えば二項係数に関する\n\n$$\n\\begin{aligned}\n(-1)^k\\binom{-1/2}{k} &=\n(-1)^k\\frac{(-1/2)(-3/2)\\cdots(-(2k-1)/2)}{k!} \\\\ &=\n\\frac{1\\cdot3\\cdots(2k-1)}{2^k k!} =\n\\frac{(2k)!}{2^{2k}k!k!} =\n\\frac{1}{2^{2k}}\\binom{2k}{k}\n\\end{aligned}\n$$\n\nもよく出て来る. $\\QED$\n\n### Gauss分布のFourier変換\n\n$a>0$ であるとする. $e^{-x^2/a}$ 型の函数を**Gauss分布函数**と呼ぶことがある.\n\n一般に函数 $f(x)$ に対して,\n\n$$\n\\hat{f}(p) = \\int_{-\\infty}^\\infty e^{-ipx} f(x)\\,dx\n$$\n\nを $f$ の**Fourier変換**(フーリエ変換)と呼ぶ. もしも実数値函数 $f(x)$ が偶函数であれば, \n\n$$\ne^{-ipx} f(x) = f(x)\\cos(px) - i f(x)\\sin(px)\n$$\n\nの虚部は奇函数になり, その積分は消えるので\n\n$$\n\\hat{f}(p) = \\int_{-\\infty}^\\infty f(x)\\cos(px)\\,dx\n$$\n\nとなる.\n\n**問題:** $a>0$ とする. $f(x)=e^{-x^2/a}$ のFourier変換を求めよ.\n\n**解答例1:** $\\ds\\cos(px)=\\sum_{k=0}^\\infty\\frac{(-p^2)^k x^{2k}}{(2k)!}$ より,\n\n$$\n\\begin{align}\n\\hat{f}(p) &=\n\\int_{-\\infty}^\\infty e^{-x^2/a} \\cos(px)\\,dx =\n\\sum_{k=0}^\\infty\\frac{(-p^2)^k}{(2k)!}\\int_{-\\infty}^\\infty e^{-x^2/a}x^{2k}\\,dx\n\\\\ &=\n\\sum_{k=0}^\\infty\\frac{(-p^2)^k}{(2k)!}\\frac{(2k)!}{2^{2k}k!} \\sqrt{a^{2k+1}\\pi} =\n\\sqrt{a\\pi}\\sum_{k=0}^\\infty\\frac{(-ap^2/4)^k}{k!} = \\sqrt{a\\pi}\\;e^{-ap^2/4}.\n\\end{align}\n$$\n\n3つ目の等号で上の方の問題の結果を用いた. $\\QED$\n\n**解答例2:** 複素解析を用いる. 複素解析さえ認めて使えば, 形式的によりわかり易く計算できる.\n\n$$\n-\\frac{x^2}{a}-ipx = \n-\\frac{1}{a}\\left(x^2 + iapx\\right) =\n-\\frac{1}{a}\\left(\\left(x+\\frac{iap}{2}\\right)^2-\\frac{-a^2p^2}{4}\\right) =\n-\\frac{1}{a}\\left(x+\\frac{iap}{2}\\right)^2 - \\frac{ap^2}{4}\n$$\n\nと平方完成し, $\\ds x=y-\\frac{iap}{2}$ と置換すると,\n\n$$\n\\begin{aligned}\n\\hat{f}(p) &= \\int_{-\\infty}^\\infty e^{-x^2/a}e^{-ipx}\\,dx =\n\\int_{-\\infty}^\\infty e^{-(x^2/a+ipx)}\\,dx \n\\\\ &=\n\\int_{-\\infty}^\\infty \\exp\\left(-\\frac{1}{a}\\left(x+\\frac{iap}{2}\\right)^2 - \\frac{ap^2}{4}\\right)\\,dx =\ne^{-ap^2/4} \\int_{-\\infty+iap/2}^{\\infty+iap/2} e^{-y^2/a}\\,dy.\n\\end{aligned}\n$$\n\nCauchyの積分定理より,\n\n$$\n\\int_{-\\infty+iap/2}^{\\infty+iap/2} e^{-y^2/a}\\,dy =\n\\int_{-\\infty}^{\\infty} e^{-y^2/a}\\,dy = \\sqrt{a\\pi}.\n$$\n\nしたがって, \n\n$$\n\\hat{f}(p) = \\int_{-\\infty}^\\infty e^{-x^2/a}e^{-ipx}\\,dx = \\sqrt{a\\pi}\\;e^{-ap^2/4}.\n\\qquad \\QED\n$$\n\n**補足:** 複素平面上の経路 $C$ を次のように定める: まず $-R$ から $R$ に直線的に移動する. 次に $R$ から $R+iap/2$ に直線的に移動する. その次に $R+iap/2$ から $-R+iap/2$ に直線的に移動する. 最後に $-R+iap/2$ から $-R$ に直線的に移動する. これによって得られる長方形型の経路が $C$ である. 上の解答例2の中のCauchyの積分定理をこの経路 $C_R$ に適用した場合を使っている. $R\\to\\infty$ とすると, 左右の縦方向に移動する経路上での積分が $0$ に収束することを使う. $\\QED$\n\n$e^{-ax^2}$ のFourier変換については\n\n* 黒木玄, ガンマ分布の中心極限定理とStirlingの公式\n\nの第6節も参照せよ.\n\n### Gauss積分の公式の導出\n\nGauss積分の計算の仕方については\n\n* 黒木玄, ガンマ分布の中心極限定理とStirlingの公式\n\nの第7節および\n\n* 高木貞治, 解析概論, 岩波書店 (1983)\n\nの第3章§35の例5,6を参照せよ.\n\n$\\ds I = \\int_{-\\infty}^\\infty e^{-x^2}\\,dx$ とおく. $I=\\sqrt{\\pi}$ であることを示したい. そのためには\n\n$$\n\\begin{aligned}\nI^2 &= \\int_{-\\infty}^\\infty e^{-x^2}\\,dx\\cdot \\int_{-\\infty}^\\infty e^{-y^2}\\,dy\n\\\\ &=\n\\int_{-\\infty}^\\infty \\left(\\int_{-\\infty}^\\infty e^{-x^2}\\,dx\\right)e^{-y^2}\\,dy =\n\\int_{-\\infty}^\\infty\\left(\\int_{-\\infty}^\\infty e^{-(x^2+y^2)}\\,dx\\right)\\,dy\n\\end{aligned}\n$$\n\nが $\\pi$ に等しいことを証明すればよい. 上の計算の2つ目と3つ目の等号で積分の線形性(A)を用いた.\n\n#### 方法1: 高さ $z$ で輪切りにする方法\n\n$\\ds I^2 = \\int_{-\\infty}^\\infty\\left(\\int_{-\\infty}^\\infty e^{-(x^2+y^2)}\\,dx\\right)\\,dy$ は2変数函数 $z=e^{-(x^2+y^2)}$ の $xyz$ 空間内のグラフと $xy$ 平面 $z=0$ のあいだに挟まれた山型の領域の体積を意味する. \n\nなぜならば, $S(y) = \\ds \\int_{-\\infty}^\\infty e^{-(x^2+y^2)}\\,dx$ はその領域の $y$ を固定したときの切断面の面積に等しく, $\\int_{-\\infty}^\\infty S(y)\\,dy$ はその切断面の面積の積分なので領域全体の体積に等しいからである. 一般に, 長さを積分すれば面積になり、面積を積分すれば体積になる.\n\nその山型の領域の体積は高さ $z$ での切断面の面積の $z=0$ から $z=1$ までの積分に等しい. 高さ $z$ での切断面は半径 $\\sqrt{x^2+y^2}=\\sqrt{-\\log z}$ の円盤になり, その面積は $-\\pi\\log z$ になる. ゆえに\n\n$$\nI^2 = \\int_0^1 (-\\pi\\log z)\\,dz = -\\pi\\,[z\\log z - z]_0^1 = \\pi.\n$$\n\nこれより $I=\\int_{-\\infty}^\\infty e^{-x^2}\\,dx = \\sqrt{\\pi}$ であることがわかる.\n\n#### 方法2: 極座標を使う方法\n\n以下の方法は2重積分の積分変数の変換の仕方(Jacobianが出て来る)を知っておかなければ使えない. \n\n$x=r\\cos\\theta$, $y=r\\sin\\theta$ とおくと,\n\n$$\nI^2 = \\int_0^{2\\pi}d\\theta\\int_0^\\infty r e^{-r^2}\\,dr =\n2\\pi \\left[\\frac{e^{-r^2}}{-2}\\right]_0^\\infty = 2\\pi\\frac{1}{2}=\\pi.\n$$\n\nゆえに $I=\\sqrt{\\pi}$.\n\n#### 方法3: $y=x \\tan\\theta$ と変数変換する方法 \n\n$I^2$ は次のようにも表せる:\n\n$$\nI^2 = 2\\int_0^\\infty\\left(\\int_{-\\infty}^\\infty e^{-(x^2+y^2)}\\,dy\\right)\\,dx.\n$$\n\nこの積分内で $x$ は $x>0$ を動くと考える.\n\n内側の積分で積分変数を $-\\infty 0, \\quad\ndy = \\frac{x}{\\cos^2\\theta}\\,d\\theta, \\quad\nx^2+y^2 = x^2(1+\\tan^2\\theta) = \\frac{x^2}{\\cos^2\\theta}\n$$\n\nなので\n\n$$\nI^2 = 2 \\int_0^\\infty\\left(\\int_{-\\pi/2}^{\\pi/2} \\exp\\left(-\\frac{x^2}{\\cos^2\\theta}\\right)\\frac{x}{\\cos^2\\theta}\\,d\\theta\\right)\\,dx.\n$$\n\nゆえに積分の順序を交換すると((J)を使う),\n\n$$\n\\begin{aligned}\nI^2 &= 2 \\int_{-\\pi/2}^{\\pi/2}\\left(\\int_0^\\infty \\exp\\left(-\\frac{x^2}{\\cos^2\\theta}\\right)\\frac{x}{\\cos^2\\theta}\\,dx\\right)\\,d\\theta\n\\\\ &=\n2 \\int_{-\\pi/2}^{\\pi/2}\\left[\\frac{1}{-2}\\exp\\left(-\\frac{x^2}{\\cos^2\\theta}\\right)\\right]_{x=0}^{x=\\infty}\\,d\\theta =\n2 \\int_{-\\pi/2}^{\\pi/2}\\frac{1}{2}\\,d\\theta = 2\\frac{\\pi}{2} = \\pi.\n\\end{aligned}\n$$\n\nしたがって $I=\\sqrt{\\pi}$.\n\n**注意:** 極座標変換 $(x,y)=(r\\cos\\theta, r\\sin\\theta)$ が有効な場面では, $y=x\\tan\\theta$ という変数変換も有効なことが多い. $\\tan\\theta$ の幾何的な意味は「原点を通る直線の傾き」であった. その意味でも $y=x\\tan\\theta$ は自然な変数変換だと言える. $\\QED$\n\n## ガンマ函数とベータ函数\n\n### ガンマ函数とベータ函数の定義\n\n$s>0$, $p>0$, $q>0$ と仮定する. $\\Gamma(s)$ と $B(p,q)$ を次の積分で定義する:\n\n$$\n\\Gamma(s) = \\int_0^\\infty e^{-x}x^{s-1}\\,dx, \\quad\nB(p,q) = \\int_0^1 x^{p-1}(1-x)^{q-1}\\,dx.\n$$\n\n$\\Gamma(s)$ をガンマ函数と, $B(p,q)$ をベータ函数と呼ぶ.\n\n**問題(ガンマ函数のGauss積分型の表示):** 次を示せ:\n\n$$\n\\Gamma(s) = 2\\int_0^\\infty e^{-y^2} y^{2s-1}\\,dy.\n$$\n\n**解答例:** ガンマ函数の積分による定義式において $x=y^2$ と置換すると, \n\n$$\n\\Gamma(s) = \\int_0^\\infty e^{-y^2} y^{2s-2}\\,2y\\,dy = 2\\int_0^\\infty e^{-y^2} y^{2s-1}\\,dy.\n\\qquad\\QED\n$$\n\n**注意:** この公式より, ガンマ函数は本質的にGauss積分の一般化になっていることがわかる. $\\QED$\n\n\n```julia\ny = symbols(\"y\")\ns = symbols(\"s\", positive=true)\n2*integrate(e^(-y^2)*y^(2s-1), (y,0,oo))\n```\n\n\n\n\n$$\\Gamma\\left(s\\right)$$\n\n\n\n**問題:** 次を示せ: $r>0$ について\n\n$$\n\\int_0^\\infty e^{-x^r}\\,dx = \n\\frac{1}{r}\\Gamma\\left(\\frac{1}{r}\\right).\n$$\n\n**略解:** $x=t^{1/r}$ と置換すればただちに得られる. $\\QED$\n\n**注意:** ガンマ函数の函数等式(下の方で示す)もしくは部分積分によって $\\ds \\frac{1}{r}\\Gamma\\left(\\frac{1}{r}\\right)=\\Gamma\\left(1+\\frac{1}{r}\\right)$ が成立することもわかる. $\\QED$\n\n\n```julia\nx = symbols(\"x\")\nr = symbols(\"r\", positive=true)\nintegrate(e^(-x^r), (x,0,oo))\n```\n\n\n\n\n$$\\Gamma\\left(1 + \\frac{1}{r}\\right)$$\n\n\n\n**問題(ガンマ函数のスケール変換):** 次を示せ:\n\n$$\n\\int_0^\\infty e^{-x/\\theta}x^{s-1}\\,dx = \\theta^s\\Gamma(s) \\quad (\\theta>0,\\ s>0).\n$$\n\nガンマ函数はこの形式でも非常によく使われる.\n\n**解答例:** $x=\\theta y$ と置換すると, $x^{s-1}\\,dx = \\theta^s y^{s-1}\\,dy$ なので示したい公式が得られる. $\\QED$.\n\n\n```julia\nx = symbols(\"x\")\ns = symbols(\"s\", positive=true)\nt = symbols(\"t\", positive=true)\nsimplify(integrate(e^(-x/t)*x^(s-1), (x,0,oo)))\n```\n\n\n\n\n$$t^{s} \\Gamma\\left(s\\right)$$\n\n\n\n**問題(ベータ函数の別の表示):** 次を示せ:\n\n$$\nB(p,q) = \n2\\int_0^{\\pi/2} (\\cos\\theta)^{2p-1}(\\sin\\theta)^{2q-1}\\,d\\theta =\n\\int_0^\\infty \\frac{t^{p-1}}{(1+t)^{p+q}}\\,dt =\n\\frac{1}{p}\\int_0^\\infty \\frac{du}{(1+u^{1/p})^{p+q}}.\n$$\n\nベータ函数のこれらの表示もよく使われる.\n\n**解答例:** $B(p,q)=\\int_0^1 x^{p-1}(1-x)^{q-1}\\,dx$ で $x=\\cos^2\\theta$ と置換すると,\n\n$$\ndx = -2\\cos\\theta\\;\\sin\\theta\\;d\\theta\n$$\n\nより, \n\n$$\nB(p,q) = 2\\int_0^{\\pi/2} (\\cos\\theta)^{2p-1}(\\sin\\theta)^{2q-1}\\,d\\theta.\n$$\n\n$B(p,q)=\\int_0^1 x^{p-1}(1-x)^{q-1}\\,dx$ で $\\ds x=\\frac{t}{1+t}=1-\\frac{1}{1+t}$ と置換すると,\n\n$$\ndx = \\frac{dt}{1+t}\n$$\n\nより, \n\n$$\nB(p,q) = \n\\int_0^\\infty \\left(\\frac{t}{1+t}\\right)^{p-1} \\left(\\frac{1}{1+t}\\right)^{q-1}\\,\\frac{dt}{(1+t)^2} =\n\\int_0^\\infty \\frac{t^{p-1}}{(1+t)^{p+q}}\\,dt\n$$\n\nさらに $t=u^{1/p}$ と置換すると, \n\n$$\nt^{p-1}\\,dt = \\frac{1}{p} \\, du\n$$\n\nより, \n\n$$\nB(p,q) = \\int_0^\\infty \\frac{t^{p-1}}{(1+t)^{p+q}}\\,dt =\n\\frac{1}{p}\\int_0^\\infty \\frac{du}{(1+u^{1/p})^{p+q}}.\n\\qquad \\QED\n$$\n\n**問題:** 次を示せ. $a0$, $q>0$ のとき,\n\n$$\n\\int_a^b (x-a)^{p-1}(b-x)^{q-1}\\,dx = (b-a)^{p+q-1} B(p,q).\n$$\n\n**証明:** $x=(1-t)a+tb=a+(b-a)t$ と積分変数を置換すると,\n\n$$\n\\int_a^b (x-a)^{p-1}(b-x)^{q-1}\\,dx =\n\\int_0^1 ((b-a)t)^{p-1}((b-a)(1-t))^{q-1}(b-a)\\,dt = (b-a)^{p+q-1}B(p,q).\n\\qquad\\QED\n$$\n\n**例:** $\\ds B(2,2)=\\int_0^1 x(1-x)\\,dx = \\frac{1}{2}-\\frac{1}{3}=\\frac{1}{6}$ なので\n\n$$\n\\int_a^b (x-a)(b-x)\\,dx = (b-a)^3 B(2,2) = \\frac{(b-a)^3}{6}.\n\\qquad \\QED\n$$\n\n**問題:** ガンマ函数を定義する積分の被積分函数のグラフを色々な $s>0$ について描いてみよ.\n\n**解答例:** 次のセルを見よ. $\\QED$\n\n\n```julia\n# ガンマ函数の積分の被積分函数のグラフ\n\nf(s,x) = e^(-x)*x^(s-1)\nx = 0.00:0.05:30.0\nPP = []\nfor s in [1/2, 1, 2, 3, 6, 10]\n P = plot(x, f.(s,x), title=\"s = $s\", titlefontsize=10)\n push!(PP, P)\nend\nfor s in [15, 20, 30]\n x = 0:0.02:2.2s\n P = plot(x, f.(s,x), title=\"s = $s\", titlefontsize=10)\n push!(PP, P)\nend\nplot(PP[1:3]..., size=(750, 200), legend=false, layout=@layout([a b c]))\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(PP[4:6]..., size=(750, 200), legend=false, layout=@layout([a b c]))\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(PP[7:9]..., size=(750, 200), legend=false, layout=@layout([a b c]))\n```\n\n\n\n\n \n\n \n\n\n\n$s$ を大きくすると, ガンマ函数の被積分函数(を函数で割ったもの)は正規分布の確率密度函数とほとんどぴったり一致するようになる. 次のセルを見よ.\n\n\n```julia\n# f(s,x) = e^{-x} x^{s-1} / Γ(s)\n# g(s,x) = e^{-(x-s)^2/(2s)} / √(2πs)\n\nf(s,x) = e^(-x+(s-1)*log(x)-lgamma(s))\ng(s,x) = e^(-(x-s)^2/(2s)) / √(2π*s)\ns = 100\nx = 0:0.5:2s\nplot(size=(400, 250))\nplot!(title=\"y = e^(-x) x^(s-1)/Gamma(s), s = $s\", titlefontsize=11)\nplot!(x, f.(s,x), label=\"Gamma dist\", lw=2)\nplot!(x, g.(s,x), label=\"normal dist\", ls=:dash, lw=2)\n```\n\n\n\n\n \n\n \n\n\n\n**問題:** ベータ函数を定義する積分の被積分函数のグラフを色々な $p,q>0$ について描いてみよ.\n\n**解答例:** 次のセルを見よ. $\\QED$\n\n\n```julia\n# ベータ函数の積分の被積分函数のグラフ\n\nf(p,q,x) = x^(p-1)*(1-x)^(q-1)\nx = 0.002:0.002:0.998\nPP = []\nfor (p,q) in [(1/2,1/2), (1,1), (1,2), (2,2), (2,3), (2,4), (4,6), (8, 12), (16, 24)]\n y = f.(p,q,x)\n P = plot(x, y, title=\"(p,q) = ($p,$q)\", titlefontsize=10, xlims=(0,1), ylims=(0,1.05*maximum(y)))\n push!(PP, P)\nend\nplot(PP[1:3]..., size=(750, 200), legend=false, layout=@layout([a b c]))\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(PP[4:6]..., size=(750, 200), legend=false, layout=@layout([a b c]))\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(PP[7:9]..., size=(750, 200), legend=false, layout=@layout([a b c]))\n```\n\n\n\n\n \n\n \n\n\n\n$p,q$ がそれらの比を保ちながら大きくすると, ベータ函数の被積分函数をベータ函数で割ったものは正規分布の被積分函数にほとんどぴったり一致するようになる. 次のセルを見よ.\n\n\n```julia\n# f(p,q,x) = x^{p-1} (1-x)^{q-1} / B(p,q)\n# μ = p/(p+q)\n# σ² = pq/((p+q)^2(p+q+1))\n# g(μ,σ²,x) = e^{-(x-μ)^2/(2σ²)} / √(2πσ²)\n\nf(p,q,x) = x^(p-1)*(1-x)^(q-1)/beta(p,q)\ng(μ,σ²,x) = e^(-(x-μ)^2/(2*σ²)) / √(2π*σ²)\np, q = 45,55\nμ = p/(p+q)\nσ² = p*q/((p+q)^2*(p+q+1))\nx = 0.000:0.002:1.000\nplot(size=(400, 250))\nplot!(title=\"y = x^(p-1) (1-x)^(q-1) / B(p,q), (p,q) = ($p,$q)\", titlefontsize=10)\nplot!(x, f.(p,q,x), label=\"Beta dist\", lw=2)\nplot!(x, g.(μ,σ²,x), label=\"normal dist\", lw=2, ls=:dash)\n```\n\n\n\n\n \n\n \n\n\n\n### ガンマ函数の特殊値と函数等式\n\n**問題(ガンマ函数の最も簡単な特殊値):** $\\Gamma(1)=1$ と $\\Gamma(1/2)=\\sqrt{\\pi}$ を示せ.\n\n**解答例:** 前者は\n\n$$\n\\Gamma(1)=\\int_0^\\infty e^{-x}\\,dx = [-e^{-x}]_0^\\infty = 1.\n$$\n\nと容易に示される. 後者を示すためには $\\Gamma(1/2)$ がGauss積分 $\\int_{-\\infty}^\\infty e^{-y^2}\\,dy=\\sqrt{\\pi}$ に等しいことを示せばよい. $x=y^2$ で置換積分すると,\n\n$$\n\\begin{aligned}\n\\Gamma(1/2) &= \\int_0^\\infty e^{-x}x^{1/2-1}\\,dx =\n\\int_0^\\infty e^{-y^2} \\frac{1}{y} 2y\\,dy \n\\\\ &= \n2\\int_0^\\infty e^{-y^2}\\,dy =\n\\int_{-\\infty}^\\infty e^{-y^2}\\,dy = \\sqrt{\\pi}. \n\\qquad \\QED\n\\end{aligned}\n$$\n\n**注意:** 上の問題の解答より, $\\Gamma(1/2)$ は本質的にGauss積分に等しい. その意味でガンマ函数はGauss積分の一般化になっていると言える. $\\QED$\n\n**問題(ガンマ函数の函数等式):** $s>0$ のとき $\\Gamma(s+1)=s\\Gamma(s)$ となることを示せ.\n\n**解答例:** 部分積分を使う. $s>0$ と仮定する. このとき\n\n$$\n\\begin{aligned}\n\\Gamma(s+1) &=\n\\int_0^\\infty e^{-x}x^s\\,dx =\n\\int_0^\\infty (-e^{-x})'x^s\\,dx\n\\\\ &=\n\\int_0^\\infty e^{-x} (x^s)'\\,dx =\n\\int_0^\\infty e^{-x} sx^{s-1}\\,dx =\ns\\Gamma(s).\n\\end{aligned}\n$$\n\n3つ目の等号で部分積分を行った. そのとき, $x\\searrow 0$ でも $x\\to\\infty$ でも $e^{-x}x^s\\to 0$ となることを使った($s>0$ と仮定したことに注意せよ). (積分以外の項が消える.) $\\QED$\n\n**注意:** 上の問題の結果を使えば, $s< 0$, $s\\ne 0,-1,-2,\\ldots$ のとき $s+n>0$ となる整数 $n$ を取れば, \n\n$$\n\\Gamma(s) = \\frac{\\Gamma(s+n)}{s(s+1)\\cdots(s+n-1)}\n$$\n\nの右辺はwell-definedになるので, この公式によってガンマ函数を $s<0$, $s\\ne 0,-1,-2,\\ldots$ の場合に自然に拡張できる. $\\QED$ \n\n**注意(ガンマ函数は階乗の一般化):** 以上の問題の結果より, 非負の整数 $n$ について\n\n$$\n\\Gamma(n+1)=n\\Gamma(n)=n(n-1)\\Gamma(n-1)=\\cdots=n(n-1)\\cdots1\\,\\Gamma(1)=n!.\n$$\n\nすなわち, $\\Gamma(s+1)$ は階乗 $n!$ の連続変数 $s$ への拡張になっていることがわかる. $\\QED$\n\n**問題(ガンマ函数の正の半整数での値):** 次を示せ: 非負の整数 $k$ に対して\n\n$$\n\\Gamma((2k+1)/2) = \\frac{1\\cdot3\\cdots(2k-1)}{2^k}\\sqrt{\\pi} =\n\\frac{(2k)!}{2^{2k}k!}\\sqrt{\\pi}\n$$\n\n**解答例1:** ガンマ函数の函数等式と $\\Gamma(1/2)=\\sqrt{\\pi}$ より\n\n$$\n\\begin{aligned}\n\\Gamma\\left(\\frac{2k+1}{2}\\right) &=\n\\frac{2k-1}{2}\\Gamma\\left(\\frac{2k-1}{2}\\right) =\n\\frac{2k-1}{2}\\frac{2k-3}{2}\\Gamma\\left(\\frac{2k-3}{2}\\right) = \\cdots \n\\\\ &=\n\\frac{2k-1}{2}\\frac{2k-3}{2}\\cdots\\frac{1}{2}\\Gamma\\left(\\frac{1}{2}\\right) = \n\\frac{1\\cdot3\\cdots(2k-1)}{2^k}\\sqrt{\\pi}.\n\\end{aligned}\n$$\n\nこれで示したい公式の1つ目の等号は示せた. 2つ目の等号は上の方のGauss積分の応用問題で使った方法を使えば同様に示される. $\\QED$\n\n**解答例2:** ガンマ函数の $\\Gamma(s)=2\\int_0^\\infty e^{-y^2}y^{2s-1}\\,dy$ という表示を使うと,\n\n$$\n\\Gamma((2k+1)/2) = 2\\int_0^\\infty e^{-y^2} y^{2k}\\,dy = \\int_{-\\infty}^\\infty e^{-y^2} y^{2k}\\,dy\n$$\n\nなので, 上の方のGauss積分の応用問題に関する結果から欲しい公式が得られる. $\\QED$\n\n### Riemannのゼータ函数の積分表示と函数等式と負の整数と正の偶数における特殊値\n\nこの節はこのノートを最初に読むときには飛ばして読んでも構わない. ガンマ函数の理論がRiemannのゼータ函数の理論と密接に関係していることを認識しておけば問題ない. \n\nBernoulli数やBernoulli多項式に関してはノート「13 Euler-Maclaurinの和公式」により詳しい解説がある.\n\n#### Riemannのゼータ函数の積分表示1\n\n**問題(Riemannのゼータ函数の積分表示1):** 次をが成立することを示せ.\n\n$$\n\\zeta(s)=\\sum_{n=1}^\\infty \\frac{1}{n^s} = \n\\frac{1}{\\Gamma(s)}\\int_0^\\infty \\frac{x^{s-1}\\,dx}{e^x-1}\n\\quad (s>1).\n$$\n\n**注意:** $x\\to 0$ のとき $\\ds \\frac{e^x-1}{x}\\to 1$ となるので, $\\ds \\frac{x}{e^x-1}$ は $x=0$ まで連続的に拡張され, この公式の積分は\n\n$$\n\\int_0^\\infty \\frac{x^{s-1}\\,dx}{e^x-1} = \n\\int_0^\\infty \\frac{x}{e^x-1} x^{s-2}\\,dx\n$$\n\nと書けるので, $s-2 > -1$ すなわち $s>1$ ならば収束している. $\\QED$\n\n**解答例:** 上の問題の結果より, $\\ds\\frac{1}{n^s} = \\frac{1}{\\Gamma(s)}\\int_0^\\infty e^{-nx}x^{s-1}\\,dx$ なので,\n\n$$\n\\begin{aligned}\n\\zeta(s) &=\\sum_{n=1}^\\infty \\frac{1}{n^s} =\n\\frac{1}{\\Gamma(s)}\\sum_{n=1}^\\infty\\int_0^\\infty e^{-nx}x^{s-1}\\,dx\n\\\\ &=\n\\frac{1}{\\Gamma(s)}\\int_0^\\infty\\sum_{n=1}^\\infty e^{-nx}x^{s-1}\\,dx =\n\\frac{1}{\\Gamma(s)}\\int_0^\\infty \\frac{x^{s-1}\\,dx}{e^x-1}.\n\\qquad \\QED\n\\end{aligned}\n$$\n\n**定義:** Bernoulli数 $B_n$ ($n=0,1,2,\\ldots$) を次の条件によって定める:\n\n$$\n\\frac{z}{e^z-1} = \\sum_{n=1}^\\infty \\frac{B_n}{n!}z^n.\n\\qquad\\QED\n$$\n\n**問題:** $B_0=1$, $\\ds B_1=-\\frac{1}{2}$ であり, $n$ が3以上の奇数のとき $B_n=0$ となることを示せ.\n\n**解答例:** $z\\to 0$ のとき, $\\ds \\frac{z}{e^z-1}\\to 1$ より $B_0=1$ となる.\n\n$$\n\\frac{z}{e^z-1}-\\frac{z}{2} = \\frac{z}{2}\\frac{e^z+1}{e^z-1} = \n\\frac{z}{2}\\frac{e^{z/2}+e^{-z/2}}{e^{z/2}-e^{-z/2}}\n$$\n\nであることと, これが偶函数であることから, $\\ds B_1=-\\frac{1}{2}$ で $n$ が3以上の奇数ならば $B_n=0$ となることがわかる. $\\QED$\n\n**問題(Riemannのゼータ函数の積分表示1'):** 非負の整数 $N$ に対して, 次を示せ:\n\n$$\n\\zeta(s) = \n\\frac{1}{\\Gamma(s)}\\left[\n\\int_1^\\infty \\frac{x^{s-1}\\,dx}{e^x-1} +\n\\int_0^1 \\left(\\frac{x}{e^x-1} - \\sum_{k=0}^N \\frac{B_k}{k!}x^k\\right)x^{s-2}\\,dx +\n\\sum_{k=0}^N \\frac{B_k}{k!}\\frac{1}{s+k-1}\n\\right].\n$$\n\nさらに右辺の括弧の内側の2つ目の積分が $s>-N$ で絶対収束していることを示せ.\n\n**解答例:** Riemannのゼータ函数の積分表示1の公式で積分を $\\int_1^\\infty$ と $\\int_0^1$ に分けて, $k=0,1,\\ldots,N$ に対する\n\n$$\n\\ds\\int_0^1\\frac{B_k}{k!}x^{s+k-2}\\,dx = \\frac{B_k}{k!}\\frac{1}{s+k-1}\n$$\n\nを足して引けば示したい公式が得られる. \n\n$$\n\\frac{x}{e^x-1} - \\sum_{k=0}^N \\frac{B_k}{k!}x^k = O(x^{N+1})\n$$\n\nであり, $\\ds\\int_0^1 x^{N+1}x^{s-2}\\,dx=\\int_0^1 x^{s+N-1}\\,dx$ が $s>-N$ で絶対収束していることから, 右辺の括弧の内側の2つ目の積分もそこで収束している. $\\QED$\n\n**問題:** Riemannのゼータ函数の積分表示1'の右辺で $\\zeta(s)$ を $s>-N$ まで拡張しておくとき, \n\n$$\n\\zeta(0) = -\\frac{1}{2}, \\quad \\zeta(-r) = -\\frac{B_{r+1}}{r+1} \\quad (r=1,2,3,\\ldots)\n$$\n\nとなることを示せ. ($r$ が2以上の偶数のとき $B_{r+1}=0$ となることに注意せよ.)\n\n**解答例:** ガンマ函数の函数等式より,\n\n$$\n\\begin{aligned}\n\\frac{1}{\\Gamma(s)}\\frac{B_k}{k!}\\frac{1}{s+k-1} &=\n\\frac{s(s+1)\\cdots(s+k-2)(s+k-1)}{\\Gamma(s+k)}\\frac{B_k}{k!}\\frac{1}{s+k-1} \n\\\\ &=\n\\frac{s(s+1)\\cdots(s+k-2)}{\\Gamma(s+k)}\\frac{B_k}{k!}\n\\end{aligned}\n$$\n\nなので, 非負の整数 $r$ に対して, $k=r+1$ とおいて $s\\to -r$ とすると,\n\n$$\n\\frac{1}{\\Gamma(s)}\\frac{B_k}{k!}\\frac{1}{s+k-1}\\to\n(-1)^r \\frac{B_{r+1}}{r+1} =\n\\begin{cases}\n-\\dfrac{1}{2} & (r=0) \\\\\n-\\dfrac{B_{r+1}}{r+1} & (r=1,2,3,\\ldots)\n\\end{cases}.\n$$\n\nただし, 等号で, $\\ds B_1=-\\frac{1}{2}$ と $r+1$ が3以上の奇数のとき $B_{r+1}=0$ となることを使った. これをRiemannのゼータ函数の積分表示1'\n\n$$\n\\zeta(s) = \n\\frac{1}{\\Gamma(s)}\\left[\n\\int_1^\\infty \\frac{x^{s-1}\\,dx}{e^x-1} +\n\\int_0^1 \\left(\\frac{x}{e^x-1} - \\sum_{k=0}^N \\frac{B_k}{k!}x^k\\right)x^{s-2}\\,dx +\n\\sum_{k=0}^N \\frac{B_k}{k!}\\frac{1}{s+k-1}\n\\right]\n$$\n\nに適用すれば,\n\n$$\n\\zeta(0) = -\\frac{1}{2}, \\quad \\zeta(-r) = -\\frac{B_{r+1}}{r+1} \\quad (r=1,2,3,\\ldots)\n$$\n\nが得られる. $\\QED$\n\n**問題:** 次を示せ.\n\n$$\n(1-2^{1-s})\\zeta(s)=\\sum_{n=1}^\\infty \\frac{(-1)^{n-1}}{n^s} = \\frac{1}{\\Gamma(s)}\\int_0^\\infty \\frac{x^{s-1}\\,dx}{e^x+1} \\quad (s>1).\n$$\n\n**注意:** この公式の積分は $s>0$ という条件を外して, $s$ が任意の複素数にしても絶対収束している. この公式は $(1-2^{1-s})\\zeta(s)$ の複素平面全体への解析接続を与える. $\\QED$\n\n**解答例:** 1つ目の等号を示そう:\n\n$$\n\\begin{aligned}\n&\n\\zeta(s) = \\frac{1}{1^s}+\\frac{1}{2^s}+\\frac{1}{3^s}+\\frac{1}{4^s}+\\cdots,\n\\\\ &\n2^{1-s}\\zeta(s) = \\frac{2}{2^s}+\\frac{2}{4^s}+\\frac{2}{6^s}+\\frac{2}{8^s}+\\cdots,\n\\\\ &\n(1-2^{1-s})\\zeta(s) = \\frac{1}{1^s}-\\frac{1}{2^s}+\\frac{1}{3^s}-\\frac{1}{4^s}+\\cdots =\n\\sum_{n=1}^\\infty \\frac{(-1)^{n-1}}{n^s}.\n\\end{aligned}\n$$\n\n2つ目の等号を示そう. 上の問題の解答例と同様にして, $\\ds\\frac{1}{n^s} = \\frac{1}{\\Gamma(s)}\\int_0^\\infty e^{-nx}x^{s-1}\\,dx$ なので,\n\n$$\n\\begin{aligned}\n\\sum_{n=1}^\\infty \\frac{(-1)^{n-1}}{n^s} &=\n\\frac{1}{\\Gamma(s)}\\sum_{n=1}^\\infty(-1)^{n-1}\\int_0^\\infty e^{-nx}x^{s-1}\\,dx\n\\\\ &=\n\\frac{1}{\\Gamma(s)}\\int_0^\\infty\\sum_{n=1}^\\infty (-1)^{n-1}e^{-nx}x^{s-1}\\,dx =\n\\frac{1}{\\Gamma(s)}\\int_0^\\infty \\frac{x^{s-1}\\,dx}{e^x+1}\\,dx.\n\\qquad \\QED\n\\end{aligned}\n$$\n\n**注意:** 以上の計算は統計力学におけるFermi-Dirac統計に関する議論に登場する. ゼータ函数は数論の基本であるだけではなく, 統計力学的にも意味を持っている. $\\QED$\n\n#### Hurwitzのゼータ函数の積分表示1\n\n**問題:** **Hurwitzのゼータ函数** $\\zeta(s,x)$ と**Bernoulli多項式** $B_k(x)$ を\n\n$$\n\\zeta(s,x) = \\sum_{k=0}^\\infty \\frac{1}{(x+k)^s}\\quad (x>0,\\;\\; s>1), \\qquad\n\\frac{te^{xt}}{e^t-1} = \\sum_{k=0}^\\infty \\frac{B_k(x)}{k!}t^k\n$$\n\nと定める. $\\zeta(s)=\\zeta(s,1)$ なのでHurwitzのゼータ函数はRiemannのゼータ函数の拡張になっている. 以下を示せ:\n\n(1) $\\quad\\ds \\zeta(s,x) = \\frac{1}{\\Gamma(s)}\\int_0^\\infty \\frac{e^{(1-x)t}t^{s-1}}{e^t-1}\\,dt$.\n\n(2) $\\quad\\ds \\zeta(s,x) = \\frac{1}{\\Gamma(s)}\\left[\n\\int_1^\\infty \\frac{e^{(1-x)t}t^{s-1}}{e^t-1}\\,dt +\n\\int_1^\\infty\\left(\\frac{t e^{(1-x)t}}{e^t-1}-\\sum_{k=0}^N\\frac{B_k(1-x)}{k!}t^k\\right)t^{s-2}\\,dt +\n\\sum_{k=0}^N \\frac{B_k(1-x)}{k!}\\frac{1}{s+k-1}\n\\right].\n$\n\n(3) Hurwitzのゼータ函数を(2)によって $s<1$ に拡張すると, $0$ 以上の整数 $m$ について\n\n$$\n\\zeta(-m,x) = \\frac{(-1)^m B_{m+1}(1-x)}{m+1} = -\\frac{B_{m+1}(x)}{m+1}.\n$$\n\n**解答例:** (1) $x,s>0$, $k\\geqq 0$ に対して, $\\ds \\frac{1}{(x+k)^s}=\\frac{1}{\\Gamma(s)}\\int_0^\\infty e^{-(x+k)t}t^{s-1}\\,dt$ を使うと, \n\n$$\n\\begin{aligned}\n\\zeta(s,x) &=\n\\sum_{k=0}^\\infty \\frac{1}{\\Gamma(s)}\\int_0^\\infty e^{-(x+k)t}t^{s-1}\\,dt =\n\\frac{1}{\\Gamma(s)}\\int_0^\\infty \\left(\\sum_{k=0}^\\infty e^{-kt}\\right)e^{-xt}t^{s-1}\\,dt \n\\\\ &=\n\\frac{1}{\\Gamma(s)}\\int_0^\\infty \\frac{e^{-xt}t^{s-1}}{1-e^{-t}}\\,dt =\n\\frac{1}{\\Gamma(s)}\\int_0^\\infty \\frac{e^{(1-x)t}t^{s-1}}{e^t-1}\\,dt.\n\\end{aligned}\n$$\n\n(2) 上の(1)の結果の右辺の積分を $0$ から $1$ への積分と $1$ から $\\infty$ の積分に分けて, $0$ から $1$ への積分の被積分函数に $\\ds\\sum_{k=0}^N\\frac{B_k(1-x)}{k!}t^k$ を足して引き, 引いた方の積分を計算すれば, (2)の公式が得られる.\n\n(3) Bernoulli多項式の定義より, $\\ds \\left(\\frac{t e^{(1-x)t}}{e^t-1} - \\sum_{k=0}^N\\frac{B_k(1-x)}{k!}t^k\\right)t^{s-1} = O(t^{s+N-1})$ となるので, (2)の右辺の $0$ から $1$ への積分は $s>-N$ で絶対収束している. $N > m$ と仮定する. $s$ が $0$ 以下の整数に近付くと $\\ds\\frac{1}{\\Gamma(s)}\\to 0$ となり, \n\n$$\n\\frac{1}{\\Gamma(s)}\\frac{1}{s+(m+1)-1} = \\frac{s(s+1)\\cdots(s+m-1)}{\\Gamma(s+m+1)} \\to (-1)^m m! \\quad (s\\to -m)\n$$\n\nより, $s\\to -m$ のとき,\n\n$$\n\\frac{1}{\\Gamma(s)}\\frac{B_{m+1}(1-x)}{(m+1)!}\\frac{1}{s+(m+1)-1} \\to \n(-1)^m m! \\frac{B_{m+1}(1-x)}{(m+1)!} =\n\\frac{(-1)^m B_{m+1}(1-x)}{m+1}\n$$\n\nとなることから, $\\ds\\zeta(s,x)=\\frac{(-1)^m B_{m+1}(1-x)}{m+1}$ が得られる. さらに, $\\ds\\frac{te^{(1-x)t}}{e^t-1} = \\frac{(-t)e^{a(-t)}}{e^{-t}-1}$ によって, $B_k(1-x)=(-1)^k B_k(x)$ となることがわかるので, $\\ds \\frac{(-1)^m B_{m+1}(1-x)}{m+1}=-\\frac{B_{m+1}(x)}{m+1}$ も得られる. $\\QED$\n\n#### Riemannのゼータ函数の積分表示2と函数等式\n\n**問題(Riemannのゼータ函数の積分表示2):** $\\theta(t)$ を\n\n$$\n\\theta(t) = \\sum_{n=1}^\\infty e^{-\\pi n^2 t} \\quad (t>0)\n$$\n\nとおくと, 次が成立することを示せ:\n\n$$\n\\pi^{-s/2}\\Gamma(s/2)\\zeta(s) = \\int_0^\\infty \\theta(t) t^{s/2-1}\\,dt \\quad (s>2).\n$$\n\n**解答例:** \n\n$$\n\\begin{aligned}\n\\pi^{-s/2}\\Gamma(s/2)\\zeta(s) &=\\sum_{n=1}^\\infty \\frac{\\Gamma(s/2)}{(\\pi n^2)^{s/2}} =\n\\sum_{n=1}^\\infty\\int_0^\\infty e^{-\\pi n^2 t} t^{s/2-1}\\,dx\n\\\\ &=\n\\int_0^\\infty\\sum_{n=1}^\\infty e^{-\\pi n^2 t} t^{s/2-1}\\,dx =\n\\int_0^\\infty \\theta(t) t^{s/2-1}\\,dt .\n\\qquad \\QED\n\\end{aligned}\n$$\n\n**問題(Riemannのゼータ函数の積分表示2'):** 上の問題の続き. $\\theta(t)$ が\n\n$$\n1+2\\theta(1/t)=t^{1/2}(1+2\\theta(t)) \\quad (t>0)\n$$\n\nすなわち\n\n$$\n\\theta(1/t) =-\\frac{1}{2} + \\frac{1}{2}t^{1/2} + t^{1/2}\\theta(t)\n$$\n\nを満たしていることを認めて, 次を示せ:\n\n$$\n\\pi^{-s/2}\\Gamma(s/2)\\zeta(s) = \n-\\frac{1}{s}-\\frac{1}{1-s} +\n\\int_1^\\infty \\theta(t) (t^{s/2}+t^{(1-s)/2})\\,\\frac{dt}{t}.\n$$\n\n$\\theta(t)$ に関する上の公式の証明についてはノート「12 Fourier解析」におけるPoissonの和公式の解説を見よ.\n\n**注意:** 上の問題の公式の右辺の積分は $s$ が任意の複素数であってもしているので, 右辺は左辺の複素平面上への解析接続を与える. さらに, 右辺は $s$ を $1-s$ で置き換える操作で不変であるから,\n\n$$\n\\hat{\\zeta}(s) = \\pi^{-s/2}\\Gamma(s/2)\\zeta(s)\n$$\n\nとおくと, \n\n$$\n\\hat{\\zeta}(1-s) = \\hat{\\zeta}(s)\n$$\n\nが成立している. これを**ゼータ函数の函数等式**と呼ぶ. $\\QED$\n\n**解答例:** 上の問題と以下の計算を合わせれば欲しい結果が得られる. 積分区間を $0$ から $1$ と $1$ から $\\infty$ に分けて, $t=1/u$ とおくと, $t^{s/2-1}\\,dt=-u^{-s/2+1}u^{-2}\\,du=-u^{-s/2-1}\\,du$ を使うと, \n$$\n\\begin{aligned}\n&\n\\int_0^\\infty \\theta(t) t^{s/2-1}\\,dt =\n\\int_0^1 \\theta(t) t^{s/2-1}\\,dt + \n\\int_1^\\infty \\theta(t) t^{s/2}\\,dt,\n\\\\ &\n\\int_0^1 \\theta(t) t^{s/2-1}\\,dt =\n\\int_1^\\infty \\left(-\\frac{1}{2} + \\frac{1}{2}t^{1/2} + t^{1/2}\\theta(t)\\right)t^{-s/2-1}\\,dt\n\\\\ &\\qquad =\n\\int_1^\\infty\\left(\n-\\frac{1}{2}t^{-s/2-1}+\\frac{1}{2}t^{(1-s)/2-1} + \\theta(t)t^{(1-s)/2-1}\n\\right)\\,dt\n\\\\ &\\qquad =\n-\\frac{1}{s}-\\frac{1}{s-1} + \\int_1^\\infty \\theta(t)t^{(1-s)/2-1}\\,dt.\n\\end{aligned}\n$$\n\n上の問題の結果と以上の計算をまとめると, 欲しい結果が得られる. $\\QED$\n\n**問題:** 上の問題の続き. ガンマ函数が Euler's reflection formula\n\n$$\n\\Gamma(s)\\Gamma(1-s) = \\frac{\\pi}{\\sin(\\pi s)}\n$$\n\nと Legendre's duplication formula\n\n$$\n\\Gamma(s)\\Gamma(s+1/2) = 2^{1-2s}\\pi^{1/2}\\Gamma(2s)\n$$\n\nを満たしていることを認めて, 上の問題の注意におけるゼータ函数の函数等式 $\\hat\\zeta(1-s)=\\hat\\zeta(s)$ が\n\n$$\n\\zeta(s) = 2^s \\pi^{s-1}\\sin\\frac{\\pi s}{2}\\,\\Gamma(1-s)\\,\\zeta(1-s)\n$$\n\nと書き直されることを示せ.\n\nLegendre's duplication formula と Euler's reflection formula はこのノートの下の方で初等的に証明される. Euler's reflection formulaの証明についてはノート「12 Fourier解析」のガンマ函数とsinの関係の節も参照せよ.\n\n**解答例:** $\\hat\\zeta(s)=\\pi^{-s/2}\\Gamma(s/2)\\zeta(s)$, $\\hat\\zeta(s)=\\hat\\zeta(1-s)$ より,\n\n$$\n\\pi^{-s/2}\\Gamma(s/2)\\zeta(s) = \\pi^{-(1-s)/2}\\Gamma((1-s)/2)\\zeta(1-s).\n$$\n\nこれは以下のように書き直される:\n\n$$\n\\zeta(s) = \\pi^{s-1/2}\\frac{\\Gamma((1-s)/2)}{\\Gamma(s/2)}\\zeta(s).\n$$\n\n一方, Euler's reflection formula の $s$ に $s/2$ を代入すると,\n\n$$\n\\Gamma(s/2)\\Gamma(1-s/2)=\\frac{\\pi}{\\sin(\\pi s/2)},\n\\quad\\text{i.e.}\\quad\n\\frac{1}{\\Gamma(s/2)} = \\pi^{-1}\\sin\\frac{\\pi s}{2}\\Gamma(1-s/2)\n$$\n\nとなり, Legendre's duplication formula の $s$ に $(1-s)/2$ を代入すると,\n\n$$\n\\Gamma((1-s)/2)\\Gamma(1-s/2)=2^s \\pi^{1/2}\\,\\Gamma(1-s),\n$$\n\nとなるので, それらを上の公式に代入すると,\n\n$$\n\\zeta(s) = 2^s \\pi^{s-1}\\sin\\frac{\\pi s}{2}\\,\\Gamma(1-s)\\,\\zeta(1-s)\n$$\n\nが得られる. $\\QED$\n\n**問題:** $k$ が正の整数であるとき $\\ds\\zeta(-(2k-1)) = -\\frac{B_{2k}}{2k}$ であるという事実と上の問題の結果から\n\n$$\n\\zeta(2k) = \\frac{2^{2k-1}(-1)^{k-1}B_{2k}}{(2k)!}\\pi^{2k}\n$$\n\nが導かれることを示せ.\n\n**解答例:** $\\ds\\zeta(-(2k-1)) = -\\frac{B_{2k}}{2k}$ と上の問題の結果より, \n\n$$\n-\\frac{B_{2k}}{2k} = \\zeta(-(2k-1)) = 2^{-(2k-1)}\\pi^{-2k}(-1)^k(2k-1)!\\zeta(2k).\n$$\n\nこれより示したい公式が得られる. $\\QED$\n\n### ベータ函数とガンマ函数の関係\n\nベータ函数はガンマ函数によって\n\n$$\nB(p,q) = \\frac{\\Gamma(p)\\Gamma(q)}{\\Gamma(p+q)}\n\\tag{$*$}\n$$\n\nと表わされる. これを証明したい. そのためには\n\n$$\n\\Gamma(p)\\Gamma(q)=\n\\int_0^\\infty\n\\left(\n\\int_0^\\infty e^{-(x+y)} x^{p-1} y^{q-1}\\,dy\n\\right)\\,dx\n$$\n\nが\n\n$$\n\\Gamma(p+q)B(p,q)=\\int_0^\\infty e^{-z}z^{p+q-1}\\,dz\n\\,\\int_0^1 t^{p-1}(1-t)^{q-1}\\,dt\n$$\n\nに等しいことを示せばよい. ガンマ函数とベータ函数の別の表示を使えば右辺も別の形になることに注意せよ.\n\n#### 方法1: 置換積分と積分の順序交換のみを使う方法\n\nガンマ函数とベータ函数のあいだの関係式は1変数の置換積分と積分の順序交換のみを使って証明可能である. 条件 $A$ に対して, $x,y$ が条件 $A$ をみたすとき値が $1$ になり, それ以外のときに値が $0$ になる $x,y$ の函数を $1_A(x,y)$ と書くことにすると,\n$$\n\\begin{aligned}\n\\Gamma(p)\\Gamma(q) &=\n\\int_0^\\infty\n\\left(\n\\int_0^\\infty e^{-(x+y)} x^{p-1} y^{q-1}\\,dy\n\\right)\\,dx\n\\\\ &=\n\\int_0^\\infty\n\\left(\n\\int_x^\\infty e^{-z} x^{p-1} (z-x)^{q-1}\\,dz\n\\right)\\,dx\n\\\\ &=\n\\int_0^\\infty\n\\left(\n\\int_0^\\infty 1_{xガンマ分布の中心極限定理とStirlingの公式\n\nの第7.4節からの引き写しである.\n\n#### 方法2: 極座標変換を使う方法\n\nこの方法は2重積分に関する知識が必要になる. 2重積分について知らない人は次の節の別の方法を参照せよ.\n\n$x=X^2$, $y=Y^2$ と変数変換すると, \n\n$$\n\\Gamma(p)\\Gamma(q) = 4\\int_0^\\infty\\int_0^\\infty e^{-(X^2+Y^2)} X^{2p-1} Y^{2q-1}\\,dX\\,dY.\n$$\n\nさらに $X=r\\cos\\theta$, $Y=r\\sin\\theta$ と変数変換すると,\n\n$$\n\\begin{aligned}\n\\Gamma(p)\\Gamma(q) &= \n4\\int_0^{\\pi/2}d\\theta\\int_0^\\infty e^{-r^2} (r\\cos\\theta)^{2p-1} (r\\sin\\theta)^{2q-1} r\\,dr\n\\\\ &=\n4\\int_0^{\\pi/2}(\\cos\\theta)^{2p-1} (\\sin\\theta)^{2q-1}\\,d\\theta\n\\int_0^\\infty e^{-r^2} r^{2(p+q)-1}\\,dr =\nB(p,q)\\Gamma(p+q).\n\\end{aligned}\n$$\n\n最後の等号でベータ函数の三角函数を用いた表示とガンマ函数のGauss積分に似た表示を用いた. $\\QED$\n\n#### 方法3: y = tx と変数変換する方法\n\n$y=tx$ とおくと, $dy = x\\,dt$ より, \n\n$$\n\\begin{aligned}\n\\Gamma(p)\\Gamma(q) &=\n\\int_0^\\infty\\left(\\int_0^\\infty e^{-(x+y)}x^{p-1}y^{q-1}\\,dy\\right)\\,dx =\n\\int_0^\\infty\\left(\\int_0^\\infty e^{-(1+t)x}x^{p+q-1}t^{q-1}\\,dt\\right)\\,dx\n\\\\ &=\n\\int_0^\\infty\\left(\\int_0^\\infty e^{-(1+t)x}x^{p+q-1}\\,dx\\right)t^{q-1}\\,dt =\n\\int_0^\\infty \\frac{\\Gamma(p+q)}{(1+t)^{p+q}} t^{q-1}\\,dt\n\\\\ &=\n\\Gamma(p+q)\\int_0^\\infty \\frac{t^{q-1}}{(1+t)^{p+q}}\\,dt =\n\\Gamma(p+q)B(p,q).\n\\end{aligned}\n$$\n\n3つ目の等号で積分順序を交換し, 4つ目の等号で $s,c>0$ についてよく使われる公式($x=y/c$ と置けば得られる公式)\n\n$$\n\\int_0^\\infty e^{-cx}x^{s-1}\\,dx = \\frac{\\Gamma(s)}{c^s}\n$$\n\nを使い, 最後の等号でベータ函数の次の表示の仕方を用いた:\n\n$$\nB(p,q) = \\int_0^1 x^{p-1}(1-x)^{q-1}\\,dx =\n\\int_0^\\infty \\frac{t^{q-1}}{(1+t)^{p+q}}\\,dt\n$$\n\nこの公式は積分変数を $\\ds x=\\frac{1}{1+t}$ と置換すれば得られる. $\\ds x = \\frac{t}{1+t}$ と置換すれば $p,q$ を交換した公式が得られる. \n\nベータ函数に関するその公式を知っていれば, ガンマ函数とベータ函数の関係を導くにはこの方法が簡単かもしれない.\n\n$y=tx$ の $t$ は直線の傾きという意味を持っている. $xy$ 平面の第一象限の点を $(x,y)$ で指定していたのを, $(x,y)=(x,tx)$ と直線の傾き $t$ と $x$ で指定するようにしたことが, 上の計算で採用した方法である. この方法はJacobianが出て来る二重積分の積分変数の変換を避けたい場合に便利である.\n\n#### ベータ函数とガンマ函数の関係の簡単な計算問題への応用\n\n**問題:** ベータ函数とガンマ函数の関係を用いて $\\Gamma(1/2)=\\sqrt{\\pi}$ を証明せよ.\n\n**解答例:** \n$$\n\\Gamma(1/2)^2 = \\frac{\\Gamma(1/2)\\Gamma(1/2)}{\\Gamma(1)} = B(1/2,1/2) =\n2\\int_0^{\\pi/2}(\\cos\\theta)^{2\\cdot1/2-1}(\\sin\\theta)^{2\\cdot1/2-1}\\,d\\theta =\n2\\int_0^{\\pi/2}d\\theta = \\pi.\n$$\n\n1つ目の等号で $\\Gamma(1)=1$ を使い, 2つ目の等号でベータ函数とガンマ函数の関係を用い, 3つ目の等号でベータ函数の三角函数を用いた表示を使った. ゆえに $\\Gamma(1/2)=\\sqrt{\\pi}$. $\\QED$\n\n**注意:** この問題の解答例はGauss積分の公式の別証明 $\\int_{-\\infty}^\\infty e^{-x^2}\\,dx=\\Gamma(1/2)=\\sqrt{\\pi}$ を与える. $\\QED$\n\n**問題:** 次の積分を計算せよ:\n\n$$\nA = \\int_0^1 x^5(1-x^2)^{3/2}\\,dx.\n$$\n\n**解答例:** $x=t^{1/2}$ と置換すると $\\ds dx=\\frac{1}{2}t^{-1/2}\\,dt$ なので,\n\n$$\nA = \\int_0^1 t^{5/2}(1-t)^{3/2}\\,\\frac{1}{2}t^{-1/2}\\,dt = \n\\frac{1}{2}\\int_0^1 t^2(1-t)^{3/2}\\,dt = \\frac{1}{2}B(3, 5/2) =\n\\frac{\\Gamma(3)\\Gamma(5/2)}{2\\Gamma(3+5/2)}.\n$$\n\n3つ目の等号で $2=3-1$, $3/2=5/2-1$ とみなしてからベータ函数の表示を得ていることに注意せよ. このステップでよく間違う.\n\n一般に非負の整数 $n$ について\n\n$$\n\\Gamma(n+1) = n!, \\quad\n\\frac{\\Gamma(s)}{\\Gamma(s+n)} = \\frac{1}{s(s+1)\\cdots(s+n-1)}\n$$\n\nなので, \n\n$$\n\\Gamma(3) = 2! = 2, \\quad\n\\frac{\\Gamma(5/2)}{\\Gamma(3+5/2)} = \\frac{1}{(5/2)(7/2)(9/2)} = \\frac{2^3}{5\\cdot 7\\cdot 9}.\n$$\n\nしたがって\n\n$$\nA = \\frac{2}{2}\\frac{2^3}{5\\cdot7\\cdot9} = \\frac{8}{315}.\n\\qquad \\QED\n$$\n\n\n```julia\nx = symbols(\"x\", real=true)\nintegrate(x^5*(1-x^2)^(Sym(3)/2), (x,0,1))\n```\n\n\n\n\n$$\\frac{8}{315}$$\n\n\n\n#### B(s, 1/2)の級数展開\n\n$\\ds\\binom{-1/2}{n}$ は次を満たしている:\n\n$$\n\\binom{-1/2}{n}(-x)^n =\n\\frac{(1/2)(3/2)\\cdots((2n-1)/2)}{n!}x^n =\n\\frac{1}{2^{2n}}\\binom{2n}{n}x^n.\n$$\n\nゆえに, $|x|<1$ のとき,\n\n$$\n(1-x)^{-1/2} = \\sum_{n=0}^\\infty \\frac{1}{2^{2n}}\\binom{2n}{n}x^n.\n$$\n\nしたがって,\n\n$$\nB(s,1/2)=\\int_0^1 x^{s-1}(1-x)^{-1/2}\\,dx=\n\\sum_{n=0}^\\infty \\frac{1}{2^{2n}}\\binom{2n}{n}\\int_0^1 x^{s+n-1}\\,dx =\n\\sum_{n=0}^\\infty \\frac{1}{2^{2n}}\\binom{2n}{n}\\frac{1}{s+n}.\n$$\n\n例えば, $s=1/2$ のとき, $B(1/2,1/2)=\\Gamma(1/2)^2=\\pi$ なので, 両辺を2で割ると,\n\n$$\n\\sum_{n=0}^\\infty \\frac{1}{2^{2n}}\\binom{2n}{n}\\frac{1}{2n+1} =\n\\frac{1}{2}B(1/2,1/2) = \\frac{\\pi}{2}.\n$$\n\nこのような公式はベータ函数について知らないと驚くべき公式に見えてしまうが, ベータ函数について知っていれば単に二項展開をベータ函数の被積分函数に適用しただけの公式に過ぎない.\n\n### ガンマ函数の無限積表示\n\n**問題(Gaussの公式):** ベータ函数とガンマ函数の関係を用いて, 次の公式を示せ.\n\n$$\n\\Gamma(s) = \\lim_{n\\to\\infty}\\frac{n^s n!}{s(s+1)\\cdots(s+n)}.\n$$\n\n**解答例:** 右辺をベータ函数と表示することを考える. 以下では $n$ は正の整数であるとし, $s>0$ と仮定する. ベータ函数とガンマ函数の函数等式および $\\Gamma(n+1)=n!$ より,\n\n$$\nB(s,n+1) = \\frac{\\Gamma(s)\\Gamma(n+1)}{\\Gamma(s+n+1)} =\n\\frac{n!}{s(s+1)\\cdots(s+n)}.\n$$\n\nゆえに\n\n$$\nn^s B(s,n+1) = \\frac{n^s n!}{s(s+1)\\cdots(s+n)}.\n$$\n\n左辺を $n\\to\\infty$ での極限を取り易い形に変形しよう. $x=t/n$ と置換することによって, $n\\to\\infty$ のとき\n\n$$\n\\begin{aligned}\nn^s B(s,n+1) &= n^s \\int_0^1 x^{s-1}(1-x)^n\\,dx\n\\\\ &=\n\\int_0^n t^{s-1}\\left(1-\\frac{t}{n}\\right)^n\\,dt \\to \\int_0^\\infty t^{s-1}e^{-t}\\,dt = \\Gamma(s).\n\\end{aligned}\n$$\n\n以上をまとめると示したい結果が得られる. $\\QED$\n\n**問題:** 上の解答例中で極限と積分の順序を交換した. その部分の議論を指数函数に関する不等式\n\n$$\n\\left(1+\\frac{t}{a}\\right)^a \\leqq e^t \\leqq \\left(1-\\frac{t}{b}\\right)^{-b}\\qquad(-a0)\n\\tag{1}\n$$\n\nと $\\ds \\left(1+\\frac{t}{a}\\right)^a$, $\\ds \\left(1-\\frac{t}{b}\\right)^{-b}$ がそれぞれ $a,b$ について単調増加, 単調減少することを用いて正当化せよ.\n\n**解答例:** 問題文の中で与えられた不等式の全体の逆元を取り, $a=m$, $b=n$ とおくと, \n\n$$\n\\left(1-\\frac{t}{n}\\right)^n \\leqq e^{-t} \\leqq \\left(1+\\frac{t}{m}\\right)^{-m} \\qquad (-m0$, $m>s$ のとき, \n\n$$\nn^s B(s,n+1) = \\int_0^n t^{s-1}\\left(1-\\frac{t}{n}\\right)^n\\,dt, \\qquad \nm^s B(s,m-s) = \\int_0^n t^{s-1}\\left(1+\\frac{t}{m}\\right)^m\\,dt\n$$\n\nが得られ, それぞれ, $n$, $m$ について単調増加, 単調減少することがわかる. これらと $\\ds\\Gamma(s)=\\int_0^\\infty t^{s-1}e^{-t}\\,dt$ を比較すると, \n\n$$\nn^s B(s,n+1) \\leqq \\Gamma(s) \\leqq m^s B(s,m-s).\n\\tag{$*$}\n$$\n\n$n^s B(s,n+1)$, $ m^s B(s,m-s)$ はそれぞれ $n$, $m$ について単調増加, 単調減少するので, どちらも $n,m\\to\\infty$ で収束する. そして, $m=n+s+1$ とおくと, \n\n$$\n\\frac{m^s B(s,m-s)}{n^s B(s,n+1)} = \\frac{(n+s+1)^s B(s,n+1)}{n^s B(s,n+1)} =\n\\left(1+\\frac{s+1}{n}\\right)^s \\to 1 \\quad(n\\to\\infty)\n$$\n\nなので, $n^s B(s,n+1)$, $ m^s B(s,m-s)$ は $n,m\\to\\infty$ で同じ値に収束する. これと不等式($*$)を合わせると, $n^s B(s,n+1)$, $ m^s B(s,m-s)$ は $n,m\\to\\infty$ で $\\Gamma(s)$ に収束することがわかる. $\\QED$\n\n**注意:** 不等式(1),(2)と $a,b$, $m,n$ に関する単調性は極限で指数函数が現われる結果を初等的に正当化するために非常に便利である. $\\QED$\n\n**問題(Weierstrassの公式):** 上の問題の結果を用いて, 次の公式を示せ.\n\n$$\n\\frac{1}{\\Gamma(s)} = \ne^{\\gamma s} s\\prod_{n=1}^\\infty\\left[\\left(1+\\frac{s}{n}\\right)e^{-s/n}\\right].\n\\tag{$*$}\n$$\n\nここで $\\gamma$ はEuler定数である:\n\n$$\n\\gamma = \\lim_{n\\to\\infty}\\left(\\sum_{k=1}^n\\frac{1}{k}-\\log n\\right) =\n0.5772\\cdots\n$$\n\n**解答例:**\n$$\n\\begin{aligned}\n&\n\\frac{s(s+1)\\cdots(s+n)}{n^s n!}\n\\\\ &=\ns\\left(1+s\\right)\\left(1+\\frac{s}{2}\\right)\\cdots\\left(1+\\frac{s}{n}\\right) e^{-s\\log n}\n\\\\ &=\ns\\left(1+s\\right)e^{-s}\n\\left(1+\\frac{s}{2}\\right)e^{-s/2}\n\\cdots\n\\left(1+\\frac{s}{n}\\right)e^{-s/n}\ne^{s\\left(1+\\frac{1}{2}+\\cdots+\\frac{1}{n}-\\log n\\right)}\n\\end{aligned}\n$$\n\nであるから, 公式($*$)を得る. $\\QED$\n\n**注意:** \n$$\n\\begin{aligned}\n\\log\\left[\\left(1+\\frac{s}{n}\\right)e^{-s/n}\\right] &=\n\\log\\left(1+\\frac{s}{n}\\right) - \\frac{s}{n} \n\\\\ &=\n\\frac{s}{n} - \\frac{s^2}{2n^2} + O\\left(\\frac{1}{n^3}\\right) - \\frac{s}{n} \n\\\\ &= -\n\\frac{s^2}{2n^2} + O\\left(\\frac{1}{n^3}\\right)\n\\end{aligned}\n$$\n\nなので\n\n$$\n\\prod_{n=1}^\\infty\\left[\\left(1+\\frac{s}{n}\\right)e^{-s/n}\\right] =\n\\prod_{n=1}^\\infty\\left[1 + O\\left(\\frac{1}{n^2}\\right)\\right]\n$$\n\nとなり, この無限積は任意の複素数 $s$ について収束する. したがって, Weierstrassの公式は $1/\\Gamma(s)$ のすべての複素数 $s$ への自然な拡張を与える. $\\QED$\n\n### sinとガンマ函数の関係\n\nsinの無限積表示と Euler's reflection formulaの証明についてはノート「12 Fourier解析」のガンマ函数とsinの関係の節も参照せよ. 以下ではsinの奇数倍角の公式を用いた証明を紹介する.\n\n#### sinの無限積表示\n\nsinの無限積表示\n\n$$\n\\frac{\\sin(\\pi s)}{\\pi} =\ns \\prod_{n=1}^\\infty\\left(1-\\frac{s^2}{n^2}\\right)\n$$\n\nを導出したい. この公式は正弦函数の奇数倍角の公式の極限としても導出されることを以下で説明しよう. (他にも様々な経路での証明がある.)\n\n非負の整数 $n$ に関する $e^{inx} = (e^{ix})^n$ の右辺に $e^{ix} = \\cos x + i\\sin x$ を代入して二項定理を適用し, 両辺の虚部を取ると次が得られる:\n\n$$\n \\sin(nx) = \\sum_{0\\leqq kThe Gamma Function\n\nの第4節に書いてある.\n\n函数 $f(t)$ を\n\n$$\nf(t) = \\Gamma(t)\\Gamma(1-t)\\frac{\\sin(\\pi t)}{\\pi}\n$$\n\nと定める. $0ガンマ分布の中心極限定理とStirlingの公式\n\nの第8節を参照せよ.\n\n### Lerchの定理とゼータ正規化積\n\n#### Lerchの定理 (Hurwitzのゼータ函数とガンマ函数の関係)\n\n**Lerchの定理:** Hurwitzのゼータ函数 $\\zeta(s,x)$ からガンマ函数が\n\n$$\n\\zeta_s(0,x) = \\log\\frac{\\Gamma(x)}{\\sqrt{2\\pi}}, \\qquad\n\\Gamma(x) = \\sqrt{2\\pi}\\;\\exp(\\zeta_s(0,x))\n$$\n\nによって得られる. ここで $\\zeta_s(s,x)$ は $\\zeta(s,x)$ の $s$ に関する偏導函数である.\n\n**証明:** $F(x)=\\zeta_s(0,x)-\\log\\Gamma(x)$ とおく. $F(x)=-\\log\\sqrt{2\\pi}$ であることを示せば十分である. \n\n(1) $(\\zeta_s(0,x))'' = (\\log\\Gamma(x))''$ を示そう. ここで $'$ は $x$ による微分を表わす. まずHurwitzのゼータ函数\n\n$$\n\\zeta(s,x) = \\sum_{k=0}^\\infty \\frac{1}{(x+k)^s}\n$$\n\nについては\n\n$$\n\\zeta_x(s,x) = -s\\zeta(s+1,x)\n$$\n\nが成立しているので, \n\n$$\n\\zeta_{xx}(s,x) = s(s+1)\\zeta(s+2,x).\n$$\n\nこれより, \n\n$$\n(\\zeta_s(0,x))'' = \\zeta_{xxs}(0,x) = \\zeta(2,x).\n$$\n\n一方, ガンマ函数\n\n$$\n\\Gamma(x) = \\lim_{\\to\\infty}\\frac{n!\\,n^x}{x(x+1)\\cdots(x+n)}\n$$\n\nについては,\n\n$$\n\\begin{aligned}\n&\n\\log\\Gamma(x) =\n\\lim_{n\\to\\infty}\\left(\n\\log n! + n\\log x - \\log x - \\log(x+1) - \\cdots - \\log(x+n)\n\\right),\n\\\\ &\n(\\log\\Gamma(x))' =\n\\lim_{n\\to\\infty}\\left(\n\\log n - \\frac{1}{x} - \\frac{1}{x+1} - \\cdots - \\frac{1}{x+n}\n\\right),\n\\\\ &\n(\\log\\Gamma(x))'' =\n\\lim_{n\\to\\infty}\\left(\n\\frac{1}{x^2} + \\frac{1}{(x+1)^2} + \\cdots + \\frac{1}{(x+n)^2}\n\\right) = \\zeta(2,x).\n\\end{aligned}\n$$\n\nこれで $(\\zeta_s(0,x))'' = (\\log\\Gamma(x))''$ が示された.\n\n(2) 上の結果より, $F(x)=\\zeta_s(0,x)-\\log\\Gamma(x)$ は $x$ の一次函数である.\n\n(3) $\\zeta_s(0,x)$ と $\\log\\Gamma(x)$ がどちらも同一の函数等式 $f(x+1)=f(x)+\\log x$ を満たすことを示そう. \n\n$$\n\\begin{aligned}\n&\n\\zeta(s,x+1) = \\zeta(s,x) - \\frac{1}{x^s},\n\\qquad\\therefore\\quad\n\\zeta_s(0,x+1) = \\zeta_s(0,x) + \\log x.\n\\\\ &\n\\log\\Gamma(x+1) = \\log(x\\Gamma(x)) = \\log\\Gamma(x) + \\log x.\n\\end{aligned}\n$$\n\n(4) $F(x)=\\zeta_s(0,x)-\\log\\Gamma(x)$ は $x$ の一次函数だったので, 上の結果より $F(x)$ は定数になる.\n\n(5) $\\zeta_s(0,1/2)=-\\log\\sqrt{2}$ を示そう.\n\n$$\n\\begin{aligned}\n\\zeta(s) - 2^{-s}\\zeta(s) &=\n\\left(\\frac{1}{1^s}+\\frac{1}{2^s}+\\frac{1}{3^s}+\\frac{1}{4^s}+\\cdots\\right) -\n\\left(\\frac{1}{2^s}+\\frac{1}{4^s}+\\cdots\\right) \n\\\\ &=\n\\frac{1}{1^s}+\\frac{1}{3^s}+\\cdots =\n\\sum_{k=0}^\\infty\\frac{1}{(2k+1)^s}\n\\end{aligned}\n$$\n\nなので\n\n$$\n\\begin{aligned}\n&\n\\zeta(s,1/2) = \\sum_{k=0}^\\infty\\frac{1}{(k+1/2)^s} =\n2^s\\sum_{k=0}^\\infty\\frac{1}{(2k+1)^s} = \n2^s(\\zeta(s) - 2^{-s}\\zeta(s)) =\n(2^s-1)\\zeta(s),\n\\\\ &\\therefore\\quad\n\\zeta_s(0,1/2) = \\zeta(0)\\log 2 = -\\frac{1}{2}\\log 2 = -\\log\\sqrt{2}.\n\\end{aligned}\n$$\n\n(6) $\\log\\Gamma(1/2)=\\log\\sqrt{\\pi}$ なので, 上の結果より, $F(x)=-\\log\\sqrt{2\\pi}$ であることがわかる. $\\QED$\n\n#### ゼータ正規化積 \n\n数列 $a_n$ に対して,\n\n$$\nf(s) = \\sum_{n=1}^N \\frac{1}{a_n^s}\n$$\n\nとおくとき, \n\n$$\nf'(0) = -\\sum_{n=1}^N \\log a_n\n$$\n\nなので, \n\n$$\n\\exp(-f'(0)) = \\prod_{n=1}^N a_n\n$$\n\nが成立している. もしも $N=\\infty$ のときの $\\ds\\prod_{n=1}^\\infty a_n$ が発散していても, $\\ds f(s)=\\sum_{n=1}^\\infty \\frac{1}{a_n^s}$ の解析接続によって, 左辺の $\\exp(-f'(0))$ はwell-definedになる可能性がある. そのとき, $\\exp(-f'(0))$ を\n\n$$\n\\exp(-f'(0)) = \\PROD_{n=1}^\\infty a_n\n$$\n\nと書き, $a_n$ 達の**ゼータ正規化積**と呼ぶ. \n\n例えば $x,x+1,x+2,x+3,\\ldots$ のゼータ正規化積はLerchの定理より, $\\ds\\frac{\\sqrt{2\\pi}}{\\Gamma(x)}$ になる. 特に $x=1$ のときの $1,2,3,4,\\ldots$ のゼータ正規化積は $\\sqrt{2\\pi}$ になる:\n\n$$\n\"\\! 1\\times 2\\times 3\\times 4\\times\\cdots \\!\" \\,= \n\\PROD_{n=1}^\\infty n = \\exp(-\\zeta'(0)) = \\sqrt{2\\pi}.\n$$\n\nこれは\n\n$$\n\"\\! 1+2+3+4+\\cdots \\!\"\\, = \\zeta(-1) = -\\frac{1}{12}\n$$\n\nの積バージョンである. \n\n## Stirlingの公式とLaplaceの方法\n\n一般に数列 $a_n,b_n$ について\n\n$$\n\\lim_{n\\to\\infty}\\frac{a_n}{b_n} = 1\n$$\n\nが成立するとき,\n\n$$\na_n\\sim b_n\n$$\n\nと書くことにする. \n\n### Stirlingの公式\n\n**Stirlingの(近似)公式:** $n\\to\\infty$ のとき,\n\n$$\nn!\\sim n^n e^{-n} \\sqrt{2\\pi n}.\n$$\n\nさらに, 両辺の対数を取ることによって, $n\\to\\infty$ のとき,\n\n$$\n\\log n! = n\\log n - n + \\frac{1}{2}\\log n + \\log\\sqrt{2\\pi} + o(1).\n$$\n\nStirlingの公式の「物理学的」もしくは「情報理論的」な応用については\n\n* 黒木玄, Kullback-Leibler情報量とSanovの定理\n\nの第1節を参照せよ.\n\n**Stirlingの公式の証明:**\n\n$$\nn! = \\Gamma(n+1) = \\int_0^\\infty e^{-x} x^n\\,dx\n$$\n\nで $x = n+\\sqrt{n}\\;y = n(1+y/\\sqrt{n})$ と置換すると, \n\n$$\nn! = \nn^n e^{-n} \\sqrt{n} \\int_{-\\sqrt{n}}^\\infty e^{-\\sqrt{n}\\;y}\\;\\left(1+\\frac{y}{\\sqrt{n}}\\right)^n\\,dy =\nn^n e^{-n} \\sqrt{n} \\int_{-\\sqrt{n}}^\\infty \\;f_n(y)\\,dy.\n$$\n\nここで, 被積分函数を $f_n(y)$ と書いた. そのとき $n\\to\\infty$ で\n\n$$\n\\begin{aligned}\n\\log f_n(y) &= -\\sqrt{n}\\;y + n\\log\\left(1+\\frac{y}{\\sqrt{n}}\\right) =\n-\\sqrt{n}\\;y + n\\left(\\frac{y}{\\sqrt{n}} - \\frac{y^2}{2n} + O\\left(\\frac{1}{n\\sqrt{n}}\\right)\\right) \n\\\\ &=\n-\\frac{y^2}{2} + O\\left(\\frac{1}{\\sqrt{n}}\\right) \\to -\\frac{y^2}{2}.\n\\end{aligned}\n$$\n\nすなわち $f_n(y)\\to e^{-y^2/2}$ となる. ゆえに\n\n$$\n\\frac{n!}{n^n e^{-n} \\sqrt{2\\pi n}} =\n\\frac{1}{\\sqrt{2\\pi}}\\int_{-\\sqrt{n}}^\\infty\\;f_n(y)\\,dy\n\\to \\frac{1}{\\sqrt{2\\pi}}\\int_{-\\infty}^\\infty e^{-y^2/2}\\,dy = 1.\n$$\n\n最後の等号でGauss積分の公式 $\\int_{-\\infty}^\\infty e^{-y^2/a}\\,dy=\\sqrt{a\\pi}$ を用いた. $\\QED$\n\n**Stirlingの公式の証明の解説:** 上の証明のポイントは $x=n+\\sqrt{n}\\;y$ という積分変数変換である. この変数変換の「正体」は $\\Gamma(n+1)=\\int_0^\\infty e^{-x} x^n\\,dx$ の被積分函数 $f(x)=e^{-x}x^n$ のグラフを描いてみれば見当がつく.\n\n$g(x)=\\log f(x)=n\\log x - x$ の導函数は $g'(x)=n/x-1$ は $x$ について単調減少であり, $x=n$ で $0$ になる. ゆえに $g(x)=\\log f(x)$ は $x=n$ で最大になる. そこで $x=n$ における $g(x)=\\log f(x)$ のTaylor展開を求めてみよう. $g''(x)=-n/x^2$, $g'''(x)=2n/x^3$ なので, $g(n)=n\\log n - n$, $g'(n)=0$, $g''(n)=-1/n$, $g'''(n)=2/n^2$ なので,\n\n$$\ng(x) = n \\log n - n -\\frac{(x-n)^2}{2n} + \\frac{(x-n)^3}{3\\,n^2} + \\cdots\n$$\n\nこれの2次の項が $-y^2/2$ になるような変数変換がちょうど $x=n+\\sqrt{n}\\;y$ になっている. これが上の証明で用いた変数変換の「正体」である. $\\QED$\n\n\n```julia\n# y = f(x) = e^{-x} x^n / (n^n * e^{-n}) のグラフは n が大きなとき,\n# Gauss近似 y = e^{-(x-n)^2/(2n)} のグラフにほぼ一致する.\n\nf(n,x) = e^(-x + n*log(x) - (n*log(n) - n))\ng(n,x) = e^(-(x-n)^2/(2n))\nPP = []\nfor n in [10, 30, 100, 300]\n x = 0:2.5n/400:2.5n\n n ≤ 20 && (x = 0:3n/400:3n)\n P = plot()\n plot!(title=\"n = $n\", titlefontsize=9)\n plot!(x, f.(n,x), label=\"\")\n plot!(x, g.(n,x), label=\"Gaussian\")\n push!(PP, P)\nend\n\nplot(PP[1:2]..., size=(700, 200))\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(PP[3:4]..., size=(700, 200))\n```\n\n\n\n\n \n\n \n\n\n\n**注意(ガンマ函数のStirlingの近似公式):** 上の証明で $n$ が整数であることは使っていない. ゆえに正の実数 $s$ について\n\n$$\n\\Gamma(s+1) \\sim s^s e^{-s} \\sqrt{2\\pi s} \\quad (s\\to\\infty)\n$$\n\nが証明されている. これの両辺を $s$ で割ると,\n\n$$\n\\Gamma(s) \\sim s^s e^{-s} s^{-1/2} \\sqrt{2\\pi} \\quad (s\\to\\infty)\n$$\n\nが得られる. これらをも**Stirlingの近似公式**と呼ぶ. $\\QED$\n\nStirlingの公式の重要な応用については\n\n* 黒木玄, 11 Kullback-Leibler情報量\n\nも参照せよ. 「Stirlingの公式」とその応用としての「KL情報量に関するSanovの定理」についてはできるだけ早く理解しておいた方がよい. $\\QED$\n\n**問題:** $n=1,2,\\ldots,10$ について Stirling の公式の相対誤差\n\n$$\n\\frac{n^n e^{-n} \\sqrt{2\\pi n}}{n!}-1\n$$\n\nを求めよ.\n\n**解答例:** 以下のセルを参照せよ. $n=5$ で相対誤差は2%を切っている. $\\QED$\n\n\n```julia\nf(n) = factorial(n)\ng(n) = n^n * exp(-n) * √(2π*n)\n[(n, f(n), g(n), g(n)/f(n)-1) for n in 1:10]\n```\n\n\n\n\n 10-element Array{Tuple{Int64,Int64,Float64,Float64},1}:\n (1, 1, 0.922137, -0.077863) \n (2, 2, 1.919, -0.0404978) \n (3, 6, 5.83621, -0.0272984) \n (4, 24, 23.5062, -0.020576) \n (5, 120, 118.019, -0.0165069) \n (6, 720, 710.078, -0.0137803) \n (7, 5040, 4980.4, -0.0118262) \n (8, 40320, 39902.4, -0.0103573) \n (9, 362880, 3.59537e5, -0.00921276) \n (10, 3628800, 3.5987e6, -0.00829596)\n\n\n\n**参考:** 上の計算を見れば, $n^n e^{-n} \\sqrt{2\\pi n}$ は $n!$ よりも微小に小さいことがわかる. その分を補正したより精密な近似式\n\n$$\nn! = n^n e^{-n} \\sqrt{2\\pi n}\\left(1+\\frac{1}{12n}+O\\left(\\frac{1}{n^2}\\right)\\right)\n$$\n\nが成立している. (実際には $O(1/n^2)$ の部分についてもっと詳しいことがわかる.)\n\n$1/(12n)$ で補正した近似式の相対誤差は $n=1$ ですでに0.1%程度と非常に小さくなる. 次のセルを見よ. $\\QED$\n\n\n```julia\nf(n) = factorial(n)\ng1(n) = n^n * exp(-n) * √(2π*n) * (1+1/(12n))\n[(n, f(n), g1(n), g1(n)/f(n)-1) for n in 1:10]\n```\n\n\n\n\n 10-element Array{Tuple{Int64,Int64,Float64,Float64},1}:\n (1, 1, 0.998982, -0.00101824) \n (2, 2, 1.99896, -0.000518567) \n (3, 6, 5.99833, -0.000278913) \n (4, 24, 23.9959, -0.00017137) \n (5, 120, 119.986, -0.000115383) \n (6, 720, 719.94, -8.28033e-5) \n (7, 5040, 5039.69, -6.22504e-5) \n (8, 40320, 40318.0, -4.84771e-5) \n (9, 362880, 3.62866e5, -3.88063e-5) \n (10, 3628800, 3.62868e6, -3.17601e-5)\n\n\n\n### Wallisの公式のStirlingの公式を使った証明\n\n**問題(Wallisの公式):** Stirlingの公式を用いて次を示せ:\n\n$$\n\\frac{1}{2^{2n}}\\binom{2n}{n} \\sim \\frac{1}{\\sqrt{\\pi n}}.\n$$\n\n**解答例:**\n$$\n\\frac{1}{2^{2n}}\\binom{2n}{n} = \\frac{(2n)!}{2^{2n}(n!)^2}\n\\sim \\frac{(2n)^{2n}e^{-2n}\\sqrt{4\\pi n}}{2^{2n}n^{2n}e^{-2n}2\\pi n} = \\frac{1}{\\sqrt{\\pi n}}.\n\\qquad \\QED\n$$\n\n**注意:** この形のWallisの公式は1次元の単純ランダムウォークの逆正弦法則に関係している.\n\n* 黒木玄, 単純ランダムウォークの逆正弦法則 (手描きのノートのPDF)\n\nを参照せよ. 特に手描きのノートのPDFファイルの12頁以降にまとまった解説がある. 1次元の単純ランダムウォークの場合には高校数学レベルの組み合わせ論的な議論とWallisの公式から逆正弦法則を導くことができる. 1次元の一般ランダムウォークの場合にはTauber型定理を使ってWallisの公式に対応する漸近挙動を証明することになる. $\\QED$\n\n\n```julia\n# Wallisの公式より\n#\n# [ 2^{2n} (n!)^2 / ((2n)! √n) ]^2 ---→ π\n#\n# 以下はこれの数値的確認\n#\n# log n! を log lgamma(n+1) で計算している. ここで lgamma(x) = log(Γ(x)).\n# lgamma(x) は対数ガンマ函数を巨大な x についても計算してくれる.\n\nf(n) = exp((2n)*log(typeof(n)(2)) + 2lgamma(n+1) - lgamma(2n+1) - log(n)/2)^2\nWallis_pi = f(big\"10.0\"^40)\nExact__pi = big(π)\n@show Wallis_pi\n@show Exact__pi\nWallis_pi - Exact__pi\n```\n\n Wallis_pi = 3.14159265358979323846264338327950280112510935008936482449955348608333403219364\n Exact__pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286198\n\n\n\n\n\n -8.307206004928574099647539110622448237409255782069327815244440488293374992724481e-35\n\n\n\n### Gauss's multiplication formula\n\n**問題(Gauss's multiplication formula):** 次を示せ: 正の整数 $n$ に対して,\n\n$$\n\\Gamma(s)\\Gamma\\left(s+\\frac{1}{n}\\right)\\cdots\\Gamma\\left(s+\\frac{n-1}{n}\\right) =\nn^{1/2-ns}(2\\pi)^{(n-1)/2}\\Gamma(ns).\n$$\n\n**解答例:** 函数 $f(s)$ を次のように定める:\n\n$$\nf(s) = \\frac{\\Gamma(s)\\Gamma\\left(s+\\frac{1}{n}\\right)\\cdots\\Gamma\\left(s+\\frac{n-1}{n}\\right)}{n^{-ns}\\Gamma(ns)}\n$$\n\n$f(s)=n^{1/2}(2\\pi)^{(n-1)/2}$ を示せばよい.\n\nガンマ函数の函数等式だけを使って, $f(s+1)=f(s)$ を示せる:\n\n$$\nf(s+1) = \nf(s)\\frac\n{s\\left(s+\\frac{1}{n}\\right)\\cdots\\left(s+\\frac{n-1}{n}\\right)}\n{n^{-n}(ns+n-1)\\cdots(ns+1)(ns)} = f(s).\n$$\n\n上で証明されているStirlingの近似公式\n\n$$\n\\Gamma(s) \\sim s^s e^{-s} s^{-1/2}\\sqrt{2\\pi} \\quad (s\\to\\infty)\n$$\n\nを使って, $s\\to\\infty$ のときの $f(s)$ の極限を求めよう. $s\\to\\infty$ のとき, $\\ds \\left(1+\\frac{a}{s}\\right)^s\\to e^a$ なので, $s\\to\\infty$ において, \n\n$$\n\\begin{aligned}\n\\Gamma(s+a) &\\sim (s+a)^{s+a-1/2} e^{-s-a} \\sqrt{2\\pi} \n\\\\ &=\ns^{s+a-1/2}e^{-s}\\sqrt{2\\pi}\\;\\left(1+\\frac{a}{s}\\right)^{s+a-1/2} e^{-a} \n\\\\ &\\sim\ns^{s+a-1/2}e^{-s}\\sqrt{2\\pi}.\n\\end{aligned}\n$$\n\nとなる. ゆえに, $\\frac{1}{n}+\\frac{2}{n}+\\cdots+\\frac{n-1}{n}=\\frac{n-1}{2}$ なので, $s\\to\\infty$ において, \n\n$$\n\\begin{aligned}\n&\n\\Gamma(s) \\sim\ns^{s-1/2} e^{-s}\\sqrt{2\\pi},\n\\\\ &\n\\Gamma\\left(s+\\frac{1}{n}\\right)\\sim\ns^{s+1/n-1/2} e^{-s} \\sqrt{2\\pi},\n\\\\ &\n\\qquad\\qquad\\cdots\\cdots\\cdots\\cdots\\cdots\n\\\\ &\n\\Gamma\\left(s+\\frac{n-1}{n}\\right)\\sim\ns^{s+(n-1)/n-1/2} e^{-s} \\sqrt{2\\pi}\n\\\\ &\n\\therefore\\quad\n\\Gamma(s)\\Gamma\\left(s+\\frac{1}{n}\\right)\\cdots\\Gamma\\left(s+\\frac{n-1}{n}\\right)\\sim\ns^{ns-1/2}e^{-ns}(2\\pi)^{n/2}\n\\\\ &\nn^{-ns}\\Gamma(ns)\\sim\nn^{-ns}(ns)^{ns-1/2}e^{-ns}\\sqrt{2\\pi} =\nn^{-1/2}s^{ns-1/2}e^{-ns}(2\\pi)^{1/2}\n\\end{aligned}\n$$\n\nとなり, \n\n$$\nf(s)\\sim\\frac{s^{ns-1/2}e^{-ns}(2\\pi)^{n/2}}{n^{-1/2}s^{ns-1/2}e^{-ns}(2\\pi)^{1/2}}=\nn^{1/2}(2\\pi)^{(n-1)/2}.\n$$\n\nゆえに整数 $N$ について, $f(s+N)=f(s)$ なので, $N\\to\\infty$ のとき $f(s)=f(s+N)\\to n^{1/2}(2\\pi)^{(n-1)/2}$ となる. これで $f(s)=2^{1/2}(2\\pi)^{(n-1)/2}$ が示された. $\\QED$\n\n**問題:** Gauss's multiplication formula の $n=2$ の場合である Legendre's duplication formula は定積分の計算だけで証明できるのであった. 上の解答例は本質的にStirlingの近似公式を使っている. Gauss's multiplication formula にも定積分の計算だけで証明する方法がないだろうか. 以下の方針で Gauss's multiplication formula を証明せよ. ただし, (3)の証明には Euler's reflection formula は使ってよいことにする. \n\n$t>0$ に対する $n-1$ 重積分 $I(t)$ を次のように定める:\n\n$$\nI(t) = \\int_0^\\infty\\cdots\\int_0^\\infty \ne^{-(t^n/(x_2\\cdots x_n)+x_2+\\cdots+x_n)}\nx_2^{-(n-1)/n}x_3^{-(n-2)/n}\\cdots x_n^{-1/n} \\,dx_2\\cdots dx_n.\n$$\n\n以下を示せ:\n\n(1) $\\ds I(t) = \\Gamma\\left(\\frac{1}{n}\\right)\\Gamma\\left(\\frac{2}{n}\\right)\\cdots\\Gamma\\left(\\frac{n-1}{n}\\right)e^{-nt}$.\n\n(2) $\\ds \\Gamma(s)\\Gamma\\left(s+\\frac{1}{n}\\right)\\cdots\\Gamma\\left(s+\\frac{n-1}{n}\\right) = \nn^{1-ns}I(0)\\Gamma(ns) =\nn^{1-ns}\\Gamma\\left(\\frac{1}{n}\\right)\\Gamma\\left(\\frac{2}{n}\\right)\\cdots\\Gamma\\left(\\frac{n-1}{n}\\right)\\Gamma(ns)$.\n\n(3) $\\ds I(0) = \n\\Gamma\\left(\\frac{1}{n}\\right)\\Gamma\\left(\\frac{2}{n}\\right)\\cdots\\Gamma\\left(\\frac{n-1}{n}\\right) =\n(2\\pi)^{(n-1)/2} n^{-1/2}$.\n\n**注意:** (1), (2) の方針の証明は\n\n* Andrews, G.E., Askey,R., and Roy, R. Special functions. Encyclopedia of Mathematics and its Applications, Vol. 71, Cambridge University Press, 1999, 2000, 681 pages.\n\nのpp.24-25で解説されている. その方法は\n\n* Liouville, J. Sur un théorème relatif à l’intégrale eulérienne de seconde espèce. Journal de mathématiques pures et appliquées 1re série, tome 20 (1855), p. 157-160. PDF\n\nの方法の再構成ということらしい.\n\n**解答例:** (1) $t=0$ のとき, $I(0)$ の積分は変数分離形になって, \n\n$$\nI(0) = \\Gamma\\left(\\frac{1}{n}\\right)\\Gamma\\left(\\frac{2}{n}\\right)\\cdots\\Gamma\\left(\\frac{n-1}{n}\\right)\n$$\n\nとなることがすぐにわかる. $I(t)$ を $t$ で微分して, $\\ds x_2 = \\frac{t^n}{x_3\\cdots x_n x_1}$ によって積分変数 $x_2$ を積分変数 $x_1$ に変換すると, \n\n$$\n\\begin{aligned}\nI'(t) &=\n\\int_0^\\infty\\cdots\\int_0^\\infty \ne^{-(t^n/(x_2\\cdots x_n)+x_2+\\cdots+x_n)}\n\\frac{-nt^{n-1}}{x_2\\cdots x_n}\nx_2^{-(n-1)/n}x_3^{-(n-2)/n}\\cdots x_n^{-1/n} \\,dx_2\\cdots dx_n\n\\\\ &=\n-n\\int_0^\\infty\\cdots\\int_0^\\infty \ne^{-(t^n/(x_2\\cdots x_n)+x_2+\\cdots+x_n)}\nt^{n-1}\nx_2^{-(n-1)/n-1}x_3^{-(n-2)/n-1}\\cdots x_n^{-1/n-1} \\,dx_2\\cdots dx_n\n\\\\ &=\n-n\\int_0^\\infty\\cdots\\int_0^\\infty \ne^{-(x_1+t^n/(x_3\\cdots x_n x_1)+x_3+\\cdots+x_n)}\n\\\\ & \\qquad\\qquad\\quad\\times\nt^{n-1}\n\\left(\\frac{t^n}{x_3\\cdots x_n x_1}\\right)^{-(2n-1)/n}\nx_3^{-(2n-2)/n}\\cdots x_n^{-(n+1)/n} \\frac{t^n}{x_3\\cdots x_n x_1^2}\\,dx_3\\cdots dx_n\\,dx_1\n\\\\ &=\n-n\\int_0^\\infty\\cdots\\int_0^\\infty \ne^{-(x_1+t^n/(x_3\\cdots x_n x_1)+x_3+\\cdots+x_n)}\nx_3^{-(n-1)/n}\\cdots x_n^{-2/n} x_1^{-1/n}\\,dx_3\\cdots dx_n\\,dx_1\n\\\\ &=\n-n I(t)\n\\end{aligned}\n$$\n\nゆえに $I(t)=I(0)e^{-nt}$. これで(1)が示された.\n\n(2) 左辺をLHSと書き, $\\ds x_1=\\frac{t^n}{x_2\\cdots x_n}$ とおくと, \n\n$$\n\\begin{aligned}\n\\text{LHS} &=\n\\int_0^\\infty\\cdots\\int_0^\\infty e^{-(x_1+\\cdots+x_n)} x_1^{s-1}x_2^{s-(n-1)/n}\\cdots x_n^{s-1/n}\\,dx_1\\cdots dx_n\n\\\\ &=\n\\int_0^\\infty\\cdots\\int_0^\\infty e^{-(t^n/(x_2\\cdots x_n)+x_2\\cdots+x_n)}\n\\left(\\frac{t^n}{x_2\\cdots x_n}\\right)^{s-1}\nx_2^{s-(n-1)/n}\\cdots x_n^{s-1/n}\n\\frac{nt^{n-1}}{x_2\\cdots x_n}\n\\,dt\\,dx_2\\cdots dx_n\n\\\\ &=\nn\\int_0^\\infty\\cdots\\int_0^\\infty e^{-(t^n/(x_2\\cdots x_n)+x_2\\cdots+x_n)}\nx_2^{-(n-1)/n}\\cdots x_n^{-1/n} t^{ns-1}\n\\,dx_2\\cdots dx_n\\,dt\n\\\\ &=\nn\\int_0^\\infty I(t) t^{ns-1}\\,dt =\nnI(0)\\int_0^\\infty e^{-nt} t^{ns-1}\\,dt =\nn^{1-ns}I(0)\\Gamma(ns).\n\\end{aligned}\n$$\n\nこれで(2)が示された.\n\n(3) $I(0)=(2\\pi)^{(n-1)/2}n^{-1/2}$ を示したい. そのためには $I(0)^2 = (2\\pi)^{n-1} n^{-1}$ を示せばよい. Euler's reflection formula より, $\\ds \\Gamma\\left(\\frac{k}{n}\\right)\\Gamma\\left(\\frac{n-k}{n}\\right) = \\frac{\\pi}{\\sin(k\\pi/n)}$ なので\n\n$$\nI(0)^2 = \\prod_{k=1}^{n-1}\\frac{\\pi}{\\sin(k\\pi/n)} =\n\\frac{\\pi^{n-1}}{\\ds\\prod_{k=1}^{n-1}\\sin\\frac{k\\pi}{n}}.\n$$\n\nそして, \n\n$$\n\\prod_{k=1}^{n-1}\\sin\\frac{k\\pi}{n} = \n\\prod_{k=1}^{n-1}\\frac{e^{\\pi ik/n}-e^{-\\pi ik/n}}{2i} =\n\\frac{e^{\\pi i(1+2+\\cdots+(n-1))/n}}{2^{n-1}i^{n-1}}\\prod_{k=1}^{n-1}(1-e^{-2\\pi ik/n}) =\n\\frac{1}{2^{n-1}}\\prod_{k=1}^{n-1}(1-e^{-2\\pi ik/n})\n$$\n\nであり, \n\n$$\n\\frac{x^n-1}{x-1} = \\prod_{k=1}^{n-1}(x-e^{-2\\pi ik/n})\n$$\n\nにおいて $x\\to 1$ とすると $\\ds \\prod_{k=1}^{n-1}(1-e^{-2\\pi ik/n})=n$ が得られる. 以上を合わせると\n\n$$\nI(0)^2 = \\frac{(2\\pi)^{n-1}}{n}.\n$$\n\n両辺の平方根を取れば(3)が得られる. $\\QED$\n\n### Laplaceの方法\n\n**Laplaceの方法:** Stirlingの公式の証明の解説のようにして見付かる変数変換はより一般の場合に非常に有用である. 以下では $\\int_{-\\infty}^\\infty$ や $\\int_0^\\infty$ を単に $\\int$ と書くことにし, \n\n$$\nZ_n = \\int e^{-nf(x)}g(x)\\,dx\n$$\n\nとおく. ただし, $f(x)$ は実数値函数で唯一つの最小値 $f(x_0)$ を持ち, $x=x_0$ において, \n\n$$\nf(x) = f(x_0) + \\frac{a}{2}(x-x_0)^2 + O((x-x_0)^3), \\quad a=f''(x_0) > 0\n$$\n\nとTaylor展開されていると仮定するし, さらに, $0$ 以上の値を持つ実数値函数 $g(x)$ は積分 $Z_n$ がうまく定義されるような適当な条件を満たしていると仮定し, $x_0$ の近傍で $g(x)>0$ を満たしていると仮定する. (ここで, $x_0$ の近傍で $g(x)>0$ が成立しているとは, ある $\\delta>0$ が存在して, $|x-x_0|<\\delta$ ならば $g(x)>0$ となることである.) このとき, \n\n$$\nZ_n = e^{-nf(x_0)} \\int \\exp\\left(-n\\left(\\frac{a}{2}(x-x_0)^2+O((x-x_0)^3)\\right)\\right)\\;g(x)\\,dx.\n$$\n\n$x=x_0+y/\\sqrt{n}$ と変数変換すると\n\n$$\nZ_n = \\frac{e^{-nf(x_0)}}{\\sqrt{n}}\n\\int \\exp\\left(-\\frac{a}{2}y^2+O\\left(\\frac{1}{\\sqrt{n}}\\right)\\right)\\;\ng\\left(x_0+\\frac{y}{\\sqrt{n}}\\right)\\,dy.\n$$\n\nそして, $n\\to\\infty$ で\n\n$$\n\\int \\exp\\left(-\\frac{a}{2}y^2+O\\left(\\frac{1}{\\sqrt{n}}\\right)\\right)\\;\ng\\left(x_0+\\frac{y}{\\sqrt{n}}\\right)\\,dy \\to\n\\int \\exp\\left(-\\frac{a}{2}y^2\\right)g(x_0)\\,dy =\n\\sqrt{\\frac{2\\pi}{a}}\\;g(x_0).\n$$\n\n$a=f''(x_0)$ とおいたことを思い出しながら, 以上をまとめると, $n\\to\\infty$ で\n\n$$\nZ_n \\sim \\frac{e^{-nf(x_0)}}{\\sqrt{n}} \\sqrt{\\frac{2\\pi}{f''(x_0)}}\\;g(x_0).\n$$\n\nすなわち, \n\n$$\n-\\log Z_n = nf(x_0) + \\frac{1}{2}\\log n - \\log\\left(\\sqrt{\\frac{2\\pi}{f''(x_0)}}\\;g(x_0)\\right) + o(1).\n$$\n\n$Z_n$ の $n\\to\\infty$ における漸近挙動を調べるための以上の方法を**Laplaceの方法**(Laplace's method)と呼ぶ. $\\QED$\n\n**問題(Stirlingの公式):** $\\ds n! = \\int_0^\\infty e^{-t}t^n\\,dt$ にLapalceの方法を適用して, Stirlingの公式を導出せよ.\n\n**解答例:** 積分変数を $t=nx$ で置換すると,\n\n$$\nn! = \\int_0^\\infty e^{-t+n\\log t}\\,dt = n^{n+1} \\int_0^\\infty e^{-n(x-\\log x)}\\,dx.\n$$\n\n$f(x)=x-\\log x$, $g(x)=1$ とおく. $f'(x)=1-1/x$, $f''(x)=1/x^2$ なので $f(x)$ は $x_0=1$ で最小になり, $f(1)=f''(1)=1$ となる. ゆえに, それらにLaplaceの方法を適用すると,\n\n$$\nn! \\sim n^{n+1}\\frac{e^{-n}}{\\sqrt{n}}\\sqrt{2\\pi} = n^n e^{-n}\\sqrt{2\\pi n}.\n\\qquad \\QED\n$$\n\nLaplaceの方法は本質的にGauss積分の応用である.\n\nGauss積分をガンマ函数に置き換えることによって得られる一般化されたLaplaceの方法の素描については\n\n* 黒木玄, 一般化されたLaplaceの方法\n\nを参照せよ. 一般化されたLaplaceの方法は\n\n* 渡辺澄夫, ベイズ統計の理論と方法, 2012\n\nの第4章の主結果であるベイズ統計における自由エネルギーの\n\n$$\nF_n = -\\log Z_n = nS + \\lambda \\log n - (m-1)\\log\\log n + O(1)\n$$\n\nの形の漸近挙動を導く議論を初等化するために役に立つ. 特異点解消は本質的に不可避だが, この形の漸近挙動だけが欲しいのであればゼータ函数を用いた精密な議論は必要ない.\n\n### Laplaceの方法の弱形\n\n**Laplaceの方法の弱形:** Laplaceの方法が使える状況では, \n\n$$\nZ_n = \\int e^{-nf(x)}g(x)\\,dx\n$$\n\nについて, 特に, $n\\to\\infty$ のとき, \n\n$$\n-\\frac{1}{n}\\log Z_n \\to f(x_0) = \\min f(x), \\quad\\text{i.e.}\\quad\nZ_n = \\int e^{-nf(x)}g(x)\\,dx = \\exp\\left(-n\\min f(x)+o(n)\\right)\n$$\n\nが成立している. この結論を**Laplaceの方法の弱形**と呼ぶことにする. Laplaceの方法のような精密な形でなくても, こちらの弱形だけで用が足りることは結構多い. $\\QED$\n\n**問題(Laplaceの方法の弱形が明瞭に成立する場合):** 閉区間 $[a,b]$ 上の実数値連続函数 $f(x)$ と $0$ 以上の値を持つ実数値函数 $g(x)$ は, $\\ds f(x_0) = \\min_{a\\leqq x\\leqq b} f(x)$ を満たすある $x_0\\in [a,b]$ の近傍で $g(x)>0$ を満たしていると仮定する. このとき, $n\\to\\infty$ において, \n\n$$\n\\int_a^b e^{-nf(x)}g(x)\\,dx = \\exp\\left(-n\\min_{a\\leqq x\\leqq b} f(x) + o(n)\\right)\n$$\n\nが成立していることを示せ. すなわち, $n\\to\\infty$ のとき, \n\n$$\n-\\frac{1}{n}\\log\\int_a^b e^{-nf(x)}g(x)\\,dx \\to \\min_{a\\leqq x\\leqq b} f(x)\n$$\n\nが成立していることを示せ.\n\n**解答例:** $\\ds f_0(x) = f(x)-\\min_{a\\leqq \\xi\\leqq b}f(\\xi)$ とおくと, $f_0(x)$ の最小値は $0$ になり, \n\n$$\n-\\frac{1}{n}\\log\\int_a^b e^{-nf(x)}g(x)\\,dx = \n\\min_{a\\leqq x\\leqq b}f(x) - \\frac{1}{n}\\log\\int_a^b e^{-nf_0(x)}g(x)\\,dx\n$$\n\nなので, $n\\to\\infty$ のとき\n\n$$\n-\\frac{1}{n}\\log\\int_a^b e^{-nf_0(x)}g(x)\\,dx \\to 0\n$$\n\nとなることを示せばよい. \n\n$\\eps > 0$ を任意に取って固定し, $A = \\{\\, x\\in[a,b]\\mid f_0(x)\\leqq\\eps\\,\\}$ とおき, その $[a,b]$ での補集合を $A^c$ と書き, \n\n$$\nZ_{0,n} = \\int_a^b e^{-nf_0(x)}g(x)\\,dx = I_n + J_n, \\quad\nI_n = \\int_A e^{-nf_0(x)}g(x)\\,dx, \\quad\nJ_n = \\int_{A^c} e^{-nf_0(x)}g(x)\\,dx.\n$$\n\nとおく. $n\\to\\infty$ のとき $-\\frac{1}{n}\\log Z_{0,n} \\to 0$ となることを示したい.\n\n$x\\in A$ について $\\eps\\geqq f_0(x)\\geqq 0$ なので, $e^{-n\\eps}\\leqq e^{-nf_0(x)}\\leqq 1$ となるので, \n\n$$\ne^{-n\\eps}\\int_A g(x)\\,dx\\leqq I_n = \\int_A e^{-nf_0(x)}g(x)\\,dx \\leqq \\int_A g(x)\\,dx.\n$$\n\n$\\ds f(x_0) = \\min_{a\\leqq x\\leqq b} f(x)$ を満たすある $x_0\\in [a,b]$ の近傍で $g(x)>0$ となっていると仮定したことより, $\\ds \\int_A g(x)\\,dx > 0$ となることにも注意せよ.\n\n$x\\in A^c$ について $f_0(x)>\\eps$ なので, $0 < e^{-nf_0(x)}0$ は幾らでも小さくできるので, 下極限と上極限が等しくなることがわかり, \n\n$$\n\\lim_{n\\to\\infty}\\left(-\\frac{1}{n}\\log Z_{0,n}\\right) = 0\n$$\n\nが得られる. $\\QED$\n\n\n```julia\n\n```\n", "meta": {"hexsha": "cd2f608e88392be367c1c991a41d7df3d0bda5e4", "size": 760860, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Old_Ver_for_Julia_v0.6/10 Gauss, Gamma, Beta.ipynb", "max_stars_repo_name": "genkuroki/Calculus", "max_stars_repo_head_hexsha": "424ef53bf493242ce48c58ba39e43b8e601eb403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2018-06-22T13:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T00:04:57.000Z", "max_issues_repo_path": "Old_Ver_for_Julia_v0.6/10 Gauss, Gamma, Beta.ipynb", "max_issues_repo_name": "genkuroki/Calculus", "max_issues_repo_head_hexsha": "424ef53bf493242ce48c58ba39e43b8e601eb403", "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": "Old_Ver_for_Julia_v0.6/10 Gauss, Gamma, Beta.ipynb", "max_forks_repo_name": "genkuroki/Calculus", "max_forks_repo_head_hexsha": "424ef53bf493242ce48c58ba39e43b8e601eb403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-12-28T19:57:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T23:23:46.000Z", "avg_line_length": 82.6034089675, "max_line_length": 7225, "alphanum_fraction": 0.6139802329, "converted": true, "num_tokens": 46219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.20689404148054266, "lm_q1q2_score": 0.0961853649920953}} {"text": "# Homework 5\n## Due Date: Tuesday, October 3rd at 11:59 PM\n\n# Problem 1\nWe discussed documentation and testing in lecture and also briefly touched on code coverage. You must write tests for your code for your final project (and in life). There is a nice way to automate the testing process called continuous integration (CI).\n\nThis problem will walk you through the basics of CI and show you how to get up and running with some CI software.\n\n### Continuous Integration\nThe idea behind continuous integration is to automate away the testing of your code.\n\nWe will be using it for our projects.\n\nThe basic workflow goes something like this:\n\n1. You work on your part of the code in your own branch or fork\n2. On every commit you make and push to GitHub, your code is automatically tested on a fresh machine on Travis CI. This ensures that there are no specific dependencies on the structure of your machine that your code needs to run and also ensures that your changes are sane\n3. Now you submit a pull request to `master` in the main repo (the one you're hoping to contribute to). The repo manager creates a branch off `master`. \n4. This branch is also set to run tests on Travis. If all tests pass, then the pull request is accepted and your code becomes part of master.\n\nWe use GitHub to integrate our roots library with Travis CI and Coveralls. Note that this is not the only workflow people use. Google git..github..workflow and feel free to choose another one for your group.\n\n### Part 1: Create a repo\nCreate a public GitHub repo called `cs207test` and clone it to your local machine.\n\n**Note:** No need to do this in Jupyter.\n\n### Part 2: Create a roots library\nUse the example from lecture 7 to create a file called `roots.py`, which contains the `quad_roots` and `linear_roots` functions (along with their documentation).\n\nAlso create a file called `test_roots.py`, which contains the tests from lecture.\n\nAll of these files should be in your newly created `cs207test` repo. **Don't push yet!!!**\n\n### Part 3: Create an account on Travis CI and Start Building\n\n#### Part A:\nCreate an account on Travis CI and set your `cs207test` repo up for continuous integration once this repo can be seen on Travis.\n\n#### Part B:\nCreate an instruction to Travis to make sure that\n\n1. python is installed\n2. its python 3.5\n3. pytest is installed\n\nThe file should be called `.travis.yml` and should have the contents:\n```yml\nlanguage: python\npython:\n - \"3.5\"\nbefore_install:\n - pip install pytest pytest-cov\nscript:\n - pytest\n```\n\nYou should also create a configuration file called `setup.cfg`:\n```cfg\n[tool:pytest]\naddopts = --doctest-modules --cov-report term-missing --cov roots\n```\n\n#### Part C:\nPush the new changes to your `cs207test` repo.\n\nAt this point you should be able to see your build on Travis and if and how your tests pass.\n\n### Part 4: Coveralls Integration\nIn class, we also discussed code coverage. Just like Travis CI runs tests automatically for you, Coveralls automatically checks your code coverage. One minor drawback of Coveralls is that it can only work with public GitHub accounts. However, this isn't too big of a problem since your projects will be public.\n\n#### Part A:\nCreate an account on [`Coveralls`](https://coveralls.zendesk.com/hc/en-us), connect your GitHub, and turn Coveralls integration on.\n\n#### Part B:\nUpdate your the `.travis.yml` file as follows:\n```yml\nlanguage: python\npython:\n - \"3.5\"\nbefore_install:\n - pip install pytest pytest-cov\n - pip install coveralls\nscript:\n - py.test\nafter_success:\n - coveralls\n```\n\nBe sure to push the latest changes to your new repo.\n\n### Part 5: Update README.md in repo\nYou can have your GitHub repo reflect the build status on Travis CI and the code coverage status from Coveralls. To do this, you should modify the `README.md` file in your repo to include some badges. Put the following at the top of your `README.md` file:\n\n```\n[](https://travis-ci.org/dsondak/cs207testing.svg?branch=master)\n\n[](https://coveralls.io/github/dsondak/cs207testing?branch=master)\n```\n\nOf course, you need to make sure that the links are to your repo and not mine. You can find embed code on the Coveralls and Travis CI sites.\n\n---\n\n# Problem 2\nWrite a Python module for reaction rate coefficients. Your module should include functions for constant reaction rate coefficients, Arrhenius reaction rate coefficients, and modified Arrhenius reaction rate coefficients. Here are their mathematical forms:\n\\begin{align}\n &k_{\\textrm{const}} = k \\tag{constant} \\\\\n &k_{\\textrm{arr}} = A \\exp\\left(-\\frac{E}{RT}\\right) \\tag{Arrhenius} \\\\\n &k_{\\textrm{mod arr}} = A T^{b} \\exp\\left(-\\frac{E}{RT}\\right) \\tag{Modified Arrhenius}\n\\end{align}\n\nTest your functions with the following paramters: $A = 10^7$, $b=0.5$, $E=10^3$. Use $T=10^2$.\n\nA few additional comments / suggestions:\n* The Arrhenius prefactor $A$ is strictly positive\n* The modified Arrhenius parameter $b$ must be real \n* $R = 8.314$ is the ideal gas constant. It should never be changed (except to convert units)\n* The temperature $T$ must be positive (assuming a Kelvin scale)\n* You may assume that units are consistent\n* Document each function!\n* You might want to check for overflows and underflows\n\n**Recall:** A Python module is a `.py` file which is not part of the main execution script. The module contains several functions which may be related to each other (like in this problem). Your module will be importable via the execution script. For example, suppose you have called your module `reaction_coeffs.py` and your execution script `kinetics.py`. Inside of `kinetics.py` you will write something like:\n```python\nimport reaction_coeffs\n# Some code to do some things\n# :\n# :\n# :\n# Time to use a reaction rate coefficient:\nreaction_coeffs.const() # Need appropriate arguments, etc\n# Continue on...\n# :\n# :\n# :\n```\nBe sure to include your module in the same directory as your execution script.\n\n\n```python\n%%file reaction_coeffs.py\nimport numpy as np\nR=8.314\ndef const(k):\n return k\n\ndef arr(A, E, T):\n #Check that A,T,E are numbers\n if ((type(A) != int and type(A) != float) or \n (type(T) != int and type(T) != float) or\n (type(E) != int and type(E) != float)):\n raise TypeError(\"All arguments must be numbers!\")\n \n elif (T<0 or A<0): # A & T must be positive\n raise ValueError(\"Temperature and Arrhenius prefactor must be positive!\")\n \n else:\n #Calculate karr\n karr = A*(np.exp(-E/(R*T)))\n return karr\n \ndef mod_arr(A,E,b,T):\n #Check that A,T,E are numbers\n if ((type(A) != int and type(A) != float) or \n (type(b) != int and type(b) != float) or\n (type(E) != int and type(E) != float) or\n (type(T) != int and type(T) != float)):\n raise TypeError(\"All arguments must be numbers!\")\n \n elif (T<0 or A<0): # A & T must be positive\n raise ValueError(\"Temperature and Arrhenius prefactor must be positive!\")\n \n else:\n #Calculate karr\n karr = A*(T**b)*(np.exp(-E/(R*T)))\n return karr\n```\n\n Overwriting reaction_coeffs.py\n\n\n\n```python\n%%file kinetics.py\nimport reaction_coeffs\n\n# Time to use a reaction rate coefficient:\nreaction_coeffs.const(107)\nreaction_coeffs.arr(107,103,102)\nreaction_coeffs.mod_arr(107,103,0.5,102)\n```\n\n Overwriting kinetics.py\n\n\n\n```python\n%%file kinetics_tests.py\nimport reaction_coeffs\n#Test k_const\ndef test_const():\n assert reaction_coeffs.const(107) == 107\n \n#Test k_arr\ndef test_arr():\n assert reaction_coeffs.arr(107,103,102) == 94.762198593430469\n\ndef test_arr_values1():\n try:\n reaction_coeffs.arr(-1,103,102)\n except ValueError as err:\n assert(type(err) == ValueError)\n \ndef test_arr_values2():\n try:\n reaction_coeffs.arr(107,103,-2)\n except ValueError as err:\n assert(type(err) == ValueError)\n\ndef test_arr_types1():\n try:\n reaction_coeffs.arr('107',103,102)\n except TypeError as err:\n assert(type(err) == TypeError)\n \ndef test_arr_types2():\n try:\n reaction_coeffs.arr(107,'103',102)\n except TypeError as err:\n assert(type(err) == TypeError)\n\ndef test_arr_types3():\n try:\n reaction_coeffs.arr(107,103,[102])\n except TypeError as err:\n assert(type(err) == TypeError) \n \n#Test mod_arr\ndef test_mod_arr():\n assert reaction_coeffs.mod_arr(107,103,0.5,102) == 957.05129266439894\n \ndef test_mod_arr_values1():\n try:\n reaction_coeffs.mod_arr(-1,103,0.5,102)\n except ValueError as err:\n assert(type(err) == ValueError)\n\ndef test_mod_arr_values2():\n try:\n reaction_coeffs.mod_arr(107,103,0.5,-2)\n except ValueError as err:\n assert(type(err) == ValueError)\n \ndef test_mod_arr_types1():\n try:\n reaction_coeffs.mod_arr('107',103,0.5,102)\n except TypeError as err:\n assert(type(err) == TypeError)\n \ndef test_mod_arr_types2():\n try:\n reaction_coeffs.mod_arr(107,'103',0.5,102)\n except TypeError as err:\n assert(type(err) == TypeError)\n\ndef test_mod_arr_types3():\n try:\n reaction_coeffs.mod_arr(107,103,[0.5],102)\n except TypeError as err:\n assert(type(err) == TypeError)\n\ndef test_mod_arr_types4():\n try:\n reaction_coeffs.mod_arr(107,103,0.5,False)\n except TypeError as err:\n assert(type(err) == TypeError)\n \n\ntest_const()\ntest_mod_arr()\ntest_arr()\ntest_arr_values1()\ntest_arr_values2()\ntest_arr_types1()\ntest_arr_types2()\ntest_arr_types3()\ntest_mod_arr_values1()\ntest_mod_arr_values2()\ntest_mod_arr_types1()\ntest_mod_arr_types2()\ntest_mod_arr_types3()\ntest_mod_arr_types4()\n```\n\n Overwriting kinetics_tests.py\n\n\n---\n\n# Problem 3\nWrite a function that returns the **progress rate** for a reaction of the following form:\n\\begin{align}\n \\nu_{A} A + \\nu_{B} B \\longrightarrow \\nu_{C} C.\n\\end{align}\nOrder your concentration vector so that \n\\begin{align}\n \\mathbf{x} = \n \\begin{bmatrix}\n \\left[A\\right] \\\\\n \\left[B\\right] \\\\\n \\left[C\\right]\n \\end{bmatrix}\n\\end{align}\n\nTest your function with\n\\begin{align}\n \\nu_{i}^{\\prime} = \n \\begin{bmatrix}\n 2.0 \\\\\n 1.0 \\\\\n 0.0\n \\end{bmatrix}\n \\qquad \n \\mathbf{x} = \n \\begin{bmatrix}\n 1.0 \\\\ \n 2.0 \\\\ \n 3.0\n \\end{bmatrix}\n \\qquad \n k = 10.\n\\end{align}\n\nYou must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests.\n\n\n```python\ndef progress_rate(v1,x,k):\n \"\"\"Returns the progress rate of a reaction of the form: v1A + v2B -> v3C.\n \n INPUTS\n =======\n v1: list, \n stoichiometric coefficient of reactants in a reaction(s)\n x: float,\n Concentration of A, B, C\n k: float, \n reaction rate coefficient\n \n RETURNS\n ========\n progress rate: a list of the progress rate of each reaction\n \n EXAMPLES\n =========\n >>> progress_rate([2.0,1.0,0.0],[1.0,2.0,3.0],10)\n [20.0]\n \"\"\"\n #Check that x and v1 are lists\n if (type(v1) != list or type(x) != list):\n raise TypeError(\"v' & x must be passed in as a list\")\n #Check that x,and k are numbers/list of numbers\n if (any(type(i) != int and type(i) != float for i in x)):\n raise TypeError(\"All elements in x must be numbers!\")\n elif (type(k) != int and type(k) != float and type(k) != list):\n raise TypeError(\"k must be a numbers!\")\n else:\n progress_rates = []\n #check for multiple reactions\n if(type(v1[0]) == list):\n for v in v1:\n for reactant in v:\n if(type(reactant) != int and type(reactant) != float):\n raise TypeError(\"All elements in v1 must be numbers!\")\n #Calculate the progress rate of each reaction\n reactions = len(v1[0])\n for j in range(reactions):\n if (type(k)== list):\n progress_rate = k[j]\n else:\n progress_rate = k\n for i in range(len(v1)):\n progress_rate = progress_rate*(x[i]**v1[i][j])\n progress_rates.append(progress_rate) \n else:\n #Check types of V1\n if (any(type(i) != int and type(i) != float for i in v1)):\n raise TypeError(\"All elements in v1 must be numbers!\")\n #Calculate the progress rate of each reaction\n progress_rate = k\n for i in range(len(v1)):\n progress_rate = progress_rate*(x[i]**v1[i])\n progress_rates.append(progress_rate)\n return progress_rates\n```\n\n\n```python\nprogress_rate([2.0,1.0,0.0],[1.0,2.0,3.0],10)\n```\n\n\n\n\n [20.0]\n\n\n\n---\n# Problem 4\nWrite a function that returns the **progress rate** for a system of reactions of the following form:\n\\begin{align}\n \\nu_{11}^{\\prime} A + \\nu_{21}^{\\prime} B \\longrightarrow \\nu_{31}^{\\prime\\prime} C \\\\\n \\nu_{12}^{\\prime} A + \\nu_{32}^{\\prime} C \\longrightarrow \\nu_{22}^{\\prime\\prime} B + \\nu_{32}^{\\prime\\prime} C\n\\end{align}\nNote that $\\nu_{ij}^{\\prime}$ represents the stoichiometric coefficient of reactant $i$ in reaction $j$ and $\\nu_{ij}^{\\prime\\prime}$ represents the stoichiometric coefficient of product $i$ in reaction $j$. Therefore, in this convention, I have ordered my vector of concentrations as \n\\begin{align}\n \\mathbf{x} = \n \\begin{bmatrix}\n \\left[A\\right] \\\\\n \\left[B\\right] \\\\\n \\left[C\\right]\n \\end{bmatrix}.\n\\end{align}\n\nTest your function with \n\\begin{align}\n \\nu_{ij}^{\\prime} = \n \\begin{bmatrix}\n 1.0 & 2.0 \\\\\n 2.0 & 0.0 \\\\\n 0.0 & 2.0\n \\end{bmatrix}\n \\qquad\n \\nu_{ij}^{\\prime\\prime} = \n \\begin{bmatrix}\n 0.0 & 0.0 \\\\\n 0.0 & 1.0 \\\\\n 2.0 & 1.0\n \\end{bmatrix}\n \\qquad\n \\mathbf{x} = \n \\begin{bmatrix}\n 1.0 \\\\\n 2.0 \\\\\n 1.0\n \\end{bmatrix}\n \\qquad\n k_{j} = 10, \\quad j=1,2.\n\\end{align}\n\nYou must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests.\n\n\n```python\nprogress_rate([[1.0,2.0],[2.0,0.0],[0.0,2.0]],[1.0,2.0,1.0],10)\n```\n\n\n\n\n [40.0, 10.0]\n\n\n\n---\n# Problem 5\nWrite a function that returns the **reaction rate** of a system of irreversible reactions of the form:\n\\begin{align}\n \\nu_{11}^{\\prime} A + \\nu_{21}^{\\prime} B &\\longrightarrow \\nu_{31}^{\\prime\\prime} C \\\\\n \\nu_{32}^{\\prime} C &\\longrightarrow \\nu_{12}^{\\prime\\prime} A + \\nu_{22}^{\\prime\\prime} B\n\\end{align}\n\nOnce again $\\nu_{ij}^{\\prime}$ represents the stoichiometric coefficient of reactant $i$ in reaction $j$ and $\\nu_{ij}^{\\prime\\prime}$ represents the stoichiometric coefficient of product $i$ in reaction $j$. In this convention, I have ordered my vector of concentrations as \n\\begin{align}\n \\mathbf{x} = \n \\begin{bmatrix}\n \\left[A\\right] \\\\\n \\left[B\\right] \\\\\n \\left[C\\right]\n \\end{bmatrix}\n\\end{align}\n\nTest your function with \n\\begin{align}\n \\nu_{ij}^{\\prime} = \n \\begin{bmatrix}\n 1.0 & 0.0 \\\\\n 2.0 & 0.0 \\\\\n 0.0 & 2.0\n \\end{bmatrix}\n \\qquad\n \\nu_{ij}^{\\prime\\prime} = \n \\begin{bmatrix}\n 0.0 & 1.0 \\\\\n 0.0 & 2.0 \\\\\n 1.0 & 0.0\n \\end{bmatrix}\n \\qquad\n \\mathbf{x} = \n \\begin{bmatrix}\n 1.0 \\\\\n 2.0 \\\\\n 1.0\n \\end{bmatrix}\n \\qquad\n k_{j} = 10, \\quad j = 1,2.\n\\end{align}\n\nYou must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests.\n\n\n```python\ndef reaction_rate(v1,v2,x,k):\n \"\"\"Returns the reaction rate of a reaction of the form: v1A + v2B -> v3C.\n \n INPUTS\n =======\n v1: 2D list, \n stoichiometric coefficient of reactants in a reaction(s)\n v2: 2D list, optional, default value is 2\n stoichiometric coefficient of products in a reaction(s)\n x: float,\n Concentration of A, B, C\n k: float, \n reaction rate coefficient\n \n RETURNS\n ========\n reaction rate: a list of the reaction rate of each reactant\n \n EXAMPLES\n =========\n >>> reaction_rate([[1.0,0.0],[2.0,0.0],[0.0,2.0]],[[0.0,1.0],[0.0,2.0],[1.0,0.0]],[1.0,2.0,1.0],10)\n [-30.0, -60.0, 20.0]\n \"\"\"\n w = progress_rate(v1,x,k)\n #Check that x,v2 and v1 are lists\n if (type(v2) != list or type(x) != list or type(v1)!= list):\n raise TypeError(\"v' & x must be passed in as a list\")\n if (any(type(i) != int and type(i) != float for i in x)):\n raise TypeError(\"All arguments must be numbers!\")\n elif (type(k) != int and type(k) != float and type(k) !=list):\n raise TypeError(\"All arguments must be numbers!\")\n else:\n reaction_rates = []\n for i in (range(len(v2))):\n reaction_rate = 0\n for j in (range(len(v2[0]))):\n reaction_rate = reaction_rate + (v2[i][j]-v1[i][j])*w[j]\n reaction_rates.append(reaction_rate)\n return reaction_rates\n```\n\n\n```python\nreaction_rate([[1.0,0.0],[2.0,0.0],[0.0,2.0]],[[0.0,1.0],[0.0,2.0],[1.0,0.0]],[1.0,2.0,1.0],10)\n```\n\n\n\n\n [-30.0, -60.0, 20.0]\n\n\n\n---\n# Problem 6\nPut parts 3, 4, and 5 in a module called `chemkin`.\n\nNext, pretend you're a client who needs to compute the reaction rates at three different temperatures ($T = \\left\\{750, 1500, 2500\\right\\}$) of the following system of irreversible reactions:\n\\begin{align}\n 2H_{2} + O_{2} \\longrightarrow 2OH + H_{2} \\\\\n OH + HO_{2} \\longrightarrow H_{2}O + O_{2} \\\\\n H_{2}O + O_{2} \\longrightarrow HO_{2} + OH\n\\end{align}\n\nThe client also happens to know that reaction 1 is a modified Arrhenius reaction with $A_{1} = 10^{8}$, $b_{1} = 0.5$, $E_{1} = 5\\times 10^{4}$, reaction 2 has a constant reaction rate parameter $k = 10^{4}$, and reaction 3 is an Arrhenius reaction with $A_{3} = 10^{7}$ and $E_{3} = 10^{4}$.\n\nYou should write a script that imports your `chemkin` module and returns the reaction rates of the species at each temperature of interest given the following species concentrations:\n\n\\begin{align}\n \\mathbf{x} = \n \\begin{bmatrix}\n H_{2} \\\\\n O_{2} \\\\\n OH \\\\\n HO_{2} \\\\\n H_{2}O\n \\end{bmatrix} = \n \\begin{bmatrix}\n 2.0 \\\\\n 1.0 \\\\\n 0.5 \\\\\n 1.0 \\\\\n 1.0\n \\end{bmatrix}\n\\end{align}\n\nYou may assume that these are elementary reactions.\n\n\n```python\n%%file chemkin.py\n\ndef progress_rate(v1,x,k):\n \"\"\"Returns the progress rate of a reaction of the form: v1A + v2B -> v3C.\n \n INPUTS\n =======\n v1: list, \n stoichiometric coefficient of reactants in a reaction(s)\n x: float,\n Concentration of A, B, C\n k: float, \n reaction rate coefficient\n \n RETURNS\n ========\n progress rate: a list of the progress rate of each reaction\n \n EXAMPLES\n =========\n >>> progress_rate([2.0,1.0,0.0],[1.0,2.0,3.0],10)\n [20.0]\n \"\"\"\n #Check that x and v1 are lists\n if (type(v1) != list or type(x) != list):\n raise TypeError(\"v' & x must be passed in as a list\")\n #Check that x,and k are numbers/list of numbers\n if (any(type(i) != int and type(i) != float for i in x)):\n raise TypeError(\"All elements in x must be numbers!\")\n elif (type(k) != int and type(k) != float and type(k) != list):\n raise TypeError(\"k must be a numbers or list!\")\n else:\n progress_rates = []\n #check for multiple reactions\n if(type(v1[0]) == list):\n for v in v1:\n for reactant in v:\n if(type(reactant) != int and type(reactant) != float):\n raise TypeError(\"All elements in v1 must be numbers!\")\n #Calculate the progress rate of each reaction\n reactions = len(v1[0])\n for j in range(reactions):\n if (type(k) == list):\n progress_rate = k[j]\n else:\n progress_rate = k\n for i in range(len(v1)):\n progress_rate = progress_rate*(x[i]**v1[i][j])\n progress_rates.append(progress_rate) \n else:\n #Check types of V1\n if (any(type(i) != int and type(i) != float for i in v1)):\n raise TypeError(\"All elements in v1 must be numbers!\")\n #Calculate the progress rate of each reaction\n progress_rate = k\n for i in range(len(v1)):\n progress_rate = progress_rate*(x[i]**v1[i])\n progress_rates.append(progress_rate)\n return progress_rates\n \ndef reaction_rate(v1,v2,x,k):\n \"\"\"Returns the reaction rate of a reaction of the form: v1A + v2B -> v3C.\n \n INPUTS\n =======\n v1: 2D list, \n stoichiometric coefficient of reactants in a reaction(s)\n v2: 2D list, optional, default value is 2\n stoichiometric coefficient of products in a reaction(s)\n x: float,\n Concentration of A, B, C\n k: float, \n reaction rate coefficient\n \n RETURNS\n ========\n reaction rate: a list of the reaction rate of each reactant\n \n EXAMPLES\n =========\n >>> reaction_rate([[1.0,0.0],[2.0,0.0],[0.0,2.0]],[[0.0,1.0],[0.0,2.0],[1.0,0.0]],[1.0,2.0,1.0],10)\n [-30.0, -60.0, 20.0]\n \"\"\"\n w = progress_rate(v1,x,k)\n #Check that x,v2 and v1 are lists\n if (type(v2) != list or type(x) != list or type(v1)!= list):\n raise TypeError(\"v' & x must be passed in as a list\")\n if (any(type(i) != int and type(i) != float for i in x)):\n raise TypeError(\"All arguments must be numbers!\")\n elif (type(k) != int and type(k) != float and type(k) !=list):\n raise TypeError(\"All arguments must be numbers!\")\n else:\n reaction_rates = []\n for i in (range(len(v2))):\n reaction_rate = 0\n for j in (range(len(v2[0]))):\n reaction_rate = reaction_rate + (v2[i][j]-v1[i][j])*w[j]\n reaction_rates.append(reaction_rate)\n return reaction_rates\n```\n\n Writing chemkin.py\n\n\n\n```python\nimport chemkin\nimport reaction_coeffs\n\nv1 = [[2.0,0.0,0.0],[1.0,0.0,1.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]]\nv2 = [[1.0,0.0,0.0],[0.0,1.0,0.0],[2.0,0.0,1.0],[0.0,0.0,1.0],[0.0,1.0,0.0]]\nx = [2.0,1.0,0.5,1.0,1.0]\n\nk1T1 = reaction_coeffs.mod_arr((10**7),(5*(10**4)),0.5,750)\nk2T1 = reaction_coeffs.const(10**4)\nk3T1 = reaction_coeffs.arr((10**8),(10**4),750)\nk1 = [k1T1,k2T1,k3T1]\n\nk2T2 = reaction_coeffs.const(10**4)\nk3T2 = reaction_coeffs.arr((10**7),(10**4),1500)\nk1T2 = reaction_coeffs.mod_arr((10**8),(5*(10**4)),0.5,1500)\nk2 = [k1T2,k2T2,k3T2]\n\nk2T3 = reaction_coeffs.const(10**4)\nk3T3 = reaction_coeffs.arr((10**7),(10**4),2500)\nk1T3 = reaction_coeffs.mod_arr((10**8),(5*(10**4)),0.5,2500)\nk3 = [k1T3,k2T3,k3T3]\n\nprint([chemkin.reaction_rate(v1,v2,x,k1),chemkin.reaction_rate(v1,v2,x,k2), chemkin.reaction_rate(v1,v2,x,k3)])\n```\n\n [[-360707.78728040616, -20470380.895447683, 20831088.682728089, 20109673.108167276, -20109673.108167276], [-281117620.76487017, -285597559.23804539, 566715180.0029155, 4479938.4731752202, -4479938.4731752202], [-1804261425.9632478, -1810437356.938905, 3614698782.902153, 6175930.9756572321, -6175930.9756572321]]\n\n\n\n```python\n%%file test.py\nimport chemkin\ndef test_progress_rate():\n assert chemkin.progress_rate([3.0,1.0,1.0],[1.0,2.0,3.0],10) == [60.0]\ntest_progress_rate()\n\ndef test_reaction_rate():\n assert chemkin.reaction_rate([[3.0,1.0,1.0]],[[1.0,2.0,1.0]],[1.0,2.0,3.0],10) == [-10.0]\ntest_reaction_rate()\n```\n\n Overwriting test.py\n\n\n\n```python\n!pytest --doctest-modules --cov-report term-missing --cov\n```\n\n \u001b[1m============================= test session starts ==============================\u001b[0m\n platform darwin -- Python 3.6.1, pytest-3.2.1, py-1.4.33, pluggy-0.4.0\n rootdir: /Users/riddhishah/Documents/cs207/cs207_riddhi_shah/homeworks/HW5, inifile:\n plugins: cov-2.3.1\n collected 0 items \u001b[0m\u001b[1m\u001b[1m\n \n \n ---------- coverage: platform darwin, python 3.6.1-final-0 -----------\n Name Stmts Miss Cover Missing\n --------------------------------------------------\n chemkin.py 43 9 79% 5, 8, 10, 18, 23, 32, 44, 46, 48\n kinetics.py 4 0 100%\n kinetics_tests.py 76 0 100%\n reaction_coeffs.py 18 0 100%\n test.py 7 0 100%\n --------------------------------------------------\n TOTAL 148 9 94%\n \n \u001b[33m\u001b[1m========================= no tests ran in 2.02 seconds =========================\u001b[0m\n\n\n---\n# Problem 7\nGet together with your project team, form a GitHub organization (with a descriptive team name), and give the teaching staff access. You can have has many repositories as you like within your organization. However, we will grade the repository called **`cs207-FinalProject`**.\n\nWithin the `cs207-FinalProject` repo, you must set up Travis CI and Coveralls. Make sure your `README.md` file includes badges indicating how many tests are passing and the coverage of your code.\n\n\n```python\n'''Done by Hongxiang in our group!'''\n```\n\n\n\n\n 'Done by Hongxiang in our group!'\n\n\n", "meta": {"hexsha": "c625354adbfec6893599341e4325c661cf073275", "size": 36022, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homeworks/HW5/HW5-Final.ipynb", "max_stars_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_stars_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "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": "homeworks/HW5/HW5-Final.ipynb", "max_issues_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_issues_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "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": "homeworks/HW5/HW5-Final.ipynb", "max_forks_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_forks_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "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": 36.0580580581, "max_line_length": 424, "alphanum_fraction": 0.5100771751, "converted": true, "num_tokens": 7414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370634623958195, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.09607921914762856}} {"text": "# Week 1\n\n__Goals for this week__\n\nWe will talk about the organization of this course, including the weekly tasks and 3 \"mini\"-projects that await you during on during this semester.\nWe will introduce the frameworks you will use and a you will get a geniality quick course (rychlokurz geniality) in Python, required library and standard structures.\n\n__What is this file?__\n\nThis is a Jupyter notebook. A file, that contains python scripts and also stores the binary results.\n\n__How can I run it?__\n\nFirs you have to run/configure your Jupyter server in your desired python environment.\nThen just follow this notebook and run it cell by cell. Try to answer - code - the questions, so you'll get better grasp on python array/list/dictionary structures.\n\n## Course Information\nIf nothing changes:\n- __Weekly tasks [7 pts]:__ First 3 weeks (after this one), you will work on the same tasks for better understanding of how neural networks work.\n- __Projects [5 pts, 13 pts, 20 pts]:__ You will work in pairs on 3 deep learning project with gradually increasing difficulty throughout the entire semester. You will present your progress during the consultations, which are marked so you will be scored continuously and for the final presentations of your solutions.\n- __Midterm [15 pts]:__ This is gonna be fun\n- __Exam [40 pts]__ This is gonna be a nightmare\n(No worries, not for you, for me to create them)\n\n### Feedback\n\n- Please use\n- Please fill our\n- This notebook is a work in progress. If you notice a mistake, notify us, raise an issue or make a pull request on\n\n### Python\n\nWe will use _Python 3.7_ compatible code in these notebooks, however it may work with older versions.\nWe assume that you have seen Python code before. If you have not, the quick course may help and also you should learn the basics as soon as possible (e.g. [W3Schools tutorial](https://www.w3schools.com/python/default.asp))).\nYour first task is to configure python environment, Tensorflow (CPU or GPU based on you HW), PyTorch, and to practice python concepts in the scripts below.\nYou should understand it fully, otherwise review your knowledge before you proceed. You will need it in the following weeks.\n\n\n```python\n# Line comment as you\n\"\"\"\nBlock comment\n\"\"\"\n\n# input and output\nname=input()\nprint(\"Hello, \"+name)\n\n```\n\n Hello, Petko a Denko\n\n\n\n```python\n# variables don't need explicit type declaration\nvar = 'Neural Networks rule!'\nvar = 2021\nvar = 20.21\nvar = True\nvar = [29,1,2021]\nvar = {'NN':'Rule!', 'year':2021}\n\n# Basic types\n2021 # integer\n36.5 # float\n'cool' # string\nTrue, False # boolean operands\nNone # null-like operand\n# python specific\n[12,34,'hello','world'] # list\n{123:456,'DL':'NN'} # dictionary\n\n# Type conversion\nfloat('36.5')\nint(36.5)\nstr(3.65)\n\n# Basic operations\na = 2 + 5 - 2.5\na += 3\nb = 2 ** 3 # exponentiation\nprint(a, b)\nprint(5 / 2)\nprint(5 // 2) # Notice the difference between these two\nprint('DL' + 'NN')\n# All compound assignment operators available\n# including += -= *= **= /= //=\n# pre/post in/decrementers not available (++ --)\n\n\n# F-strings\nprint(f'1 + 2 = {1 + 2}, a = {a}')\nprint('1 + 2 = {1 + 2}, a = {a}') # We need the f at the start for {} to work as expression wrappers.\n\n```\n\n 7.5 8\n 2.5\n 2\n DLNN\n 1 + 2 = 3, a = 7.5\n 1 + 2 = {1 + 2}, a = {a}\n\n\n\n```python\n# Conditions\nif a > 4 and b < 3: # and, or and not are the basic logical operators\n print('a') # Indentation by spaces or tabs tells us where the statement belongs. print('a') is in the if.\nelif b > 5:\n print('b') # Indentation by spaces or tabs tells us where the statement belongs. print('b') is in the elif.\nelse:\n print('c') # Indentation by spaces or tabs tells us where the statement belongs. print('c') is in the else.\nprint('d') # But print('d') is outside, it will print every time.\n\n# Loops\nwhile a < 10:\n if b > 3:\n a += 1 # More indentation for code that is \"deeper\"\n else:\n a += 2\nprint(f'a = {a}')\n\n# 'while' loops are not considered 'pythonic'. 'for' loops are more common\nfor char in 'string':\n print(char)\n\n```\n\n b\n d\n a = 10.5\n s\n t\n r\n i\n n\n g\n\n\n\n```python\n# Lists - work like C arrays, but they are not dependent on element type\na = [1, 2.4, 10e-7, 0b1001, 'some \"text\"'] # embedded \"\" in '', works vice versa\nlen(a) # Length\nprint(a[1]) # Second element\nprint(a[1:3]) # Second to third element\na.append(4) # Adding at the end\ndel a[3] # Removing at the index\nprint([]) # Empty array\nprint(a)\n\n# This is why for loops are used more often\nfor el in a:\n# but be careful with iterations over list which contain different var types - it is your responsibility\n print(el + 1)\n\n```\n\n\n```python\na = [1, 2.4, 10e-7, 0b1001]\n# We can define lists with list comprehension statements\nb = [el + 2 for el in a]\nprint(b)\n\n```\n\n [3, 4.4, 2.000001, 11]\n\n\n\n```python\n# Dictionaries - key-based structures\na = {\n 'layer_1': 'dense',\n 5: 'five',\n 4: 'four',\n 'result': [1, 2, 3]\n}\nprint(a['layer_1'])\na['layer_2'] = 'ReLU'\nif 'result' in a: # Does key exist?\n print(a['result'])\n{} # Empty\ndel a[5] # Remove record\n \nprint()\nprint('Keys:')\nfor key in a:\n print(key)\n \nprint()\nprint('Keys and values:')\nfor key, value in a.items():\n print(key, ':', value)\n \n# Dictionaries can be also defined via comprehension statement\na = {i: i**2 for i in [1, 2, 3, 4]}\nprint(a)\n\n```\n\n dense\n [1, 2, 3]\n \n Keys:\n layer_1\n 4\n result\n layer_2\n \n Keys and values:\n layer_1 : dense\n 4 : four\n result : [1, 2, 3]\n layer_2 : ReLU\n {1: 1, 2: 4, 3: 9, 4: 16}\n\n\n\n```python\n# Most common and useful iterators\nprint('range(start, stop, step)')\nfor i in range(10,20,2):\n print(i)\n\nprint()\nprint('enumerate')\nlowercase = ['a', 'b', 'c']\nfor i, el in enumerate(lowercase): # iterates over elements attaching the index order\n print(i, el)\n\nprint()\nprint('zip') # Like a zip - side-by-side merges lists together for iteration\nuppercase = ['A', 'B', 'C']\nnumbers = [1,2,3]\nfor n, a, b in zip(numbers,lowercase, uppercase):\n print(n, a, b)\n\n```\n\n range(start, stop, step)\n 10\n 12\n 14\n 16\n 18\n \n enumerate\n 0 a\n 1 b\n 2 c\n \n zip\n 1 a A\n 2 b B\n 3 c C\n\n\n\n```python\n# Functions\ndef example_function(a, b=1, c=1): # b and c have default values\n return a*b, a*c # we return two values at the same time\n\na, b = example_function(1, 2, 3) # and we can assign both values at the same time as well\nprint(a, b)\nprint(example_function(4))\nprint(example_function(5, 2))\nprint(example_function(5, c=2)) # Notice how do the arguments behave\n\n# Classes\nclass A:\n\n def __init__(self, b): # Constructor\n self.b = b # Object variable\n\n def add_to_b(self, c): # self is always the first argument and it references the object itself\n self.b += c\n\n def sub_from_b(self, c):\n self.add_to_b(-c) # Calling object method\n\n def __str__(self): # every python class contain several default methods that start and end with __\n return f'Class A, b={self.b}'\n\n # be careful with naming and using underscores _\n # private, protected and public is expressed by underscores\n # default is public\n def foo(self):\n print(\"I'm public\")\n\n def _bar(self):\n print(\"I'm protected\")\n def __nope(self):\n\n print(\"You shall not print me, I'm private\")\n\na = A(5)\na.add_to_b(1)\nprint(a.b)\na.sub_from_b(2)\nprint(a.b)\nprint(a)\na.foo()\na.bar()\na.nope()\n```\n\n### Linear Algebra\n\nNeural network models can be defined using vectors and matrices, i.e. concepts from linear algebra.\nThe _DeepLearningBook_ dedicates first pages for linear algebra, we will be using a bit of it during this semester, therefore you should know how basic linear operations work. Some of the concepts were covered during your _Algebra and Discrete Mathematics_ course. Read the provided links to review necessary topics (note that there are some questions at the end of each page) and solve the exercises in this notebook.\n\n#### Vectors\n- [On vectors](https://www.mathsisfun.com/algebra/vectors.html)\n- [On dot product](https://www.mathsisfun.com/algebra/vectors-dot-product.html)\n\nIn these labs we use _DeepLearningBook_ notation: simple italic for scalars $x$, lowercase bold italic for vectors $\\boldsymbol{x}$ and uppercase bold italics for matrices $\\boldsymbol{X}$.\nPlease, keep this notation in mind.\n\n### NumPy\n\n[Numpy](https://numpy.org/) is a popular Python library for scientific computation. It provides a convenient way of working with vectors and matrices.\nIdeally try to use NumPy to solve these exercises.\n\n\n\n```python\nimport numpy as np\n```\n\n__Exercise 1.1:__ Calculate the following:\n\n$\n\\begin{align}\n\\boldsymbol{a} = \\begin{bmatrix}0 \\\\ 1 \\\\ 3 \\end{bmatrix} \\ \\\n\\boldsymbol{b} = \\begin{bmatrix}2 \\\\ 4 \\\\ 1 \\end{bmatrix}\n\\end{align}\n$\n\n$5\\boldsymbol{a} = ?$\n\n$\\boldsymbol{a} + \\boldsymbol{b} = ?$\n\n$\\boldsymbol{a} \\cdot \\boldsymbol{b} = ?$\n\n$||\\boldsymbol{a}|| = ?$\n\n\n\nTODO\n\n\n```python\n# Init vectors\na = np.array([0, 1, 3])\nb = np.array([2, 4, 1])\n\n# Basic operations, results for E 1.1\nprint(5*a)\nprint(a + b)\nprint(np.dot(a, b))\nprint(np.linalg.norm(a))\n```\n\n [ 0 5 15]\n [2 5 4]\n 7\n 3.1622776601683795\n\n\n__Exercise 1.2:__ Determine quickly whether or not two vectors (e.g. $\\boldsymbol{a}$ and $\\boldsymbol{b}$) are orthogonal (perpendicular)?\n\nTODO\n\n\n```python\n# Perpendicularity (similarity) of vectors\nnp.linalg.norm(a - b)\n```\n\n\n\n\n 4.123105625617661\n\n\n\n__Exercise 1.3:__ Compute which vector is longer, $\\boldsymbol{a}$ or $\\boldsymbol{b}$?\n\n\n```python\n# Length of vectors\nlen_a = np.linalg.norm(a)\nlen_b = np.linalg.norm(b)\n\nprint('a' if len_a > len_b else 'b')\n```\n\n b\n\n\n#### Matrices\n- [On matrices](https://www.mathsisfun.com/algebra/matrix-introduction.html)\n- [On matrix multiplication](https://www.mathsisfun.com/algebra/matrix-multiplying.html)\n\n\n__INFO: NumPy array indexing__\n\n\n```python\n# Indexing, i.e. selecting elements from an array / vector / matrix\n\nW = np.array([\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n])\n\nW[1, 1] # Element from second row of second column\nW[0] # First row\nW[[0, 2]] # First AND third row\nW[:, 0] # First column\nW[1, [0, 2]] # First AND third column of second row\n\n# Access array slices by index\na = np.zeros([10,10])\na[:3] = 1\na[:, :3] = 2\na[:3, :3] = 3\nrows = [4,6,7]\ncols = [9,3,5]\na[rows, cols] = 4\nprint(a)\n\n# transposition\na = np.arange(24).reshape(2,3,4)\nprint(a.shape)\nprint(a)\na=np.transpose(a, (2,1,0))\n# swap 0th and 2nd axes\nprint(a.shape)\nprint(a)\n\n```\n\n [[3. 3. 3. 1. 1. 1. 1. 1. 1. 1.]\n [3. 3. 3. 1. 1. 1. 1. 1. 1. 1.]\n [3. 3. 3. 1. 1. 1. 1. 1. 1. 1.]\n [2. 2. 2. 0. 0. 0. 0. 0. 0. 0.]\n [2. 2. 2. 0. 0. 0. 0. 0. 0. 4.]\n [2. 2. 2. 0. 0. 0. 0. 0. 0. 0.]\n [2. 2. 2. 4. 0. 0. 0. 0. 0. 0.]\n [2. 2. 2. 0. 0. 4. 0. 0. 0. 0.]\n [2. 2. 2. 0. 0. 0. 0. 0. 0. 0.]\n [2. 2. 2. 0. 0. 0. 0. 0. 0. 0.]]\n (2, 3, 4)\n [[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n \n [[12 13 14 15]\n [16 17 18 19]\n [20 21 22 23]]]\n (4, 3, 2)\n [[[ 0 12]\n [ 4 16]\n [ 8 20]]\n \n [[ 1 13]\n [ 5 17]\n [ 9 21]]\n \n [[ 2 14]\n [ 6 18]\n [10 22]]\n \n [[ 3 15]\n [ 7 19]\n [11 23]]]\n\n\n__Exercise 1.4:__ Calculate the following. Vectors are columns by default.\n\n$\n\\boldsymbol{C} = \\begin{bmatrix}0 & 2 & 4\\\\ 1 & 2 & 5 \\end{bmatrix}\n\\boldsymbol{d} = \\begin{bmatrix} 1 & 7 \\end{bmatrix}\n\\boldsymbol{E} = \\begin{bmatrix} 1 & 2 \\\\ 3 & 4 \\\\ \\end{bmatrix}\n$\n\n$\\boldsymbol{C}\\boldsymbol{d} = ?$\n\n$\\boldsymbol{C}\\boldsymbol{E} = ?$\n\n$\\boldsymbol{d}^T \\boldsymbol{C} - \\boldsymbol{d}^T = ?$\n\n$\\boldsymbol{C}^T\\boldsymbol{d} = ?$\n\n$\\boldsymbol{C}\\boldsymbol{d}^T = ?$\n\n$\\boldsymbol{d}\\boldsymbol{E} = ?$\n\n\n```python\n# Init matrices\n# One way:\nC = np.array([\n [0, 2, 4],\n [1, 2, 5]\n])\n\nd = np.array([1, 7])\n\n# Other way:\nE = np.arange(4).reshape(2, 2)\n\nprint(C.T * d)\nprint(C.T @ E)\nprint(d * C.T - d)\n```\n\n [[ 0 7]\n [ 2 14]\n [ 4 35]]\n [[ 2 3]\n [ 4 8]\n [10 19]]\n [[-1 0]\n [ 1 7]\n [ 3 28]]\n\n\n__Exercise 1.5:__ We can express the result of general matrix-vector product $\\boldsymbol{Ex}_1$ as a vector of dot products.\nIs it possible to do the same with $\\boldsymbol{x}_2^T\\boldsymbol{E}$?\n\n\n```python\n# There is a difference between a 1-D vector and a column matrix in numpy:\nx1 = np.array([1, 2]) # This is a vector\nx2 = np.array([ # This is a matrix\n [1],\n [2]\n])\n\n# First let's see the dimensions of these two\nprint(x1.shape)\nprint(x2.shape)\n\n# Matrix - vector multiplicataion\n# Then we can multiply them with E using np.matmul or @ matrix multiplication operator\nprint(E @ x1)\n\n# TODO x_2^T \\times E\n\n```\n\n (2,)\n (2, 1)\n [2 8]\n [[2]\n [8]]\n\n\n__Exercise 1.6:__ What is the difference between the two results from previous code cell?\n\nTODO actually, just think about the answer ;)\n\n\n### Derivatives\n\nThe final topic to cover are derivatives.\nAlmost all training algorithms of neural networks in practice are based on calculating the derivatives with respect to (w.r.t.) parameters of the model.\nYou should know the basics from your _Calculus course_ (Matematická analýza), but just in case, we recommend you to read the following to refresh your memory:\n\n- [On derivatives](https://www.mathsisfun.com/calculus/derivatives-introduction.html)\n\nYou won't need to use derivatives during this course, so you won't need to learn all the [derivative rules](https://www.mathsisfun.com/calculus/derivatives-rules.html). However we need you to have an intuition about what derivatives are and what is their geometric interpretation. In essence, we need you to understand that a derivative tells us what is the slope of the tangent at given point. You should understand what is happening in the gif below:\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(6,6))\ntangents = plt.imread('images/tangents.gif')\nplt.imshow(tangents)\n```\n\n
License: en:User:Dino, User:Lfahlberg CC BY-SA 3.0, via Wikimedia Commons
\n\nPartial derivatives are a concept you might have not head about before.\nIt is applied when we derive a function with more than one variable.\nIn such case we can actually derive a function in any direction.\n\nRead the following link:\n\n- [On partial derivatives](https://www.mathsisfun.com/calculus/derivatives-partial.html)\n\nFunction of one variable (1D) is a curve, and of two variables (2D) is a topographical relief.\n2D function can be visualized by a 3D graph.\nIn this graph you can pick a point and then ask, what is a slope of the tangent in any direction.\nMost commonly you would calculate the slope along axes of both variables (let's say $x,y$): $\\frac{df}{dx}$ and $\\frac{df}{dy}$.\n\nVector of derivatives w.r.t. all the parameters is called a _gradient_.\nGenerally for function $f$ with arbitrary number of parameters $x_1. x_2, ..., x_N = \\boldsymbol{x}$, the gradient $\\triangledown f$ is defined as:\n\n\\begin{equation}\n\\triangledown f(\\boldsymbol{x}) = \\frac{df}{d\\boldsymbol{x}} = \\begin{bmatrix}\\frac{df}{dx_1} \\\\ \\frac{df}{dx_2} \\\\ \\vdots \\\\ \\frac{df}{dx_N} \\end{bmatrix}\n\\end{equation}\n\nGradient is the most important concept from this week's lab. The gradient is a vector quantity that tells us the _direction of steepest ascent_ at each point. This is a very important property, which we will often use in the following weeks. The magnitude of this vector tells us how steep this ascent is, i.e. what is the slope of the tangent in the direction of the gradient.\n\nTo cpmpare _derivative_ and _gradient_:\n\n- _Derivative_ is a quantity that tells us, what is the rate of change in given direction.\n- _Gradient_ is a quantity that tells us what is the direction of the steepest rate of change, along with the rate of this change.\n\nObserve the difference between these two concepts in the Figure below. All the plots show the same function $F(x,y) = \\sin(x) \\cos(y)$. In first two plots we shot the derivatives w.r.t $y$ and $x$ respectively. These are shown as white arrows. Notice that they all point in one direction. On the other hand in the last plot we show the gradients. If we interpret the derivatives from the two previous plots as vectors, these gradients are in fact their sum.\n\n\n\n```python\nfrom backstage import plots\nplots.derivatives_plot()\n```\n\n__Exercise 1.8:__ With the following derivative rules:\n- $(af)' = af'$\n- $(f + g)' = f' + g'$\n- $(x^k)' = kx^{k-1}$\n\nCalculate the following:\n\n$f(x^2 + y^2 + 2x)$\n\n$\\frac{df}{dx}=?$\n\n$\\frac{df}{dy}=?$\n\n$\\triangledown f(x, y) = ?$\n\n$g(x_1, x_2, \\dots, x_N) = g(\\boldsymbol{x}) = \\boldsymbol{a} \\cdot \\boldsymbol{x}$\n\n$\\triangledown g(\\boldsymbol{x}) = ?$\n\n\n\n```python\n# TODO Derivatives ... by hand... on your paper\n```\n\n### Correct Answers\n\n__E 1.4:__\n\nThe term $\\boldsymbol{C}\\boldsymbol{d}^T$ is not valid. You can not multiply two matrices with dimensions $3 \\times 2$ and $1 \\times 2$.\nAlso the term $\\boldsymbol{E}\\boldsymbol{d} is also invalid.\n\n__E 1.7:__\n\n$\\frac{df}{dx}= 2x + 2$\n\n$\\frac{df}{dy}= 2y$\n\n$\\triangledown f(x, y) = \\begin{bmatrix}2x + 2 \\\\ 2y \\end{bmatrix} $\n\n$\\triangledown g(\\boldsymbol{x}) = \\boldsymbol{a}$\n\n\n```python\n\n```\n\n\n \nCreated in Deepnote\n", "meta": {"hexsha": "d3ddf247e16de0a49b46b16007735d5383ca9cfd", "size": 168446, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week_1/TrainExercises.ipynb", "max_stars_repo_name": "denislaca/neural_networks_at_fiit", "max_stars_repo_head_hexsha": "0d8c889e1334bd5db7ff6028453897411cafa610", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week_1/TrainExercises.ipynb", "max_issues_repo_name": "denislaca/neural_networks_at_fiit", "max_issues_repo_head_hexsha": "0d8c889e1334bd5db7ff6028453897411cafa610", "max_issues_repo_licenses": ["BSD-2-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": "week_1/TrainExercises.ipynb", "max_forks_repo_name": "denislaca/neural_networks_at_fiit", "max_forks_repo_head_hexsha": "0d8c889e1334bd5db7ff6028453897411cafa610", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 168446.0, "max_line_length": 168446, "alphanum_fraction": 0.9193153889, "converted": true, "num_tokens": 5593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.20434190478229486, "lm_q1q2_score": 0.09579356958889225}} {"text": "```python\n\"\"\"Intermolecular Interactions and Symmetry-Adapted Perturbation Theory\"\"\"\n\n__authors__ = \"Konrad Patkowski\"\n__email__ = [\"patkowsk@auburn.edu\"]\n\n__copyright__ = \"(c) 2008-2020, The Psi4Education Developers\"\n__license__ = \"BSD-3-Clause\"\n__date__ = \"2020-07-16\"\n```\n\nThis lab activity is designed to teach students about weak intermolecular interactions, and the calculation and interpretation of the interaction energy between two molecules. The interaction energy can be broken down into physically meaningful contributions (electrostatics, induction, dispersion, and exchange) using symmetry-adapted perturbation theory (SAPT). In this exercise, we will calculate complete interaction energies and their SAPT decomposition using the procedures from the Psi4 software package, processing and analyzing the data with NumPy and Matplotlib.\n\nPrerequisite knowledge: the Hartree-Fock method, molecular orbitals, electron correlation and the MP2 theory. The lab also assumes all the standard Python prerequisites of all Psi4Education labs.\n\nLearning Objectives: \n1. Recognize and appreciate the ubiquity and diversity of intermolecular interactions.\n2. Compare and contrast the supermolecular and perturbative methods of calculating interaction energy.\n3. Analyze and interpret the electrostatic, induction, dispersion, and exchange SAPT contributions at different intermolecular separations.\n\nAuthor: Konrad Patkowski, Auburn University (patkowsk@auburn.edu; ORCID: 0000-0002-4468-207X)\n\nCopyright: Psi4Education Project, 2020\n\n# Weak intermolecular interactions \n\nIn this activity, you will examine some properties of weak interactions between molecules. As the molecular subunits are not connected by any covalent (or ionic) bonds, we often use the term *noncovalent interactions*. Suppose we want to calculate the interaction energy between molecule A and molecule B for a certain geometry of the A-B complex (obviously, this interaction energy depends on how far apart the molecules are and how they are oriented). The simplest way of doing so is by subtraction (in the so-called *supermolecular approach*):\n\n\\begin{equation}\nE_{\\rm int}=E_{\\rm A-B}-E_{\\rm A}-E_{\\rm B}\n\\end{equation}\n\nwhere $E_{\\rm X}$ is the total energy of system X, computed using our favorite electronic structure theory and basis set. A negative value of $E_{\\rm int}$ means that A and B have a lower energy when they are together than when they are apart, so they do form a weakly bound complex that might be stable at least at very low temperatures. A positive value of $E_{\\rm int}$ means that the A-B complex is unbound - it is energetically favorable for A and B to go their separate ways. \n\nLet's consider a simple example of two interacting helium atoms and calculate $E_{\\rm int}$ at a few different interatomic distances $R$. You will use Psi4 to calculate the total energies that you need to perform subtraction. When you do so for a couple different $R$, you will be able to sketch the *potential energy curve* - the graph of $E_{\\rm int}(R)$ as a function of $R$.\n\nOK, but how should you pick the electronic structure method to calculate $E_{\\rm A-B}$, $E_{\\rm A}$, and $E_{\\rm B}$? Let's start with the simplest choice and try out the Hartree-Fock (HF) method. In case HF is not accurate enough, we will also try the coupled-cluster method with single, double, and perturbative triple excitations - CCSD(T). If you haven't heard about CCSD(T) before, let's just state that it is **(1)** usually very accurate (it's even called the *gold standard* of electronic structure theory) and **(2)** very expensive for larger molecules. For the basis set, let's pick the augmented correlation consistent triple-zeta (aug-cc-pVTZ) basis of Dunning which should be quite OK for both HF and CCSD(T).\n\n\n\n```python\n# A simple Psi4 input script to compute the potential energy curve for two helium atoms\n\n%matplotlib notebook\nimport time\nimport numpy as np\nimport scipy\nfrom scipy.optimize import *\nnp.set_printoptions(precision=5, linewidth=200, threshold=2000, suppress=True)\nimport psi4\nimport matplotlib.pyplot as plt\n\n# Set Psi4 & NumPy Memory Options\npsi4.set_memory('2 GB')\npsi4.core.set_output_file('output.dat', False)\n\nnumpy_memory = 2\n\npsi4.set_options({'basis': 'aug-cc-pVTZ',\n 'e_convergence': 1e-10,\n 'd_convergence': 1e-10,\n 'INTS_TOLERANCE': 1e-15})\n\n\n```\n\nWe need to collect some data points to graph the function $E_{\\rm int}(R)$. Therefore, we set up a list of distances $R$ for which we will run the calculations (we go with 11 of them). For each distance, we need to remember three values ($E_{\\rm A-B}$, $E_{\\rm A}$, and $E_{\\rm B}$). For this purpose, we will prepare two $11\\times 3$ NumPy arrays to hold the HF and CCSD(T) results. \n\n\n\n```python\ndistances = [4.0,4.5,5.0,5.3,5.6,6.0,6.5,7.0,8.0,9.0,10.0]\nehf = np.zeros((11,3))\neccsdt = np.zeros((11,3))\n\n\n```\n\nWe are almost ready to crunch some numbers! One question though: how are we going to tell Psi4 whether we want $E_{\\rm A-B}$, $E_{\\rm A}$, or $E_{\\rm B}$? \nWe need to define three different geometries. The $E_{\\rm A-B}$ one has two helium atoms $R$ atomic units from each other - we can place one atom at $(0,0,0)$ and the other at $(0,0,R)$. The other two geometries involve one actual helium atom, with a nucleus and two electrons, and one *ghost atom* in place of the other one. A ghost atom does not have a nucleus or electrons, but it does carry the same basis functions as an actual atom - we need to calculate all energies in the same basis set, with functions centered at both $(0,0,0)$ and $(0,0,R)$, to prevent the so-called *basis set superposition error*. In Psi4, the syntax `Gh(X)` denotes a ghost atom where basis functions for atom type X are located. \n\nUsing ghost atoms, we can now easily define geometries for the $E_{\\rm A}$ and $E_{\\rm B}$ calculations.\n\n\n\n```python\nfor i in range(len(distances)):\n dimer = psi4.geometry(\"\"\"\n He 0.0 0.0 0.0\n --\n He 0.0 0.0 \"\"\"+str(distances[i])+\"\"\"\n units bohr\n symmetry c1\n \"\"\")\n\n psi4.energy('ccsd(t)') #HF will be calculated along the way\n ehf[i,0] = psi4.variable('HF TOTAL ENERGY')\n eccsdt[i,0] = psi4.variable('CCSD(T) TOTAL ENERGY')\n psi4.core.clean()\n\n monomerA = psi4.geometry(\"\"\"\n He 0.0 0.0 0.0\n --\n Gh(He) 0.0 0.0 \"\"\"+str(distances[i])+\"\"\"\n units bohr\n symmetry c1\n \"\"\")\n\n psi4.energy('ccsd(t)') #HF will be calculated along the way\n ehf[i,1] = psi4.variable('HF TOTAL ENERGY')\n eccsdt[i,1] = psi4.variable('CCSD(T) TOTAL ENERGY')\n psi4.core.clean()\n\n monomerB = psi4.geometry(\"\"\"\n Gh(He) 0.0 0.0 0.0\n --\n He 0.0 0.0 \"\"\"+str(distances[i])+\"\"\"\n units bohr\n symmetry c1\n \"\"\")\n\n psi4.energy('ccsd(t)') #HF will be calculated along the way\n ehf[i,2] = psi4.variable('HF TOTAL ENERGY')\n eccsdt[i,2] = psi4.variable('CCSD(T) TOTAL ENERGY')\n psi4.core.clean()\n\n\n```\n\nWe have completed the $E_{\\rm A-B}$, $E_{\\rm A}$, or $E_{\\rm B}$ calculations for all 11 distances $R$ (it didn't take that long, did it?). We will now perform the subtraction to form NumPy arrays with $E_{\\rm int}(R)$ values for each method, converted from atomic units (hartrees) to kcal/mol, and graph the resulting potential energy curves using the matplotlib library. \n\n\n\n```python\n#COMPLETE the two lines below to generate interaction energies. Convert them from atomic units to kcal/mol.\neinthf = \neintccsdt = \n\nprint ('HF PEC',einthf)\nprint ('CCSD(T) PEC',eintccsdt)\n\nplt.plot(distances,einthf,'r+',linestyle='-',label='HF')\nplt.plot(distances,eintccsdt,'bo',linestyle='-',label='CCSD(T)')\nplt.hlines(0.0,4.0,10.0)\nplt.legend(loc='upper right')\nplt.show()\n\n```\n\n*Questions* \n1. Which curve makes more physical sense?\n2. Why does helium form a liquid at very low temperatures?\n3. You learned in freshman chemistry that two helium atoms do not form a molecule because there are two electrons on a bonding orbital and two electrons on an antibonding orbital. How does this information relate to the behavior of HF (which does assume a molecular orbital for every electron) and CCSD(T) (which goes beyond the molecular orbital picture)?\n4. When you increase the size of the interacting molecules, the CCSD(T) method quickly gets much more expensive and your calculation might take weeks instead of seconds. It gets especially expensive for the calculation of $E_{\\rm A-B}$ because A-B has more electrons than either A or B. Your friend suggests to use CCSD(T) only for the easier terms $E_{\\rm A}$ and $E_{\\rm B}$ and subtract them from $E_{\\rm A-B}$ calculated with a different, cheaper method such as HF. Why is this a really bad idea?\n\n*To answer the questions above, please double click this Markdown cell to edit it. When you are done entering your answers, run this cell as if it was a code cell, and your Markdown source will be recompiled.*\n\n\nA nice feature of the supermolecular approach is that it is very easy to use - you just need to run three standard energy calculations, and modern quantum chemistry codes such as Psi4 give you a lot of methods to choose from. However, the accuracy of subtraction hinges on error cancellation, and we have to be careful to ensure that the errors do cancel between $E_{\\rm A-B}$ and $E_{\\rm A}+E_{\\rm B}$. Another drawback of the supermolecular approach is that it is not particularly rich in physical insight. All that we get is a single number $E_{\\rm int}$ that tells us very little about the underlying physics of the interaction. Therefore, one may want to find an alternative approach where $E_{\\rm int}$ is computed directly, without subtraction, and it is obtained as a sum of distinct, physically meaningful terms. Symmetry-adapted perturbation theory (SAPT) is such an alternative approach.\n\n# Symmetry-Adapted Perturbation Theory (SAPT)\n\nSAPT is a perturbation theory aimed specifically at calculating the interaction energy between two molecules. Contrary to the supermolecular approach, SAPT obtains the interaction energy directly - no subtraction of similar terms is needed. Moreover, the result is obtained as a sum of separate corrections accounting for the electrostatic, induction, dispersion, and exchange contributions to interaction energy, so the SAPT decomposition facilitates the understanding and physical interpretation of results.\n- *Electrostatic energy* arises from the Coulomb interaction between charge densities of isolated molecules.\n- *Induction energy* is the energetic effect of mutual polarization between the two molecules.\n- *Dispersion energy* is a consequence of intermolecular electron correlation, usually explained in terms of correlated fluctuations of electron density on both molecules.\n- *Exchange energy* is a short-range repulsive effect that is a consequence of the Pauli exclusion principle.\n\nIn this activity, we will explore the simplest level of the SAPT theory called SAPT0 (see [Parker:2014] for the definitions of different levels of SAPT). A particular SAPT correction $E^{(nk)}$ corresponds to effects that are of $n$th order in the intermolecular interaction and $k$th order in the intramolecular electron correlation. In SAPT0, intramolecular correlation is neglected, and intermolecular interaction is included through second order:\n\n\\begin{equation}\nE_{\\rm int}^{\\rm SAPT0}=E^{(10)}_{\\rm elst}+E^{(10)}_{\\rm exch}+E^{(20)}_{\\rm ind,resp}+E^{(20)}_{\\rm exch-ind,resp}+E^{(20)}_{\\rm disp}+E^{(20)}_{\\rm exch-disp}+\\delta E^{(2)}_{\\rm HF}\n\\end{equation}\n\nIn this equation, the consecutive corrections account for the electrostatic, first-order exchange, induction, exchange induction, dispersion, and exchange dispersion effects, respectively. The additional subscript ''resp'' denotes that these corrections are computed including response effects - the HF orbitals of each molecule are relaxed in the electric field generated by the other molecule. The last term $\\delta E^{(2)}_{\\rm HF}$ approximates third- and higher-order induction and exchange induction effects and is taken from a supermolecular HF calculation.\n\nSticking to our example of two helium atoms, let's now calculate the SAPT0 interaction energy contributions using Psi4. In the results that follow, we will group $E^{(20)}_{\\rm ind,resp}$, $E^{(20)}_{\\rm exch-ind,resp}$, and $\\delta E^{(2)}_{\\rm HF}$ to define the total induction effect (including its exchange quenching), and group $E^{(20)}_{\\rm disp}$ with $E^{(20)}_{\\rm exch-disp}$ to define the total dispersion effect.\n\n\n\n```python\ndistances = [4.0,4.5,5.0,5.3,5.6,6.0,6.5,7.0,8.0,9.0,10.0]\neelst = np.zeros((11))\neexch = np.zeros((11))\neind = np.zeros((11))\nedisp = np.zeros((11))\nesapt = np.zeros((11))\n\nfor i in range(len(distances)):\n dimer = psi4.geometry(\"\"\"\n He 0.0 0.0 0.0\n --\n He 0.0 0.0 \"\"\"+str(distances[i])+\"\"\"\n units bohr\n symmetry c1\n \"\"\")\n\n psi4.energy('sapt0')\n eelst[i] = psi4.variable('SAPT ELST ENERGY') * 627.509\n eexch[i] = psi4.variable('SAPT EXCH ENERGY') * 627.509\n eind[i] = psi4.variable('SAPT IND ENERGY') * 627.509\n edisp[i] = psi4.variable('SAPT DISP ENERGY') * 627.509\n esapt[i] = psi4.variable('SAPT TOTAL ENERGY') * 627.509\n psi4.core.clean()\n\nplt.close()\nplt.ylim(-0.2,0.4)\nplt.plot(distances,eelst,'r+',linestyle='-',label='SAPT0 elst')\nplt.plot(distances,eexch,'bo',linestyle='-',label='SAPT0 exch')\nplt.plot(distances,eind,'g^',linestyle='-',label='SAPT0 ind')\nplt.plot(distances,edisp,'mx',linestyle='-',label='SAPT0 disp')\nplt.plot(distances,esapt,'k*',linestyle='-',label='SAPT0 total')\nplt.hlines(0.0,4.0,10.0)\nplt.legend(loc='upper right')\nplt.show()\n\n```\n\n*Questions* \n1. What is the origin of attraction between two helium atoms?\n2. For the interaction of two helium atoms, which SAPT terms are *long-range* (vanish with distance like some inverse power of $R$) and which are *short-range* (vanish exponentially with $R$ just like the overlap of molecular orbitals)?\n3. The dispersion energy decays at large $R$ like $R^{-n}$. Find the value of $n$ by fitting a function to the five largest-$R$ results. You can use `scipy.optimize.curve_fit` to perform the fitting, but you have to define the appropriate function first.\nDoes the optimal exponent $n$ obtained by your fit agree with what you know about van der Waals dispersion forces? Is the graph of dispersion energy shaped like the $R^{-n}$ graph for large $R$? What about intermediate $R$?\n\n*Do you know how to calculate $R^{-n}$ if you have an array with $R$ values? If not, look it up in the NumPy documentation!* \n\n\n\n```python\n#COMPLETE the definition of function f below.\ndef f\n\nndisp = scipy.optimize.curve_fit(f,distances[-5:],edisp[-5:])\nprint (\"Optimal dispersion exponent:\",ndisp[0][0])\n\n```\n\n# Interaction between two water molecules\n\nFor the next part, you will perform the same analysis and obtain the supermolecular and SAPT0 data for the interaction of two water molecules. We now have many more degrees of freedom: in addition to the intermolecular distance $R$, we can change the relative orientation of two molecules, or even their internal geometries (O-H bond lengths and H-O-H angles). In this way, the potential energy curve becomes a multidimensional *potential energy surface*. It is hard to graph functions of more than two variables, so we will stick to the distance dependence of the interaction energies. Therefore, we will assume one particular orientation of two water molecules (a hydrogen-bonded one) and vary the intermolecular distance $R$ while keeping the orientation, and molecular geometries, constant. The geometry of the A-B complex has been defined for you, but you have to request all the necessary Psi4 calculations and extract the numbers that you need. To save time, we will downgrade the basis set to aug-cc-pVDZ and use MP2 (an approximate method that captures most of electron correlation) in place of CCSD(T).\n\n*Hints:* To prepare the geometries for the individual water molecules A and B, copy and paste the A-B geometry, but use the Gh(O2)... syntax to define the appropriate ghost atoms. Remember to run `psi4.core.clean()` after each calculation.\n\n\n\n```python\ndistances_h2o = [2.7,3.0,3.5,4.0,4.5,5.0,6.0,7.0,8.0,9.0]\nehf_h2o = np.zeros((10,3))\nemp2_h2o = np.zeros((10,3))\npsi4.set_options({'basis': 'aug-cc-pVDZ'})\n\nfor i in range(len(distances_h2o)):\n dimer = psi4.geometry(\"\"\"\n O1\n H1 O1 0.96\n H2 O1 0.96 H1 104.5\n --\n O2 O1 \"\"\"+str(distances_h2o[i])+\"\"\" H1 5.0 H2 0.0\n X O2 1.0 O1 120.0 H2 180.0\n H3 O2 0.96 X 52.25 O1 90.0\n H4 O2 0.96 X 52.25 O1 -90.0\n units angstrom\n symmetry c1\n \"\"\")\n\n#COMPLETE the MP2 energy calculations for A-B, A, and B, and prepare the data for the graph.\n#Copy and paste the A-B geometry, but use the Gh(O2)... syntax to define the appropriate ghost atoms for the A and B calculations. \n#Remember to run psi4.core.clean() after each calculation.\n\nprint ('HF PEC',einthf_h2o)\nprint ('MP2 PEC',eintmp2_h2o)\n\nplt.close()\nplt.plot(distances_h2o,einthf_h2o,'r+',linestyle='-',label='HF')\nplt.plot(distances_h2o,eintmp2_h2o,'bo',linestyle='-',label='MP2')\nplt.hlines(0.0,2.5,9.0)\nplt.legend(loc='upper right')\nplt.show()\n\n```\n\n\n```python\neelst_h2o = np.zeros((10))\neexch_h2o = np.zeros((10))\neind_h2o = np.zeros((10))\nedisp_h2o = np.zeros((10))\nesapt_h2o = np.zeros((10))\n\n#COMPLETE the SAPT calculations for 10 distances to prepare the data for the graph.\n\nplt.close()\nplt.ylim(-10.0,10.0)\nplt.plot(distances_h2o,eelst_h2o,'r+',linestyle='-',label='SAPT0 elst')\nplt.plot(distances_h2o,eexch_h2o,'bo',linestyle='-',label='SAPT0 exch')\nplt.plot(distances_h2o,eind_h2o,'g^',linestyle='-',label='SAPT0 ind')\nplt.plot(distances_h2o,edisp_h2o,'mx',linestyle='-',label='SAPT0 disp')\nplt.plot(distances_h2o,esapt_h2o,'k*',linestyle='-',label='SAPT0 total')\nplt.hlines(0.0,2.5,9.0)\nplt.legend(loc='upper right')\nplt.show()\n\n```\n\nBefore we proceed any further, let us check one thing about your first MP2 water-water interaction energy calculation, the one that produced `eintmp2_h2o[0]`. Here's the geometry of that complex again:\n\n\n\n```python\n#all x,y,z in Angstroms\natomtypes = [\"O1\",\"H1\",\"H2\",\"O2\",\"H3\",\"H4\"]\ncoordinates = np.array([[0.116724185090, 1.383860971547, 0.000000000000],\n [0.116724185090, 0.423860971547, 0.000000000000],\n [-0.812697549673, 1.624225775439, 0.000000000000],\n [-0.118596320329, -1.305864713301, 0.000000000000],\n [0.362842754701, -1.642971982825, -0.759061990794],\n [0.362842754701, -1.642971982825, 0.759061990794]])\n\n```\n\nFirst, write the code to compute the four O-H bond lengths and two H-O-H bond angles in the two molecules. *(Hint: if the angles look weird, maybe they are still in radians - don't forget to convert them to degrees.)* Are the two water molecules identical?\n\nThen, check the values of the MP2 energy for these two molecules (the numbers $E_{\\rm A}$ and $E_{\\rm B}$ that you subtracted to get the interaction energy). If the molecules are the same, why are the MP2 energies close but not the same?\n\n*Hints:* The most elegant way to write this code is to define functions `distance(point1,point2)` for the distance between two points $(x_1,y_1,z_1)$ and $(x_2,y_2,z_2)$, and `angle(vec1,vec2)` for the angle between two vectors $(x_{v1},y_{v1},z_{v1})$ and $(x_{v2},y_{v2},z_{v2})$. Recall that the cosine of this angle is related to the dot product $(x_{v1},y_{v1},z_{v1})\\cdot(x_{v2},y_{v2},z_{v2})$. If needed, check the documentation on how to calculate the dot product of two NumPy vectors. \n\nWhen you are parsing the NumPy array with the coordinates, remember that `coordinates[k,:]` is the vector of $(x,y,z)$ values for atom number $k$, $k=0,1,2,\\ldots,N_{\\rm atoms}-1$. \n\n\n\n```python\n\n#COMPLETE the distance and angle calculations below.\nro1h1 = \nro1h2 = \nro2h3 = \nro2h4 = \nah1o1h2 = \nah3o2h4 = \nprint ('O-H distances: %5.3f %5.3f %5.3f %5.3f' % (ro1h1,ro1h2,ro2h3,ro2h4))\nprint ('H-O-H angles: %6.2f %6.2f' % (ah1o1h2,ah3o2h4))\nprint ('MP2 energy of molecule 1: %18.12f hartrees' % emp2_h2o[0,1])\nprint ('MP2 energy of molecule 2: %18.12f hartrees' % emp2_h2o[0,2])\n\n```\n\nWe can now proceed with the analysis of the SAPT0 energy components for the complex of two water molecules. *Please edit this Markdown cell to write your answers.*\n1. Which of the four SAPT terms are long-range, and which are short-range this time?\n2. For the terms that are long-range and decay with $R$ like $R^{-n}$, estimate $n$ by fitting a proper function to the 5 data points with the largest $R$, just like you did for the two interacting helium atoms (using `scipy.optimize.curve_fit`). How would you explain the power $n$ that you obtained for the electrostatic energy?\n\n\n\n```python\n#COMPLETE the optimizations below. \nnelst_h2o = \nnind_h2o = \nndisp_h2o = \nprint (\"Optimal electrostatics exponent:\",nelst_h2o[0][0])\nprint (\"Optimal induction exponent:\",nind_h2o[0][0])\nprint (\"Optimal dispersion exponent:\",ndisp_h2o[0][0])\n\n```\n\nThe water molecules are polar - each one has a nonzero dipole moment, and at large distances we expect the electrostatic energy to be dominated by the dipole-dipole interaction (at short distances, when the orbitals of two molecules overlap, the multipole approximation is not valid and the electrostatic energy contains the short-range *charge penetration* effects). Let's check if this is indeed the case. In preparation for this, we first find the HF dipole moment vector for each water molecule. \n\n\n\n```python\nwaterA = psi4.geometry(\"\"\"\nO 0.116724185090 1.383860971547 0.000000000000\nH 0.116724185090 0.423860971547 0.000000000000\nH -0.812697549673 1.624225775439 0.000000000000\nunits angstrom\nnoreorient\nnocom\nsymmetry c1\n\"\"\")\n\ncomA = waterA.center_of_mass()\ncomA = np.array([comA[0],comA[1],comA[2]])\nE, wfn = psi4.energy('HF',return_wfn=True)\ndipoleA = np.array([psi4.variable('SCF DIPOLE X'),psi4.variable('SCF DIPOLE Y'),\n psi4.variable('SCF DIPOLE Z')])*0.393456 # conversion from Debye to a.u.\npsi4.core.clean()\nprint(\"COM A in a.u.\",comA)\nprint(\"Dipole A in a.u.\",dipoleA)\n\nwaterB = psi4.geometry(\"\"\"\nO -0.118596320329 -1.305864713301 0.000000000000\nH 0.362842754701 -1.642971982825 -0.759061990794\nH 0.362842754701 -1.642971982825 0.759061990794\nunits angstrom\nnoreorient\nnocom\nsymmetry c1\n\"\"\")\n\ncomB = waterB.center_of_mass()\ncomB = np.array([comB[0],comB[1],comB[2]])\nE, wfn = psi4.energy('HF',return_wfn=True)\ndipoleB = np.array([psi4.variable('SCF DIPOLE X'),psi4.variable('SCF DIPOLE Y'),\n psi4.variable('SCF DIPOLE Z')])*0.393456 # conversion from Debye to a.u.\npsi4.core.clean()\nprint(\"COM B in a.u.\",comB)\nprint(\"Dipole B in a.u.\",dipoleB)\n\ncomA_to_comB = comB - comA\nprint(\"Vector from COMA to COMB:\",comA_to_comB)\n\n\n```\n\nOur goal now is to plot the electrostatic energy from SAPT against the interaction energy between two dipoles $\\boldsymbol{\\mu_A}$ and $\\boldsymbol{\\mu_B}$:\n\n\\begin{equation}\nE_{\\rm dipole-dipole}=\\frac{\\boldsymbol{\\mu_A}\\cdot\\boldsymbol{\\mu_B}}{R^3}-\\frac{3(\\boldsymbol{\\mu_A}\\cdot{\\mathbf R})(\\boldsymbol{\\mu_B}\\cdot{\\mathbf R})}{R^5} \n\\end{equation}\n\nProgram this formula in the `dipole_dipole` function below, taking ${\\mathbf R}$, $\\boldsymbol{\\mu_A}$, and $\\boldsymbol{\\mu_B}$ in atomic units and calculating the dipole-dipole interaction energy, also in atomic units (which we will later convert to kcal/mol). \nWith your new function, we can populate the `edipdip` array of dipole-dipole interaction energies for all intermolecular separations, and plot these energies alongside the actual electrostatic energy data from SAPT. \n\nNote that ${\\mathbf R}$ is the vector from the center of mass of molecule A to the center of mass of molecule B. For the shortest intermolecular distance, the atomic coordinates are listed in the code above, so `R = comA_to_comB`. For any other distance, we obtained the geometry of the complex by shifting one water molecule away from the other along the O-O direction, so we need to shift the center of mass of the second molecule in the same way.\n\n\n\n```python\n#the geometries are related to each other by a shift of 1 molecule along the O-O vector:\nOA_to_OB = (np.array([-0.118596320329,-1.305864713301,0.000000000000])-np.array(\n [0.116724185090,1.383860971547,0.000000000000]))/0.529177249\nOA_to_OB_unit = OA_to_OB/np.sqrt(np.sum(OA_to_OB*OA_to_OB))\nprint(\"Vector from OA to OB:\",OA_to_OB,OA_to_OB_unit)\n\ndef dipole_dipole(R,dipA,dipB):\n#COMPLETE the definition of the dipole-dipole energy. All your data are in atomic units.\n\nedipdip = []\nfor i in range(len(distances_h2o)):\n shiftlength = (distances_h2o[i]-distances_h2o[0])/0.529177249\n R = comA_to_comB + shiftlength*OA_to_OB_unit\n edipdip.append(dipole_dipole(R,dipoleA,dipoleB)*627.509)\n\nedipdip = np.array(edipdip)\nprint (edipdip)\n\nplt.close()\nplt.ylim(-10.0,10.0)\nplt.plot(distances_h2o,eelst_h2o,'r+',linestyle='-',label='SAPT0 elst')\nplt.plot(distances_h2o,edipdip,'bo',linestyle='-',label='dipole-dipole')\nplt.hlines(0.0,2.5,9.0)\nplt.legend(loc='upper right')\nplt.show()\n\n```\n\nWe clearly have a favorable dipole-dipole interaction, which results in negative (attractive) electrostatic energy. This is how the origins of hydrogen bonding might have been explained to you in your freshman chemistry class: two polar molecules have nonzero dipole moments and the dipole-dipole interaction can be strongly attractive. However, your SAPT components show you that it's not a complete explanation: the two water molecules are bound not only by electrostatics, but by two other SAPT components as well. Can you quantify the relative (percentage) contributions of electrostatics, induction, and dispersion to the overall interaction energy at the van der Waals minimum? This minimum is the second point on your curve, so, for example, `esapt_h2o[1]` is the total SAPT interaction energy.\n\n\n\n```python\n#now let's examine the SAPT0 contributions at the van der Waals minimum, which is the 2nd point on the curve\n#COMPLETE the calculation of percentages.\npercent_elst = \npercent_ind = \npercent_disp = \nprint ('At the van der Waals minimum, electrostatics, induction, and dispersion')\nprint (' contribute %5.1f, %5.1f, and %5.1f percent of interaction energy, respectively.'\n % (percent_elst,percent_ind,percent_disp))\n\n\n```\n\nYou have now completed some SAPT calculations and analyzed the meaning of different corrections. Can you complete the table below to indicate whether different SAPT corrections can be positive (repulsive), negative (attractive), or both, and why?\n\n\n\n```python\n#Type in your answers below.\n#COMPLETE this table. Do not remove the comment (#) signs.\n#\n#SAPT term Positive/Negative/Both? Why?\n#Electrostatics\n#Exchange\n#Induction\n#Dispersion\n\n```\n\n# Ternary diagrams\n\nHigher levels of SAPT calculations can give very accurate interaction energies, but are more computationally expensive than SAPT0. SAPT0 is normally sufficient for qualitative accuracy and basic understanding of the interaction physics. One important use of SAPT0 is to *classify different intermolecular complexes according to the type of interaction*, and a nice way to display the results of this classification is provided by a *ternary diagram*.\n\nThe relative importance of attractive electrostatic, induction, and dispersion contributions to a SAPT interaction energy for a particular structure can be marked as a point inside a triangle, with the distance to each vertex of the triangle depicting the relative contribution of a given type (the more dominant a given contribution is, the closer the point lies to the corresponding vertex). If the electrostatic contribution is repulsive, we can display the relative magnitudes of electrostatic, induction, and dispersion terms in the same way, but we need the second triangle (the left one). The combination of two triangles forms the complete diagram and we can mark lots of different points corresponding to different complexes and geometries.\n\nLet's now mark all your systems on a ternary diagram, in blue for two helium atoms and in red for two water molecules. What kinds of interaction are represented? Compare your diagram with the one pictured below, prepared for 2510 different geometries of the complex of two water molecules, with all kinds of intermolecular distances and orientations (this graph is taken from [Smith:2016]). What conclusions can you draw about the interaction of two water molecules at *any* orientation?\n\n\n\n```python\ndef ternary(sapt, title='', labeled=True, view=True, saveas=None, relpath=False, graphicsformat=['pdf']):\n#Adapted from the QCDB ternary diagram code by Lori Burns\n \"\"\"Takes array of arrays *sapt* in form [elst, indc, disp] and builds formatted\n two-triangle ternary diagrams. Either fully-readable or dotsonly depending\n on *labeled*.\n \"\"\"\n from matplotlib.path import Path\n import matplotlib.patches as patches\n\n # initialize plot\n plt.close()\n fig, ax = plt.subplots(figsize=(6, 3.6))\n plt.xlim([-0.75, 1.25])\n plt.ylim([-0.18, 1.02])\n plt.xticks([])\n plt.yticks([])\n ax.set_aspect('equal')\n\n if labeled:\n # form and color ternary triangles\n codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]\n pathPos = Path([(0., 0.), (1., 0.), (0.5, 0.866), (0., 0.)], codes)\n pathNeg = Path([(0., 0.), (-0.5, 0.866), (0.5, 0.866), (0., 0.)], codes)\n ax.add_patch(patches.PathPatch(pathPos, facecolor='white', lw=2))\n ax.add_patch(patches.PathPatch(pathNeg, facecolor='#fff5ee', lw=2))\n\n # label corners\n ax.text(1.0,\n -0.15,\n u'Elst (−)',\n verticalalignment='bottom',\n horizontalalignment='center',\n family='Times New Roman',\n weight='bold',\n fontsize=18)\n ax.text(0.5,\n 0.9,\n u'Ind (−)',\n verticalalignment='bottom',\n horizontalalignment='center',\n family='Times New Roman',\n weight='bold',\n fontsize=18)\n ax.text(0.0,\n -0.15,\n u'Disp (−)',\n verticalalignment='bottom',\n horizontalalignment='center',\n family='Times New Roman',\n weight='bold',\n fontsize=18)\n ax.text(-0.5,\n 0.9,\n u'Elst (+)',\n verticalalignment='bottom',\n horizontalalignment='center',\n family='Times New Roman',\n weight='bold',\n fontsize=18)\n\n xvals = []\n yvals = []\n cvals = []\n geomindex = 0 # first 11 points are He-He, the next 10 are H2O-H2O\n for sys in sapt:\n [elst, indc, disp] = sys\n\n # calc ternary posn and color\n Ftop = abs(indc) / (abs(elst) + abs(indc) + abs(disp))\n Fright = abs(elst) / (abs(elst) + abs(indc) + abs(disp))\n xdot = 0.5 * Ftop + Fright\n ydot = 0.866 * Ftop\n if geomindex <= 10:\n cdot = 'b'\n else:\n cdot = 'r'\n if elst > 0.:\n xdot = 0.5 * (Ftop - Fright)\n ydot = 0.866 * (Ftop + Fright)\n #print elst, indc, disp, '', xdot, ydot, cdot\n\n xvals.append(xdot)\n yvals.append(ydot)\n cvals.append(cdot)\n geomindex += 1\n\n sc = ax.scatter(xvals, yvals, c=cvals, s=15, marker=\"o\", \n edgecolor='none', vmin=0, vmax=1, zorder=10)\n\n # remove figure outline\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n\n # save and show\n plt.show()\n return 1\n\nsapt = []\nfor i in range(11):\n sapt.append([eelst[i],eind[i],edisp[i]])\nfor i in range(10):\n sapt.append([eelst_h2o[i],eind_h2o[i],edisp_h2o[i]])\nidummy = ternary(sapt)\nfrom IPython.display import Image\nImage(filename='water2510.png')\n\n```\n\n# Some further reading:\n\n1. How is the calculation of SAPT corrections actually programmed? The Psi4NumPy projects has some tutorials on this topic: https://github.com/psi4/psi4numpy/tree/master/Tutorials/07_Symmetry_Adapted_Perturbation_Theory \n2. A classic (but recently updated) book on the theory of interactions between molecules: \"The Theory of Intermolecular Forces\"\n\t> [[Stone:2013](https://www.worldcat.org/title/theory-of-intermolecular-forces/oclc/915959704)] A. Stone, Oxford University Press, 2013\n3. The classic review paper on SAPT: \"Perturbation Theory Approach to Intermolecular Potential Energy Surfaces of van der Waals Complexes\"\n\t> [[Jeziorski:1994](http://pubs.acs.org/doi/abs/10.1021/cr00031a008)] B. Jeziorski, R. Moszynski, and K. Szalewicz, *Chem. Rev.* **94**, 1887 (1994)\n4. A brand new (as of 2020) review of SAPT, describing new developments and inprovements to the theory: \"Recent developments in symmetry‐adapted perturbation theory\"\n\t> [[Patkowski:2020](https://onlinelibrary.wiley.com/doi/abs/10.1002/wcms.1452)] K. Patkowski, *WIREs Comput. Mol. Sci.* **10**, e1452 (2020)\n5. The definitions and practical comparison of different levels of SAPT: \"Levels of symmetry adapted perturbation theory (SAPT). I. Efficiency and performance for interaction energies\"\n\t> [[Parker:2014](http://aip.scitation.org/doi/10.1063/1.4867135)] T. M. Parker, L. A. Burns, R. M. Parrish, A. G. Ryno, and C. D. Sherrill, *J. Chem. Phys.* **140**, 094106 (2014)\n6. An example study making use of the SAPT0 classification of interaction types, with lots of ternary diagrams in the paper and in the supporting information: \"Revised Damping Parameters for the D3 Dispersion Correction to Density Functional Theory\"\n\t> [[Smith:2016](https://pubs.acs.org/doi/abs/10.1021/acs.jpclett.6b00780)] D. G. A. Smith, L. A. Burns, K. Patkowski, and C. D. Sherrill, *J. Phys. Chem. Lett.* **7**, 2197 (2016).\n\n", "meta": {"hexsha": "b6741e2a13c223f230d6345905e5b822ecf2dd4f", "size": 42401, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Example/Psi4Education/sapt0_student.ipynb", "max_stars_repo_name": "yychuang/109-2-compchem-lite", "max_stars_repo_head_hexsha": "cbf17e542f9447e89fb48de1b28759419ffff956", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2019-12-19T22:56:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T00:58:56.000Z", "max_issues_repo_path": "Example/Psi4Education/sapt0_student.ipynb", "max_issues_repo_name": "yychuang/109-2-compchem-lite", "max_issues_repo_head_hexsha": "cbf17e542f9447e89fb48de1b28759419ffff956", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-22T14:40:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T17:27:01.000Z", "max_forks_repo_path": "Example/Psi4Education/sapt0_student.ipynb", "max_forks_repo_name": "yychuang/109-2-compchem-lite", "max_forks_repo_head_hexsha": "cbf17e542f9447e89fb48de1b28759419ffff956", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-11-17T15:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T00:05:55.000Z", "avg_line_length": 54.0140127389, "max_line_length": 1121, "alphanum_fraction": 0.6310700219, "converted": true, "num_tokens": 9484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.20434189993684584, "lm_q1q2_score": 0.09579356731739117}} {"text": "# 13 Euler-Maclaurinの和公式\n\n黒木玄\n\n2018-07-04~2019-04-03\n\n* Copyright 2018 Gen Kuroki\n* License: MIT https://opensource.org/licenses/MIT\n* Repository: https://github.com/genkuroki/Calculus\n\nこのファイルは次の場所できれいに閲覧できる:\n\n* http://nbviewer.jupyter.org/github/genkuroki/Calculus/blob/master/13%20Euler-Maclaurin%20summation%20formula.ipynb\n\n* https://genkuroki.github.io/documents/Calculus/13%20Euler-Maclaurin%20summation%20formula.pdf\n\nこのファイルは Julia Box で利用できる.\n\n自分のパソコンにJulia言語をインストールしたい場合には\n\n* [WindowsへのJulia言語のインストール](http://nbviewer.jupyter.org/gist/genkuroki/81de23edcae631a995e19a2ecf946a4f)\n\n* [Julia v1.1.0 の Windows 8.1 へのインストール](https://nbviewer.jupyter.org/github/genkuroki/msfd28/blob/master/install.ipynb)\n\nを参照せよ. 前者は古く, 後者の方が新しい.\n\n論理的に完璧な説明をするつもりはない. 細部のいい加減な部分は自分で訂正・修正せよ.\n\n$\n\\newcommand\\eps{\\varepsilon}\n\\newcommand\\ds{\\displaystyle}\n\\newcommand\\Z{{\\mathbb Z}}\n\\newcommand\\R{{\\mathbb R}}\n\\newcommand\\C{{\\mathbb C}}\n\\newcommand\\QED{\\text{□}}\n\\newcommand\\root{\\sqrt}\n\\newcommand\\bra{\\langle}\n\\newcommand\\ket{\\rangle}\n\\newcommand\\d{\\partial}\n\\newcommand\\sech{\\operatorname{sech}}\n\\newcommand\\cosec{\\operatorname{cosec}}\n\\newcommand\\sign{\\operatorname{sign}}\n\\newcommand\\real{\\operatorname{Re}}\n\\newcommand\\imag{\\operatorname{Im}}\n$\n\n

目次

\n\n\n\n```julia\nusing Base.MathConstants\nusing Base64\nusing Printf\nusing Statistics\nconst e = ℯ\nendof(a) = lastindex(a)\nlinspace(start, stop, length) = range(start, stop, length=length)\n\nusing Plots\ngr(); ENV[\"PLOTS_TEST\"] = \"true\"\n#clibrary(:colorcet)\nclibrary(:misc)\n\nfunction pngplot(P...; kwargs...)\n sleep(0.1)\n pngfile = tempname() * \".png\"\n savefig(plot(P...; kwargs...), pngfile)\n showimg(\"image/png\", pngfile)\nend\npngplot(; kwargs...) = pngplot(plot!(; kwargs...))\n\nshowimg(mime, fn) = open(fn) do f\n base64 = base64encode(f)\n display(\"text/html\", \"\"\"\"\"\")\nend\n\nusing SymPy\n#sympy.init_printing(order=\"lex\") # default\n#sympy.init_printing(order=\"rev-lex\")\n\nusing SpecialFunctions\nusing QuadGK\n```\n\n## Bernoulli多項式\n\n### Bernoulli多項式の定義\n\n**定義(Bernoulli多項式):** Bernoulli多項式** $B_n(x)$ ($n=0,1,2,\\ldots$)を\n\n$$\n\\frac{ze^{zx}}{e^z-1} = \\sum_{n=0}^\\infty \\frac{B_n(x)}{n!}z^n\n$$\n\nによって定義する. $\\QED$\n\n\n\n### Bernoulli多項式の基本性質\n\n**一般化Bernoulli多項式の基本性質:** Bernoulli多項式 $B_n(x)$ は以下の性質を満たしている:\n\n(1) $B_0(x)=1$.\n\n(2) $\\ds\\int_0^1 B_n(x)\\,dx = \\delta_{n,0}$.\n\n(3) $\\ds B_n(x+h) = \\sum_{k=0}^n\\binom{n}{k}B_{n-k}(x)h^k = \n\\sum_{k=0}^n \\binom{n}{k} B_k(x) h^{n-k}$.\n\n(4) $B_n'(x)=nB_{n-1}(x)$.\n\n(5) $\\ds B_n(x+1)=B_n(x)+nx^{n-1}$.\n\n(6) $B_n(1-x)=(-1)^n B_n(x)$.\n\n(7) $B_n(1)=B_n(0)+\\delta_{n,1}$ となる.\n\n(8) $B_n(0)=1$, $\\ds B_n(0)=-\\frac{1}{2}$ とな, $n$ が3以上の奇数ならば $B_n(0)=0$ となる.\n\n**証明:** (1) $e^{zx}=1+O(z)$, $\\ds\\frac{e^z-1}{z}=1+O(z)$ より, $\\ds\\frac{ze^{zx}}{e^z-1}=1+O(z)$ なので $B_0(x) = 1$.\n\n(2)を示そう.\n\n$$\n\\begin{aligned}\n&\n\\int_0^1 \\frac{ze^{zx}}{e^z-1}\\,dx = \\frac{z}{e^z-1}\\int_0^1 e^{zx}\\,dx = \n\\frac{z}{e^z-1}\\frac{e^z-1}{z} = 1, \n\\\\ &\n\\int_0^1\\frac{ze^{zx}}{e^z-1}\\,dx = \\sum_{n=0}^\\infty\\frac{z^n}{n!}\\int_0^1 B_n(x)\\,dx\n\\end{aligned}\n$$\n\nなので, これらを比較して $\\ds\\int_0^1 B_n(x)\\,dx = \\delta_{n,0}$.\n\n(3) 二項定理より,\n\n$$\n\\int_0^1 (x+y)^n\\,dy = \n\\sum_{k=0}^n \\binom{n}{k} x^{n-k} \\int_0^1 y^k\\,dy.\n$$\n\nゆえに, $x$ の函数を $x$ の函数に移す線形写像(前方移動平均)\n\n$$\nf(x)\\mapsto \\int_0^1 f(x+y)\\,dy\n$$\n\nは多項式を多項式に移し, 最高次の係数が1の多項式を最高次の係数が1の同次の多項式に移す. これより, 線形写像 $\\ds f(x)\\mapsto \\int_0^1 f(x+y)\\,dy$ は多項式どうしの一対一対応を与える線形写像になっていることがわかる. そして,\n\n$$\n\\begin{aligned}\n&\n\\int_0^1\\frac{ze^{z(x+y)}}{e^z-1}\\,dx = \n\\sum_{n=0}^\\infty\\frac{\\int_0^1 B_n(x+y)\\,dy}{n!}z^n, \n\\\\ &\n\\int_0^1\\frac{ze^{z(x+y)}}{e^z-1}\\,dx = \n\\frac{ze^{zx}}{e^z-1}\\int_0^1 e^{zy}\\,dy =\n\\frac{ze^{zx}}{e^z-1}\\frac{e^z-1}{z} =\ne^{zx} =\n\\sum_{n=0}^\\infty \\frac{x^n}{n!}z^n\n\\end{aligned}\n$$\n\nなので, これらを比較して,\n\n$$\n\\int_0^1 B_n(x+y)\\,dy = x^n\n$$\n\nが成立することがわかる. ゆえに, \n\n$$\n\\int_0^1 B_n(x+h+y)\\,dy = (x+h)^n = \\sum_{k=0}^n \\binom{n}{k}x^{n-k}h^k =\n\\int_0^1 \\sum_{k=0}^n \\binom{n}{k}B_{n-k}(x+y)h^k \\,dy\n$$\n\nより\n\n$$\nB_n(x+h) = \\sum_{k=0}^n \\binom{n}{k}B_{n-k}(x)h^k.\n$$\n\n(4) すぐ上の等式の右辺の $h$ の係数を見ることによって,\n\n$$\nB_n'(x) = n B_{n-1}(x).\n$$\n\n(5) Bernoulli多項式の母函数の $x$ に $x+1$ を代入すると,\n\n$$\n\\frac{ze^{z(x+1)}}{e^z-1} = \\frac{ze^z e^{zx}}{e^z-1} =\n\\frac{z(1+(e^z-1))e^{zx}}{e^z-1} = \\frac{ze^{zx}}{e^z-1} + ze^{zx}\n$$\n\nなので両辺を $z$ について展開して比較すれば(5)が得られる.\n\n(6) Bernoulli多項式の母函数の $x$ に $1-x$ を代入すると,\n\n$$\n\\frac{ze^{z(1-x)}}{e^z-1} = \\frac{ze^z e^{-zx}}{e^z-1} =\n\\frac{ze^{-zx}}{1-e^{-z}} = \\frac{-ze^{-zx}}{e^{-z}-1}\n$$\n\nとBernoulli多項式の母函数の $z$ に $-z$ を代入したものになるので, 両辺を $z$ について展開して比較すれば(5)が得られる.\n\n(7) 上の(2)と(4)より, $n$ が2以上のとき,\n\n$$\nB_n(1)-B_n(0) = \\int_0^1 B_n'(x)\\,dx = n\\int_0^1 B_{n-1}(x)\\,dx = n\\delta_{n-1,0} = \\delta_{n,1}\n$$\n\nゆえに $n$ が2以上のとき $B_n(1)=B_n(0)+\\delta_{n,1}$.\n\n(8) 次の函数が $z$ の偶函数で $z\\to 0$ で $1$ になることから, (6)が得られる:\n\n$$\n\\frac{z}{e^z-1} + \\frac{z}{2} = \\frac{z}{2}\\frac{e^{z/2}+e^{-z/2}}{e^{z/2}-e^{-z/2}}.\n\\qquad \\QED\n$$\n\n**注意:** $B_n=B_n(0)$ は**Bernoulli数**と呼ばれている. (3)で $(x,h)$ を $(0,x)$ で置き換えると, Bernoulli多項式がBernoulli数で表わされることがわかる:\n\n$$\nB_n(x) = \\sum_{k=0}^n \\binom{n}{k}B_k x^{n-k}.\n$$\n\n上の定理の条件(1),(2),(4)によってBernoulli多項式 $B_n(x)$ が $n$ について帰納的に一意的に決まる. $\\QED$\n\n**例:** \n$$\nB_0 = 1, \\quad B_1 = -\\frac{1}{2}, \\quad\nB_2 = \\frac{1}{6}, \\quad B_3=0, \\quad B_4 = -\\frac{1}{30}\n$$\n\nなので\n\n$$\n\\begin{aligned}\n&\nB_0(x)=1, \\quad \nB_1(x)=x-\\frac{1}{2}, \\quad\nB_2(x)=x^2-x+\\frac{1}{6}, \n\\\\ &\nB_3(x)=x^3-\\frac{3}{2}x^2+\\frac{1}{2}x, \\quad\nB_4(x)=x^4-2x^3+x^2-\\frac{1}{30}.\n\\qquad\\QED\n\\end{aligned}\n$$\n\n\n```julia\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nx = symbols(\"x\", real=true)\n[BernoulliPolynomial(n,x) for n in 0:10]\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}1\\\\x - \\frac{1}{2}\\\\x^{2} - x + \\frac{1}{6}\\\\x^{3} - \\frac{3 x^{2}}{2} + \\frac{x}{2}\\\\x^{4} - 2 x^{3} + x^{2} - \\frac{1}{30}\\\\x^{5} - \\frac{5 x^{4}}{2} + \\frac{5 x^{3}}{3} - \\frac{x}{6}\\\\x^{6} - 3 x^{5} + \\frac{5 x^{4}}{2} - \\frac{x^{2}}{2} + \\frac{1}{42}\\\\x^{7} - \\frac{7 x^{6}}{2} + \\frac{7 x^{5}}{2} - \\frac{7 x^{3}}{6} + \\frac{x}{6}\\\\x^{8} - 4 x^{7} + \\frac{14 x^{6}}{3} - \\frac{7 x^{4}}{3} + \\frac{2 x^{2}}{3} - \\frac{1}{30}\\\\x^{9} - \\frac{9 x^{8}}{2} + 6 x^{7} - \\frac{21 x^{5}}{5} + 2 x^{3} - \\frac{3 x}{10}\\\\x^{10} - 5 x^{9} + \\frac{15 x^{8}}{2} - 7 x^{6} + 5 x^{4} - \\frac{3 x^{2}}{2} + \\frac{5}{66}\\end{array} \\right] \\]\n\n\n\n\n```julia\n# (2) ∫_0^1 B_n(x) dx = δ_{n0}\n\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nx = symbols(\"x\", real=true)\n[integrate(BernoulliPolynomial(n,x), (x,0,1)) for n = 0:10]'\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rrrrrrrrrrr}1&0&0&0&0&0&0&0&0&0&0\\end{array}\\right]\\]\n\n\n\n\n```julia\n# (3) B_n(x+h) = Σ_{k=0}^n binom(n,k) B_{n-k}(x) h^k\n\nBernoulliNumber(n) = sympy.bernoulli(n)\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nBinomCoeff(n,k) = sympy.binomial_coefficients_list(n)[k+1]\nx, h = symbols(\"x h\", real=true)\n[BernoulliPolynomial(n,x) == sum(k->BinomCoeff(n,k)*BernoulliNumber(k)*x^(n-k), 0:n) for n in 0:10]'\n```\n\n\n\n\n 1×11 LinearAlgebra.Adjoint{Bool,Array{Bool,1}}:\n true true true true true true true true true true true\n\n\n\n\n```julia\n# (4) B_n'(x) = n B_{n-1}(x)\n\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nx = symbols(\"x\", real=true)\n[diff(BernoulliPolynomial(n,x), x) == n*BernoulliPolynomial(n-1,x) for n = 1:10]'\n```\n\n\n\n\n 1×10 LinearAlgebra.Adjoint{Bool,Array{Bool,1}}:\n true true true true true true true true true true\n\n\n\n\n```julia\n# (5) B_n(x+1) = B_n(x) + n x^{n-1}\n\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nx = symbols(\"x\", real=true)\n[simplify(BernoulliPolynomial(n,x+1) - BernoulliPolynomial(n,x)) for n in 0:10]\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}0\\\\1\\\\2 x\\\\3 x^{2}\\\\4 x^{3}\\\\5 x^{4}\\\\6 x^{5}\\\\7 x^{6}\\\\8 x^{7}\\\\9 x^{8}\\\\10 x^{9}\\end{array} \\right] \\]\n\n\n\n\n```julia\n# (6) B_n(1-x) = (-1)^n B_n(x)\n\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nx = symbols(\"x\", real=true)\n[expand(BernoulliPolynomial(n,1-x)) == (-1)^n*BernoulliPolynomial(n,x) for n in 0:10]'\n```\n\n\n\n\n 1×11 LinearAlgebra.Adjoint{Bool,Array{Bool,1}}:\n true true true true true true true true true true true\n\n\n\n\n```julia\n# (7) B_n(1) = B_n(0) + δ_{n1}\n\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nx = symbols(\"x\", real=true)\n[expand(BernoulliPolynomial(n,1)) - BernoulliPolynomial(n,0) for n in 0:10]'\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rrrrrrrrrrr}0&1&0&0&0&0&0&0&0&0&0\\end{array}\\right]\\]\n\n\n\n\n```julia\n# (8) B_n = B_n(0) は n が3以上の奇数ならば0になる.\n\nBernoulliNumber(n) = sympy.bernoulli(n)\n[(n, BernoulliNumber(n)) for n in 0:10]\n```\n\n\n\n\n 11-element Array{Tuple{Int64,Sym},1}:\n (0, 1) \n (1, -1/2) \n (2, 1/6) \n (3, 0) \n (4, -1/30)\n (5, 0) \n (6, 1/42) \n (7, 0) \n (8, -1/30)\n (9, 0) \n (10, 5/66)\n\n\n\n### べき乗和\n\n$m$ は正の整数であるする. Bernoulli多項式について, \n\n$$\nB_{m+1}(x+1)-B_{m+1}(x) = (m+1)x^m, \n\\quad\\text{i.e.}\\quad\nx^m = \\frac{B_{m+1}(x+1)-B_{m+1}(x)}{m+1}\n$$\n\nが成立しているので, これを $x=0,1,\\ldots,n$ について足し上げると,\n\n$$\n\\sum_{j=1}^n j^m = \\frac{B_{m+1}(n+1)-B_{m+1}}{m+1}.\n\\qquad \\QED\n$$\n\n\n```julia\nPowerSum(m, n) = sum(j->j^m, 1:n)\nBernoulliNumber(n) = sympy.bernoulli(n)\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\nPowerSumFormula(m, n) = (BernoulliPolynomial(m+1,n+1)-BernoulliNumber(m+1))/(m+1)\n[(m, PowerSum(m,10), PowerSumFormula(m, 10)) for m in 1:10]\n```\n\n\n\n\n 10-element Array{Tuple{Int64,Int64,Sym},1}:\n (1, 55, 55) \n (2, 385, 385) \n (3, 3025, 3025) \n (4, 25333, 25333) \n (5, 220825, 220825) \n (6, 1978405, 1978405) \n (7, 18080425, 18080425) \n (8, 167731333, 167731333) \n (9, 1574304985, 1574304985) \n (10, 14914341925, 14914341925)\n\n\n\n### Bernoulli数の計算法\n\nBernoulli数 $B_n$ は\n\n$$\\displaystyle\n\\frac{z}{e^z-1}=\\sum_{n=1}^\\infty B_n\\frac{z^n}{n!}\n$$\n\nで定義される. しかし, この展開を直接計算することによって Bernoulli 数を求めるのは効率が悪い.\n\nまず, 左辺の $z\\to 0$ の極限を取ることによって $B_0=1$ であることはすぐにわかる.\n\n次に, $n$ が $3$ 以上の奇数のとき $B_n=0$ となることを(再び)示そう. \n\n$$\\displaystyle\n\\frac{z}{e^z-1} + \\frac z2\n=\\frac z2\\frac{e^z+1}{e^z-1} \n=\\frac z2\\frac{e^{z/2}+e^{-z/2}}{e^{z/2}-e^{-z/2}}\n$$\n\nより, 左辺は偶函数になるので, その展開の奇数次の項は消える. このことから, $B_1=-1/2$ でかつ, $0=B_3=B_5=B_7=\\cdots$ であることもわかる.\n\n$$\\displaystyle\n\\frac{ze^z}{e^z-1}\n=\\sum_{j,k=0}^\\infty \\frac{z^j}{j!}\\frac{B_k z^k}{k!}\n=\\sum_{n=0}^\\infty\\left(\\sum_{k=0}^n \\binom{n}{k} B_k\\right)\\frac{z^n}{n!}\n$$\n\nでかつ\n\n$$\\displaystyle\n\\frac{ze^z}{e^z-1}\n=\\frac{z}{e^z-1}+z\n=\\sum_{n=0}^\\infty(B_n+\\delta_{n1})\\frac{z^n}{n!}\n$$\n\nなので, これらを比較すると\n\n$$\\displaystyle\n\\sum_{k=0}^{n-1} \\binom{n}{k} B_k = \\delta_{n1}.\n$$\n\nゆえに, $n$ を $n+1$ で置き換え, $n\\geqq 1$ とし, $B_n$ を他で表わす式に書き直すと\n\n$$\\displaystyle\nB_n = -\\frac{1}{n+1}\\sum_{k=0}^{n-1}\\binom{n+1}{k}B_k\n\\qquad (n\\geqq 1).\n$$\n\nこれを使えば帰納的に $B_n$ を求めることができる. $B_0=1$, $B_1=-1/2$, $0=B_3=B_5=B_7=\\cdots$ であることを使うと, \n\n$$\\displaystyle\nB_{2m} = -\\frac{1}{2m+1}\\left(\n1 -\\frac{2m+1}{2}\n+\\sum_{k=1}^{m-1}\\binom{2m+1}{2k}B_{2k}\n\\right).\n$$\n\n**問題:** 上の方ではSymPyにおけるBernoulli数の函数を利用した. Bernoulli数を計算するためのプログラムを自分で書け. $\\QED$\n\n**解答例:** 次のセルの通り. $\\QED$\n\n\n```julia\n# binomial coefficient: binom(n,k) = n(n-1)・(n-k+1)/k!\n#\nmydiv(a, b) = a / b\nmydiv(a::Integer, b::Integer) = a ÷ b\nfunction binom(n, k)\n k < 0 && return zero(n)\n k == 0 && return one(n)\n b = one(n)\n for j in 1:k\n b = mydiv(b*(n-k+j), j)\n end\n b\nend\n \n@show binom(Rational(big\"100\")/3, 30)\n\n# Bernoulli numbers: B(n) = Bernoulli[n+1] = B_n\n#\nstruct Bernoulli{T}\n B::Array{T,1}\nend\nfunction Bernoulli(; maxn=200)\n B = zeros(Rational{BigInt},maxn+1)\n B[1] = 1 # B_0\n B[2] = -1//2 # B_1\n for n in big\"2\":2:maxn+1\n B[n+1] = -(1//(n+1))*sum(j->binom(n+1,j)*B[j+1], 0:n-1)\n # B_n = -(1/(n+1)) Σ_{j=0}^{n-1} binom(n+1,j)*B_j\n end\n Bernoulli(B)\nend\n(B::Bernoulli)(n) = B.B[n+1]\n\nmaxn = 200\n@time B = Bernoulli(maxn=maxn) # B_n を B_{maxn} まで計算\nBB(n) = float(B(n)) # B(n) = B_n である. BB(n)はその浮動小数点版\n\n# SymPyのBernoulli数と比較して正しく計算できているかどうかを確認\n#\nBernoulliNumber(n) = sympy.bernoulli(n)\n@show B_eq_B = [B(n) == BernoulliNumber(n) for n in 0:maxn]\nprintln()\n@show all(B_eq_B)\n\nmaxnprint = 30\nprintln()\nfor n in [0; 1; 2:2:maxnprint]\n println(\"B($n) = \", B(n))\nend\nprintln()\nfor n in [0; 1; 2:2:maxnprint]\n println(\"BB($n) = \", BB(n))\nend\n```\n\n binom(Rational(#= In[11]:15 =# @big_str(\"100\")) / 3, 30) = 11240781188817808072725280//984770902183611232881\n 1.913094 seconds (17.53 M allocations: 309.111 MiB, 19.93% gc time)\n B_eq_B = [B(n) == BernoulliNumber(n) for n = 0:maxn] = Bool[true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true]\n \n all(B_eq_B) = true\n \n B(0) = 1//1\n B(1) = -1//2\n B(2) = 1//6\n B(4) = -1//30\n B(6) = 1//42\n B(8) = -1//30\n B(10) = 5//66\n B(12) = -691//2730\n B(14) = 7//6\n B(16) = -3617//510\n B(18) = 43867//798\n B(20) = -174611//330\n B(22) = 854513//138\n B(24) = -236364091//2730\n B(26) = 8553103//6\n B(28) = -23749461029//870\n B(30) = 8615841276005//14322\n \n BB(0) = 1.0\n BB(1) = -0.50\n BB(2) = 0.1666666666666666666666666666666666666666666666666666666666666666666666666666674\n BB(4) = -0.03333333333333333333333333333333333333333333333333333333333333333333333333333359\n BB(6) = 0.02380952380952380952380952380952380952380952380952380952380952380952380952380947\n BB(8) = -0.03333333333333333333333333333333333333333333333333333333333333333333333333333359\n BB(10) = 0.0757575757575757575757575757575757575757575757575757575757575757575757575757578\n BB(12) = -0.2531135531135531135531135531135531135531135531135531135531135531135531135531131\n BB(14) = 1.166666666666666666666666666666666666666666666666666666666666666666666666666661\n BB(16) = -7.092156862745098039215686274509803921568627450980392156862745098039215686274513\n BB(18) = 54.97117794486215538847117794486215538847117794486215538847117794486215538847111\n BB(20) = -529.1242424242424242424242424242424242424242424242424242424242424242424242424247\n BB(22) = 6192.123188405797101449275362318840579710144927536231884057971014492753623188388\n BB(24) = -86580.25311355311355311355311355311355311355311355311355311355311355311355311313\n BB(26) = 1.425517166666666666666666666666666666666666666666666666666666666666666666666661e+06\n BB(28) = -2.729823106781609195402298850574712643678160919540229885057471264367816091954032e+07\n BB(30) = 6.015808739006423683843038681748359167714006423683843038681748359167714006423638e+08\n\n\n### 周期的Bernoulli多項式のFourier級数展開\n\n$\\widetilde{B}_k(x) = B_k(x-\\lfloor x\\rfloor)$ を**周期的Bernoulli多項式**と呼ぶことにする. 周期的Bernoulli多項式は $\\widetilde{B}_k(x+1)=\\widetilde{B}_k(x)$ を満たしている. \n\n周期的Bernoulli多項式の母函数 $\\ds\\frac{z e^{z(x-\\lfloor x\\rfloor)}}{e^z-1}$ の $x$ の函数としての Fourier係数 $a_n(z)$ は次のように求まる:\n\n$$\n\\frac{e^z-1}{z}a_n(z) = \\int_0^1 e^{zx}e^{-2\\pi inx}\\,dx =\n\\left[\\frac{e^{(z-2\\pi in)x}}{z-2\\pi in}\\right]_{x=0}^{x=1} = \n\\frac{e^z-1}{z-2\\pi in},\n\\qquad\na_n(z) = \\frac{z}{z-2\\pi in}.\n$$\n\nゆえに $a_0(z)=1$ であり, $n\\ne 0$ のとき\n\n$$\na_n(z) = -\\sum_{k=1}^\\infty \\frac{z^k}{(2\\pi in)^k}\n$$\n\nこれより, $\\widetilde{B}_k(x)$ のFourier係数 $a_{k,n}$ は, $a_{0,n}=\\delta_{n,0}$, $a_{k,0}=\\delta_{k,0}$ を満たし, $k\\ne 0$, $n\\geqq 1$ のとき\n\n$$\na_{k,n} = -\\frac{k!}{(2\\pi in)^k}\n$$\n\nとなることがわかる. したがって, Fourier級数論より, $k=1$ のときは整数ではない実数 $x$ について, $k\\geqq 2$ の場合にはすべての実数 $x$ について次が成立することがわかる:\n\n$$\n\\widetilde{B}_k(x) = B_k(x-\\lfloor x\\rfloor) =\n-k!\\sum_{n\\ne 0} \\frac{e^{2\\pi inx}}{(2\\pi in)^k}.\n$$\n\nすなわち, $k=1,2,3,\\ldots$ について\n\n$$\n\\widetilde{B}_{2k-1}(x) = \n(-1)^k 2(2k-1)!\\sum_{n=1}^\\infty\\frac{\\sin(2\\pi nx)}{(2\\pi n)^{2k-1}}, \n\\qquad\n\\widetilde{B}_{2k}(x) = \n(-1)^{k-1} 2(2k)!\\sum_{n=1}^\\infty \\frac{\\cos(2\\pi nx)}{(2\\pi n)^{2k}}. \n$$\n\nこのことから, $k$ が大きいとき(実際には $k=5,6$ 程度ですでに), 周期的Bernoulli多項式は $n=1$ の項だけで\n\n$$\n\\widetilde{B}_{2k-1}(x) \\approx\n(-1)^k 2(2k-1)!\\frac{\\sin(2\\pi x)}{(2\\pi)^{2k-1}}, \n\\qquad\n\\widetilde{B}_{2k}(x) \\approx\n(-1)^{k-1} 2(2k)!\\frac{\\cos(2\\pi x)}{(2\\pi)^{2k}}\n$$\n\nと近似できることがわかる. 適当にスケールすれば周期的Bernoulli多項式は $k\\to\\infty$ で三角函数に収束する.\n\n\n```julia\nBBB = Bernoulli(Float64.(B.B)) # Float64 Bernoulli numbers\nBP(k,x) = sum(j->binom(k,j)*BBB(k-j)*x^j, 0:k) # Float64 Bernoulli polynomial\nPBP(k,x) = BP(k, x - floor(x)) # periodic Bernoulli polynomial\n\n# partial sum of Fourier series of periodic Bernoulli polynomial\nfunction PSFS(k, N, x)\n k == 0 && return zero(x)\n if isodd(k)\n return (-1)^((k+1)÷2)*2*factorial(k)*sum(n->sin(2π*n*x)/(2π*n)^k, 1:N)\n else\n return (-1)^(k÷2-1)*2*factorial(k)*sum(n->cos(2π*n*x)/(2π*n)^k, 1:N)\n end\nend\n\nPP = []\nx = -1.0:0.001:0.999\nfor (k,N) in [(1,20), (2,10), (3,3), (4,2), (5,1), (6,1)]\n y = PBP.(k,x)\n z = PSFS.(k, N, x)\n ymin = 1.2*minimum(y)\n ymax = 2.7*maximum(y)\n P = plot(legend=:topleft, size=(400, 250), ylim=(ymin, ymax))\n plot!(x, y, label=\"B_$k(x-[x])\")\n plot!(x, z, label=\"partial sum of Fourier series (N=$N)\")\n push!(PP, P)\nend\n\nplot(PP[1:2]..., size=(750, 280))\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(PP[3:4]..., size=(750, 280))\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(PP[5:6]..., size=(750, 280))\n```\n\n\n\n\n \n\n \n\n\n\n## Euler-Maclaurinの和公式\n\n### Euler-Maclaurinの和公式の導出\n\nBernoulli多項式 $B_n(x)$ とBernoulli数 $B_n$ について\n\n$$\n\\begin{aligned}\n&\nB_0(x) = 1, \\quad \\frac{d}{dx}\\frac{B_n(x)}{n!} = \\frac{B_{n-1}(x)}{(n-1)!}, \n\\\\ &\nB_1(0)=-\\frac{1}{2}, \\quad B_1(1)=\\frac{1}{2},\n\\\\ &\nB_n(1)=B_n(0)=B_n \\quad (n=0,2,3,4,5,\\ldots) \n\\\\ &\nB_{2j+1} = 0 \\quad (j=1,2,3,\\ldots)\n\\end{aligned}\n$$\n\nが成立している. 以下ではしばらくのあいだこれらの条件しか使わない.\n\n部分積分を繰り返すことによって,\n\n$$\n\\begin{aligned}\n\\int_0^1 f(x)\\,dx &= \\int_0^1 B_0(x)f(x)\\,dx \n\\\\ &=\n[B_1(x)f(x)]_0^1 - \\int_0^1 B_1(x)f'(x)\\,dx \n\\\\ &=\n[B_1(x)f(x)]_0^1 - \\frac{1}{2}[B_2(x)f'(x)]_0^1 + \\int_0^1 \\frac{B_2(x)}{2}f''(x)\\,dx \n\\\\ &=\n[B_1(x)f(x)]_0^1 - \\frac{1}{2}[B_2(x)f'(x)]_0^1 + \\frac{1}{3!}[B_3(x)f''(x)]_0^1 - \\int_0^1 \\frac{B_3(x)}{3!}f'''(x)\\,dx\n\\\\ &=\n\\cdots\\cdots\\cdots\\cdots\\cdots\n\\\\ &=\n\\sum_{k=1}^n \\frac{(-1)^{k-1}}{k!}\\left[B_k(x)f^{(k-1)}(x)\\right]_0^1 + \n(-1)^n\\int_0^1 \\frac{B_n(x)}{n!}f^{(n)}(x)\\,dx\n\\\\ &=\n\\frac{f(0)+f(1)}{2} + \\sum_{k=2}^n(-1)^{k-1}\\frac{B_k}{k!} (f^{(k-1)}(1)-f^{(k-1)}(0)) + \n(-1)^n\\int_0^1 \\frac{B_n(x)}{n!}f^{(n)}(x)\\,dx.\n\\end{aligned}\n$$\n\n実数 $x$ に対して, $x$ 以下の最大の整数を $\\lfloor x\\rfloor$ と書く. このとき, $x-\\lfloor x\\rfloor$ は $x$ の「小数部分」になる. このように記号を準備しておくと, 整数 $j$ に対して, \n\n$$\n\\begin{aligned}\n\\int_j^{j+1} f(x)\\,dx &= \\int_0^1 f(x+j)\\,dx\n\\\\ &=\n\\frac{f(j)+f(j+1)}{2} + \\sum_{k=2}^n (-1)^{k-1} \\frac{B_k}{k!} (f^{(k-1)}(j+1)-f^{(k-1)}(j)) + \n(-1)^n\\int_0^1 \\frac{B_n(x)}{n!}f^{(n)}(x+j)\\,dx\n\\\\ &=\n\\frac{f(j)+f(j+1)}{2} + \\sum_{k=2}^n (-1)^{k-1}\\frac{B_k}{k!} (f^{(k-1)}(j+1)-f^{(k-1)}(j)) + \n(-1)^n\\int_j^{j+1} \\frac{B_n(x-\\lfloor x\\rfloor)}{n!}f^{(n)}(x)\\,dx.\n\\end{aligned}\n$$\n\n$af(j), a+1:b-1)\n - sum(k -> (\n BernoulliNumber(k)/factorial(Sym(k))\n * (diff(f(x), x, k-1)(x=>b) - diff(f(x), x, k-1)(x=>a))\n ), 2:n)\n )\nend\n\nfunction EulerMaclaurinRemainder(f, a, b, n)\n x = symbols(\"x\", real=true)\n g = diff(f(x), x, n)\n (-1)^(n-1) * sum(k -> (\n integrate(BernoulliPolynomial(n,x)*g(x=>x+k), (x,0,1))\n ), a:b-1)/factorial(Sym(n))\nend\n\nx = symbols(\"x\", real=true)\n\n[integrate(x^m, (x, 0, 10)) for m in 7:15] |> display\n\n[\n EulerMaclaurinIntegral(x->x^m, 0, 10, 5) - EulerMaclaurinRemainder(x->x^m, 0, 10, 5)\n for m in 7:15\n] |> display\n```\n\n\n\\[ \\left[ \\begin{array}{r}12500000\\\\\\frac{1000000000}{9}\\\\1000000000\\\\\\frac{100000000000}{11}\\\\\\frac{250000000000}{3}\\\\\\frac{10000000000000}{13}\\\\\\frac{50000000000000}{7}\\\\\\frac{200000000000000}{3}\\\\625000000000000\\end{array} \\right] \\]\n\n\n\n\\[ \\left[ \\begin{array}{r}12500000\\\\\\frac{1000000000}{9}\\\\1000000000\\\\\\frac{100000000000}{11}\\\\\\frac{250000000000}{3}\\\\\\frac{10000000000000}{13}\\\\\\frac{50000000000000}{7}\\\\\\frac{200000000000000}{3}\\\\625000000000000\\end{array} \\right] \\]\n\n\n**Euler-Maclaurinの和公式の解釈2:** Euler-Maclaurinの和公式は次のように書き直される:\n\n$$\n\\begin{aligned}\n&\n\\sum_{j=a}^b f(j) = \n\\int_a^b f(x)\\,dx + \\frac{f(a)+f(b)}{2} + \n\\sum_{1\\leqq i\\leqq n/2} \\frac{B_{2i}}{(2i)!} (f^{(2i-1)}(b)-f^{(2i-1)}(a)) + R_n,\n\\\\ &\nR_n = (-1)^{n-1}\\int_a^b \\frac{B_n(x-\\lfloor x\\rfloor)}{n!}f^{(n)}(x)\\,dx\n\\end{aligned}\n$$\n\nこれは $n$ が3以上の奇数のとき $B_n=0$ となることを使うと次のように書き直される:\n\n$$\n\\begin{aligned}\n&\n\\sum_{j=a}^b f(j) = \n\\int_a^b f(x)\\,dx + \\frac{f(a)+f(b)}{2} + \n\\sum_{k=2}^n \\frac{B_k}{k!} (f^{(k-1)}(b)-f^{(k-1)}(a)) + R_n,\n\\\\ &\nR_n = (-1)^{n-1}\\int_a^b \\frac{B_n(x-\\lfloor x\\rfloor)}{n!}f^{(n)}(x)\\,dx\n\\end{aligned}\n$$\n\nこの等式は函数 $f$ の整数における値の和 $\\ds\\sum_{j=a}^b f(j)$ を積分 $\\ds\\int_a^b f(x)\\,dx$ で近似したときの誤差が\n\n$$\n\\frac{f(a)+f(b)}{2} + \n\\sum_{1\\leqq i\\leqq n/2} \\frac{B_{2i}}{(2i)!} (f^{(2i-1)}(b)-f^{(2i-1)}(a)) + R_n\n$$\n\nになっていることを意味している. 例えば, $n=1$ の場合には, $\\ds B_1(x)=x-\\frac{1}{2}$ なので,\n\n$$\n\\sum_{j=a}^b f(j) = \n\\int_a^b f(x)\\,dx + \\frac{f(a)+f(b)}{2} + \n\\int_a^b\\left(x-\\lfloor x\\rfloor-\\frac{1}{2}\\right)f'(x)\\,dx.\n$$\n\n$n=2$ の場合には $\\ds B_2(x)=x^2-x+\\frac{1}{6}$, $\\ds B_2=\\frac{1}{6}$ であり,\n\n$$\n\\sum_{j=a}^b f(j) = \n\\int_a^b f(x)\\,dx + \\frac{f(a)+f(b)}{2} +\n\\frac{f'(b)-f'(a)}{12} -\n\\int_a^b\\frac{B_2(x-\\lfloor x\\rfloor)}{2}f''(x)\\,dx.\n$$\n\nとなる. $\\QED$\n\n\n```julia\n# すぐ上の公式を検証\n\nPowerSum(m, n) = sum(j->j^m, 1:n)\nBernoulliNumber(n) = sympy.bernoulli(n)\nBernoulliPolynomial(n,x) = sympy.bernoulli(n,x)\n\nfunction EulerMaclaurinSum(f, a, b, n)\n x = symbols(\"x\", real=true)\n (\n integrate(f(x), (x, a, b))\n + (f(a)+f(b))/Sym(2)\n + sum(k -> (\n BernoulliNumber(k)/factorial(Sym(k))\n * (diff(f(x), x, k-1)(x=>b) - diff(f(x), x, k-1)(x=>a))\n ), 2:n)\n )\nend\n\nfunction EulerMaclaurinRemainder(f, a, b, n)\n x = symbols(\"x\", real=true)\n g = diff(f(x), x, n)\n (-1)^(n-1) * sum(k -> (\n integrate(BernoulliPolynomial(n,x)*g(x=>x+k), (x,0,1))\n ), a:b-1)/factorial(Sym(n))\nend\n\n[PowerSum(m, 10) for m in 1:10] |> display\n\n[EulerMaclaurinSum(x->x^m, 1, 10, m+1) for m in 1:10] |> display\n\n[\n EulerMaclaurinSum(x->x^m, 1, 10, m-1) + EulerMaclaurinRemainder(x->x^m, 1, 10, m-1)\n for m in 3:10\n] |> display\n\n[\n EulerMaclaurinSum(x->x^m, 1, 10, m-2) + EulerMaclaurinRemainder(x->x^m, 1, 10, m-2)\n for m in 4:10\n] |> display\n\n[\n EulerMaclaurinSum(x->x^m, 1, 10, m-3) + EulerMaclaurinRemainder(x->x^m, 1, 10, m-3)\n for m in 5:10\n] |> display\n```\n\n\n 10-element Array{Int64,1}:\n 55\n 385\n 3025\n 25333\n 220825\n 1978405\n 18080425\n 167731333\n 1574304985\n 14914341925\n\n\n\n\\[ \\left[ \\begin{array}{r}55\\\\385\\\\3025\\\\25333\\\\220825\\\\1978405\\\\18080425\\\\167731333\\\\1574304985\\\\14914341925\\end{array} \\right] \\]\n\n\n\n\\[ \\left[ \\begin{array}{r}3025\\\\25333\\\\220825\\\\1978405\\\\18080425\\\\167731333\\\\1574304985\\\\14914341925\\end{array} \\right] \\]\n\n\n\n\\[ \\left[ \\begin{array}{r}25333\\\\220825\\\\1978405\\\\18080425\\\\167731333\\\\1574304985\\\\14914341925\\end{array} \\right] \\]\n\n\n\n\\[ \\left[ \\begin{array}{r}220825\\\\1978405\\\\18080425\\\\167731333\\\\1574304985\\\\14914341925\\end{array} \\right] \\]\n\n\n### Euler-Maclaurinの和公式の形式的導出\n\n函数 $f(x)$ に対して, ある函数 $F(x)$ で\n\n$$\nF(x+1) - F(x) = f(x+h)\n$$\n\nという条件を満たすものを求める問題を考える. そのとき, $\\ds D=\\frac{\\d}{\\d x}$ とおくと, 形式的にその条件は\n\n$$\n(e^D-1)F(x) = e^{hD}f(x) = De^{hD}\\int f(x)\\,dx\n$$\n\nと書き直される. これより, 形式的には\n\n$$\nF(x) = \\frac{De^{hD}}{e^D-1}\\int f(x)\\,dx =\n\\sum_{k=0}^\\infty \\frac{B_k(h)}{k!}D^k \\int f(x)\\,dx =\n\\int f(x)\\,dx + \\sum_{k=1}^\\infty \\frac{B_k(h)}{k!}f^{(k-1)}(x).\n$$\n\nこれより, 整数 $an$ のとき, \n\n$$\n\\begin{aligned}\n\\log n! &= \\log N! + \\log n - \\sum_{j=n}^N \\log j\n\\\\ &= \\log N! + \\log n -\\left(\n\\int_n^N \\log x\\,dx + \\frac{\\log n+\\log N}{2} +\n\\sum_{k=2}^{K-1}\\frac{B_k}{k(k-1)} \\left(\\frac{1}{N^{k-1}} - \\frac{1}{n^{k-1}}\\right) + \nR_{K,N}\n\\right)\n\\\\ &=\n\\log N! - \\left(N\\log N - N + \\frac{1}{2}\\log N\\right) - \n\\sum_{k=2}^{K-1} \\frac{B_k}{k(k-1)} \\frac{1}{N^{k-1}}\n\\\\ &\\,+\nn\\log n - n +\\frac{1}{2}\\log n +\n\\sum_{k=2}^{K-1}\\frac{B_k}{k(k-1)} \\frac{1}{n^{k-1}} + R_{K,N},\n\\\\ \nR_{K,N} &= (-1)^{K-1}\\int_n^N \\frac{\\tilde{B}_K(x)}{K}\\frac{(-1)^{K-1}}{x^K}\\,dx\n\\end{aligned}\n$$\n\nただし, $\\tilde{B}_n(x)=B_n(\\lfloor x\\rfloor)$ とおいた. \n\nここでは, $N\\to\\infty$ のとき\n\n$$\n\\log N! - \\left(N\\log N - N + \\frac{1}{2}\\log N\\right) \\to \\sqrt{2\\pi}\n$$\n\nとなることは既知であるものとする. 例えば, ノート「10 Gauss積分, ガンマ函数, ベータ函数」「12 Fourier解析」のStirlingの近似公式の節を参照して欲しい. 以下ではそれらのノートよりも精密な結果を得る.\n\nこのとき, 上の結果で $N\\to\\infty$ とすると,\n\n$$\n\\begin{aligned}\n&\n\\log n! =\nn\\log n - n +\\frac{1}{2}\\log n + \\log\\sqrt{2\\pi} +\n\\sum_{k=2}^{K-1}\\frac{B_k}{k(k-1)} \\frac{1}{n^{k-1}} + R_K,\n\\\\ & \nR_K = (-1)^{K-1}\\int_n^\\infty \\frac{\\tilde{B}_K(x)}{K}\\frac{(-1)^{K-1}}{x^K}\\,dx = \nO\\left(\\frac{1}{n^{K-1}}\\right).\n\\end{aligned}\n$$\n\n$K=2L+1$ とおくことによって次が得られる: 正の整数 $L$ に対して,\n\n$$\n\\log n! =\nn\\log n - n + \\frac{1}{2}\\log n + \\log\\sqrt{2\\pi} +\n\\sum_{l=1}^L \\frac{B_{2l}}{(2l)(2l-1)}\\frac{1}{n^{2l-1}} + O\\left(\\frac{1}{n^{2L}}\\right).\n$$\n\nこれが求めていた結果である.\n\n例えば, $L=2$ のとき, $\\ds B_2=\\frac{1}{6}$, $\\ds B_4=-\\frac{1}{30}$ なので,\n\n$$\n\\log n! =\nn\\log n - n + \\frac{1}{2}\\log n + \\log\\sqrt{2\\pi} +\n\\frac{1}{12n} - \\frac{1}{360n^3} + O\\left(\\frac{1}{n^4}\\right).\n$$\n\nこれより, \n\n$$\nn! = n^n e^{-n}\\sqrt{2\\pi n}\n\\left(1+\\frac{1}{12n} + \\frac{1}{288n^2} - \\frac{139}{51840n^3} + O\\left(\\frac{1}{n^4}\\right)\\right).\n$$\n\n\n```julia\nx = symbols(\"x\")\nseries(exp(x/12-x^3/360), x, n=4)\n```\n\n\n\n\n\\begin{equation*}1 + \\frac{x}{12} + \\frac{x^{2}}{288} - \\frac{139 x^{3}}{51840} + O\\left(x^{4}\\right)\\end{equation*}\n\n\n\n### Poissonの和公式とEuler-Maclaurinの和公式の関係\n\nPoissonの和公式とは, 急減少函数 $f(x)$ に対して,\n\n$$\n\\sum_{m\\in\\Z} f(m) = \\sum_{n\\in\\Z} \\hat{f}(n), \\qquad\n\\hat{f}(p) = \\int_\\R f(x)e^{2\\pi i px}\\,dx\n$$\n\nが成立するという結果であった. これの右辺は以下のように変形できる:\n\n$$\n\\begin{aligned}\n\\sum_{n\\in\\Z} \\hat{f}(n) &=\n\\sum_{n\\in\\Z} \\int_\\R f(x)e^{2\\pi i nx}\\,dx =\n\\int_\\R f(x)\\,dx + 2\\sum_{n=1}^\\infty\\int_\\R f(x)\\cos(2\\pi nx)\\,dx\n\\\\ &=\n\\int_\\R f(x)\\,dx - \\sum_{n=1}^\\infty\\int_\\R f'(x)\\frac{\\sin(2\\pi nx)}{\\pi n}\\,dx\n\\\\ &=\n\\int_\\R f(x)\\,dx + \\int_\\R \\left(-\\sum_{n=1}^\\infty\\frac{\\sin(2\\pi nx)}{\\pi n}\\right)f'(x)\\,dx\n\\end{aligned}\n$$\n\n2つ目の等号では $e^{2\\pi inx}+e^{-2\\pi inx}=2\\cos(2\\pi nx)$ を用い, 3つ目の等号では部分積分を実行し, 4つ目の等号では無限和と積分の順序を交換した. それらの操作は $f(x)$ が急減少函数であれば容易に正当化される. \n\n一方, Euler-Maclaurinの和公式の\n\n$$\nB_1(x-\\lfloor x\\rfloor) = x - \\lfloor x\\rfloor - \\frac{1}{2}\n$$\n\nを使う場合から, \n\n$$\n\\sum_{m\\in\\Z} f(m) =\n\\int_\\R f(x)\\,dx + \\int_\\R \\left(x - \\lfloor x\\rfloor - \\frac{1}{2}\\right) f'(x)\\,dx\n$$\n\nが導かれる. これは部分積分によって得られる次の公式からただちに導かれる易しい公式であることにも注意せよ:\n\n$$\n\\begin{aligned}\n\\int_n^{n+1} \\left(x - n - \\frac{1}{2}\\right) f'(x)\\,dx &=\n\\left[\\left(x - n - \\frac{1}{2}\\right)f(x)\\right]_n^{n+1} - \\int_n^{n+1}f(x)\\,dx - n\n\\\\ &=\n\\frac{f(n+1)-f(n)}{2} - \\int_n^{n+1}f(x)\\,dx.\n\\end{aligned}\n$$\n\n以上の2つの結果を比較すると, Poissonの和公式とEuler-Maclaurinの和公式の $B_1(x-\\lfloor x\\rfloor)$ を使った場合は, \n\n$$\nx - \\lfloor x\\rfloor - \\frac{1}{2} =\n-\\sum_{n=1}^\\infty\\frac{\\sin(2\\pi nx)}{\\pi n}\n\\tag{$*$}\n$$\n\nという公式で結び付いていることがわかる. この公式を認めれば, Euler-Maclaurinの和公式の $B_1(x-\\lfloor x\\rfloor)$ を使った場合からPoissonの和公式が導かれる. \n\n公式($*$)の左辺はいわゆる**のこぎり波**であり, 右辺はそのFourier級数である. 公式($*$)はFourier級数論における非常に有名な公式であり, 本質的にそれと同じ公式はFourier級数論について書かれた文献には例として必ず載っていると言ってよいくらいである. (Fourier級数論より, 公式($*$)は $x$ が整数でないときには実際に成立していることがわかる.)\n\nこのように, のこぎり波のFourier級数展開という非常に特殊な公式はPoissonの和公式という一般的な公式を導くだけの力を持っているのである. \n\n**まとめ:** のこぎり波のFourier級数展開は部分積分を通してPoissonの和公式と本質的に同値である! $\\QED$\n\nこの節で解説したことは次の文献で指摘されている:\n\n* Tim Jameson, An elementary derivation of the Poisson summation formula\n\n\n```julia\nB_1(x) = x - 1/2\nb(x) = B_1(x - floor(x))\nS(N,x) = -sum(n->sin(2π*n*x)/(π*n), 1:N)\nx = -2:0.001:1.999\nN = 10\nplot(size=(400,200), ylim=(-0.6,1.2), legend=:top)\nplot!(x, b.(x), label=\"B_1(x-[x]) = x - [x] -1/2\")\nplot!(x, S.(N,x), label=\"partial sum of Fourier series (N=$N)\")\n```\n\n\n\n\n \n\n \n\n\n\n**補足:** このノートの上の方の周期的Bernoulli多項式 $B_k(x-\\lfloor x\\rfloor)$ のFourier級数展開の節を見ればわかるように, \n\n$$\n\\sum_{n=1}^\\infty \\frac{\\cos(2\\pi nx)}{n^k}, \\quad\n\\sum_{n=1}^\\infty \\frac{\\sin(2\\pi nx)}{n^k}\n$$\n\nの型のFourier級数の収束先は平行移動と定数倍の違いを除いて周期的Bernoulli多項式になる. $\\QED$\n\n### 台形公式とPoissonの和公式の関係\n\n簡単のため $f(x)$ は $\\R$ 上の急減少函数であるとし, $a,b\\in\\Z$ かつ $a1$ のとき(より一般には $\\real s>1$ のとき),\n\n$$\n\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}\n$$\n\nは絶対収束しているのであった. これにEuler-Maclaurinの和公式\n\n$$\n\\begin{aligned}\n&\n\\sum_{j=a}^b f(j) = \n\\int_a^b f(x)\\,dx + \\frac{f(a)+f(b)}{2} + \n\\sum_{k=2}^n \\frac{B_k}{k!} (f^{(k-1)}(b)-f^{(k-1)}(a)) + R_n,\n\\\\ &\nR_n = (-1)^{n-1}\\int_a^b \\frac{B_n(x-\\lfloor x\\rfloor)}{n!}f^{(n)}(x)\\,dx\n\\end{aligned}\n$$\n\nを適用してみよう.\n\n### 解析接続\n\n$\\real s > 1$ であるとし, $f(x)=x^{-s}$ とおく. このとき, \n\n$$\n\\begin{aligned}\n&\n\\int_a^\\infty f(x)\\,dx = \\int_1^\\infty x^{-s}\\,dx = \n\\left[\\frac{x^{-s+1}}{-s+1}\\right]_1^\\infty = \\frac{a^{-(s-1)}}{s-1}, \\qquad\nf(b)=b^{-s}\\to 0 \\quad(b\\to\\infty).\n\\\\ &\n\\frac{B_k}{k!}f^{(k-1)}(x) = \n\\frac{B_k}{k}\\binom{-s}{k-1} x^{-s-k+1}, \\quad\n\\frac{B_n(x-\\lfloor x\\rfloor)}{n!}f^{(n)}(x) = \n\\binom{-s}{n}B_n(x-\\lfloor x\\rfloor)x^{-s-n}\n\\end{aligned}\n$$\n\nなので, 2以上の整数 $n$ について,\n\n$$\n\\begin{aligned}\n&\n\\zeta(s) = \\frac{1}{s-1} + \\frac{1}{2} - \n\\sum_{k=2}^n \\frac{B_k}{k}\\binom{-s}{k-1} + R_n,\n\\\\ &\nR_n = (-1)^{n-1}\\binom{-s}{n}\\int_1^\\infty B_n(x-\\lfloor x\\rfloor)x^{-s-n}\\,dx.\n\\end{aligned}\n$$\n\n積分 $R_n$ は $\\real s+n>1$ ならば絶対収束している. ゆえに, 複素平面全体に $\\zeta(s)$ を自然に拡張する方法(解析接続する方法)が得られた.\n\n$\\ds \\sum_{k=1}^\\infty \\frac{1}{n^s}$ そのものではなく, $n=a$ から始まる無限和 $\\ds \\sum_{k=a}^\\infty \\frac{1}{n^s}=\\zeta(s)-\\sum_{n=1}^{a-1}\\frac{1}{n^s}$ にEuler-Maclaurinの和公式を適用すると,\n\n$$\n\\begin{aligned}\n&\n\\zeta(s) = \\sum_{n=1}^{a-1} \\frac{1}{n^s} - \\frac{a^{1-s}}{1-s} + \n\\frac{1}{2a^s} - \\sum_{k=2}^n \\frac{B_k}{k a^{s+k-1}}\\binom{-s}{k-1} + R_{n,a},\n\\\\ &\nR_{n,a} = (-1)^{n-1}\\binom{-s}{n}\\int_a^\\infty B_n(x-\\lfloor x\\rfloor)x^{-s-n}\\,dx.\n\\end{aligned}\n$$\n\n\n```julia\n# 上の公式における ζ(s) - R_{n,a} の函数化\n\n# ζ(s) - R_{n,a} = Σ_{m=1}^{a-1} m^{-s} - a^{1-s}/(1-s) + 1/(2a^s)\n# - Σ_{k=2}^n B_k/(k a^{s+k-1}) binom(-s,k-1) (k is even)\n#\nfunction ApproxZeta(a, n, s)\n ss = float(big(s))\n z = zero(ss)\n z += (a ≤ 1 ? zero(ss) : sum(m->m^(-ss), 1:a-1)) # Σ_{m=1}^{a-1} m^{-s}\n z += -a^(1-ss)/(1-ss) # -a^{1-s}/(1-s)\n n == 0 && return z\n z += 1/(2*a^ss) # 1/(2a^s)\n n == 1 && return z\n z -= sum(k -> BB(k)/(k*a^(ss+k-1))*binom(-ss,k-1), 2:2:n)\n # -Σ_{k=2}^n B_k/(k a^{s+k-1}) binom(-s,k-1) (k is even)\nend\n\nA = ApproxZeta(40, 80, big\"0.5\")\nZ = zeta(big\"0.5\")\n@show A\n@show Z;\n```\n\n A = -1.460354508809586812889499152515298012467229331012581490542886087825530529474572\n Z = -1.460354508809586812889499152515298012467229331012581490542886087825530529474503\n\n\n$\\real s > 0$ のとき, \n\n$$\n\\frac{1}{2a^s} - \\sum_{k=2}^n \\frac{B_k}{k a^{s+k-1}}\\binom{-s}{k-1} + R_{n,a}\n$$\n\nは $a\\to\\infty$ で $0$ に収束するので,\n\n$$\n\\zeta(s) = \\lim_{a\\to\\infty}\\left(\\sum_{n=1}^{a-1} \\frac{1}{n^s} - \\frac{a^{1-s}}{1-s}\\right)\n\\quad (\\real s > 0)\n$$\n\nが成立することがわかる. これは, Dirichlet級数の部分和 $\\ds\\sum_{n=1}^{a-1}\\frac{1}{n^s}$ から補正項\n\n$$\n\\frac{a^{1-s}}{1-s}\n$$\n\nを引き去ってから, Dirichlet級数の総和を取れば, $0 < \\real s < 1$ でも収束して, $\\zeta(s)$ の正確な値が得られることを意味している.\n\n\n```julia\n# 上の結果のプロット\n\nApproxZeta0(a, s) = sum(n->n^(-s), 1:a-1) - a^(1-s)/(1-s)\na = 100\ns = 0.05:0.01:0.95\n@time z = zeta.(s)\n@time w = ApproxZeta0.(a, s)\nplot(size=(400, 250), legend=:bottomleft, xlabel=\"s\")\nplot!(s, z, label=\"zeta(s)\", lw=2)\nplot!(s, w, label=\"Euler-Maclaurin sum for n=0, a=$a\", lw=2, ls=:dash)\n```\n\n 0.235033 seconds (507.61 k allocations: 26.628 MiB, 13.12% gc time)\n 0.108976 seconds (319.80 k allocations: 15.620 MiB)\n\n\n\n\n\n \n\n \n\n\n\n\n```julia\n# さらに項の数を1つ増やした場合のプロット\n\n# ζ(s) - R_{1,a} = Σ_{n=1}^{a-1} n^{-s} - a^{1-s}/(1-s) + 1/(2a^s)\n#\nApproxZeta1(a, s) = sum(n->n^(-s), 1:a-1) - a^(1-s)/(1-s) + 1/(2*a^s)\n\ns = -0.95:0.01:0.5\na = 10^3\n@time z = zeta.(s)\n@time w = ApproxZeta1.(a,s)\nplot(size=(400, 250), legend=:bottomleft, xlabel=\"s\")\nplot!(s, z, label=\"zeta(s)\", lw=2)\nplot!(s, w, label=\"Euler-Maclaurin sum for n=1, a=$a\", lw=2, ls=:dash)\n```\n\n 0.000172 seconds (8 allocations: 1.563 KiB)\n 0.117856 seconds (313.70 k allocations: 15.673 MiB)\n\n\n\n\n\n \n\n \n\n\n\n\n```julia\n# さらに一般の場合のプロット\n#\n# Euler-Maclaurinの和公式で ζ(s) の負の s での値をぴったり近似できていることがわかる.\n\n[(-m, zeta(-m), Float64(ApproxZeta(2, 17, -m))) for m = 0:12] |> display\n\nn = 10\ns = -1.5:0.05:0.5\na = 10\n@time z = zeta.(s)\n@time w = ApproxZeta.(a, n, s)\nP1 = plot(size=(400, 250), legend=:bottomleft, xlabel=\"s\")\nplot!(s, z, label=\"zeta(s)\", lw=2)\nplot!(s, w, label=\"Euler-Maclaurin sum for a=$a, n=$n\", lw=2, ls=:dash)\n\nn = 17\ns = -16:0.05:-2.0\na = 2\n@time z = zeta.(s)\n@time w = ApproxZeta.(a, n, s)\nP2 = plot(size=(400, 250), legend=:topright, xlabel=\"s\")\nplot!(s, z, label=\"zeta(s)\", lw=2)\nplot!(s, w, label=\"Euler-Maclaurin sum for a=$a, n=$n\", lw=2, ls=:dash)\n```\n\n\n 13-element Array{Tuple{Int64,Float64,Float64},1}:\n (0, -0.5, -0.5) \n (-1, -0.08333333333333338, -0.08333333333333333) \n (-2, -0.0, -1.2954252832641667e-77) \n (-3, 0.008333333333333345, 0.008333333333333333) \n (-4, -0.0, -3.454467422037778e-77) \n (-5, -0.0039682539682539715, -0.003968253968253968)\n (-6, -0.0, 0.0) \n (-7, 0.004166666666666668, 0.004166666666666667) \n (-8, -0.0, 0.0) \n (-9, -0.007575757575757582, -0.007575757575757576) \n (-10, -0.0, -4.421718300208356e-75) \n (-11, 0.0210927960927961, 0.021092796092796094) \n (-12, -0.0, 0.0) \n\n\n 0.000048 seconds (8 allocations: 800 bytes)\n 0.144020 seconds (387.92 k allocations: 19.316 MiB)\n 0.000267 seconds (8 allocations: 2.719 KiB)\n 0.069766 seconds (555.19 k allocations: 20.968 MiB, 17.44% gc time)\n\n\n\n\n\n \n\n \n\n\n\n\n```julia\ndisplay(P1)\n```\n\n\n \n\n \n\n\n上と下のグラフを見ればわかるように, Euler-Maclaurinの和公式によって負の実数での $\\zeta$ 函数の値を非常によく近似できている. 実は $\\zeta(s)$ を実部が負の複素数まで拡張してもこの近似はうまく行っている.\n\n\n```julia\ndisplay(P2)\n```\n\n\n \n\n \n\n\n### ζ(2)の近似計算\n\n$\\ds\\zeta(2)=\\sum_{n=1}^\\infty \\frac{1}{n^2}$ を計算せよという問題は**Basel問題**と呼ばれているらしい. Basel問題はEulerによって1743年ころに解かれたらしい. Eulerがどのように考えたかについては次の文献を参照せよ.\n\n* 杉本敏夫, バーゼル問題とオイラー, 2007年8月23日, 数理解析研究所講究録, 第1583巻, 2008年, pp.159-167\n\nEulerは $\\zeta(2)$ の近似値を自ら開発したEuler-Maclaurinの和公式を使って精密に計算したらしい.\n\n近似式\n\n$$\n\\zeta(s) \\approx\n\\sum_{n=1}^{a-1} \\frac{1}{n^s} - \\frac{a^{1-s}}{1-s} + \n\\frac{1}{2a^s} - \\sum_{k=2}^n \\frac{B_k}{k a^{s+k-1}}\\binom{-s}{k-1} \n$$\n\nを用いて, $\\zeta(2)$ を計算してみよう. 3以上の奇数 $n$ について $B_n=0$ となるので, $n=2m$ のとき, 右辺の項数は $a+m+1$ になる.\n\n例えば, $a=10$, $m=9$ とし, 20項の和を取ると,\n\n$$\n\\zeta(2) \\approx 1.64493\\;40668\\;4749\\cdots\n$$\n\nとなり, 正確な値 $\\ds\\frac{\\pi^2}{6}=1.64493\\;40668\\;4822\\cdots$ と小数点以下第11桁まで一致している. \n\nEulerは後に $\\ds\\zeta(2)=\\frac{\\pi^2}{6}$ を得る. Eulerは競争相手に議論に厳密性に欠けるとして様々な批判を受けたのだが, 以上のような数値計算の結果を知っていたので, 正解を得たという確信は微塵も揺らがなかっただろうと思われる.\n\n**注意:** 論理的に厳密な証明の方法が発達した現代においても, 人間は常に証明を間違う可能性がある. 人間が行った証明は絶対的には信用できない. だから, たとえ証明が完成したと思っていたとしても, 可能ならば数値計算によって論理的に厳密な証明以外の証拠を作っていた方が安全だと思われる. $\\QED$\n\n**注意:** 数学のノートを作りながら, 気軽に数値的証拠も同時に得るための道具として, 筆者がこのノート作成のために用いているJulia言語JupyterNbextensionsのLive Markdown Previewはこれを書いている時点で相当に優秀な道具であるように思われる. $\\QED$\n\n\n```julia\n# 20項の和\n\nN = 20\n[(m, N-m-1, 2m, ApproxZeta(N-m-1, 2m, 2) - big(π)^2/6) for m in 2:N÷2-1] |> display\n\nm = 9\na = N-m-1\nZ = big(π)^2/6\nA = ApproxZeta(a, m, 2)\n@show a,m\n@show Z\n@show A;\n```\n\n\n 8-element Array{Tuple{Int64,Int64,Int64,BigFloat},1}:\n (2, 17, 4, -5.77451793863474833797788940478358503699585407578399357681001619323664145261758e-11) \n (3, 16, 6, 4.808127352395625095013460112150325878389866054958153137408430487774776509324829e-13) \n (4, 15, 8, -8.630887513943044224615236465465206970650911046136527708026292186723865816966492e-15) \n (5, 14, 10, 3.116217978527385328054235573023871173466586797186396436897662720414552852297451e-16) \n (6, 13, 12, -2.200847274100542514575619216657515798396053843860275532661691594239630209744406e-17)\n (7, 12, 14, 3.035248943857815147777677383711316694019656935103319432181355248871820406062584e-18) \n (8, 11, 16, -8.335321043122531064769674746337938450627967961329547742403411230422546148897753e-19)\n (9, 10, 18, 4.746601814392005312714027578027970306539540935051342164737224161514796063021067e-19) \n\n\n (a, m) = (10, 9)\n Z = 1.644934066848226436472415166646025189218949901206798437735558229370007470403185\n A = 1.644934066847493071302595112118921642731166540690350214159737969261778785588307\n\n\n### s = 1でのζ(s)の定数項がEuler定数になること\n\n$\\zeta(s)=\\ds\\sum_{n=1}^\\infty \\frac{1}{n^s}$ にEuler-Maclaurinの和公式を使って, 2以上の $n$ について次の公式が得られるのであった:\n\n$$\n\\begin{aligned}\n&\n\\zeta(s) = \\frac{1}{s-1} + \\frac{1}{2} - \n\\sum_{k=2}^n \\frac{B_k}{k}\\binom{-s}{k-1} + R_n,\n\\\\ &\nR_n = (-1)^{n-1}\\binom{-s}{n}\\int_1^\\infty B_n(x-\\lfloor x\\rfloor)x^{-s-n}\\,dx.\n\\end{aligned}\n$$\n\n$n=1$ の場合には\n\n\\begin{aligned}\n\\sum_{j=a}^b f(j) &= \n\\int_a^b f(x)\\,dx + f(a) + \\int_a^b (x-\\lfloor x\\rfloor)f'(x)\\,dx\n\\\\ &=\n\\int_a^b f(x)\\,dx + f(a) + \\sum_{j=a}^{b-1}\\int_0^1 x f'(x+j)\\,dx\n\\end{aligned}\n\nを $f(x)=x^{-s}$, $f'(x)=-sx^{-s-1}$, $a=1$, $b=\\infty$ の場合に適用して,\n\n$$\n\\zeta(s) = \n\\frac{1}{s-1} + 1 - s\\sum_{j=1}^\\infty\\int_0^1 \\frac{x}{(x+j)^{s+1}}\\,dx\n$$\n\nを得る. したがって,\n\n$$\n\\lim_{s\\to 1}\\left(\\zeta(s)-\\frac{1}{s-1}\\right) =\n1 - \\sum_{j=1}^\\infty\\int_0^1 \\frac{x}{(x+j)^2}\\,dx.\n$$\n\nそして, $x=t-j$ と置換すると, \n\n$$\n\\begin{align}\n-\\int_0^1\\frac{x}{(x+j)^2}\\,dx &= \n-\\int_j^{j+1}\\frac{-(t-j)}{t^2}\\,dt = \n-\\left[\\log t + \\frac{j}{t}\\right]_j^{j+1} \n\\\\ &=\n-\\log(j+1)+\\log j -\\frac{j}{j+1}+1 =\n\\frac{1}{j+1} + \\log j - \\log(j+1)\n\\end{align}\n$$\n\nなので, これを $j=1$ から $j=N-1$ まで足し上げることによって,\n\n$$\n1 - \\sum_{j=1}^{n-1}\\int_0^1\\frac{x}{(x+j)^2}\\,dx =\n\\sum_{j=1}^N\\frac{1}{j} - \\log N.\n$$\n\nこれの $N\\to\\infty$ での極限はEuler定数 $\\gamma=0.5772\\cdots$ の定義であった. 以上によって次が示された:\n\n$$\n\\lim_{s\\to 1}\\left(\\zeta(s)-\\frac{1}{s-1}\\right) = \\gamma = 0.5772\\cdots.\n$$\n\n### 負の整数におけるゼータ函数の特殊値の計算\n\nEuler-Maclaurinの和公式: $3$ 以上の整数 $k$ について $B_k=0$ なので, 以下の公式で $k$ は偶数のみを動くとしてよい:\n\n$$\n\\begin{aligned}\n&\n\\sum_{n=a}^b f(n) = \n\\int_a^b f(x)\\,dx + \\frac{f(a)+f(b)}{2} + \n\\sum_{k=2}^m \\frac{B_k}{k!}(f^{(k-1)}(b) - f^{(k-1)}(a)) + R_m,\n\\\\ &\nR_n = (-1)^{m-1}\\int_a^b \\frac{\\tilde{B}_m(x)}{m!} f^{(m)}(x)\\,dx.\n\\end{aligned}\n$$\n\nここで $\\tilde{B}_m(x)=B_m(x-\\lfloor x\\rfloor)$ とおいた.\n\nEuler-Maclaurinの和公式を $f(x)=n^{-s}$, $a=1$, $b=\\infty$ の場合に適用することによって $\\zeta(s)$ は次の形で $\\Re s > 1-m$ まで自然に延長(解析接続)されるのであった:\n\n$$\n\\zeta(s) = \n\\frac{1}{s-1} + \\frac{1}{2} -\n\\frac{1}{1-s}\\sum_{k=2}^m \\binom{1-s}{k} B_k + \n(-1)^{m-1}\\int_a^b \\binom{-s}{m} \\tilde{B}_m(x) x^{-s-m}\\,dx.\n$$\n\nこの公式と $k\\geqq 2$ のとき $\\ds\\binom{1}{k}=0$ となることより, \n\n$$\n\\zeta(0) = \\frac{1}{0-1} + \\frac{1}{2} = -\\frac{1}{2}.\n$$\n\n$r$ は正の整数であるとする. このとき, $m>r$ とすると $\\ds\\binom{r}{m}=0$ となるので, $B_0=1$, $B_1=-1/2$ なので,\n\n$$\n\\begin{aligned}\n\\zeta(-r) &=\n-\\frac{1}{r+1} + \\frac{1}{2} -\n\\frac{1}{r+1}\\sum_{k=2}^{r+1} \\binom{m+1}{k} B_k\n\\\\ =&\n-\\frac{1}{r+1}\\sum_{k=0}^{r+1} \\binom{m+1}{k} B_k =\n-\\frac{B_{r+1}}{r+1}.\n\\end{aligned}\n$$\n\n最後の等号で, Bernoulli数を帰納的に計算するために使える公式 $\\ds\\sum_{k=0}^r \\binom{r+1}{k}B_k=0$ を用いた. 例えば, $r=1$ のとき $B_0+2B_1=1+2(-1/2)=0$ となり, $r=2$ のとき, $B_0+3B_1+3B_2=1+3(-1/2)+3(1/6)=0$ となる.\n\n以上によって次が証明された:\n\n$$\n\\zeta(0)=-\\frac{1}{2}, \\quad\n\\zeta(-r) = -\\frac{B_{r+1}}{r+1} \\quad (r=1,2,3,\\ldots).\n$$\n\nこれらの公式は $B_n(1)=B_n+\\delta_{n,1}$, $B_1=-1/2$ を使うと, \n\n$$\n\\zeta(-r) = -\\frac{B_{r+1}(1)}{r+1} \\quad (r=0,1,2,\\ldots)\n$$\n\nの形にまとめられる.\n\n### 発散級数の有限部分と ζ(-r) の関係\n\n前節の結果 $\\ds\\zeta(-r)=-\\frac{B_{r+1}(1)}{r+1}$ ($r=0,1,2,\\ldots$) は\n\n$$\n\\begin{aligned}\n&\n1+1+1+1+\\cdots = -\\frac{1}{2},\n\\\\ &\n1+2+3+4+\\cdots = -\\frac{1}{12}\n\\end{aligned}\n$$\n\nのような印象的な形式で書かれることもある. ただし, その場合には左辺が通常の無限和ではなく, ゼータ函数 $\\zeta(s)$ の解析接続の意味であることを了解しておかなければいけない. \n\n実はさらに解析接続として理解するだけではなく, 「左辺の発散する無限和から適切に無限大を引き去れば右辺に等しくなる」というようなタイプの命題をうまく作ることもできる. 以下ではそのことを解説しよう.\n\n以下, $\\eta$ は非負の実数に値を持つ $\\R$ 上の**急減少函数**であると仮定する. ($\\R$ 上の急減少函数とは $\\R$ 上の $C^\\infty$ 函数でそれ自身およびそのすべての階数の導函数に任意の多項式函数をかけたものが $|x|\\to\\infty$ で $0$ に収束するもののことである.) さらに, \n\n$$\n\\eta(0)=1, \\quad \\eta'(0)=0\n$$\n\nと仮定する. 例えば $\\eta(x)=e^{-x^2}$ はそのような函数の例になっている.\n\nこのとき, $\\eta(x)$ が急減少函数であることより, $N>0$ のとき, 級数\n\n$$\n\\sum_{n=1}^\\infty n^r \\eta(n/N) = 1^r\\eta(1/N) + 2^r\\eta(2/N) + 3^r\\eta(3/N) + \\cdots\n$$\n\nは常に絶対収束する. $r$ が非負の整数のとき, $N\\to\\infty$ とすると, この級数は発散級数 $1^r+2^r+3^r+\\cdots$ になってしまう. 以下の目標は, Euler-Maclaurinの和公式を使うと, その $N\\to\\infty$ での発散部分が $CN^{r+1}$ ($C$ は $\\eta$ と $r$ で具体的に決まる定数) の形にまとまることを示すことである. そして, 残った有限部分は**常に** $\\zeta(-r)$ に収束することも示される.\n\n$\\tilde{B}_n(x)=B_n(x-\\lfloor x\\rfloor)$ と書くことにする.\n\nこのとき, $f(x)=\\eta(x/N)$ にEuler-Maclaurinの和公式を適用すると, $f(0)=1$, $f'(0)=f(\\infty)=f'(\\infty)=0$ より, \n$$\n\\begin{aligned}\n1+\\sum_{n=1}^\\infty\\eta(x/N) &= \n\\sum_{n=0}^\\infty\\eta(x/N) \n\\\\ &= \n\\int_0^\\infty\\eta(x/N)\\,dx + \\frac{1}{2} +B_2(f'(\\infty)-f'(0)) - \n\\int_0^\\infty\\frac{\\tilde{B}_2(x)}{2!}\\frac{1}{N^2}\\eta''(x/N)\\,dx\n\\\\ &=\nN\\int_0^\\infty\\eta(y)\\,dy + \\frac{1}{2} -\n\\frac{1}{N}\\int_0^\\infty\\frac{\\tilde{B}_2(Ny)}{2!}\\eta''(y)\\,dy.\n\\end{aligned}\n$$\n\nゆえに, $\\zeta(0)=-1/2$ を使うと,\n\n$$\n\\sum_{n=1}^\\infty\\eta(x/N) - N\\int_0^\\infty\\eta(y)\\,dy =\n\\zeta(0) + O(1/N).\n$$\n\nこれは $N\\to\\infty$ で発散級数 $1+1+1+1+\\cdots$ になる無限和 $\\ds \\sum_{n=1}^\\infty\\eta(x/N)$ から, その発散部分 $\\ds N\\int_0^\\infty\\eta(y)\\,dy$ を引き去って, $N\\to\\infty$ の極限を取ると, $\\zeta(0)$ に収束することを意味している. これが欲しい結果の1つ目である.\n\n$r$ は正の整数であるとし, $f(x)=x^r\\eta(x/N)$ とおく. そのとき, Leibnitz則\n\n$$\n(\\varphi(x) \\psi(x))^{(m)} = \\sum_{i=0}^r \\binom{m}{i}\\varphi^{(i)}(x)\\psi^{(m-i)}(x)\n\\\\\n$$\n\nを使うと,\n\n$$\nf^{(r+2)}(x) = \\frac{1}{N^2}F(x/N), \\quad\nF(y) = \\binom{r+2}{0}y^r\\eta^{(r+2)}(y) + \\cdots + \\binom{r+2}{r}r!\\eta(y)\n$$\n\nその $f(x)$ にEuler-Maclaurinの和公式を適用すると, $f^{(k)}(\\infty)=f^{(k)}(\\infty)=0$ および,\n\n$$\nf(0) = f'(0) = \\cdots = f^{(r-1)}(0) = f^{(r+1)}(0) = 0, \\quad\nf^{(r)}(0) = r!\n$$\n\nより, \n\n$$\n\\begin{aligned}\n\\sum_{n=1}^\\infty n^r\\eta(n/N) &=\n\\sum_{n=0}^\\infty f(n) =\n\\int_0^\\infty f(x)\\,dx - \\frac{B_{r+1}}{(r+1)!}r! - \\frac{B_{r+2}}{(r+2)!}0 + \n(-1)^{r+1}\\int_0^\\infty \\frac{\\tilde{B}_{r+2}(x)}{(r+2)!} f^{(r+2)}(x)\\,dx\n\\\\ &=\nN^{r+1}\\int_0^\\infty y^r\\eta(y)\\,dy - \\frac{B_{r+1}}{r+1} +\n(-1)^{r+1}\\frac{1}{N}\\int_0^\\infty \\frac{\\tilde{B}_{r+2}(Ny)}{(r+2)!} F(y)\\,dy\n\\\\ &=\nN^{r+1}\\int_0^\\infty y^r\\eta(y)\\,dy - \\frac{B_{r+1}}{r+1} + O(1/N).\n\\end{aligned}\n$$\n\nゆえに, $\\ds\\zeta(-r)=-\\frac{B_{r+1}}{r+1}$ を使うと,\n\n$$\n\\sum_{n=1}^\\infty n^r\\eta(n/N) - N^{r+1}\\int_0^\\infty y^r\\eta(y)\\,dy =\n\\zeta(-r) + O(1/N).\n$$\n\nこれは $N\\to\\infty$ で発散級数 $1^r+2^r+3^r+4^r+\\cdots$ になる無限和 $\\ds \\sum_{n=1}^\\infty n^r\\eta(x/N)$ から, その発散部分 $\\ds N^{r+1}\\int_0^\\infty y^r\\eta(y)\\,dy$ を引き去って, $N\\to\\infty$ の極限を取ると, $\\zeta(-r)$ に収束することを意味している. これが欲しい結果である.\n\n**注意:** 以上の計算のポイントは, 非負の急減少函数 $\\eta(x)$ で $\\eta(0)=1$, $\\eta'(0)=0$ を満たすもので発散級数を正則化して得られる級数の場合には, Euler-Maclaurinの和公式の「途中の項」がほとんど消えてしまうことである. $C N^{r+1}$ 型の発散項と定数項と $O(1/N)$ の部分の3つの項しか生き残らない. $\\QED$\n\n**注意:** 以上の結果に関するより進んだ解説については次のリンク先を参照せよ:\n\n* Terence Tao, The Euler-Maclaurin formula, Bernoulli numbers, the zeta function, and real-variable analytic continuation, Blog: What's new, 10 April, 2010.\n\nこのブログ記事はかなり読み易い. $\\QED$\n\n**問題:** 以上の結果を数値計算でも確認してみよ. $\\QED$\n\n**ヒント:** $\\eta(x)=e^{-x^2}$ の場合を試してみよ. そのとき,\n\n$$\n\\int_0^\\infty y^r\\eta(y)\\,dy = \n\\int_0^\\infty y^r e^{-y^2}\\,dy = \n\\frac{1}{2}\\Gamma\\left(\\frac{r+1}{2}\\right)\n$$\n\nとなっている. $\\QED$\n\n**解答例:** 次のリンク先のノートを見よ.\n\n* 黒木玄, ζ(s) の Re s < 1 での様子 $\\QED$\n\n\n```julia\ny = symbols(\"y\", real=true)\nr = symbols(\"r\", positive=true)\nintegrate(y^r*exp(-y^2), (y, 0, oo))\n```\n\n\n\n\n\\begin{equation*}\\frac{\\Gamma\\left(\\frac{r}{2} + \\frac{1}{2}\\right)}{2}\\end{equation*}\n\n\n\n\n```julia\n\n```\n", "meta": {"hexsha": "67c37566ed2a68e9e13fdf3a6bda3d56f06ed915", "size": 794741, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "13 Euler-Maclaurin summation formula.ipynb", "max_stars_repo_name": "genkuroki/Calculus", "max_stars_repo_head_hexsha": "424ef53bf493242ce48c58ba39e43b8e601eb403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2018-06-22T13:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T00:04:57.000Z", "max_issues_repo_path": "13 Euler-Maclaurin summation formula.ipynb", "max_issues_repo_name": "genkuroki/Calculus", "max_issues_repo_head_hexsha": "424ef53bf493242ce48c58ba39e43b8e601eb403", "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": "13 Euler-Maclaurin summation formula.ipynb", "max_forks_repo_name": "genkuroki/Calculus", "max_forks_repo_head_hexsha": "424ef53bf493242ce48c58ba39e43b8e601eb403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-12-28T19:57:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T23:23:46.000Z", "avg_line_length": 102.3754991627, "max_line_length": 3580, "alphanum_fraction": 0.6436927251, "converted": true, "num_tokens": 30688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.21469142916152645, "lm_q1q2_score": 0.09565137261131625}} {"text": "\n\nEsté um notebook Colab contendo exercícios de programação em python, numpy e pytorch.\n\n## Coloque seu nome\n\n\n```python\nprint('Meu nome é: Fernanda Caldas')\n```\n\n Meu nome é: Fernanda Caldas\n\n\n# Parte 1:\n\n## Exercícios de Processamento de Dados\n\nNesta parte pode-se usar as bibliotecas nativas do python como a `collections`, `re` e `random`. Também pode-se usar o NumPy.\n\n## Exercício 1.1\nCrie um dicionário com os `k` itens mais frequentes de uma lista.\n\nPor exemplo, dada a lista de itens `L=['a', 'a', 'd', 'b', 'd', 'c', 'e', 'a', 'b', 'e', 'e', 'a']` e `k=2`, o resultado deve ser um dicionário cuja chave é o item e o valor é a sua frequência: {'a': 4, 'e': 3}\n\n\n```python\nfrom collections import Counter\n\ndef top_k(L, k):\n return Counter(L).most_common(k)\n```\n\nMostre que sua implementação está correta usando uma entrada com poucos itens:\n\n\n```python\nL = ['f', 'a', 'a', 'd', 'b', 'd', 'c', 'e', 'a', 'b', 'e', 'e', 'a', 'd']\nk = 3\nresultado = top_k(L=L, k=k)\nprint(f'resultado: {resultado}')\n```\n\n resultado: [('a', 4), ('d', 3), ('e', 3)]\n\n\nMostre que sua implementação é eficiente usando uma entrada com 10M de itens:\n\n\n```python\nimport random\nL = random.choices('abcdefghijklmnopqrstuvwxyz', k=10_000_000)\nk = 10000\n```\n\n\n```python\n%%timeit\nresultado = top_k(L=L, k=k)\n```\n\n 1 loop, best of 5: 538 ms per loop\n\n\n## Exercício 1.2\n\nEm processamento de linguagem natural, é comum convertemos as palavras de um texto para uma lista de identificadores dessas palavras. Dado o dicionário `V` abaixo onde as chaves são palavras e os valores são seus respectivos identificadores, converta o texto `D` para uma lista de identificadores.\n\nPalavras que não existem no dicionário deverão ser convertidas para o identificador do token `unknown`.\n\nO código deve ser insensível a maiúsculas (case-insensitive).\n\nSe atente que pontuações (vírgulas, ponto final, etc) também são consideradas palavras.\n\n\n```python\n\"\"\"\nEu tinha conseguido fazer até a parte abaixo. \nNão estava encontrando uma função para substituir o vetor K pelos identificadores, nem tornar case-insensitive.\n\"\"\"\n\nimport re\nD = 'Eu gosto de comer pizza.'\nK = re.findall(r\"[\\w']+|[.,!?;]\", D)\nprint(K)\n\"\"\"\nNo código do aluno Andersson Andreé Romero Deza, aprendi essa função \"get()\" que substitui os tokens pelos identificadores.\n\nO segundo parâmetro (value) retorna o valor atribuído a uma palavra que não esteja no dicionário. [https://www.w3schools.com/python/ref_dictionary_get.asp]\n\nNo mesmo código, também encontrei a opção \"text.lower()\" que torna o código case-insensitive ao deixar tudo minúsculo.\n\nAgradeço ao Andersson pela ajuda neste exercício.\n\"\"\"\n\ndef tokens_to_ids(text, vocabulary):\n import re\n \n K = re.findall(r\"[\\w']+|[.,!?;]\", text.lower())\n ids = []\n \n for k in K:\n ids.append(vocabulary.get(k, vocabulary['unknown']))\n \n return ids\n```\n\n ['Eu', 'gosto', 'de', 'comer', 'pizza', '.']\n\n\nMostre que sua implementação esta correta com um exemplo pequeno:\n\n---\n\n\n\n\n```python\nV = {'eu': 1, 'de': 2, 'gosto': 3, 'comer': 4, '.': 5, 'unknown': -1}\nD = 'Eu gosto de comer pizza.'\n\nprint(tokens_to_ids(D, V))\n```\n\n [1, 3, 2, 4, -1, 5]\n\n\nMostre que sua implementação é eficiente com um exemplo grande:\n\n\n```python\nV = {'eu': 1, 'de': 2, 'gosto': 3, 'comer': 4, '.': 5, 'unknown': -1}\nD = ' '.join(1_000_000 * ['Eu gosto de comer pizza.'])\n```\n\n\n```python\n%%timeit\nresultado = tokens_to_ids(D, V)\n```\n\n 1 loop, best of 5: 2.62 s per loop\n\n\n## Exercício 1.3\n\nEm aprendizado profundo é comum termos que lidar com arquivos muito grandes.\n\nDado um arquivo de texto onde cada item é separado por `\\n`, escreva um programa que amostre `k` itens desse arquivo aleatoriamente.\n\nNota 1: Assuma amostragem de uma distribuição uniforme, ou seja, todos os itens tem a mesma probablidade de amostragem.\n\nNota 2: Assuma que o arquivo não cabe em memória.\n\nNota 3: Utilize apenas bibliotecas nativas do python.\n\n\n```python\ndef sample(path: str, k: int):\n import random\n \n with open(path) as f:\n D = [line.rstrip('\\n') for line in f] #Fonte: https://stackoverflow.com/a/17570045\n \n return random.choices(D, k = k)\n```\n\nMostre que sua implementação está correta com um exemplo pequeno:\n\n\n```python\nfilename = 'small.txt'\ntotal_size = 100\nn_samples = 10\n\nwith open(filename, 'w') as fout:\n fout.write('\\n'.join(f'line {i}' for i in range(total_size)))\n\nsamples = sample(path=filename, k=n_samples)\nprint(samples)\nprint(len(samples) == n_samples)\n```\n\n ['line 99', 'line 94', 'line 3', 'line 56', 'line 98', 'line 17', 'line 96', 'line 41', 'line 58', 'line 86']\n True\n\n\nMostre que sua implementação é eficiente com um exemplo grande:\n\n\n```python\nfilename = 'large.txt'\ntotal_size = 1_000_000\nn_samples = 10000\n\nwith open(filename, 'w') as fout:\n fout.write('\\n'.join(f'line {i}' for i in range(total_size)))\n```\n\n\n```python\n%%timeit\nsamples = sample(path=filename, k=n_samples)\nassert len(samples) == n_samples\n```\n\n 1 loop, best of 5: 256 ms per loop\n\n\n# Parte 2:\n\n## Exercícios de Numpy\n\nNesta parte deve-se usar apenas a biblioteca NumPy. Aqui não se pode usar o PyTorch.\n\n## Exercício 2.1\n\nQuantos operações de ponto flutuante (flops) de soma e de multiplicação tem a multiplicação matricial $AB$, sendo que a matriz $A$ tem tamanho $m \\times n$ e a matriz $B$ tem tamanho $n \\times p$?\n\nResposta:\n- número de somas: $m\\cdot p\\cdot n$\n- número de multiplicações: $m\\cdot p\\cdot (n-1)$\n\n## Exercício 2.2\n\nEm programação matricial, não se faz o loop em cada elemento da matriz,\nmas sim, utiliza-se operações matriciais.\n\nDada a matriz `A` abaixo, calcule a média dos valores de cada linha sem utilizar laços explícitos.\n\nUtilize apenas a biblioteca numpy.\n\n\n```python\nimport numpy as np\nnp.set_printoptions(edgeitems=10, linewidth=180)\n```\n\n\n```python\nA = np.arange(24).reshape(4, 6)\nprint(A)\n```\n\n [[ 0 1 2 3 4 5]\n [ 6 7 8 9 10 11]\n [12 13 14 15 16 17]\n [18 19 20 21 22 23]]\n\n\n\n```python\nnp.sum(A, axis=1)/(A.shape[1])\n```\n\n\n\n\n array([ 2.5, 8.5, 14.5, 20.5])\n\n\n\n## Exercício 2.3\n\nSeja a matriz $C$ que é a normalização da matriz $A$:\n$$ C(i,j) = \\frac{A(i,j) - A_{min}}{A_{max} - A_{min}} $$\n\nNormalizar a matriz `A` do exercício acima de forma que seus valores fiquem entre 0 e 1.\n\n\n```python\nfrom numpy import array\n\nC = (array(A) - np.amin(A))/(np.amax(A) - np.amin(A))\nC\n```\n\n\n\n\n array([[0. , 0.04347826, 0.08695652, 0.13043478, 0.17391304, 0.2173913 ],\n [0.26086957, 0.30434783, 0.34782609, 0.39130435, 0.43478261, 0.47826087],\n [0.52173913, 0.56521739, 0.60869565, 0.65217391, 0.69565217, 0.73913043],\n [0.7826087 , 0.82608696, 0.86956522, 0.91304348, 0.95652174, 1. ]])\n\n\n\n## Exercício 2.4\n\nModificar o exercício anterior de forma que os valores de cada *coluna* da matriz `A` sejam normalizados entre 0 e 1 independentemente dos valores das outras colunas.\n\n\n\n```python\nC = (array(A) - array(A.min(axis=0)))/(array(A.max(axis=0)) - array(A.min(axis=0)))\nC\n```\n\n\n\n\n array([[0. , 0. , 0. , 0. , 0. , 0. ],\n [0.33333333, 0.33333333, 0.33333333, 0.33333333, 0.33333333, 0.33333333],\n [0.66666667, 0.66666667, 0.66666667, 0.66666667, 0.66666667, 0.66666667],\n [1. , 1. , 1. , 1. , 1. , 1. ]])\n\n\n\n## Exercício 2.5\n\nModificar o exercício anterior de forma que os valores de cada *linha* da matriz `A` sejam normalizados entre 0 e 1 independentemente dos valores das outras linhas.\n\n\n\n```python\nC = ((array(A.T) - array((A.T).min(axis=0)))/(array((A.T).max(axis=0)) - array((A.T).min(axis=0)))).T\nC\n```\n\n\n\n\n array([[0. , 0.2, 0.4, 0.6, 0.8, 1. ],\n [0. , 0.2, 0.4, 0.6, 0.8, 1. ],\n [0. , 0.2, 0.4, 0.6, 0.8, 1. ],\n [0. , 0.2, 0.4, 0.6, 0.8, 1. ]])\n\n\n\n## Exercício 2.6\n\nA [função softmax](https://en.wikipedia.org/wiki/Softmax_function) é bastante usada em apredizado de máquina para converter uma lista de números para uma distribuição de probabilidade, isto é, os números ficarão normalizados entre zero e um e sua soma será igual à um.\n\nImplemente a função softmax com suporte para batches, ou seja, o softmax deve ser aplicado a cada linha da matriz. Deve-se usar apenas a biblioteca numpy. Se atente que a exponenciação gera estouro de representação quando os números da entrada são muito grandes. Tente corrigir isto.\n\n#### Resposta:\n\nEm [Stack Overflow](https://stackoverflow.com/a/34969389), é sugerida a seguinte adaptação para números muito grandes:\n\n\\begin{equation}\n\\sigma(\\mathbf{z})_i = \\frac{e^{z_i - z_{max}}}{\\sum_{j=1}^K e^{z_j - z_{max}}}\n\\end{equation}\npois teríamos\n\n\\begin{equation}\n\\sigma(\\mathbf{z})_i = \\frac{e^{z_i}}{e^{z_{max}}\\sum_{j=1}^K e^{z_j} e^{-z_{max}}} = \\frac{e^{z_i}}{\\sum_{j=1}^K e^{z_j}}\n\\end{equation}\n\n\n```python\nimport numpy as np\nfrom numpy import array\n\n\ndef softmax(A):\n '''\n Aplica a função de softmax à matriz `A`.\n\n Entrada:\n `A` é uma matriz M x N, onde M é o número de exemplos a serem processados\n independentemente e N é o tamanho de cada exemplo.\n \n Saída:\n Uma matriz M x N, onde a soma de cada linha é igual a um.\n '''\n aux = np.zeros(A.shape)\n mx = A.max(axis=1)\n den = np.sum(np.exp(array(A.T) - (A.T).max(axis=0)), axis=0)\n for i in range(A.shape[0]):\n aux[i] = np.exp(array(A[i,:]) - array(mx[i]))/array(den[i])\n \n return aux\n```\n\nMostre que sua implementação está correta usando uma matriz pequena como entrada:\n\n\n```python\nA = np.array([[0.5, -1, 1000],\n [-2, 0, 0.5]])\nsoftmax(A)\n```\n\n\n\n\n array([[0. , 0. , 1. ],\n [0.04861082, 0.35918811, 0.59220107]])\n\n\n\nO código a seguir verifica se sua implementação do softmax está correta. \n- A soma de cada linha de A deve ser 1;\n- Os valores devem estar entre 0 e 1\n\n\n```python\nnp.allclose(softmax(A).sum(axis=1), 1) and softmax(A).min() >= 0 and softmax(A).max() <= 1\n```\n\n\n\n\n True\n\n\n\nMostre que sua implementação é eficiente usando uma matriz grande como entrada:\n\n\n```python\nA = np.random.uniform(low=-10, high=10, size=(128, 100_000))\n```\n\n\n```python\n%%timeit\nsoftmax(A)\n```\n\n 1 loop, best of 5: 593 ms per loop\n\n\n\n```python\nSM = softmax(A)\nnp.allclose(SM.sum(axis=1), 1) and SM.min() >= 0 and SM.max() <= 1\n```\n\n\n\n\n True\n\n\n\n## Exercício 2.7\n\nA codificação one-hot é usada para codificar entradas categóricas. É uma codificação onde apenas um bit é 1 e os demais são zero, conforme a tabela a seguir.\n\n| Decimal | Binary | One-hot\n| ------- | ------ | -------\n| 0 | 000 | 1 0 0 0 0 0 0 0\n| 1 | 001 | 0 1 0 0 0 0 0 0\n| 2 | 010 | 0 0 1 0 0 0 0 0\n| 3 | 011 | 0 0 0 1 0 0 0 0\n| 4 | 100 | 0 0 0 0 1 0 0 0\n| 5 | 101 | 0 0 0 0 0 1 0 0\n| 6 | 110 | 0 0 0 0 0 0 1 0\n| 7 | 111 | 0 0 0 0 0 0 0 1\n\nImplemente a função one_hot(y, n_classes) que codifique o vetor de inteiros y que possuem valores entre 0 e n_classes-1.\n\n\n\n```python\nimport sys\nnp.set_printoptions(suppress=True)\n\ndef one_hot(y, n_classes):\n A = ((10**(n_classes - y - 1)).astype(int)).astype(str)\n \n return np.char.zfill(A, n_classes)\n```\n\n\n```python\nN_CLASSES = 9\nN_SAMPLES = 10\ny = (np.random.rand((N_SAMPLES)) * N_CLASSES).astype(int)\nprint(y)\nprint(one_hot(y, N_CLASSES))\n```\n\n [3 8 5 5 6 7 6 7 2 4]\n ['000100000' '000000001' '000001000' '000001000' '000000100' '000000010' '000000100' '000000010' '001000000' '000010000']\n\n\nMostre que sua implementação é eficiente usando uma matriz grande como entrada:\n\n\n```python\nN_SAMPLES = 100_000\nN_CLASSES = 1_000\ny = (np.random.rand((N_SAMPLES)) * N_CLASSES).astype(int)\n```\n\n\n```python\n%%timeit\none_hot(y, N_CLASSES)\n```\n\n 1 loop, best of 5: 221 ms per loop\n\n\n## Exercício 2.8\n\nImplemente uma classe que normalize um array de pontos flutuantes `array_a` para a mesma média e desvio padrão de um outro array `array_b`, conforme exemplo abaixo:\n```\narray_a = np.array([-1, 1.5, 0])\narray_b = np.array([1.4, 0.8, 0.3, 2.5])\nnormalize = Normalizer(array_b)\nnormalized_array = normalize(array_a)\nprint(normalized_array) # Deve imprimir [0.3187798 2.31425165 1.11696854]\n```\n\nMostre que seu código está correto com o exemplo abaixo:\n\n\n```python\narray_a = [-1, 1.5, 0]\narray_b = [1.4, 0.8, 0.3, 2.5]\nnormalize = Normalizer(array_b)\nnormalized_array = normalize(array_a)\nprint(normalized_array)\n```\n\n# Parte 3:\n\n## Exercícios Pytorch: Grafo Computacional e Gradientes\n\nNesta parte pode-se usar quaisquer bibliotecas.\n\nUm dos principais fundamentos para que o PyTorch seja adequado para deep learning é a sua habilidade de calcular o gradiente automaticamente a partir da expressões definidas. Essa facilidade é implementada através do cálculo automático do gradiente e construção dinâmica do grafo computacional.\n\n## Grafo computacional\n\nSeja um exemplo simples de uma função de perda J dada pela Soma dos Erros ao Quadrado (SEQ - Sum of Squared Errors): \n$$ J = \\sum_i (x_i w - y_i)^2 $$\nque pode ser reescrita como:\n$$ \\hat{y_i} = x_i w $$\n$$ e_i = \\hat{y_i} - y_i $$\n$$ e2_i = e_i^2 $$\n$$ J = \\sum_i e2_i $$\n\nAs redes neurais são treinadas através da minimização de uma função de perda usando o método do gradiente descendente. Para ajustar o parâmetro $w$ precisamos calcular o gradiente $ \\frac{ \\partial J}{\\partial w} $. Usando a\nregra da cadeia podemos escrever:\n$$ \\frac{ \\partial J}{\\partial w} = \\frac{ \\partial J}{\\partial e2_i} \\frac{ \\partial e2_i}{\\partial e_i} \\frac{ \\partial e_i}{\\partial \\hat{y_i} } \\frac{ \\partial \\hat{y_i}}{\\partial w}$$ \n\n```\n y_pred = x * w\n e = y_pred - y\n e2 = e**2\n J = e2.sum()\n```\n\nAs quatro expressões acima, para o cálculo do J podem ser representadas pelo grafo computacional visualizado a seguir: os círculos são as variáveis (tensores), os quadrados são as operações, os números em preto são os cálculos durante a execução das quatro expressões para calcular o J (forward, predict). O cálculo do gradiente, mostrado em vermelho, é calculado pela regra da cadeia, de trás para frente (backward).\n\n\n\nPara entender melhor o funcionamento do grafo computacional com os tensores, recomenda-se leitura em:\n\nhttps://pytorch.org/docs/stable/notes/autograd.html\n\n\n```python\nimport torch\n```\n\n\n```python\ntorch.__version__\n```\n\n\n\n\n '1.10.0+cu111'\n\n\n\n**Tensor com atributo .requires_grad=True**\n\nQuando um tensor possui o atributo `requires_grad` como verdadeiro, qualquer expressão que utilizar esse tensor irá construir um grafo computacional para permitir posteriormente, após calcular a função a ser derivada, poder usar a regra da cadeia e calcular o gradiente da função em termos dos tensores que possuem o atributo `requires_grad`.\n\n\n\n```python\ny = torch.arange(0, 8, 2).float()\ny\n```\n\n\n\n\n tensor([0., 2., 4., 6.])\n\n\n\n\n```python\nx = torch.arange(0, 4).float()\nx\n```\n\n\n\n\n tensor([0., 1., 2., 3.])\n\n\n\n\n```python\nw = torch.ones(1, requires_grad=True)\nw\n```\n\n\n\n\n tensor([1.], requires_grad=True)\n\n\n\n## Cálculo automático do gradiente da função perda J\n\nSeja a expressão: $$ J = \\sum_i ((x_i w) - y_i)^2 $$\n\nQueremos calcular a derivada de $J$ em relação a $w$.\n\n## Forward pass\n\nDurante a execução da expressão, o grafo computacional é criado. Compare os valores de cada parcela calculada com os valores em preto da figura ilustrativa do grafo computacional.\n\n\n```python\n# predict (forward)\ny_pred = x * w; print('y_pred =', y_pred)\n\n# cálculo da perda J: loss\ne = y_pred - y; print('e =',e)\ne2 = e.pow(2) ; print('e2 =', e2)\nJ = e2.sum() ; print('J =', J)\n```\n\n y_pred = tensor([0., 1., 2., 3.], grad_fn=)\n e = tensor([ 0., -1., -2., -3.], grad_fn=)\n e2 = tensor([0., 1., 4., 9.], grad_fn=)\n J = tensor(14., grad_fn=)\n\n\n## Backward pass\n\nO `backward()` varre o grafo computacional a partir da variável a ele associada (raiz) e calcula o gradiente para todos os tensores que possuem o atributo `requires_grad` como verdadeiro.\nObserve que os tensores que tiverem o atributo `requires_grad` serão sempre folhas no grafo computacional.\nO `backward()` destroi o grafo após sua execução. Esse comportamento é padrão no PyTorch. \n\nA título ilustrativo, se quisermos depurar os gradientes dos nós que não são folhas no grafo computacional, precisamos primeiro invocar `retain_grad()` em cada um desses nós, como a seguir. Entretanto nos exemplos reais não há necessidade de verificar o gradiente desses nós.\n\n\n```python\ne2.retain_grad()\ne.retain_grad()\ny_pred.retain_grad()\n```\n\nE agora calculamos os gradientes com o `backward()`.\n\nw.grad é o gradiente de J em relação a w.\n\n\n```python\nif w.grad: w.grad.zero_()\nJ.backward()\nprint(w.grad)\n```\n\n tensor([-28.])\n\n\nMostramos agora os gradientes que estão grafados em vermelho no grafo computacional:\n\n\n```python\nprint(e2.grad)\nprint(e.grad)\nprint(y_pred.grad)\n```\n\n tensor([1., 1., 1., 1.])\n tensor([ 0., -2., -4., -6.])\n tensor([ 0., -2., -4., -6.])\n\n\n## Exercício 3.1\nCalcule o mesmo gradiente ilustrado no exemplo anterior usando a regra das diferenças finitas, de acordo com a equação a seguir, utilizando um valor de $\\Delta w$ bem pequeno.\n\n$$ \\frac{\\partial J}{\\partial w} = \\frac{J(w + \\Delta w) - J(w - \\Delta w)}{2 \\Delta w} $$\n\n\n```python\ndef J_func(w, x, y):\n J = torch.sum((x*w - y)**2)\n \n return J\n\ndef grad_J(w, dw, x, y):\n grad = (J_func(w + dw, x, y) - J_func(w - dw, x, y))/(2*dw)\n \n return grad\n\n# Calcule o gradiente usando a regra diferenças finitas\n# Confira com o valor já calculado anteriormente\nx = torch.arange(0, 4).float()\ny = torch.arange(0, 8, 2).float()\nw = torch.ones(1)\ndw = 0.01*torch.ones(1)\ngrad = grad_J(w, dw, x, y)\nprint('grad=', grad)\n```\n\n grad= tensor([-28.0000])\n\n\n\n```python\nw\n```\n\n\n\n\n tensor([1.])\n\n\n\n\n```python\nx\n```\n\n\n\n\n tensor([0., 1., 2., 3.])\n\n\n\n## Exercício 3.2\n\nMinimizando $J$ pelo gradiente descendente\n\n$$ w_{k+1} = w_k - \\lambda \\frac {\\partial J}{\\partial w} $$\n\nSupondo que valor inicial ($k=0$) $w_0 = 1$, use learning rate $\\lambda = 0.01$ para calcular o valor do novo $w_{20}$, ou seja, fazendo 20 atualizações de gradientes. Deve-se usar a função `J_func` criada no exercício anterior.\n\nConfira se o valor do primeiro gradiente está de acordo com os valores já calculado acima\n\n\n```python\nlearning_rate = 0.01\niteracoes = 20\n\nx = torch.arange(0, 4).float()\ny = torch.arange(0, 8, 2).float()\nw = torch.ones(1)\nJ = torch.ones(iteracoes)\ndw = 0.05*w\n\nfor i in range(iteracoes):\n print('i =', i)\n J[i] = J_func(w, x, y)\n print('J=', J[i])\n grad = grad_J(w, dw, x, y)\n print('grad =',grad)\n w = w - learning_rate*grad\n print('w =', w)\n\nimport matplotlib.pyplot as plt\n# Plote o gráfico da loss J pela iteração i\nplt.plot(J)\n```\n\n## Exercício 3.3\n\nRepita o exercício 2 mas usando agora o calculando o gradiente usando o método backward() do pytorch. Confira se o primeiro valor do gradiente está de acordo com os valores anteriores. Execute essa próxima célula duas vezes. Os valores devem ser iguais.\n\n\n\n```python\nlearning_rate = 0.01\niteracoes = 20\n\nx = torch.arange(0, 4).float()\ny = torch.arange(0, 8, 2).float()\nw = torch.ones(1, requires_grad=True)\n\nfor i in range(iteracoes):\n print('i =', i)\n J = J_func(w, x, y)\n print('J=', J)\n grad = ?\n print('grad =',grad)\n w = ?\n print('w =', w)\n\n# Plote aqui a loss pela iteração\n```\n\n##Exercício 3.4\n\nQuais são as restrições na escolha dos valores de $\\Delta w$ no cálculo do gradiente por diferenças finitas?\n\nResposta:\n\n##Exercício 3.5\n\nAté agora trabalhamos com $w$ contendo apenas um parâmetro. Suponha agora que $w$ seja uma matriz com $N$ parâmetros e que o custo para executar $(x_i w - y_i)^2$ seja $O(N)$.\n> a) Qual é o custo computacional para fazer uma única atualização (um passo de gradiente) dos parâmetros de $w$ usando o método das diferencas finitas?\n>\n> b) Qual é o custo computacional para fazer uma única atualização (um passo de gradiente) dos parâmetros de $w$ usando o método do backpropagation?\n\n\n\nResposta (justifique):\n\na)\n\nb)\n\n##Exercício 3.6\n\nQual o custo (entropia cruzada) esperado para um exemplo (uma amostra) no começo do treinamento de um classificador inicializado aleatoriamente?\n\nA equação da entropia cruzada é:\n$$L = - \\sum_{j=0}^{K-1} y_j \\log p_j, $$\nOnde:\n\n- K é o número de classes;\n\n- $y_j=1$ se $j$ é a classe do exemplo (ground-truth), 0 caso contrário. Ou seja, $y$ é um vetor one-hot;\n\n- $p_j$ é a probabilidade predita pelo modelo para a classe $j$.\n\nA resposta tem que ser em função de uma ou mais das seguintes variáveis:\n\n- K = número de classes\n\n- B = batch size\n\n- D = dimensão de qualquer vetor do modelo\n\n- LR = learning rate\n\nResposta:\n\nFim do notebook.\n", "meta": {"hexsha": "6a5a6fd6c567b964e0343fff833771a2af520aaf", "size": 66417, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ex01/Fernanda_Caldas/FernandaCaldas_Semana_1.ipynb", "max_stars_repo_name": "flych3r/IA025_2022S1", "max_stars_repo_head_hexsha": "8a5a92a0d22c3a602906bdc3b8c7eb8ae325e88b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-20T21:16:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T22:20:26.000Z", "max_issues_repo_path": "ex01/Fernanda_Caldas/FernandaCaldas_Semana_1.ipynb", "max_issues_repo_name": "flych3r/IA025_2022S1", "max_issues_repo_head_hexsha": "8a5a92a0d22c3a602906bdc3b8c7eb8ae325e88b", "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": "ex01/Fernanda_Caldas/FernandaCaldas_Semana_1.ipynb", "max_forks_repo_name": "flych3r/IA025_2022S1", "max_forks_repo_head_hexsha": "8a5a92a0d22c3a602906bdc3b8c7eb8ae325e88b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2022-03-16T15:39:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T14:04:34.000Z", "avg_line_length": 33.6118421053, "max_line_length": 9685, "alphanum_fraction": 0.5272896999, "converted": true, "num_tokens": 6876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668680822513, "lm_q2_score": 0.2365162364457076, "lm_q1q2_score": 0.09545011679299543}} {"text": "```python\nfrom IPython.core.display import HTML\nHTML(\"\")\n```\n\n\n\n\n\n\n\n\n# Lecture 8, Optimality conditions \n\nWe are still studying the full problem\n\n$$\n\\begin{align} \\\n\\min \\quad &f(x)\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_k(x) = 0\\text{ for all }k=1,\\ldots,K\\\\\n&x\\in \\mathbb R^n.\n\\end{align}\n$$\n\n## What aspects are important for optimality conditions?\n* Think about this for a while\n* You can first think about the case without constraints and, then, what should be added there\n\n\n## Optimality conditions for **unconstrained** optimization\n\n* (**Necessary condition**) Let $f$ be twice differentiable at $x^*\\in\\mathbb R^n$. If $x^*$ is a local minimizer, then $\\nabla f(x^*)=0$ and the Hessian matrix $H(x^*)$ is positively semidefinite.\n* (**Sufficient condition**) Let $f$ be twice continuously differentiable at $x^*\\in\\mathbb R^n$. If $\\nabla f(x^*)=0$ and $H(x^*)$ is positively definite, then $x^*$ is a strict local minimizer.\n\nIn order to identify which points are optimal, we want to define similar conditions as there are for unconstrained problems through the gradient:\n\n>If $x$ is a local optimum to function $f$, then $\\nabla f(x)=0$.\n\n## Karush-Kuhn-Tucker (KKT) conditions\n\n\n\n**Theorem (First order Karush-Kuhn-Tucker (KKT) Necessary Conditions)** \n\nLet $x^*$ be a local minimum for problem\n$$\n$$\n\\begin{align} \\\n\\min \\quad &f(x)\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_k(x) = 0\\text{ for all }k=1,\\ldots,K\\\\\n&x\\in \\mathbb R^n.\n\\end{align}\n$$\n$$\n\nLet us assume that objective and constraint functions are continuosly differentiable at a point $x^*$ and assume that $x^*$ satisfies some regularity conditions (see e.g., https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions#Regularity_conditions_.28or_constraint_qualifications.29 ). Then there exists unique Lagrance multiplier vectors $\\mu^*=(\\mu_1^*,\\ldots,\\mu_J^*)$ and $\\lambda^* = (\\lambda^*_1,\\ldots,\\lambda_K^*)$ such that\n\n$$\n\\begin{align}\n&\\nabla_xL(x^*,\\mu^*,\\lambda^*) = 0\\\\\n&\\mu_j^*\\geq0,\\text{ for all }j=1,\\ldots,J \\text{ (also known as **Dual feasibility**)}\\\\\n&\\mu_j^*g_j(x^*)=0,\\text{for all }j=1,\\ldots,J,\n\\end{align}\n$$\n\nwhere $L$ is the *Lagrangian function* $$L(x,\\mu,\\lambda) = f(x)- \\sum_{j=1}^J\\mu_jg_j(x) -\\sum_{k=1}^K\\lambda_kh_k(x)$$.\n\n\n* Lagrangian Function can be viewed as a function aggregated the original objective function plus the **penalized terms on constraint violations**.\n\n## An example of constraint qualifications for inequality constraint problems\n\n\n**Definition (regular point)**\n\nA point $x^*\\in S$ is *regular* if the set of gradients of the active inequality constraints \n\n$$\n\\{\\nabla g_j(x^*) | \\text{ constraint } i \\text{ is active}\\}\n$$\n\nis linearly independent. This means that none of them can be expressed as a linear combination of the others. (*In a simple language one might say that they point to different directions; as an example you can think of the basis vectors of $\\mathbb R^n$*.)\n\nKKT conditions were developed independently by \n* William Karush:\"Minima of Functions of Several Variables with Inequalities as Side Constraints\". *M.Sc. Dissertation*, Dept. of Mathematics, Univ. of Chicago, 1939\n* Harold W. Kuhn & Albert W. Tucker: \"Nonlinear programming\", In: *Proceedings of 2nd Berkeley Symposium*, pp. 481–492, 1951\n\nThe coefficients $\\mu$ and $\\lambda$ are called the *KKT multipliers*.\n\nThe first equality \n\n$$\n\\nabla_xL(x,\\mu,\\lambda) = 0\n$$\n\nis called the stationary rule and the requirement \n\n$$\n\\mu_j^*g_j(x)=0,\\text{for all }j=1,\\ldots,J\n$$\n\nis called the complementarity rule.\n\n### Note:\n\n* In some cases, the necessary conditions are also sufficient for optimality.\n\n* For example, the necessary conditions mentioned above are sufficient for optimality if $f$, $g_j$ and $h_k (\\forall j, k)$ are convex (in a minimization problem).\n\n## Example\n\nConsider the optimization problem\n\n$$\n\\begin{align}\n\\min &\\qquad (x_1^2+x^2_2+x^2_3)\\\\\n\\text{s.t}&\\qquad x_1+x_2+x_3-3\\geq 0.\n\\end{align}\n$$\n\nLet us verify the KKT necessary conditions for the local optimum $x^*=(1,1,1)$.\n\nWe can see that\n\n$$\nL(x,\\mu,\\lambda) = (x_1^2+x_2^2+x_3^2)-\\mu_1(x_1+x_2+x_3-3)\n$$\n\nand thus\n\n$$\n\\nabla_x L(x,\\mu,\\lambda) = (2x_1-\\mu_1,2x_2-\\mu_1,2x_3-\\mu_1)\n$$\n\nand if $\\nabla_x L([1,1,1],\\mu,\\lambda)=0$, then \n\n$$\n2-\\mu_1=0 $$\nwhich holds when $$\n\\mu_1=2.\n$$\n\nIn addition to this, we can see that $x^*_1+x^*_2+x^*_3-3= 0$. Thus, the completementarity rule holds even though $\\mu_1\\neq 0$.\n\n## Example 2\n\nLet us check the KKT conditions for a solution that is not a local optimum. Let us have $x^*=(0,1,1)$.\n\n$$\n\\nabla_x L(x,\\mu,\\lambda) = (2x_1-\\mu_1,2x_2-\\mu_1,2x_3-\\mu_1)\n$$\n\n\nWe can easily see that in this case, the conditions are \n\n$$\\left\\{\n\\begin{array}{c}\n-\\mu_1 = 0\\\\\n2-\\mu_1=0\n\\end{array}\n\\right.\n$$\n\nClearly, there does not exist a $\\mu_1\\in \\mathbb R$ such that these equalities would hold.\n\n## Example 3\n\nLet us check the KKT conditions for another solution that is not a local optimum. Let us have $x^*=(2,2,2)$.\n\n$$\n\\nabla_x L(x,\\mu,\\lambda) = (2x_1-\\mu_1,2x_2-\\mu_1,2x_3-\\mu_1)\n$$\n\n\nWe can easily see that in this case, the conditions are\n\n$$\n4-\\mu_1 = 0\n$$\n\nNow, $\\mu_1=4$ satisfies this equation. However, now\n\n$$\n\\mu_1(x^*_1+x^*_2+x^*_3-3)=4(6-3) = 12 \\neq 0.\n$$\n\nThus, the completementarity rule fails and the KKT conditions are not true.\n\n\n### Another example\n\nFormulate the KKT conditions for the following example:\n$$\nmin 𝑓(\\mathbf{x}) = (𝑥_1 − 3)^2 + (𝑥_2 − 2)^2\\\\\ns.t. \\\\\n𝑥_1^2 + 𝑥_2^2 ≤ 5,\\\\\n𝑥_1 + 2𝑥_2 = 4,\\\\\n𝑥_1, 𝑥_2 ≥ 0\n$$\n\nCheck them for $x^* = (2,1)$\n\n* This part will be completed during the lecture by students (10 min).\n* You need to use both conditions to find the KKT multipliers. There are three inequality constraints (j=1,2,3) and one equality constraint. \n\n### A reminder of KKT necessary conditions:\n$$\n\\begin{align}\n&\\nabla_xL(x^*,\\mu^*,\\lambda^*) = 0\\\\\n&\\mu_j^*\\geq0,\\text{ for all }j=1,\\ldots,J\\\\\n&\\mu_j^*g_j(x^*)=0,\\text{for all }j=1,\\ldots,J,\n\\end{align}\n$$\n\nwhere $L$ is the *Lagrangian function* $$L(x,\\mu,\\lambda) = f(x)- \\sum_{j=1}^J\\mu_jg_j(x) -\\sum_{k=1}^K\\lambda_kh_k(x)$$\n\n\n```python\n\n```\n\n## Geometric interpretation of the KKT conditions\n\n## Stationary rule\n\nConsider the *Lagrangian function* L as: $$L(x,\\mu,\\lambda) = f(x)- \\sum_{j=1}^J\\mu_jg_j(x) -\\sum_{k=1}^K\\lambda_kh_k(x)$$.\n\nThe stationary rule is:\n$$\n\\nabla_xL(x,\\mu,\\lambda) = 0\n$$\n\nThe stationary rule can be written as: There exist $\\mu,\\lambda'$ so that\n\n$$\n-\\nabla f(x) = -\\sum_{j=1}^K\\mu_j\\nabla g_j(x) + \\sum_{k=1}^K\\lambda'_k\\nabla h_k(x).\n$$\n\nNotice that we have slightly different $\\lambda'$.\n\nNow, remember that the $-\\nabla v(x)$ gives us the direction of reduction for a function $v$.\n\nThus, the above equation means that the direction of reduction of the function $-\\nabla f(x)$ is countered by the direction of the reduction of the inequality constraints $-\\nabla g_j(x)$ and the directions of either growth (or reduction, since $\\lambda'$ can be negative) of the equality constraints $\\nabla h_k(x)$.\n\n**This means that the function cannot get reduced without reducing the inequality constraints (making the solution infeasible, if already at the bound), or increasing or decreasing the equality constraints (making, thus, the solution again infeasible).**\n\n\n\n#### With just one inequality constraint this means that the negative gradients of $f$ and $g$ must point to the same direction.\n\n\n\n#### With equality constraints this means that the negative gradient of the objective function and the gradient of the equality constraint must either point to the same or opposite directions\n\n\n\n## Complementarity conditions\nAnother way of expressing complementarity condition\n\n$$\n\\mu_jg_j(x) = 0 \\text{ for all } j=1,\\ldots,J\n$$\n\nis to say that both $\\mu_j$ and $g_j(x)$ cannot be positive at the same time. Especially, if $\\mu_j>0$, then $g_j(x)=0$.\n\n**This means that if we want to use the gradient of a constraint for countering the reduction of the function, then the constraint must be at the boundary.**\n\n### Sufficient conditions:\n\n* The necessary conditions are sufficient for optimality if $f$, $g_j$ and $h_k (\\forall j, k)$ are convex (in a minimization problem).\n\n* In general, the necessary conditions are not sufficient for optimality and additional information is required, e.g., the Second Order Sufficient Conditions for smooth functions.\n\n\n### Second-order sufficient conditions (Projected Hessian is positive definite)\n\nFor a smooth, non-linear optimization problem, a second order sufficient condition is given as follows:\n\nIf $(x^*, \\mu^*, \\lambda^*$ be a constrained local minimum for the Lagrangian function\n\n$$L(x,\\mu,\\lambda) = f(x)- \\sum_{j=1}^J\\mu_jg_j(x) -\\sum_{k=1}^K\\lambda_kh_k(x)$$\n\nThen, \n\n$$ d^T \\nabla _{\\mathbf{xx}}^2L(x^*,\\mu^*,\\lambda^*) d > 0 \\text { (Hessian is positive definite) }$$ \n\n\nBut in constrained optimization we are **not interested in all d**.\n\nInstead, we are looking for the $d$ vectors that lies on the tangent space (active constraints).\n\n\n* i.e., $$ \\forall d \\neq 0 \\text{, } [\\nabla _{x}g_{j}(x^{*}),\\nabla _{x}h_{k}(x^{*})]^Td = 0 \\text{; } \\forall j, k.$$\n\n\n", "meta": {"hexsha": "8280c4a54a2b99ec8ed20852de256f0053c3ce1f", "size": 17224, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture 8, optimality conditions.ipynb", "max_stars_repo_name": "bshavazipour/TIES483-2022", "max_stars_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "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": "Lecture 8, optimality conditions.ipynb", "max_issues_repo_name": "bshavazipour/TIES483-2022", "max_issues_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "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": "Lecture 8, optimality conditions.ipynb", "max_forks_repo_name": "bshavazipour/TIES483-2022", "max_forks_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-03T09:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T09:40:02.000Z", "avg_line_length": 26.8286604361, "max_line_length": 471, "alphanum_fraction": 0.5334417092, "converted": true, "num_tokens": 3000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845759920814681, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.09521612218460948}} {"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols\nfrom IPython.display import Image\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Projection matrices and least squares\n\n\n\n## Least squares\n\n* Consider from the previous lecture the three data point in the plane\n$$ ({t}_{i},{y}_{i}) =(1,1), (2,2),(3,2) $$\n* From this we need to construct a straight line\n* This could be helpful say in, statistics (remember, though in statistics we might have to get rid of statistical outliers)\n* Nonetheless (view image above) we note that we have a straight line in slope-intercept form\n$$ {y}={C}+{Dt} $$\n* On the line at *t* values of 1, 2, and 3 we will have\n$$ {y}_{1}={C}+{D}=1 \\\\ {y}_{2}={C}+{2D}=2 \\\\ {y}_{3}={C}+{3D}=2 $$\n* The actual *y* values at these *t* values are 1, 2, and 2, though\n* We are thus including an error of\n$$ \\delta{y} \\\\ { \\left( { e }_{ 1 } \\right) }^{ 2 }={ \\left[ \\left( C+D \\right) -1 \\right] }^{ 2 }\\\\ { \\left( { e }_{ 2 } \\right) }^{ 2 }={ \\left[ \\left( C+2D \\right) -2 \\right] }^{ 2 }\\\\ { \\left( { e }_{ 3 } \\right) }^{ 2 }={ \\left[ \\left( C+3D \\right) -2 \\right] }^{ 2 } $$\n* Since some are positive and some are negative (actual values below or above the line), we simply determine the square (which will always be positive)\n* Adding the (three in our example here) squares we have the sum total of the error (which is actuall just the sqautre of the distance between the line and actual *y* values)\n* The line will be the best fit when this error sum is at a minimum (hence *least squares*)\n* We can do this with calculus or with linear algebra\n* For calculus we take the partial derivatives of both unknowns and set to zero\n* For linear algebra we project orthogonally onto the columnspace (hence minimizing the error)\n * Note that the solution **b** does not exist in the columnspace (it is not a linear combination of the columns)\n\n### Calculus method\n\n* We'll create a function *f*(C,D) and successively take the partial derivatives of both variables and set it to zero\n* We fill then have two equation with two unknowns to solve (which is easy enough to do manually or by simple linear algebra and row reduction)\n\n\n```python\nC, D = symbols('C D')\n```\n\n\n```python\ne1_squared = ((C + D) - 1) ** 2\ne2_squared = ((C + 2 * D) - 2) ** 2\ne3_squared = ((C + 3 * D) - 2) ** 2\nf = e1_squared + e2_squared + e3_squared\nf\n```\n\n\n\n\n$$\\left(C + D - 1\\right)^{2} + \\left(C + 2 D - 2\\right)^{2} + \\left(C + 3 D - 2\\right)^{2}$$\n\n\n\n\n```python\nf.expand() # Expanding the expression\n```\n\n\n\n\n$$3 C^{2} + 12 C D - 10 C + 14 D^{2} - 22 D + 9$$\n\n\n\n* Doing the partial derivatives will be\n$$ f\\left( C,D \\right) =3{ C }^{ 2 }+12CD-10C+14{ D }^{ 2 }-22D+9\\\\ \\frac { \\partial f }{ \\partial C } =6C+12D-10=0\\\\ \\frac { \\partial f }{ \\partial D } =12C+28D-22=0 $$\n\n\n```python\nf.diff(C) # Taking the partial derivative with respect to C\n```\n\n\n\n\n$$6 C + 12 D - 10$$\n\n\n\n\n```python\nf.diff(D) # Taking the partial derivative with respect to D\n```\n\n\n\n\n$$12 C + 28 D - 22$$\n\n\n\n* Setting both equal to zero (and creating a simple augmented matrix) we get\n$$ 6C+12D-10=0\\\\ 12C+28D-22=0\\\\ \\therefore \\quad 6C+12D=10\\\\ \\therefore \\quad 12C+28D=22 $$\n\n\n```python\nA_augm = Matrix([[6, 12, 10], [12, 28, 22]])\nA_augm\n```\n\n\n\n\n$$\\left[\\begin{matrix}6 & 12 & 10\\\\12 & 28 & 22\\end{matrix}\\right]$$\n\n\n\n\n```python\nA_augm.rref() # Doing a Gauss-Jordan elimination to reduced row echelon form\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & \\frac{2}{3}\\\\0 & 1 & \\frac{1}{2}\\end{matrix}\\right], & \\begin{bmatrix}0, & 1\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* We now have a solution\n$$ {y}=\\frac{2}{3} + \\frac{1}{2}{t}$$\n\n### Linear algebra\n\n* We note that we can construct the following\n$$ {C}+{1D}={1} \\\\ {C}+{2D}={2} \\\\ {C}+{3D}={2} \\\\ {C}\\begin{bmatrix} 1 \\\\ 1\\\\ 1 \\end{bmatrix}+{D}\\begin{bmatrix} 1 \\\\ 2 \\\\ 3 \\end{bmatrix}=\\begin{bmatrix} 1 \\\\ 2 \\\\ 2 \\end{bmatrix} \\\\ A\\underline { x } =\\underline { b } \\\\ \\begin{bmatrix} 1 & 1 \\\\ 1 & 2 \\\\ 1 & 3 \\end{bmatrix}\\begin{bmatrix} C \\\\ D \\end{bmatrix}=\\begin{bmatrix} 1 \\\\ 2 \\\\ 2 \\end{bmatrix} $$\n* **b** is not in the columnspace of A and we have to do orthogonal projection\n$$ { A }^{ T }A\\hat { x } ={ A }^{ T }\\underline { b } \\\\ \\hat { x } ={ \\left( { A }^{ T }A \\right) }^{ -1 }{ A }^{ T }\\underline { b } $$\n\n\n```python\nA = Matrix([[1, 1], [1, 2], [1, 3]])\nb = Matrix([1, 2, 2])\nA, b # Showing the two matrices\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 1\\\\1 & 2\\\\1 & 3\\end{matrix}\\right], & \\left[\\begin{matrix}1\\\\2\\\\2\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n\n```python\nx_hat = (A.transpose() * A).inv() * A.transpose() * b\nx_hat\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{2}{3}\\\\\\frac{1}{2}\\end{matrix}\\right]$$\n\n\n\n* Again, we get the same values for C and D\n\n* Remember the following\n$$ \\underline{b} = \\underline{p}+\\underline{e} $$\n* **p** and **e** are perpendicular\n* Indeed **p** is in the columnspace of A and **e** is perpendicular to the columspace (or any vector in the columnspace)\n\n## Example problem\n\n### Example problem 1\n\n* Find the quadratic (second order polynomial) equation through the origin, with the following data points: (1,1), (2,5) and (-1,-2)\n\n#### Solution\n\n* Let's just think about a quadratic equation in *y* and *t*\n$$ {y}={c}_{1} +{C}{t}+{D}{t}^{2} $$\n* Through the origin (0,0) means *y* = 0 and *t* = 0, thus we have\n$$ {0}={c}_{1} +{C}{0}+{D}{0}^{2} \\\\ {c}_{1}=0 \\\\ {y}={C}{t}+{D}{t}^{2} $$\n\n* This gives us three equation for our three data points\n$$ C\\left( 1 \\right) +D{ \\left( 1 \\right) }^{ 2 }=1\\\\ C\\left( 2 \\right) +D{ \\left( 2 \\right) }^{ 2 }=5\\\\ C\\left( -1 \\right) +D{ \\left( -1 \\right) }^{ 2 }=-2\\\\ C\\begin{bmatrix} 1 \\\\ 2 \\\\ -1 \\end{bmatrix}+D\\begin{bmatrix} 1 \\\\ 4 \\\\ 1 \\end{bmatrix}=\\begin{bmatrix} 1 \\\\ 5 \\\\ -2 \\end{bmatrix}\\\\ A=\\begin{bmatrix} 1 & 1 \\\\ 2 & 4 \\\\ -1 & 1 \\end{bmatrix}\\\\ \\underline { x } =\\begin{bmatrix} C \\\\ D \\end{bmatrix}\\\\ \\underline { b } =\\begin{bmatrix} 1 \\\\ 5 \\\\ -2 \\end{bmatrix} $$\n\n* Clearly **b** is not in the columnspace of A and we have to project orthogonally onto the columnspace using\n$$ \\hat { x } ={ \\left( { A }^{ T }A \\right) }^{ -1 }{ A }^{ T }\\underline { b } $$\n\n\n```python\nA = Matrix([[1, 1], [2, 4], [-1, 1]])\nb = Matrix([1, 5, -2])\nx_hat = (A.transpose() * A).inv() * A.transpose() * b\nx_hat\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{41}{22}\\\\\\frac{5}{22}\\end{matrix}\\right]$$\n\n\n\n* Here's a simple plot of the equation\n\n\n```python\nimport matplotlib.pyplot as plt # The graph plotting module\nimport numpy as np # The numerical mathematics module\n%matplotlib inline\n```\n\n\n```python\nx = np.linspace(-2, 3, 100) # Creating 100 x-values\ny = (41 / 22) * x + (5 / 22) * x ** 2 # From the equation above\nplt.figure(figsize = (8, 6)) # Creating a plot of the indicated size\nplt.plot(x, y, 'b-') # Plot the equation above , in essence 100 little plots using small segmnets of blue lines\nplt.plot(1, 1, 'ro') # Plot the point in a red dot\nplt.plot(2, 5, 'ro')\nplt.plot(-1, -2, 'ro')\nplt.plot(0, 0, 'gs') # Plot the origin as a green square\nplt.show(); # Create the plot\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "f9dc1b5ec2f99f52a1dae06fbc11ed76d16a55a1", "size": 29457, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_16_Projection_matrices_and_least_squares.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_16_Projection_matrices_and_least_squares.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_16_Projection_matrices_and_least_squares.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": 46.980861244, "max_line_length": 11756, "alphanum_fraction": 0.6730488509, "converted": true, "num_tokens": 3189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.19930799790404563, "lm_q1q2_score": 0.09498613609530993}} {"text": "# Basic Concepts\nThe bottom-up analysis of dynamic states of a network is based on network topology and kinetic theory describing the links in the network. In this chapter, we provide a primer for the basic concepts of dynamic analysis of network states. We also discuss basics of the kinetic theory that is needed to formulate and understand detailed dynamic models of biochemical reaction networks. \n\n## Properties of Dynamic States\nThe three key dynamic properties outlined in the introduction - time constants, aggregate variables and transitions - are detailed in this section. \n\n### Time scales \nA fundamental quantity in dynamic analysis is the _time constant_. A time constant is a measure of time span over which significant changes occur in a state variable. It is thus a scaling factor for time and determines where in the time scale spectrum one needs to focus attention when dealing with a particular process or event of interest. \n\nA general definition of a time constant is given by \n\n$$\\begin{equation} \\tau = \\frac{\\Delta x}{|dx/dt|_{avg}} \\tag{2.1} \\end{equation}$$\n\nwhere $\\Delta{x}$ is a characteristic change in the state variable $x$ of interest and $|dx/dt|_{avg}$\nis an estimate of the rate of change of the variable $x$. Notice the ratio between $\\Delta{x}$ and the average derivative has units of time, and the time constant characterizes the time span over which these changes in $x$ occur, see Figure 2.1. \n\n\n\n**Figure 2.1:** Illustration of the concept of a time constant, $\\tau$, and its estimation as $\\tau = \\Delta x\\ / |dx/dt|_{avg}.$\n\nIn a network, there are many time constants. In fact, there is a spectrum of time constants, $\\tau_1,\\ \\tau_2, \\dots \\tau_r$ where $r$ is the rank of the Jacobian matrix defining the dynamic dimensionality of the dynamic response of the network. This spectrum of time constants typically spans many orders of magnitude. The consequences of a well-separated set of time constants is a key concern in the analysis of network dynamics. \n\n### Forming aggregate variables through \"pooling\" \nOne important consequence of time scale hierarchy is the fact that we will have fast and slow events. If fast events are filtered out or ignored, one removes a dynamic degree of freedom from the dynamic description, thus reducing the dynamic dimension of a system. Removal of a dynamic dimension leads to \"coarse-graining\" of the dynamic description. Reduction in dynamic dimension results in the combination, or pooling, of variables into aggregate variables. \n\nA simple example can be obtained from upper glycolysis. The first three reactions of this pathway are: \n\n$$\\begin{equation} \\text{glucose}\\ \\underset{\\stackrel{\\frown}{ATP \\ ADP}}{\\stackrel{HK}{\\longrightarrow}} \\text{G6P} \\underset{\\text{fast}, \\tau_f}{\\stackrel{PGI}{\\leftrightharpoons}} \\text{F6P} \\underset{\\stackrel{\\frown}{ATP \\ ADP}}{\\stackrel{PFK}{\\longrightarrow}} \\text{FDP} \\tag{2.2} \\end{equation}$$\n\nThis schema includes the second step in glycolysis where glucose-6-phosphate (G6P) is converted to fructose-6-phosphate (F6P) by the phosphogluco-isomerase (PGI). Isomerases are highly active enzymes and have rate constants that tend to be fast. In this case, PGI has a much faster response time than the response time of the flanking kinases in this pathway, hexokinase (HK) and phosphofructokinase (PFK). If one considers a time period that is much greater than $\\tau_f$ (the time constant associated with PGI), this system is simplified to: \n\n$$\\begin{equation} \\underset{\\stackrel{\\frown}{ATP \\ ADP}}{\\stackrel{HK}{\\longrightarrow}} \\ \\underset{t \\gg \\tau_f}{\\text{HP}} \\ \\underset{\\stackrel{\\frown}{ATP \\ ADP}}{\\stackrel{PFK}{\\longrightarrow}} \\tag{2.3} \\end{equation}$$\n\nwhere HP = (G6P+F6P) is the hexosephosphate pool. At a slow time scale (i.e, long compared to $\\tau_f$), the isomerase reaction has effectively equilibrated, leading to the removal of its dynamics from the network. As a result, F6P and G6P become dynamically coupled and can be considered to be a single variable. HP is an example of an aggregate variable that results from pooling G6P and F6P into a single variable. Such aggregation of variables is a consequence of time-scale hierarchy in networks. Determining how to aggregate variables into meaningful quantities becomes an important consideration in the dynamic analysis of network states. Further examples of pooling variables are given in Section 2.3. \n\n### Transitions \nThe dynamic analysis of a network comes down to examining its transient behavior as it moves from one state to another. \n\n\n\n**Figure 2.2:** Illustration of a transition from one state to another. (a) A simple transition. (b) A more complex set of transitions.\n\nOne type of transition, or _transient response,_ is illustrated in Figure 2.2a, where a system is in a homeostatic state, labeled as state $\\text{#1}$, and is perturbed at time zero. Over some time period, as a result of the perturbation, it transitions into another homeostatic state (state $\\text{#2}$). We are interested in characteristics such as the time duration of this response, as well as looking at the dynamic states that the network exhibits during this transition. Complex types of transitions are shown in Figure 2.2b. \n\nIt should be noted that when complex kinetic models are studied, there are two ways to perturb a system and induce a transient response. One is to instantaneously change the initial condition of one of the state variables (typically a concentration), and the second is to change the state of an environmental variable that represents an input to the system. The latter perturbation is the one that is biologically meaningful, whereas the former may be of some mathematical interest. \n\n### Visualizing dynamic states \nThere are several ways to graphically represent dynamic states: \n\n* First, we can represent them on a map (Figure 2.3a). If we have a reaction or a compound map for a network of interest, we can simply draw it out on a computer screen and leave open spaces above the arrows and the concentrations into which we can write numerical values for these quantities. These quantities can then be displayed dynamically as the simulation proceeds, or by a graph showing the changes in the variable over time. This representation requires writing complex software to make such an interface. \n\n* A second, and probably more common, way of viewing dynamic states is to simply graph the state variables, $x$, as a function of time (Figure 2.3b). Such graphs show how the variables move up and down, and on which time scales. Often, one uses a logarithmic scale for the y-axis, and that often delineates the different time constants on which a variable moves. \n\n* A third way to represent dynamic solutions is to plot two state variables against one another in a two-dimensional plot (Figure 2.3c). This representation is known as a _phase portrait_. Plotting two variables against one another traces out a curve in this plane along which time is a parameter. At the beginning of the trajectory, time is zero, and at the end, time has gone to infinity. These phase portraits will be discussed in more detail in Chapter 3.\n\n\n\n**Figure 2.3:** Graphical representation of dynamic states.\n\n## Primer on Rate Laws\nThe reaction rates, $v_i$, are described mathematically using kinetic theory. In this section, we will discuss some of the fundamental concepts of kinetic theory that lead to their formation. \n\n### Elementary reactions \nThe fundamental events in chemical reaction networks are elementary reactions. There are two types of elemental reactions: \n\n$$\\begin{align} &\\text{linear} &x \\stackrel{v}{\\rightarrow} \\tag{2.4a} \\\\ &\\text{bi-linear} & x_1 + x_2 \\stackrel{v}{\\rightarrow} \\tag{2.4b} \\end{align}$$\n\nA special case of a bi-linear reaction is when $x_1$ is the same as $x_2$ in which case the reaction is second order. \n\nElementary reactions represent the irreducible events of chemical transformations, analogous to a base pair being the irreducible unit of DNA sequence. Note that rates, $v$, and concentrations, $x$, are non-negative variables, that is; \n\n$$\\begin{equation} x \\geq 0, \\ v \\geq 0 \\tag{2.5} \\end{equation}$$\n\n### Mass action kinetics \nThe fundamental assumption underlying the mathematical description of reaction rates is that they are proportional to the collision frequency of molecules taking part in a reaction. Most commonly, reactions are bi-linear, where two different molecules collide to produce a chemical transformation. The probability of a collision is proportional to the concentration of a chemical species in a 3-dimensional unconstrained domain. This proportionality leads to the elementary reaction rates: \n\n$$\\begin{align} \\text{linear} \\ \\ &v = kx \\ &\\text{where the units on}& \\ k \\ \\text{are time}^{-1} \\ \\text{and} \\tag{2.6a} \\\\ \\text{bi-linear} \\ \\ &v = kx_1x_2 \\ &\\text{where the units on}& \\ k \\ \\text{are time}^{-1}\\text{conc}^{-1} \\tag{2.6b} \\end{align}$$\n\n### Enzymes increase the probability of the 'right' collision \nNot all collisions of molecules have the same probability of producing a chemical reaction. Collisions at certain angles are more likely to produce a reaction than others. As illustrated in Figure 2.4, molecules bound to the surface of an enzyme can be oriented to produce collisions at certain angles, thus accelerating the reaction rate. The numerical values of the rate constants are thus genetically determined as the structure of a protein is encoded in the sequence of the DNA. Sequence variation in the underlying gene in a population leads to differences amongst the individuals that make up the population. Principles of enzyme catalysis are further discussed in Section 5.1. \n\n\n\n**Figure 2.4:** A schematic showing how the binding sites of two molecules on an enzyme bring them together to collide at an optimal angle to produce a reaction. Panel A: Two molecules can collide at random and various angles in free solution. Only a fraction of the collisions lead to a chemical reaction. Panel B: Two molecules bound to the surface of a reaction can only collide at a highly restricted angle, substantially enhancing the probability of a chemical reaction between the two compounds. Redrawn based on (Lowenstein, 2000).\n\n### Generalized mass action kinetics \nThe reaction rates may not be proportional to the concentration in certain circumstances, and we may have what are called _power-law kinetics_. The mathematical form of the elementary rate laws are \n\n$$\\begin{align} v &= kx^a \\tag{2.7a} \\\\ v &= kx_1^ax_2^b \\tag{2.7b} \\end{align}$$\n\nwhere $a$ and $b$ can be greater or smaller than unity. In cases where a restricted geometry reduces the probability of collision relative to a geometrically-unrestricted case, the numerical values of $a$ and $b$ are less than unity, and vice versa. \n\n### Combining elementary reactions \nIn the analysis of chemical kinetics, the elementary reactions are often combined into reaction mechanisms. Following are two such examples: \n\n#### Reversible reactions:\nIf a chemical conversion is thermodynamically reversible, then the two opposite reactions can be combined as\n\n$$\\begin{equation} x_1 \\underset{v_{-}}{\\stackrel{v_+}{\\rightleftharpoons}} x_2 \\end{equation}$$\n\nThe net rate of the reaction can then be described by the difference between the forward and reverse reactions; \n\n$$\\begin{align} v_{net} &= v^+ - v^- = k^+x_1 - k^-x_2, \\tag{2.8a} \\\\ &K_{eq} = x_2 / x_1 = k^+/k^- \\tag{2.8b} \\end{align}$$\n\nwhere $K_{eq}$ is the equilibrium constant for the reaction. Note that $v_{net}$ can be positive or negative. Both $k^+$ and $k^-$ have units of reciprocal time. They are thus inverses of time constants. Similarly, a net reversible bi-linear reaction can be written as \n\n$$\\begin{equation} x_1 + x_2 \\underset{v_{-}}{\\stackrel{v_+}{\\rightleftharpoons}} x_3 \\end{equation}$$\n\nThe net rate of the reaction can then be described by \n\n$$\\begin{align} v_{net} &= v^+ - v^- = k^+x_1x_2 - k^-x_3, \\\\ &K_{eq} = x_3 / x_1x_2 = k^+/k^- \\end{align}$$\n\nwhere $K_{eq}$ is the equilibrium constant for the reaction. The units on the rate constant $(k^+)$ for a bi-linear reaction are concentration per time. Note that we can also write this equation as \n\n$$\\begin{equation} v_{net} = k^+x_1x_2 - k^-x_3 = k^+(x_1x_2 - x_3/K_{eq}) \\end{equation}$$\n\nthat can be a convenient form as often the $K_{eq}$ is a known number with a thermodynamic basis, and thus only a numerical value for $k^+$ needs to be estimated. \n\n#### Converting enzymatic reaction mechanisms into rate laws: \nOften, more complex combinations of elementary reactions are analyzed. The classical irreversible Michaelis-Menten mechanism is comprised of three elementary reactions. \n\n$$\\begin{equation} S + E \\underset{v_{-1} = k_{-1}x}{\\stackrel{v_1 = k_1se}{\\rightleftharpoons}} X \\stackrel{v_2 = k_2x}{\\longrightarrow} E + P \\end{equation}$$\n\nwhere a substrate, $S$, binds to an enzyme to form a complex, $X$, that can break down to generate the product, $P$. The concentrations of the corresponding chemical species is denoted with the same lower case letter; i.e., $e=[E]$, etc. This reaction mechanism has two conservation quantities associated with it: one on the enzyme $e_{tot} = e + x$ and one on the substrate $s_{tot} = s+x+p$. \n\nA quasi-steady-state assumption (QSSA), $dx/dt=0$, is then applied to generate the classical rate law\n\n$$\\begin{equation} \\frac{ds}{dt} = \\frac{-v_ms}{K_m + s} \\tag{2.9} \\end{equation}$$\n\nthat describes the kinetics of this reaction mechanism. This expression is the best-known rate equation in enzyme kinetics. It has two parameters: the maximal reaction rate $v_m$, and the Michaelis-Menten constant $K_m = (k_{-1} + k_2)/k_1$. The use and applicability of kinetic assumptions to deriving rate laws for enzymatic reaction mechanisms is discussed in detail in Chapter 5. \n\nIt should be noted that the elimination of the elementary rates through the use of the simplifying kinetic assumptions _fundamentally changes_ the mathematical nature of the dynamic description from that of bi-linear equations to that of hyperbolic equations (i.e., Eq. 2.9) and, more generally, to ratios of polynomial functions. \n\n### Pseudo-first order rate constants (PERCs) \nThe effects of temperature, pH, enzyme concentrations, and other factors that influence the kinetics can often be accounted for in a condition specific numerical value of a constant that looks like a regular elementary rate constant, as in Eq (2.4). The advantage of having such constants is that it simplifies the network dynamic analysis. The disadvantage is that dynamic descriptions based on PERCs are condition specific. This issue is discussed in Parts 3 and 4 of the book. \n\n### The mass action ratio ($\\Gamma$) \nThe equilibrium relationship among reactants and products of a chemical reaction are familiar to the reader. For example, the equilibrium relationship for the PGI reaction (Eq. (2.8)) is \n\n$$\\begin{equation} K_{eq} = \\frac{[\\text{F6P}]_{eq}}{[\\text{G6P}]_{eq}} \\tag{2.10} \\end{equation}$$\n\nThis relationship is observed in a closed system after the reaction is allowed to proceed to equilibrium over a long time, $t \\rightarrow \\infty$, (which in practice has a meaning relative to the time constant of the reaction, $t \\gg \\tau_f$). \n\nHowever, in a cell, as shown in Eq. (2.2), the PGI reactions operate in an \"open\" environment, i.e., G6P is being produced and F6P is being consumed. The reaction reaches a steady state in a cell that will have concentration values that are different from the equilibrium value. The _mass action ratio_ for open systems, defined to be analogous to the equilibrium constant, is \n\n$$\\begin{equation} \\Gamma = \\frac{[\\text{F6P}]_{ss}}{[\\text{G6P}]_{ss}} \\tag{2.11} \\end{equation}$$\n\nThe mass action ratio is denoted by $\\Gamma$ in the literature. \n\n### 'Distance' from equilibrium \nThe numerical value of the ratio $\\Gamma / K_{eq}$ relative to unity can be used as a measure of how far a reaction is from equilibrium in a cell. Fast reversible reactions tend to be close to equilibrium in an open system. For instance, the net reaction rate for a reversible bi-linear reaction (Eq. (2.2)) can be written as: \n\n$$\\begin{equation} v_{net} = k^+x_1x_2 - k^-x_3 = k^+x_1x_2(1 - \\Gamma/K_{eq}) \\end{equation}$$\n\nIf the reaction is \"fast\" then $(k^+x_1x_2)$ is a \"large\" number and thus $(1 - \\Gamma/K_{eq})$ tends to be a \"small\" number, since the net reaction rate is balanced relative to other reactions in the network. \n\n### Recap \nThese basic considerations of reaction rates and enzyme kinetic rate laws are described in much more detail in other standard sources, e.g., (Segal, 1975). In this text, we are not so concerned about the details of the mathematical form of the rate laws, but rather with the order-of-magnitude of the rate constants and how they influence the properties of the dynamic response. \n\n## More on Aggregate Variables\nPools, or aggregate variables, form as a result of well-separated time constants. Such pools can form in a hierarchical fashion. Aggregate variables can be physiologically significant, such as the total inventory of high-energy phosphate bonds, or the total inventory of particular types of redox equivalents. These important concepts are perhaps best illustrated through a simple example that should be considered a primer on a rather important and intricate subject matter. Formation of aggregate variables in complex models is seen throughout Parts III and IV of this text. \n\n\n\n**Figure 2.5:** The chemical transformations involved in the distribution of high-energy phosphate bonds among adenosines.\n\n### Distribution of high-energy phosphate among the adenylate phosphates \nIn Figure 2.5 we show the skeleton structure of the transfer of high-energy phosphate bonds among the adenylates. In this figure we denote the use of ATP by $v_1$ and the synthesis of ATP from ADP by $v_2$, $v_5$ and $v_{-5}$ denote the reaction rates of adenylate kinase that distributes the high energy phosphate bonds among ATP, ADP, and AMP, through the reaction \n\n$$\\begin{equation} 2 \\text{ADP} \\leftrightharpoons \\text{ATP} + \\text{AMP} \\tag{2.12} \\end{equation}$$\n\nFinally, the synthesis of AMP and its degradation is denoted by $v_3$ and $v_4$, respectively. The dynamic mass balance equations that describe this schema are: \n\n$$\\begin{align} \\frac{d \\text{ATP}}{dt} &= -v_1 + v_2 + v_{5, net} \\tag{2.13a} \\\\ \\frac{d \\text{ADP}}{dt} &= v_1 - v_2 - 2 v_{5, net} \\tag{2.13b} \\\\ \\frac{d \\text{AMP}}{dt} &= v_3 - v_4 + v_{5, net} \\tag{2.13c} \\end{align} $$\n\nThe responsiveness of these reactions falls into three categories: $v_{5, net} (=v_5 - v_{-5})$ is a _fast_ reversible reaction, $v_1$ and $v_2$ have _intermediate_ time scales, and the kinetics of $v_3$ and $v_4$ are _slow_ and have large time constants associated with them. Based on this time scale decomposition, we can combine the three concentrations so that they lead to the elimination of the reactions of a particular response time category on the right hand side of (Eq. 2.13). These combinations are as follows: \n\n* First, we can eliminate all but the slow reactions by forming the sum of the adenosine phosphates. \n\n $$\\begin{equation} \\frac{d}{dt}(\\text{ATP} + \\text{ADP} + \\text{AMP}) = v_3 - v_4\\ \\text{(slow)} \\tag{2.14} \\end{equation}$$\n\n The only reaction rates that appear on the right hand side of the equation are $v_3$ and $v_4$, that are the slowest reactions in the system. Thus, the summation of ATP, ADP, and AMP is a pool or aggregate variable that is expected to exhibit the slowest dynamics in the system. \n\n\n* The second pooled variable of interest is the summation of 2ATP and ADP that represents the total number of high energy phosphate bonds found in the system at any given point in time: \n \n $$\\begin{equation} \\frac{d}{dt}(2 \\text{ATP} + \\text{ADP}) = -v_1 + v_2\\ \\text{(intermediate)} \\tag{2.15} \\end{equation}$$\n\n This aggregate variable is only moved by the reaction rates of intermediate response times, those of $v_1$ and $v_2$. \n\n\n* The third aggregate variable we can form is the sum of the energy carrying nucleotides which are \n\n $$\\begin{equation} \\frac{d}{dt}(\\text{ATP} + \\text{ADP}) = -v_{5, net}\\ \\text{(fast)} \\tag{2.16} \\end{equation}$$\n\n This summation will be the fastest aggregate variable in the system. \n\nNotice that by combining the concentrations in certain ways, we define aggregate variables that may move on distinct time scales in the simple model system, and, in addition, we can interpret these variables in terms of their metabolic physiological significance. However, in general, time scale decomposition is more complex as the concentrations that influence the rate laws may move on many time scales and the arguments in the rate law functions must be pooled as well. \n\n### Using ratios of aggregate variables to describe metabolic physiology \nWe can define an aggregate variable that represents the _capacity_ to carry high-energy phosphate bonds. That simply is the summation of $\\text{ATP} + \\text{ADP} + \\text{AMP}.$ This number multiplied by 2 would be the total number of high energy phosphate bonds that can be stored in this system. The second variable that we can define here would be the _occupancy_ of that capacity, $\\textit{2ATP + ADP}$, which is simply an enumeration of how much of that capacity is occupied by high-energy phosphate bonds. Notice that the occupancy variable has a conjugate pair, which would be the vacancy variable. The ratio of these two aggregate variables forms a charge \n\n$$\\begin{equation} \\text{charge} = \\frac{\\text{occupancy}}{\\text{capacity}} \\tag{2.17} \\end{equation}$$\n\ncalled the _energy charge,_ given by \n\n$$\\begin{equation} \\text{E.C} = \\frac{2 \\text{ATP} \\ + \\ \\text{ADP}}{2(\\text{ATP} \\ + \\ \\text{ADP} \\ + \\ \\text{AMP})} \\tag{2.18} \\end{equation}$$\n\nwhich is a variable that varies between 0 and 1. This quantity is the _energy charge_ defined by Daniel Atkinson (Atkinson, 1968). In cells, the typical numerical range for this variable when measured is 0.80-0.90. \n\nIn a similar way, one can define other redox charges. For instance, the _catabolic redox charge_ on the NADH carrier can be defined as \n\n$$\\begin{equation} \\text{C.R.C} = \\frac{\\text{NADH}}{\\text{NADH} \\ + \\ \\text{NAD}} \\tag{2.19} \\end{equation}$$\n\nwhich simply is the fraction of the NAD pool that is in the reduced form of NADH. It typically has a low numerical value in cells, i.e., about 0.001-0.0025, and therefore this pool is typically discharged by passing the redox potential to the electron transfer system (ETS). The _anabolic redox charge_\n\n$$\\begin{equation} \\text{A.R.C} = \\frac{\\text{NADPH}}{\\text{NADPH} \\ + \\ \\text{NADP}} \\tag{2.20} \\end{equation}$$\n\nin contrast, tends to be in the range of 0.5 or higher, and thus this pool is charged and ready to drive biosynthetic reactions. Therefore, pooling variables together based on a time scale hierarchy and chemical characteristics can lead to aggregate variables that are physiologically meaningful. \n\nIn Chapter 8 we further explore these fundamental concepts of time scale hierarchy. They are then used in Parts III and IV in interpreting the dynamic states of realistic biological networks. \n\n## Time Scale Decomposition\n### Reduction in dimensionality \nAs illustrated by the examples given in the previous section, most biochemical reaction networks are characterized by many time constants. Typically, these time constants are of very different orders of magnitude. The hierarchy of time constants can be represented by the time axis, Figure 2.6. Fast transients are characterized by the processes at the extreme left and slow transients at the extreme right. The process time scale, i.e., the time scale of interest, can be represented by a _window of observation_ on this time axis. Typically, we have three principal ranges of time constants of interest if we want to focus on a limited set of events taking place in a network. We can thus decompose the system response in time. To characterize network dynamics completely we would have to study all the time constants. \n\n\n\n**Figure 2.6:** Schematic illustration of network transients that overlap with the time span of observation. n, n + 1, ... represent the decadic order of time constants. \n\n### Three principal time constants \nOne can readily conceptualize this by looking at a three-dimensional linear system where the first time constant represents the fast motion, the second represents the time scale of interest, and the third is a slow motion, see Figure 2.7. The general solution to a three-dimensional linear system is \n\n$$\\begin{align} \\textbf{x}(t) &=\\textbf{v}_1 \\langle \\textbf{u}_1, \\ \\textbf{x}_0 \\rangle \\ \\text{exp}(\\lambda_1 t) && \\text{fast} \\\\ &+\\textbf{v}_2 \\langle \\textbf{u}_2, \\ \\textbf{x}_0 \\rangle \\ \\text{exp}(\\lambda_2 t) && \\text{intermediate} \\\\ &+\\textbf{v}_3 \\langle \\textbf{u}_3, \\ \\textbf{x}_0 \\rangle \\ \\text{exp}(\\lambda_3 t) && \\text{slow} \\tag{2.21} \\end{align}$$\n\nwhere $\\textbf{v}_i$ are the _eigenvectors,_ $\\textbf{u}_i$ are the _eigenrows,_ and $\\boldsymbol{\\lambda}_i$ are the _eigenvalues_ of the Jacobian matrix. The eigenvalues are negative reciprocals of time constants. \n\nThe terms that have time constants faster than the observed window can be eliminated from the dynamic description as these terms are small. However, the mechanisms which have transients slower than the observed time exhibit high \"inertia\" and hardly move from their initial state and can be considered constants. \n\n\n\n**Figure 2.7:** A schematic of a decay comprised of three dynamic modes with well-separated time constants. \n\n#### Example: 3D motion simplifying to a 2D motion \nFigure 2.8 illustrates a three-dimensional space where there is rapid motion into a slow two-dimensional subspace. The motion in the slow subspace is spanned by two \"slow\" eigenvectors, whereas the fast motion is in the direction of the \"fast\" eigenvector. \n\n\n\n**Figure 2.8:** Fast motion into a two-dimensional subspace.\n\n### Multiple time scales \nIn reality there are many more than three time scales in a realistic network. In metabolic systems there are typically many time scales and a hierarchical formation of pools, Figure 2.9. The formation of such hierarchies will be discussed in Parts III and IV of the text. \n\n\n\n**Figure 2.9:** Multiple time scales in a metabolic network and the process of pool formation. This figure represents human folate metabolism. (a) A map of the folate network. (b) An illustration progressive pool formation. Beyond the first time scale pools form between CHF and CH2F; and 5MTHF, 10FTHF, SAM; and MET and SAH (these are abbreviations for the long, full names of these metabolites). DHF and THF form a pool beyond the second time scale. Beyond the third time scale CH2F/CHF join the 5MTHF/10FTHF/SAM pool. Beyond the fourth time scale HCY joins the MET/SAH pool. Ultimately, on time scales on the order of a minute and slower, interactions between the pools of folate carriers and methionine metabolites interact. Courtesy of Neema Jamshidi (Jamshidi, 2008a).\n\n## Network Structure versus Dynamics\nThe stoichiometric matrix represents the topological structure of the network, and this structure has significant implications with respect to what dynamic states a network can take. Its null spaces give us information about pathways and pools. It also determines the structural features of the gradient matrix. Network topology can have a dominant effect on network dynamics. \n\n### The null spaces of the stoichiometric matrix \nAny matrix has a right and a left null space. The right null space, normally called just the null space, is defined by all vectors that give zero when post-multiplying that matrix: \n\n$$\\begin{equation} \\textbf{Sv}=0 \\tag{2.22} \\end{equation}$$\n\nThe null space thus contains all the steady state flux solutions for the network. The null space can be spanned by a set of basis vectors that are pathway vectors (SB1). \n\nThe left null space is defined by all vectors that give zero when pre-multiplying that matrix: \n\n$$\\begin{equation} \\textbf{lS}=0 \\tag{2.23} \\end{equation}$$\n\nThese vectors $\\textbf{l}$ correspond to pools that are always conserved at all time scales. We will call them _time invariants_. Throughout the book we will look at these properties of the stoichiometric matrices that describe the networks being studied. \n\n\n\n**Figure 2.10:** A schematic showing how the structure of $\\textbf{S}$ and $\\textbf{G}$ form matrices that have non-zero elements in the same location if one of these matrices is transposed. The columns of $\\textbf{S}$ and the rows of $\\textbf{G}$ have similar but not identical vectors in an n-dimensional space. Note that this similarity only holds once the two opposing elementary reactions have been combined into a net reaction.\n\n### The structure of the gradient matrix \nWe will now examine some of the properties of $\\textbf{G}$. If a compound $x_i$ participates in reaction $v_j$, then the entry $s_{i,j}$ is non-zero. Thus, a net reaction \n\n$$\\begin{equation} x_i + x_{i + 1} \\stackrel{v_j}{\\leftrightharpoons} x_{i + 2} \\tag{2.24} \\end{equation}$$\n\nwith a net reaction rate \n\n$$\\begin{equation} v_j = v_j^+ - v_j^- \\tag{2.25} \\end{equation}$$\n\ngenerates three non-zero entries in $\\textbf{S}$: $s_{i,j}$, $s_{i + 1,j}$, and $s_{i + 2,j}$. Since compounds $x_i$, $x_{i + 1}$, and $x_{i + 2}$ influence reaction $v_j$, they will also generate non-zero elements in $\\textbf{G}$, see Figure 2.10. Thus, non-zero elements generated by the reactions are: \n\n$$\\begin{equation} g_{j, i} = \\frac{\\partial v_j}{\\partial x_i}, \\ g_{j, i + 1} = \\frac{\\partial v_j}{\\partial x_{i + 1}}, \\ \\text{and} \\ g_{j, i + 2} = \\frac{\\partial v_j}{\\partial x_{i + 2}} \\tag{2.26} \\end{equation}$$\n\nIn general, every reaction in a network is a reversible reaction. Hence we have the the following relationships between the elements of $\\textbf{S}$ and $\\textbf{G}$: \n\n$$\\begin{align} \\text{if} \\ &s_{i, j} = 0 \\ \\text{then} \\ g_{j, i} = 0 \\\\ \\text{if} \\ &s_{i, j} \\ne 0 \\ \\text{then} \\ g_{j, i} \\ne 0 \\\\ \\text{if} \\ &s_{i, j} > 0 \\ \\text{then} \\ g_{j, i} < 0 \\\\ \\text{if} \\ &s_{i, j} < 0 \\ \\text{then} \\ g_{j, i} >0 \\end{align}$$\n\nNote that for the rare cases where a reaction is effectively irreversible, an element in $\\textbf{G}$ can become very small, but in principle finite.\n\nIt can thus be seen that \n\n$$\\begin{equation} -\\textbf{G}^T \\ \\tilde \\ \\ \\textbf{S} \\tag{2.27} \\end{equation}$$\n\nin the sense that both will have non-zero elements in the same location. These elements will have opposite signs. \n\n### Stoichiometric autocatalysis \nThe fundamental structure of most catabolic pathways in a cell is such that a compound is imported into a cell and then some property stored on cofactors is transferred to the compound and the molecule is thus \"charged\" with this property. This charged form is then degraded into a waste product that is secreted from the cell. During that degradation process, the property that the molecule was charged with is re-extracted from the compound, often in larger quantities than was used in the initial charging of the compound. This pathway structure is the cellular equivalent of \"it takes money to make money,\" and its basic network structure is in Figure 2.11. \n\n\n\n**Figure 2.11:** The prototypic pathway structure for degradation of a carbon substrate.\n\nThis figure illustrates the import of a substrate, $S$, to a cell. It is charged with high-energy phosphate bonds to form an intermediate, $X$. $X$ is then subsequently degraded to a waste product, $W$, that is secreted. In the degradation process, ATP is recouped in a larger quantity than was used in the charging process. This means that there is a net production of ATP in the two steps, and that difference can be used to drive various load functions on metabolism. \n\nThe consequence of this schema is basically _stoichiometric autocatalysis_ that can lead to multiple steady states. The rate of formation of $\\text{ATP}$ from this schema as balanced by the load parameters is illustrated in Figure 2.12. This figure shows that the $\\text{ATP}$ generation is 0 if all the adenosine phosphates are in the form of $\\text{ATP}$ because there is no $\\text{ADP}$ to drive the conversion of X to W. The $\\text{ATP}$ generation is also 0 if there is no $\\text{ATP}$ available, because $S$ cannot be charged to form $X$. The curve in between $\\text{ATP} = 0$ and $\\text{ATP} = \\text{ATP}_{max}$ will be positive. The $\\text{ATP}$ load, or use rate, will be a curve that grows with $\\text{ATP}$ concentration and is sketched here as a hyperbolic function. As shown, there are three intersections in this curve, with the upper stable steady-state being the physiological state of this system. This system can thus have multiple steady-states and this property is a consequence of the topological structure of this reaction network. \n\n### Network structure \nThe three topics discussed in this section show that the stoichiometric matrix has a dominant effect on integrated network functions and sets constraints on the dynamic states that a network can achieve. The numerical values of the elements of the gradient matrix determine which of these states are chosen. \n\n## Physico-Chemical Effects\nMolecules have other physico-chemical properties besides the collision rates that are used in kinetic theory. They also have osmotic properties and are electrically charged. Both of these features influence dynamic descriptions of biochemical reaction networks. \n\n### The constant volume assumption \nMost systems that we identify in systems biology correspond to some biological entity. Such entities may be an organelle like the nucleus or the mitochondria, or it may be the whole cell, as illustrated in Figure 2.13. \n\nA compound, $x_i$, internal to the system, has a mass balance on the total amount per cell. We denote this quantity with an $M_i$. $M_i$ is a product of the volume per cell, $V$, and the concentration of the compound, $x_i$, which is amount per volume \n\n$$\\begin{equation} M_i = V \\ x_i \\tag{2.28} \\end{equation}$$\n\nThe time derivative of the amount per cell is given by: \n\n$$\\begin{equation} \\frac{M_i}{dt} = \\frac{d}{dt}(V \\ x_i) = V \\frac{d x_i}{dt} + x_i \\frac{dV}{dt} \\tag{2.29} \\end{equation}$$\n\n\n\n**Figure 2.13:** An illustration of a 'system' with a defined boundary, inputs and outputs, and an internal network of reactions. The $V$ volume of the system may change over time. $\\Pi$ denotes osmotic pressure, see (Eq. 2.32).\n\nThe time change of the amount $M_i$ per cell is thus dependent on two dynamic variables. One is $dx_i/dt$ which is the time change in the concentration of $x_i$, and the second is $dV/dt$ which is the change in volume with time. The volume is typically taken to be time invariant and therefore the term $dV/dt$ is equal to 0 and therefore results in a system that is of _constant volume_. In this case \n\n$$\\begin{equation} \\frac{d x_i}{dt} = \\frac{1}{V}\\frac{d M_i}{dt} \\tag{2.30} \\end{equation}$$\n\nThis constant volume assumption (recall Table 1.2) needs to be carefully scrutinized when one builds kinetic models since volumes of cellular compartments tend to fluctuate and such fluctuations can be very important. Very few kinetic models in the current literature account for volume variation because it is mathematically challenging and numerically difficult to deal with. A few kinetic models have appeared, however, that do take volume fluctuations into account (Joshi, 1989m and Klipp, 2005). \n\n### Osmotic balance \nMolecules come with osmotic pressure, electrical charge, and other properties, all of which impact the dynamic states of networks. For instance, in cells that do not have rigid walls, the osmotic pressure has to be balanced inside $(\\Pi_{in})$ and outside $(\\Pi_{out})$ of the cell (Figure 2.13), i.e., \n\n$$\\begin{equation} \\Pi_{in} = \\Pi_{out} \\tag{2.31} \\end{equation}$$\n\nAt first approximation, osmotic pressure is proportional to the total solute concentration, \n\n$$\\begin{equation} \\Pi = R T \\sum_i x_i \\tag{2.32} \\end{equation}$$\n\nalthough some compounds are more osmotically-active than others and have osmotic coefficients that are not unity. The consequences are that if a reaction takes one molecule and splits it into two, the reaction comes with an increase in osmotic pressure that will impact the total solute concentration allowable inside the cell, as it needs to be balanced relative to that outside the cell. Osmotic balance equations are algebraic equations that are often complicated and therefore are often conveniently ignored in the formulation of a kinetic model. \n\n### Electroneutrality \nAnother constraint on dynamic network models is the accounting for electrical charge. Molecules tend to be charged positively or negatively. Elementary charges cannot be separated, and therefore the total number of positive and negative charges within a compartment must balance. Any import and export in and out of a compartment of a charged species has to be counterbalanced by the equivalent number of molecules of the opposite charge crossing the membrane. Typically, bilipid membranes are impermeable to cations, but permeable to anions. For instance, the deliberate displacement of sodium and potassium by the ATP-driven sodium potassium pump is typically balanced by chloride ions migrating in and out of a cell or a compartment leading to a state of electroneutrality both inside and outside the cell. The equations that describe electroneutrality are basically a summation of the charge, $z_i$, of a molecule multiplied by its concentration, \n\n$$\\begin{equation} \\sum_i z_ix_i = 0 \\tag{2.33} \\end{equation}$$\n\nand such terms are summed up over all the species in a compartment. That sum has to add up to 0 to maintain electroneutrality. Since that summation includes concentrations of species, it represents an algebraic equation that is a constraint on the allowable concentration states of a network.\n\n## Summary\n\n* Time constants are key quantities in dynamic analysis. Large biochemical reaction networks typically have a broad spectrum of time constants. \n\n* Well-separated time constants lead to pooling of variables to form aggregates. Aggregate variables represent a coarse-grained (i.e., lower dimensional) view of network dynamics and can lead to physiologically meaningful variables. \n\n* Elementary reactions and mass action kinetics are the irreducible events in dynamic descriptions of networks. Elementary reactions are often combined into reaction mechanisms from which rate laws are derived using simplifying assumptions. \n\n* Network structure has an overarching effect on network dynamics. Certain physico-chemical effects can as well. Thus topological analysis is useful, and so is a careful examination of the assumptions (recall Table 1.2) that underlie the dynamic mass balances (Eq. (1.1)) for the system being modeled and simulated. \n\n$\\tiny{\\text{© B. Ø. Palsson 2011;}\\ \\text{This publication is in copyright.}\\\\ \\text{Subject to statutory exception and to the provisions of relevant collective licensing agreements,}\\\\ \\text{no reproduction of any part may take place without the written permission of Cambridge University Press.}}$\n", "meta": {"hexsha": "0ebffc93944ed0ed95b71f46b3b8efbb2da0bba6", "size": 44601, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/education/sb2/chapters/sb2_chapter2.ipynb", "max_stars_repo_name": "z-haiman/MASSpy", "max_stars_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "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": "docs/education/sb2/chapters/sb2_chapter2.ipynb", "max_issues_repo_name": "z-haiman/MASSpy", "max_issues_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "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": "docs/education/sb2/chapters/sb2_chapter2.ipynb", "max_forks_repo_name": "z-haiman/MASSpy", "max_forks_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "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": 101.1360544218, "max_line_length": 1074, "alphanum_fraction": 0.6992219905, "converted": true, "num_tokens": 9845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882834101888134, "lm_q2_score": 0.19436781335210207, "lm_q1q2_score": 0.09490657873450717}} {"text": "```R\noptions(warn=-1)\n# load library\nlibrary(reshape2) # for melt and cast functions\nlibrary(ggplot2) # for plotting functions\nlibrary(tm) # text mining library\n#install.packages(\"SnowballC\")\nlibrary(SnowballC)\n```\n\n## Question 1\n\n### 1. Derive expectation and maximation steps of hard-EM algorithm for document clustering\n\n- N is the total number of documents, K is the number of clusters.\n- {d1....dn} are the documents, with corresponding latent variables {z1...zn) where zn:=(zn1,....,znk) is the cluster assignment vector for the nth documents, znk = 1 if the document belongs to the cluster k and zero otherwise. \n- Parameters: Phi k is the cluster proportion,and mu k is the word proportion. Where the sum of phi of all clusters equal to 1 and the sum of word proportion of all words in cluster k equal to 1.\n\\begin{equation}\n\\sum_{k=1}^{K} \\varphi_{k}=1\n\\end{equation}\n\nand \n\n\\begin{equation}\n\\sum_{w \\in \\mathcal{A}} \\mu_{k, w}=1\n\\end{equation}\n\nThen the probability of observed documents is given by:\n\\begin{equation}\n\\begin{aligned}\np\\left(d_{1}, \\ldots, d_{N}\\right)=\\prod_{n=1}^{N} p\\left(d_{n}\\right) &=\\prod_{n=1}^{N} \\sum_{k=1}^{K} p\\left(z_{n, k}=1, d_{n}\\right) \\\\\n&=\\prod_{n=1}^{N} \\sum_{k=1}^{K}\\left(\\varphi_{k} \\prod_{w \\in \\mathcal{A}} \\mu_{k, w}^{c\\left(w, d_{n}\\right)}\\right)\n\\end{aligned}\n\\end{equation}\n\n\nApply log to above, then the log-likelihood is:\n\n\\begin{equation}\n\\begin{aligned}\n\\ln p\\left(d_{1}, \\ldots, d_{N}\\right)=\\sum_{n=1}^{N} \\ln p\\left(d_{n}\\right) &=\\sum_{n=1}^{N} \\ln \\sum_{k=1}^{K} p\\left(z_{n, k}=1, d_{n}\\right) \\\\\n&=\\sum_{n=1}^{N} \\ln \\sum_{k=1}^{K}\\left(\\varphi_{k} \\prod_{w \\in \\mathcal{A}} \\mu_{k, w}^{c\\left(w, d_{n}\\right)}\\right)\n\\end{aligned}\n\\end{equation}\n\n\nTo maximise the Likelihood of incomplete Data, we use EM algorithm.\n\nFirst, as the parameters are unknown, we initialize the starting values of parameters θ. These values will be called θold, and the unknown parameters we want to estimate will be θnew. \n\n\\begin{equation}\n\\theta^{\\text {old }}=\\left(\\boldsymbol{\\varphi}^{\\text {old }}, \\boldsymbol{\\mu}_{1}^{\\text {old }}, \\ldots, \\boldsymbol{\\mu}_{K}^{\\text {old }}\\right)\n\\end{equation}\n\nDefine Q function:\n\n\\begin{equation}\n\\begin{aligned}\nQ\\left(\\boldsymbol{\\theta}, \\boldsymbol{\\theta}^{\\text {old }}\\right) &:=\\sum_{n=1}^{N} \\sum_{k=1}^{K} p\\left(z_{n, k}=1 \\mid d_{n}, \\boldsymbol{\\theta}^{\\text {old }}\\right) \\ln p\\left(z_{n, k}=1, d_{n} \\mid \\boldsymbol{\\theta}\\right) \\\\\n&=\\sum_{n=1}^{N} \\sum_{k=1}^{K} p\\left(z_{n, k}=1 \\mid d_{n}, \\boldsymbol{\\theta}^{\\text {old }}\\right)\\left(\\ln \\varphi_{k}+\\sum_{w \\in \\mathcal{A}} c\\left(w, d_{n}\\right) \\ln \\mu_{k, w}\\right) \\\\\n&=\\sum_{n=1}^{N} \\sum_{k=1}^{K} \\gamma\\left(z_{n, k}\\right)\\left(\\ln \\varphi_{k}+\\sum_{w \\in \\mathcal{A}} c\\left(w, d_{n}\\right) \\ln \\mu_{k, w}\\right)\n\\end{aligned}\n\\end{equation}\n\nwhere \n\n\\begin{equation}\n\\gamma\\left(z_{n, k}\\right) = p\\left(z_{n, k}=1 \\mid d_{n}, \\boldsymbol{\\theta}^{\\text {old }}\\right)\n\\end{equation}\n\nare the responsability factors\n\nE step: \n1. calculate γ(znk) based on estimated parameters\n\\begin{equation}\n\\gamma\\left(z_{n k}\\right):=p\\left(z_{n k}=1 \\mid \\boldsymbol{d}_{n}, \\boldsymbol{\\theta}^{\\text {old }}\\right)\n\\end{equation}\n\n2. for each document, find the cluster with the maximum probability. \n\n\\begin{equation}\nZ^{*}=\\operatorname{argmax}_{z} \\gamma\\left(z_{n, k}\\right)=\\operatorname{argmax}_{z} p\\left(z_{n, k}=1 \\mid d_{n}, \\theta^{\\text {old }}\\right)\n\\end{equation}\n\nM step:\n\nFor hard EM, there is no expectation on the latent variables, so :\n\n\\begin{equation}\n\\mathcal{Q}\\left(\\theta, \\theta^{\\text {old }}\\right)=\\sum_{n=1}^{N} \\ln p\\left(z_{n, k=Z^{*}}=1, d_{n} \\mid \\theta\\right)\n\\end{equation}\n\nFind: \n\\begin{equation}\n\\operatorname{argmax}_{\\theta} \\sum_{n=1}^{N}\\left(\\ln \\varphi_{k=Z^{*}}+\\sum_{w \\in \\mathcal{A}} c\\left(w, d_{n}\\right) \\ln \\mu_{k=Z^{*}, w}\\right)\n\\end{equation}\n\n1. Sub the z* calculated into the partial derivatives below and recalculate the estimations of the parametors, update the parameters.\n\n\n\\begin{equation}\n\\varphi_{k}=\\frac{N_{k}}{N} \\text { where } N_{k}:=\\sum_{n=1}^{N} \\gamma\\left(z_{n, k}\\right)\n\\end{equation}\n\nand \n\n\\begin{equation}\n\\mu_{k, w}=\\frac{\\sum_{n=1}^{\\prime} \\gamma\\left(z_{n, k}\\right) c\\left(w, d_{n}\\right)}{\\sum_{w^{\\prime} \\in \\mathcal{A}} \\sum_{n=1}^{N} \\gamma\\left(z_{n, k}\\right) c\\left(w^{\\prime}, d_{n}\\right)}\n\\end{equation}\n\nUse \\begin{equation}\n\\boldsymbol{\\theta}^{\\text {old }} \\leftarrow \\boldsymbol{\\theta}^{\\text {new }}\n\\end{equation} and repeat until converge\n\n\n### 2. Implement the hard-EM and soft-EM\n\n\n```R\n# Initialize parameters (theta_old function)\ntheta <- function(size, K, seed = 123456){\n set.seed(seed) # set seed\n phi.hat <- matrix(1/K,nrow = K, ncol=1) # assume all clusters have the same size (we will update this later on)\n mu.hat <- matrix(runif(K*size),nrow = K, ncol = size) # initiate Mu \n mu.hat <- prop.table(mu.hat, margin = 1) # normalization to ensure that sum of each row is 1\n \n return (list(\"phi.hat\" = phi.hat, \"mu.hat\" = mu.hat))\n}\n\n# Helper Function \n# This function is needed to prevent numerical overflow/underflow when working with small numbers\nlogSum <- function(v) {\n m = max(v)\n return ( m + log(sum(exp(v-m))))\n}\n```\n\n\n```R\n# train objective function\ntrain_obj <- function(theta_old, wf) { \n N <- dim(wf)[2] # number of documents\n K <- dim(theta_old$mu.hat)[1] # number of cluster\n \n nloglike = 0\n for (n in 1:N){\n lprob <- matrix(0,ncol = 1, nrow=K) \n for (k in 1:K){\n lprob[k,1] = sum(wf[,n] * log(theta_old$mu.hat[k,])) \n }\n nloglike <- nloglike - logSum(lprob + log(theta_old$phi))\n }\n \n return (nloglike)\n}\n```\n\n\n```R\n# EM function for document clustering(hard & soft)\nEM.step <- function(wf, K = 4, max.epoch=10, soft = TRUE, seed){ \n \n # Parameters Setting\n N <- ncol(wf) # number of documents\n W <- nrow(wf) # number of words i.e. vocabulary size\n theta_old = theta(W, K, seed = seed) # initialize parameters\n gamma <- matrix(,nrow=N, ncol=K) # empty posterior matrix\n \n # check initial values\n print(train_obj(theta_old,wf))\n # EM-step\n for(epoch in 1:max.epoch){\n \n \n # E step: \n for (n in 1:N){\n for (k in 1:K){\n ## calculate the posterior based on the estimated mu and rho in the \"log space\"\n gamma[n,k] <- log(theta_old$phi.hat[k]) + sum(wf[,n] * log(theta_old$mu.hat[k,])) \n }\n # normalisation to sum to 1 in the log space\n logZ = logSum(gamma[n,])\n gamma[n,] = gamma[n,] - logZ\n }\n \n # converting back from the log space \n gamma <- exp(gamma)\n \n # for hard EM, we want the k with the highest probability to be 1\n if(soft == FALSE){\n # hard assignments:\n max.prob <- gamma==apply(gamma, 1, max) # for each point find the cluster with the maximum (estimated) probability\n gamma[max.prob] <- 1 # assign each point to the cluster with the highest probability\n gamma[!max.prob] <- 0 # remove points from clusters with lower probabilites\n }\n \n \n # M step:\n # we need this matrix (same shape as the ) here because when calculating mean, \n # it can result in zero which leads to log calculation result in NaN, to avoid this issue, add a small number to avoid 0\n eps = matrix(1e-10, nrow = W, ncol = K)\n for (k in 1:K){\n ## recalculate the estimations:\n theta_old$phi.hat[k] <- sum(gamma[,k])/N # the cluster size\n theta_old$mu.hat[k,] <- ((wf%*%gamma[,k])+eps[,k])/sum((wf%*%gamma[,k])+eps[,k]) # new means (cluster cenroids)\n }\n # evaluate and compare likelihood\n print(train_obj(theta_old,wf))\n }\n \n # keep the final parameters and gamma (posterior matrix)\n return(list(\"theta\"= theta_old,\"posterior\"=gamma))\n}\n```\n\n### 3. run soft-EM and hard-EM on provided data with K = 4\n\n\n```R\n## read the file (each line of the text file is one document)\ntext <- readLines('./Task2A.txt')\n\n## the terms before '\\t' are the lables (the newsgroup names) and all the remaining text after '\\t' are the actual documents\ndocs <- strsplit(text, '\\t')\nrm(text) # just free some memory!\n\n# store the labels for evaluation\nlabels <- unlist(lapply(docs, function(x) x[1]))\n\n# store the unlabeled texts \ndocs <- data.frame(unlist(lapply(docs, function(x) x[2]))) \n```\n\n\n```R\n# preprocessing\ndocs$doc_id <- rownames(docs)\ncolnames(docs) <- c(\"text\",\"doc_id\")\n\n# create a corpus\ndocs <- DataframeSource(docs)\ncorp <- Corpus(docs)\n\n# Preprocessing:\ncorp <- tm_map(corp, removeWords, stopwords(\"english\")) # remove stop words \n#(the most common word in a language that can be find in any document)\ncorp <- tm_map(corp, removePunctuation) # remove punctuation\ncorp <- tm_map(corp, stemDocument) # perform stemming (reducing inflected and derived words to their root form)\ncorp <- tm_map(corp, removeNumbers) # remove all numbers\ncorp <- tm_map(corp, stripWhitespace) # remove redundant spaces \n\n# Create a matrix which its rows are the documents and colomns are the words. \n# Each number in Document Term Matrix shows the frequency of a word (colomn header) in a particular document (row title)\ndtm <- DocumentTermMatrix(corp)\n# reduce the sparcity of out dtm\ndtm <- removeSparseTerms(dtm, 0.90)\n\n# store word frequency into a matrix\nwf <- t(as.matrix(dtm))\n```\n\n\n```R\n# run soft and hard EM\nEM_soft <- EM.step(wf, K=4, max.epoch=15,soft = TRUE, seed = 123456) \nEM_hard <- EM.step(wf, K=4, max.epoch=15,soft = FALSE, seed = 123456) \n```\n\n [1] 459718.3\n [1] 425849.8\n [1] 422287.2\n [1] 420268.8\n [1] 419696.7\n [1] 419511.3\n [1] 419432.7\n [1] 419403\n [1] 419385.8\n [1] 419303.3\n [1] 419291.5\n [1] 419283\n [1] 419274.8\n [1] 419248.1\n [1] 419226.4\n [1] 419218.6\n [1] 459718.3\n [1] 425717.5\n [1] 422187.1\n [1] 420212.3\n [1] 419695.3\n [1] 419536.1\n [1] 419450\n [1] 419417.2\n [1] 419402\n [1] 419394.1\n [1] 419387.3\n [1] 419383.3\n [1] 419382.4\n [1] 419382.5\n [1] 419382.5\n [1] 419382.5\n\n\n### 4. Perform PCA on clustering\n\n\n```R\n##--- Cluster Visualization -------------------------------------------------\ncluster.viz <- function(counts, color.vector, title=' '){\n # PCA\n p.comp <- prcomp(counts, scale. = TRUE, center = TRUE)\n # visualize\n plot(p.comp$x, col=color.vector, pch=1, main=title)\n}\n```\n\n\n```R\n# visualization settings\noptions(repr.plot.width=18, repr.plot.height=10)\npar(mfrow=c(1,2))\n\n# Get the color.vector(labels) \nlabel.soft <- apply(EM_soft$posterior, 1, which.max)\nlabel.hard <- apply(EM_hard$posterior, 1, which.max)\n\n# normalize the count matrix for better visualization\ncounts <- scale(wf)\ncounts[is.nan(counts)] <- 0\n\n# visualize the clusters estimated by soft and hard EM\ncluster.viz(t(counts), label.soft, 'Estimated Clusters (Soft EM) - normalized')\ncluster.viz(t(counts), label.hard, 'Estimated Clusters (Hard EM) - normalized')\ncluster.viz(t(wf), label.soft, 'Estimated Clusters (Soft EM)')\ncluster.viz(t(wf), label.hard, 'Estimated Clusters (Hard EM)')\n# visualize the real clusters\ncluster.viz(t(counts), factor(labels), 'Real Clusters - normalized')\ncluster.viz(t(wf), factor(labels), 'Real Clusters')\n```\n", "meta": {"hexsha": "36db60e01b3da4708f88f4cd38f99a71a6fce079", "size": 228543, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Machine Learning study notes/Latent Variable Models and Neural Networks/src/31436285_assessment_2_q1.ipynb", "max_stars_repo_name": "alanwzy/my-projects", "max_stars_repo_head_hexsha": "35279795a8b2d61f82ad0118f493a18b293459f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-05T04:26:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T04:26:12.000Z", "max_issues_repo_path": "Machine Learning study notes/Latent Variable Models and Neural Networks/src/31436285_assessment_2_q1.ipynb", "max_issues_repo_name": "alanwzy/my-projects", "max_issues_repo_head_hexsha": "35279795a8b2d61f82ad0118f493a18b293459f8", "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": "Machine Learning study notes/Latent Variable Models and Neural Networks/src/31436285_assessment_2_q1.ipynb", "max_forks_repo_name": "alanwzy/my-projects", "max_forks_repo_head_hexsha": "35279795a8b2d61f82ad0118f493a18b293459f8", "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": 461.703030303, "max_line_length": 91694, "alphanum_fraction": 0.9262064469, "converted": true, "num_tokens": 3765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.1968262036430985, "lm_q1q2_score": 0.09457079413162413}} {"text": "
\n\n
    \n\n\n
[mlcourse.ai](https://mlcourse.ai) - Open Machine Learning Course
\n\n
\n\nAuteur: [Alexey Natekin](https://www.linkedin.com/in/natekin/), fondateur d’OpenDataScience, Machine Learning Evangelist. Traduit et édité par [Olga Daykhovskaya](https://www.linkedin.com/in/odaykhovskaya/), [Anastasia Manokhina](https://www.linkedin.com/in/anastasiamanokhina/), [Egor Polusmak](https://www.linkedin.com/in/egor-polusmak/), [Yuanyuan Pao](https://www.linkedin.com/in/yuanyuanpao/) et [Ousmane Cissé](https://github.com/oussou-dev). Ce matériel est soumis aux termes et conditions de la licence [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/). L'utilisation gratuite est autorisée à des fins non commerciales.\n\n
\n \n
Thème 10. Gradient Boosting
\n\n\n\n\n\nJusqu'à présent, nous avons couvert 9 sujets allant de l'analyse exploratoire de données à l'analyse de séries chronologiques en Python:\n\n1. [Analyse exploratoire de données avec Pandas](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-1-exploratory-data-analysis-with-pandas-de57880f1a68)\n2. [Visualisation de données avec Python](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-2-visual-data-analysis-in-python-846b989675cd)\n3. [Classification, arbres-de-décision et k plus proches voisins](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-3-classification-decision-trees-and-k-nearest-neighbors-8613c6b6d2cd)\n4. [Classification linéaire et régression](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-4-linear-classification-and-regression-44a41b9b5220)\n5. [Bagging et random forest](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-5-ensemble-of-algorithms-and-random-forest-8e05246cbba7)\n6. [Feature Engineering and Feature Selection](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-6-feature-engineering-and-feature-selection-8b94f870706a)\n7. [Apprentissage non supervisé : (ACP) Analyse en Composantes Principales et Clustering](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-7-unsupervised-learning-pca-and-clustering -db7879568417)\n8. [Vowpal Wabbit : Learning with Gigabytes of Data](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-8-vowpal-wabbit-fast-learning-with-gigabytes-of-data-60f750086237)\n9. [Analyse des séries temporelles en Python](https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-9-time-series-analysis-in-python-a270cb05e0b3)\n\nAujourd'hui, nous allons examiner l'un des algorithmes d'apprentissage automatique les plus populaires et les plus pratiques : le Gradient Boosting.\n\n
Sommaire de l'article
\n\n\nNous vous recommandons de lire cet article dans l’ordre décrit ci-dessous, mais n'hésitez pas à parcourir les différentes sections.\n\n

\n\n\n# 1. Introduction et histoire du Boosting\nPresque tout le monde en dans le domaine de l'apprentissage automatique a entendu parler du Gradient boosting. Nombreux data scientist incluent cet algorithme dans leur boîte à outils en raison des bons résultats obtenus sur tout problème (inconnu) donné.\n\nDe plus, XGBoost est souvent la recette standard pour [gagner](https://github.com/dmlc/xgboost/blob/master/demo/README.md#usecases) les cmpétitions de [ML](http://blog.kaggle.com/tag/xgboost/). Il est si populaire que l’idée de superposer des XGBoosts est devenue un mème. De plus, le boosting est un composant important dans [de nombreux systèmes de recommandation](https://en.wikipedia.org/wiki/Learning_to_rank#Practical_usage_by_search_engines); parfois, il est même considérée comme une [marque](https://yandex.com/company/technologies/matrixnet/).\nPenchons-nous sur l'histoire et le développement du boosting.\n\nLe boosting est né de [la question :](http://www.cis.upenn.edu/~mkearns/papers/boostnote.pdf) est-il possible d'obtenir un modèle fort à partir d'un grand nombre de modèles relativement faibles et simples ? Par «modèles faibles», nous n'entendons pas de simples modèles de base tels que les arbres de décision, mais des modèles avec des performances de précision médiocres, où médiocre est un peu meilleur que le hasard.\n\n[Une réponse mathématique positive](http://www.cs.princeton.edu/~schapire/papers/strengthofweak.pdf) a été identifiée, mais il a fallu quelques années pour développer des algorithmes pleinement fonctionnels basés sur cette solution, par exemple AdaBoost. Ces algorithmes adoptent une approche dite \"gourmande\" : ils construisent d’abord une combinaison linéaire de modèles simples (algorithmes de base) en repesant les données d’entrée. Ensuite, le modèle (généralement un arbre de décision) est construit sur des objets précédemment prédits de manière incorrecte, auxquels des pondérations plus importantes ont été attribuées.\n\n\nDe nombreux cours d'apprentissage automatique étudient AdaBoost - l'ancêtre du GBM (Gradient Boosting Machine). Cependant, depuis la fusion d'AdaBoost avec GBM, il est devenu évident qu'AdaBoost n'est qu'une variante particulière de GBM.\n\nL'algorithme lui-même a une interprétation visuelle très claire et une intuition permettant de définir des poids. Jetons un coup d'œil au problème de classification des jouets suivant dans lequel nous allons scinder les données entre les arbres de profondeur 1 (également appelés «stumps») à chaque itération d'AdaBoost. Pour les deux premières itérations, nous avons l'image suivante :\n\n\n\nLa taille du point correspond à son poids, attribué à une prédiction incorrecte. À chaque itération, nous pouvons constater que ces poids augmentent - les \"stumps\" ne peuvent pas faire face à ce problème. Cependant, si nous votons (de manière pondérée) pour les \"stumps\", nous obtiendrons les bonnes classifications :\n\n\n\nPseudocode:\n- Initialiser les poids des échantillons $\\Large w_i^{(0)} = \\frac{1}{l}, i = 1, \\dots, l$.\n- pour tout $t = 1, \\dots, T$\n    * Entraînez l'algo $\\Large b_t$, laissez $\\epsilon_t$ être l’erreur d’entraînement.\n * $\\Large \\alpha_t = \\frac{1}{2}ln\\frac{1 - \\epsilon_t}{\\epsilon_t}$.\n    * Mettez à jour les poids des échantillons : $\\Large w_i^{(t)} = w_i^{(t-1)} e^{-\\alpha_t y_i b_t(x_i)}, i = 1, \\dots, l$.\n * Normaliser les poids des échantillons: $\\Large w_0^{(t)} = \\sum_{j = 1}^k w_j^{(t)}, w_i^{(t)} = \\frac{w_i^{(t)}}{w_0^{(t)}}, i = 1, \\dots, l$.\n- Retourne $\\sum_t^{T}\\alpha_tb_t$\n\n\n[Voici](https://www.youtube.com/watch?v=k4G2VCuOMMg) un exemple plus détaillé d'AdaBoost où, en itérant, nous pouvons voir que les poids augmentent, en particulier à la frontière entre les classes.\n\nAdaBoost fonctionne bien, mais [le manque](https://www.cs.princeton.edu/courses/archive/spring07/cos424/papers/boosting-survey.pdf) d'explication de la raison de la réussite de l'algorithme a semé le doute. Certains considéraient cela comme un super-algorithme, une solution miracle, mais d'autres étaient sceptiques et pensaient qu'AdaBoost était juste trop bien sur-appris\n\nLe problème de sur-apprentissage existait bel et bien, surtout lorsque les données présentaient de fortes valeurs aberrantes. Par conséquent, dans ce type de problème, AdaBoost était instable. Heureusement, quelques professeurs du département de statistique de Stanford, qui avaient créé Lasso, Elastic Net et Random Forest, ont commencé à étudier l'algorithme. En 1999, Jerome Friedman a proposé la généralisation du développement d’algorithmes de Boosting - Gradient Boosting (Machine), également connu sous le nom de GBM. Avec ce travail, Friedman a mis en place la base statistique de nombreux algorithmes fournissant l'approche générale du Boosting pour l'optimisation dans l'espace fonctionnel.\n\nCART, bootstrap, et beaucoup d'autres algorithmes sont issus du département des statistiques de Stanford. Ce faisant, leurs noms seront introduits dans les prochains manuels. Ces algorithmes sont très pratiques et certains travaux récents ne sont pas encore largement adoptés. Par exemple, consultez [glinternet](https://arxiv.org/abs/1308.2719).\n\nPas beaucoup d'enregistrements vidéo de Friedman sont disponibles. Bien qu'il y ait une très intéressante [interview](https://www.youtube.com/watch?v=8hupHmBVvb0) avec lui sur la création de CART et sur la façon dont ils ont résolu les problèmes de statistiques (similaires à la data analysis et à la data science aujourd'hui) il y a plus de 40 ans.\n\nIl existe également une excellente [conférence](https://www.youtube.com/watch?v=zBk3PK3g-Fc) de Hastie, une rétrospective sur l'analyse de données fournie par l'un des créateurs des méthodes que nous utilisons tous les jours.\n\nEn général, la recherche en ingénierie et en algorithmes est passée d'une approche à part entière à la construction et à l'étude d'algorithmes. D'un point de vue mathématique, il ne s'agit pas d'un gros changement : nous ajoutons (ou renforçons) des algorithmes faibles et élargissons notre ensemble avec des améliorations progressives pour les parties des données où le modèle était inexact. Mais, cette fois, le prochain modèle simple ne repose pas uniquement sur des objets repondérés, mais améliore son approximation du gradient de la fonction objective globale. Ce concept ouvre grandement nos algorithmes à l'imagination et aux extensions.\n\n\n\n## Histoire de la GBM\n\nPlus de 10 ans après l’introduction de la GBM, celle-ci est devenue un élément essentiel de la boîte à outils de la science des données.\nGBM a été étendu pour s’appliquer à différents problèmes statistiques : GLMboost et GAMboost pour renforcer les modèles GAM existants, CoxBoost pour les courbes de survie et RankBoost et LambdaMART pour le classement.\nDe nombreuses réalisations de GBM sont également apparues sous différents noms et sur différentes plateformes : GBM stochastique, GBDT (arbres de décision boostés par gradient), GBRT (arbres de régression boostés par gradient), MART (arbres de régression additive multiples), etc. En outre, la communauté du ML (Machine Learning) était très segmentée et dissociée, ce qui rendait difficile de savoir à quel point la stimulation était devenue généralisée.\n\nDans le même temps, le boosting avait été activement utilisé dans le classement des recherches. Ce problème a été réécrit en termes de fonction de perte qui pénalise les erreurs dans l'ordre de sortie. Il est donc devenu pratique de l'insérer simplement dans la GBM. AltaVista a été l’une des premières entreprises à introduire le renforcement du classement. Bientôt, les idées se répandent dans Yahoo, Yandex, Bing, etc. Une fois que cela s'est produit, le boosting est devenu l'un des principaux algorithmes utilisés non seulement dans la recherche, mais également dans les technologies de base de l'industrie.\n\nLes compétitions ML, en particulier Kaggle, ont joué un rôle majeur dans la popularisation du Boosting. À présent, les chercheurs disposaient d’une plate-forme commune leur permettant de faire face à différents problèmes de science des données avec un grand nombre de participants du monde entier. Avec Kaggle, il est possible de tester de nouveaux algorithmes sur les données réelles, ce qui permet aux algorithmes de \"briller\", et de fournir des informations complètes sur le partage des résultats de performance de modèle entre jeux de données de compétition. C’est exactement ce qui est arrivé avec le Boosting quand il a été utilisé chez [Kaggle](http://blog.kaggle.com/2011/12/21/score-xavier-conort-on-coming-second-in-give-me-some-credit/) (voir les entretiens avec les gagnants de Kaggle à partir de 2011 qui ont principalement utilisé le boosting). La bibliothèque [XGBoost](https://github.com/dmlc/xgboost) a rapidement gagné en popularité après son apparition. XGBoost n'est pas un nouvel algorithme unique. il s'agit simplement d'une réalisation extrêmement efficace de la GBM classique avec des heuristiques supplémentaires.\n\nCet algorithme a suivi le chemin très typique des algorithmes ML aujourd'hui : problème mathématique et savoir-faire algorithmique pour des applications pratiques réussies et une adoption en masse des années après sa première apparition.\n\n# 2. L'algorithme GBM\n### Problème\n\nNous allons résoudre le problème de l'approximation des fonctions dans un contexte d'apprentissage supervisé général. Nous avons un ensemble de fonctionnalités $ \\large x $ et les variables cibles $\\large y, \\large \\left\\{ (x_i, y_i) \\right\\}_{i=1, \\ldots,n}$ que nous utilisons pour restaurer la dépendance $\\large y = f(x) $. Nous restaurons la dépendance en approximant $ \\large \\hat{f}(x) $ et en comprenant quelle approximation est la meilleure lorsque nous utilisons la fonction de perte $ \\large L(y,f) $, que nous voulons minimiser: $ \\large y \\approx \\hat{f}(x), \\large \\hat{f}(x) = \\underset{f(x)}{\\arg\\min} \\ L(y,f(x)) $.\n\n\n\nPour le moment, nous ne faisons aucune hypothèse concernant le type de dépendance $ \\large f(x) $, le modèle de notre approximation $ \\large \\hat{f}(x) $ ou la distribution de la variable cible $ \\large y $. Nous nous attendons seulement à ce que la fonction $ \\large L(y,f) $ soit différentiable. Notre approche est très générale : nous définissons $ \\large \\hat {f}(x) $ en minimisant la perte :\n$$ \\large \\hat{f}(x) = \\underset{f(x)}{\\arg\\min} \\ \\mathbb {E} _{x,y}[L(y,f(x))] $$\n\nMalheureusement, le nombre de fonctions $ \\large f(x) $ n'est pas simplement grand, mais son espace fonctionnel est infiniment dimensionnel. C'est pourquoi il est acceptable pour nous de limiter l'espace de recherche par une famille de fonctions $ \\large f(x, \\theta), \\theta \\in \\mathbb{R}^d $. Cela simplifie beaucoup l'objectif car nous avons maintenant une optimisation solvable des valeurs de paramètres:\n$ \\large \\hat{f}(x) = f(x, \\hat{\\theta}),$\n$$\\large \\hat{\\theta} = \\underset{\\theta}{\\arg\\min} \\ \\mathbb {E} _{x,y}[L(y,f(x,\\theta))] $$\n\nDes solutions analytiques simples pour trouver les paramètres optimaux $ \\large \\hat{\\theta} $ n'existant souvent pas, les paramètres sont généralement approximés de manière itérative. Pour commencer, nous écrivons la fonction de perte empirique $ \\large L_{\\theta}(\\hat{\\theta}) $ qui nous permettra d’évaluer nos paramètres en utilisant nos données. De plus, écrivons notre approximation $ \\large \\hat{\\theta} $ pour un certain nombre d'itérations $ \\large M $ sous forme de somme:\n$ \\large \\hat{\\theta} = \\sum_{i = 1}^M \\hat{\\theta_i}, \\\\\n\\large L_{\\theta}(\\hat{\\theta}) = \\sum_{i = 1}^N L(y_i,f(x_i, \\hat{\\theta}))$\n\nEnsuite, il ne reste plus qu'à trouver un algorithme itératif approprié pour minimiser $\\large L_{\\theta}(\\hat{\\theta})$. La descente de gradient est l'option la plus simple et la plus fréquemment utilisée. Nous définissons le gradient comme étant $\\large \\nabla L_{\\theta}(\\hat{\\theta})$ et y ajoutons nos évaluations itératives $\\large \\hat{\\theta_i}$ (puisque nous minimisons la perte, nous ajoutons le signe moins). Notre dernière étape consiste à initialiser notre première approximation $\\large \\hat{\\theta_0}$ et à choisir le nombre d'itérations $\\large M$. Passons en revue les étapes de cet algorithme inefficace et naïf pour approximer $\\large \\hat{\\theta}$:\n\n1. Définir l'approximation initiale des paramètres $\\large \\hat{\\theta} = \\hat{\\theta_0}$\n2. Pour chaque itération $\\large t = 1, \\dots, M$, répétez les étapes 3 à 7:\n3. Calculer le gradient de la fonction de perte $\\large \\nabla L_{\\theta}(\\hat{\\theta})$ pour l'approximation courante $\\large \\hat{\\theta}$\n$\\large \\nabla L_{\\theta}(\\hat{\\theta}) = \\left[\\frac{\\partial L(y, f(x, \\theta))}{\\partial \\theta}\\right]_{\\theta = \\hat{\\theta}}$\n4. Définir l'approximation itérative actuelle $\\large \\hat{\\theta_t}$ en fonction du gradient calculé\n$\\large \\hat{\\theta_t} \\leftarrow −\\nabla L_{\\theta}(\\hat{\\theta})$\n5. Mettre à jour l'approximation des paramètres $\\large \\hat{\\theta}$:\n$\\large \\hat{\\theta} \\leftarrow \\hat{\\theta} + \\hat{\\theta_t} = \\sum_{i = 0}^t \\hat{\\theta_i} $\n6. Enregistrer le résultat de l'approximation $\\large \\hat{\\theta}$:\n$\\large \\hat{\\theta} = \\sum_{i = 0}^M \\hat{\\theta_i} $\n7. Utiliser la fonction trouvée $\\large \\hat{f}(x) = f(x, \\hat{\\theta})$\n\n\n\n### Descente de gradient fonctionnel\n\nImaginons une seconde que nous puissions améliorer l'optimisation dans l'espace des fonctions et rechercher de manière itérative les approximations $\\large \\hat{f}(x)$ en tant que fonctions elles-mêmes. Nous allons exprimer notre approximation comme une somme d'améliorations incrémentales, chacune étant une fonction. Pour plus de commodité, nous commencerons immédiatement par la somme de l'approximation initiale $\\large \\hat{f_0}(x)$:\n$$\\large \\hat{f}(x) = \\sum_{i = 0}^M \\hat{f_i}(x)$$\n\nRien n'est encore arrivé. nous avons seulement décidé de chercher notre approximation $\\large \\hat{f}(x)$ non pas comme un grand modèle avec beaucoup de paramètres (par exemple, un réseau de neurones), mais comme une somme de fonctions prétendant que nous nous déplaçons dans un espace fonctionnel.\n\nAfin d'accomplir cette tâche, nous devons limiter notre recherche à une famille de fonctions $\\large \\hat{f}(x) = h(x, \\theta)$. Il y a quelques problèmes ici - tout d’abord, la somme des modèles peut être plus compliquée que n’importe quel modèle de cette famille; Deuxièmement, l'objectif général est toujours dans l'espace fonctionnel. Notons qu'à chaque étape, nous devrons choisir un coefficient optimal $\\large \\rho \\in \\mathbb{R}$. Pour l'étape $\\large t$, le problème est le suivant:\n$$\\large \\hat{f}(x) = \\sum_{i = 0}^{t-1} \\hat{f_i}(x), \\\\\n\\large (\\rho_t,\\theta_t) = \\underset{\\rho,\\theta}{\\arg\\min} \\ \\mathbb {E} _{x,y}[L(y,\\hat{f}(x) + \\rho \\cdot h(x, \\theta))], \\\\\n\\large \\hat{f_t}(x) = \\rho_t \\cdot h(x, \\theta_t)$$\n\nC'est ici que la magie opère. Nous avons défini tous nos objectifs en termes généraux, comme si nous pouvions former tout type de modèle $\\large h(x, \\theta)$ pour n’importe quel type de fonction de perte $\\large L(y, f(x, \\theta))$. En pratique, c'est extrêmement difficile, mais heureusement, il existe un moyen simple de résoudre ce problème.\n\nConnaissant l'expression du gradient de la fonction de perte, nous pouvons calculer sa valeur sur nos données. Donc, entraînons les modèles de telle sorte que nos prédictions soient davantage corrélées à ce gradient (avec un signe moins). En d'autres termes, nous allons utiliser les moindres carrés pour corriger les prédictions avec ces résidus. Pour les tâches de classification, de régression et de classement, nous minimiserons la différence quadratique entre les pseudo-résidus $\\large r$ et nos prédictions. Pour l'étape $\\large t$, le problème final se présente comme suit:\n$$ \\large \\hat{f}(x) = \\sum_{i = 0}^{t-1} \\hat{f_i}(x), \\\\\n\\large r_{it} = -\\left[\\frac{\\partial L(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x)=\\hat{f}(x)}, \\quad \\mbox{for } i=1,\\ldots,n ,\\\\\n\\large \\theta_t = \\underset{\\theta}{\\arg\\min} \\ \\sum_{i = 1}^{n} (r_{it} - h(x_i, \\theta))^2, \\\\\n\\large \\rho_t = \\underset{\\rho}{\\arg\\min} \\ \\sum_{i = 1}^{n} L(y_i, \\hat{f}(x_i) + \\rho \\cdot h(x_i, \\theta_t))$$\n\n\n\n### L'algorithme GBM classique de Friedman\n\nNous pouvons maintenant définir l’algorithme GBM classique proposé par Jerome Friedman en 1999. C’est un algorithme supervisé qui a les composants suivants:\n\n- ensemble de données $\\large \\left\\{ (x_i, y_i) \\right\\}_{i=1, \\ldots,n}$;\n- nombre d'itérations $\\large M$;\n- choix de la fonction de perte $\\large L(y, f)$ avec un gradient défini;\n- choix de la famille de fonctions des algorithmes de base $\\large h(x, \\theta)$ avec la procédure d'apprentissage;\n- hyperparamètres supplémentaires $\\large h(x, \\theta)$ (par exemple, dans les arbres de décision, la profondeur de l’arbre);\n\nLa seule chose qui reste est l'approximation initiale $\\large f_0(x)$. Pour simplifier, pour une approximation initiale, une valeur constante $\\large \\gamma$ est utilisée. La valeur constante, ainsi que le coefficient optimal $\\large \\rho $, sont identifiés via une recherche binaire ou un autre algorithme de recherche de ligne sur la fonction de perte initiale (et non un gradient). Nous avons donc notre algorithme GBM décrit comme suit:\n\n1. Initialiser GBM avec une valeur constante $\\large \\hat{f}(x) = \\hat{f}_0, \\hat{f}_0 = \\gamma, \\gamma \\in \\mathbb{R}$\n$\\large \\hat{f}_0 = \\underset{\\gamma}{\\arg\\min} \\ \\sum_{i = 1}^{n} L(y_i, \\gamma)$\n2. Pour chaque itération $\\large t = 1, \\dots, M$, répéter :\n3. Calculer les pseudo-résidus $\\large r_t$\n$\\large r_{it} = -\\left[\\frac{\\partial L(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x)=\\hat{f}(x)}, \\quad \\mbox{for } i=1,\\ldots,n$\n4. Construire le nouvel algorithme de base $\\large h_t(x)$ sous forme de régression sur les pseudo-résidus $\\large \\left\\{ (x_i, r_{it}) \\right\\}_{i=1, \\ldots,n}$\n5. Trouver le coefficient optimal $\\large \\rho_t $ à $\\large h_t(x)$ concernant la fonction de perte initiale\n$\\large \\rho_t = \\underset{\\rho}{\\arg\\min} \\ \\sum_{i = 1}^{n} L(y_i, \\hat{f}(x_i) + \\rho \\cdot h(x_i, \\theta))$\n6. Enregistrer $\\large \\hat{f_t}(x) = \\rho_t \\cdot h_t(x)$\n7. Mettre à jour l'approximation courante $\\large \\hat{f}(x)$\n$\\large \\hat{f}(x) \\leftarrow \\hat{f}(x) + \\hat{f_t}(x) = \\sum_{i = 0}^{t} \\hat{f_i}(x)$\n8. Composez le mrdèle final GBM $\\large \\hat{f}(x)$\n$\\large \\hat{f}(x) = \\sum_{i = 0}^M \\hat{f_i}(x) $\n9. Conquérir Kaggle et le reste du monde\n\n### Exemple pas à pas: comment fonctionne la GBM\n\nVoyons un exemple du fonctionnement de la GBM. Dans cet exemple de basé sur un jeu, nous allons restaurer une fonction bruyante $\\large y = cos(x) + \\epsilon, \\epsilon \\sim \\mathcal{N}(0, \\frac{1}{5}), x \\in [-5,5]$.\n\n\n\nIl s’agit d’un problème de régression avec une cible à valeur réelle. Nous allons donc choisir d’utiliser la fonction de perte d’erreur quadratique moyenne. Nous allons générer 300 paires d'observations et les approximer avec des arbres de décision de profondeur 2. Réunissons tout ce dont nous avons besoin pour utiliser GBM:\n- Jeu de données $\\large \\left\\{ (x_i, y_i) \\right\\}_{i=1, \\ldots,300}$ ✓\n- Nombre d'itérations $\\large M = 3$ ✓;\n- La fonction de perte d'erreur quadratique moyenne $\\large L(y, f) = (y-f)^2$ ✓\n- Le gradient de perte en $\\large L(y, f) = L_2$ n'est que des résidus $\\large r = (y - f)$ ✓;\n- Arbre de décision en tant qu'algorithme de base $\\large h(x)$ ✓;\n- Hyperparamètres des arbres de décision : la profondeur des arbres est égale à 2 ✓;\n\nPour l'erreur quadratique moyenne, l'initialisation $\\large \\gamma$ et les coefficients $\\large \\rho_t$ sont simples. Nous initialiserons GBM avec la valeur moyenne $\\large \\gamma = \\frac{1}{n} \\cdot \\sum_{i = 1}^n y_i$ et définirons tous les coefficients $\\large \\rho_t$ sur 1.\n\nNous allons lancer GBM et dessiner deux types de graphes : l’approximation courante $\\large \\hat{f}(x)$ (graphe bleu) et chaque arbre $\\large \\hat{f_t}(x)$ construit sur ses pseudo-résidus (graphe vert). Le numéro du graphique correspond au numéro d'itération :\n\n\n\nÀ la deuxième itération, nos arbres ont retrouvé la forme de base de la fonction. Cependant, à la première itération, nous voyons que l'algorithme n'a construit que la \"branche gauche\" de la fonction ($\\large x \\in [-5, -4]$). Cela était dû au fait que nos arbres n’avaient tout simplement pas assez de profondeur pour construire une branche symétrique à la fois et qu’ils se concentraient sur la branche gauche présentant l’erreur la plus grande. Par conséquent, la branche de droite n'est apparue qu'après la deuxième itération.\n\nLe reste du processus se déroule comme prévu : à chaque étape, nos pseudo-résidus ont diminué et GBM a amélioré de mieux en mieux la fonction d'origine à chaque itération. Cependant, par construction, les arbres ne peuvent pas se rapprocher d'une fonction continue, ce qui signifie que GBM n'est pas idéal dans cet exemple. Pour jouer avec les approximations de fonctions GBM, vous pouvez utiliser la démo interactive impressionnante de ce blog intitulée [Brilliantly wrong](http://arogozhnikov.github.io/2016/06/24/gradient_boosting_explained.html) :\n\n\n\n# 3. Fonctions de perte\n\nSi nous voulons résoudre un problème de classification au lieu d'une régression, qu'est-ce qui changerait ? Il suffit de choisir une fonction de perte appropriée, $\\large L(y, f)$. C’est le moment le plus important qui détermine exactement comment nous allons optimiser et à quelles caractéristiques nous pouvons nous attendre dans le modèle final.\n\nEn règle générale, nous n'avons pas besoin de l'inventer nous-mêmes : les chercheurs l'ont déjà fait pour nous. Aujourd'hui, nous allons explorer les fonctions de perte pour les deux objectifs les plus courants : la régression $\\large y \\in \\mathbb{R}$ et la classification binaire $\\large y \\in \\left\\{-1, 1\\right\\}$.\n\n### Fonctions de perte liées à la régression\n\nCommençons par un problème de régression pour $\\large y \\in \\mathbb{R}$. Afin de choisir la fonction de perte appropriée, nous devons déterminer quelles propriétés de la distribution conditionnelle $\\large (y|x)$ nous souhaitons restaurer. Les options les plus courantes sont:\n\n- $\\large L(y, f) = (y - f)^2$ a.k.a. $\\large L_2$ perte ou perte gaussienne. C'est la moyenne conditionnelle classique, qui est le cas le plus simple et le plus courant. Si nous n'avons pas d'informations supplémentaires ou d'exigences pour qu'un modèle soit robuste, nous pouvons utiliser la perte gaussienne.\n- perte $\\large L_1$ ou $\\large L_1$ ou perte laplacienne. Au premier abord, cette fonction ne semble pas pouvoir être différenciée, mais définit en réalité la médiane conditionnelle. Comme nous le savons, la médiane est robuste aux valeurs aberrantes, raison pour laquelle cette fonction de perte est meilleure dans certains cas. La pénalité pour les grandes variations n’est pas aussi lourde que dans $\\large L_2$.\n- $ \\large \\begin{equation} L(y, f) =\\left\\{ \\begin{array}{@{}ll@{}} (1 - \\alpha) \\cdot |y - f|, & \\text{if}\\ y-f \\leq 0 \\\\ \\alpha \\cdot |y - f|, & \\text{if}\\ y-f >0 \\end{array}\\right. \\end{equation}, \\alpha \\in (0,1)\n$ a.k.a. $\\large L_q$ perte ou perte de Quantile. Au lieu de la médiane, il utilise des quantiles. Par exemple, $\\large \\alpha = 0.75$ correspond au 75%-quantile. Nous pouvons voir que cette fonction est asymétrique et pénalise les observations qui se trouvent du côté droit du quantile défini.\n\n\n\nUtilisons la fonction de perte $\\large L_q$ sur nos données. L'objectif est de restaurer le quantile conditionnel de cosinus à 75%. Mettons tout en œuvre pour GBM:\n- Jeu de données $\\large \\left\\{ (x_i, y_i) \\right\\}_{i=1, \\ldots,300}$ ✓\n- Un nombre d'itérations $\\large M = 3$ ✓;\n- Fonction de perte pour les quantiles $ \\large \\begin{equation} L_{0.75}(y, f) =\\left\\{\n\\begin{array}{@{}ll@{}} 0.25 \\cdot |y - f|, & \\text{if}\\ y-f \\leq 0 \\\\ 0.75 \\cdot |y - f|, & \\text{if}\\ y-f >0 \\end{array}\\right. \\end{equation} $ ✓;\n- Gradient $\\large L_{0.75}(y, f)$ - fonction pondérée par $\\large \\alpha = 0.75$. Nous allons former un modèle basé sur des arbres pour la classification :\n$\\large r_{i} = -\\left[\\frac{\\partial L(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x)=\\hat{f}(x)} = $\n$\\large = \\alpha I(y_i > \\hat{f}(x_i) ) - (1 - \\alpha)I(y_i \\leq \\hat{f}(x_i) ), \\quad \\mbox{for } i=1,\\ldots,300$ ✓;\n- Arbre de décision en tant qu'algorithme de base $\\large h(x)$ ✓;\n- Hyperparamètre des arbres : profondeur = 2 ✓;\n\nPour notre approximation initiale, nous prendrons le quantile nécessaire de $\\large y$. Cependant, nous ne savons rien des coefficients optimaux $\\large \\rho_t$, nous allons donc utiliser la recherche par ligne standard. Les résultats sont les suivants :\n\n\n\nNous pouvons observer que, à chaque itération, $\\large r_{i} $ ne prend que 2 valeurs possibles, mais GBM est toujours capable de restaurer notre fonction initiale.\n\nLes résultats globaux de GBM avec fonction de perte quantile sont les mêmes que les résultats avec fonction de perte quadratique décalée par $\\large \\approx 0.135$. Mais si nous utilisions le 90%-quantile, nous n'aurions pas assez de données car les classes seraient déséquilibrées. Nous devons nous en souvenir lorsque nous traitons des problèmes non standard.\n\n*\"Quelques mots sur les fonctions de perte de régression\"*\n\nPour les tâches de régression, de nombreuses fonctions de perte ont été développées, certaines avec des propriétés supplémentaires. Par exemple, ils peuvent être robustes, comme dans la [fonction de perte de Huber](https://en.wikipedia.org/wiki/Huber_loss). Pour un petit nombre de valeurs aberrantes, la fonction de perte fonctionne comme $\\large L_2$, mais après un seuil défini, la fonction devient $\\large L_1$. Cela permet de réduire l'effet des valeurs aberrantes et de se concentrer sur l'image globale.\n\nNous pouvons illustrer cela avec l'exemple suivant. Les données sont générées à partir de la fonction $\\large y = \\frac{sin(x)}{x}$ avec ajout de bruit, un mélange de distributions normales et de distributions de Bernulli. Nous montrons les fonctions sur les graphes A-D et le GBM correspondant sur F-H (le graphe E représente la fonction initiale):\n\n [Taille originale](https://habrastorage.org/web/130/05b/222/13005b222e8a4eb68c3936216c05e276.jpg).\n\n\nDans cet exemple, nous avons utilisé des splines comme algorithme de base. Vous voyez, il ne faut pas toujours que ce soit des arbres pour le Bosting ?\n\nNous pouvons clairement voir la différence entre les fonctions $\\large L_2$, $\\large L_1$ et la perte de Huber. Si nous choisissons des paramètres optimaux pour la perte de Huber, nous pouvons obtenir la meilleure approximation possible parmi toutes nos options. La différence est également visible dans les quantiles de 10%, 50% et 90%.\n\nMalheureusement, la fonction de perte de Huber n’est prise en charge que par très peu de bibliothèques / packages populaires; h2o le supporte, mais pas XGBoost. Il est pertinent pour d'autres choses plus exotiques comme les [expectiles conditionnelles](https://www.slideshare.net/charthur/quantile-and-expectile-regression), mais il peut quand même s'agir de connaissances intéressantes.\n\n\n### Fonctions de perte de classification\n\nMaintenant, regardons le problème de classification binaire $\\large y \\in \\left\\{-1, 1\\right\\}$. Nous avons vu que GBM peut même optimiser des fonctions de perte non différenciables. Techniquement, il est possible de résoudre ce problème avec une perte de régression $\\large L_2$, mais ce ne serait pas correct.\n\nLa distribution de la variable cible nécessite que nous utilisions un \"log-likehood\", il nous faut donc différentes fonctions de perte pour les cibles multipliées par leurs prédictions : $\\large y \\cdot f$. Les choix les plus courants seraient les suivants: \n\n- $\\large L(y, f) = log(1 + exp(-2yf))$ ak.a. Perte logistique ou perte de Bernoulli. Cela a une propriété intéressante qui pénalise même les classes correctement prédites, ce qui aide non seulement à optimiser la perte, mais également à écarter davantage les classes, même si toutes les classes sont correctement prédites.\n- perte de $\\large L(y, f) = exp(-yf)$ a.k.a. AdaBoost. Le classique AdaBoost est équivalent à GBM avec cette fonction de perte. Conceptuellement, cette fonction est très similaire à la perte logistique, mais elle est plus pénalisée de façon exponentielle si la prédiction est fausse.\n\n\n\nGénérons un nouveau jeu de données pour notre problème de classification. En guise de base, nous prendrons notre cosinus \"bruyant\" et nous utiliserons la fonction de signe pour les classes de la variable cible. Nos données ressemblent à ceci (le \"jitter-noise\" est ajouté pour plus de clarté) :\n\n\n\n\nNous utiliserons la perte logistique pour rechercher ce que nous améliorons réellement. Donc, encore une fois, nous avons mis en place ce que nous allons utiliser pour GBM :\n- jeu de données $\\large \\left\\{ (x_i, y_i) \\right\\}_{i=1, \\ldots,300}, y_i \\in \\left\\{-1, 1\\right\\}$ ✓\n- Nombre d'itérations $\\large M = 3$ ✓;\n- Perte logistique en tant que fonction de perte, son gradient est calculé de la manière suivante :\n$\\large r_{i} = \\frac{2 \\cdot y_i}{1 + exp(2 \\cdot y_i \\cdot \\hat{f}(x_i)) }, \\quad \\mbox{for } i=1,\\ldots,300$ ✓;\n- Arbre de décision en tant qu'algorithme de base $\\large h(x)$ ✓;\n- Hyperparamètres des arbres de décision : la profondeur de l'arbre est égale à 2 ✓;\n\nCette fois, l'initialisation de l'algorithme est un peu plus difficile. Premièrement, nos classes sont déséquilibrées (63% contre 37%). Deuxièmement, il n’existe pas de formule analytique connue pour l’initialisation de notre fonction de perte, nous devons donc rechercher $\\large \\hat{f_0} = \\gamma$ via search :\n\n\n\n\nNotre approximation initiale optimale est d'environ -0,273. Vous auriez pu deviner que c'était négatif car il est plus rentable de tout prédire comme la classe la plus populaire, mais il n'y a pas de formule pour la valeur exacte. Maintenant, commençons enfin par GBM, et regardons ce qui se passe réellement sous le capot: \n\n\n\nL'algorithme a restauré avec succès la séparation entre nos classes. Vous pouvez voir comment les zones \"inférieures\" se séparent car les arbres sont plus confiants dans la prédiction correcte de la classe négative et comment se forment les deux étapes des classes mixtes. Il est clair que nous avons beaucoup d'observations correctement classées et un certain nombre d'observations avec des erreurs importantes qui sont apparues en raison du bruit dans les données.\n\n### Poids\n\nParfois, nous voulons une fonction de perte plus spécifique pour notre problème. Par exemple, dans les séries chronologiques financières, il se peut que nous souhaitions accorder plus de poids aux mouvements importants dans la série chronologique; pour la prévision du taux de désabonnement, il est plus utile de prédire le désabonnement des clients ayant un LTV élevé (ou une valeur à vie: combien d'argent un client rapportera-t-il à l'avenir ?). \n\n\n\nLe guerrier statistique inventerait sa propre fonction de perte, en écrivant le gradient (pour un entraînement plus efficace, incluez le Hessian) et vérifierait avec soin si cette fonction remplissait les propriétés requises. Cependant, il y a de fortes chances que quelqu'un commette une erreur quelque part, se heurte à des difficultés de calcul et consacre une quantité excessive de temps à la recherche.\n\nAu lieu de cela, un instrument très simple a été inventé (ce dont on se souvient rarement dans la pratique) : peser des observations et attribuer des fonctions de pondération. L'exemple le plus simple d'une telle pondération est la définition de pondérations pour la balance de classes. En général, si nous savons qu'un sous-ensemble de données, tant dans les variables d'entrée $\\large x$ que dans la variable cible $\\large y$, a une plus grande importance pour notre modèle, nous leur attribuons simplement une pondération plus importante, $\\large w(x,y)$. L’objectif principal est de satisfaire aux exigences générales en matière de poids: \n$$ \\large w_i \\in \\mathbb{R}, \\\\\n\\large w_i \\geq 0 \\quad \\mbox{for } i=1,\\ldots,n, \\\\\n\\large \\sum_{i = 1}^n w_i > 0 $$\n\nLes poids peuvent réduire considérablement le temps passé à ajuster la fonction de perte à la tâche que nous résolvons et encourager les expériences sur les propriétés des modèles cibles. L'attribution de ces poids est entièrement fonction de la créativité. Nous ajoutons simplement des poids scalaires:\n$$ \\large L_{w}(y,f) = w \\cdot L(y,f), \\\\\n\\large r_{it} = - w_i \\cdot \\left[\\frac{\\partial L(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x)=\\hat{f}(x)}, \\quad \\mbox{for } i=1,\\ldots,n$$\n\nIl est clair que, pour les poids arbitraires, nous ne connaissons pas les propriétés statistiques de notre modèle. Lier les poids aux valeurs $\\large y$ peut souvent être trop compliqué. Par exemple, l'utilisation de poids proportionnels à $\\large |y|$ dans la fonction de perte $\\large L_1$ n'est pas équivalente à la perte de $\\large L_2$ car le gradient ne prendra pas en compte les valeurs des prédictions elles-mêmes : $\\large \\hat{f}(x)$.\n\nNous mentionnons tout cela afin de mieux comprendre nos possibilités. Créons des poids très exotiques pour notre jeu de données. Nous allons définir une fonction de poids fortement asymétrique comme suit :\n$$ \\large \\begin{equation} w(x) =\\left\\{ \\begin{array}{@{}ll@{}} 0.1, & \\text{if}\\ x \\leq 0 \\\\ 0.1 + |cos(x)|, & \\text{if}\\ x >0 \\end{array}\\right. \\end{equation} $$\n\n\n\nAvec ces poids, nous nous attendons à obtenir deux propriétés : moins de détails pour les valeurs négatives de $\\large x$ et la forme de la fonction, similaire au cosinus initial. Nous reprenons les réglages des autres GBM de notre exemple précédent avec une classification incluant la recherche par ligne pour les coefficients optimaux. Regardons ce que nous avons :\n\n\n\nNous avons atteint le résultat escompté. Premièrement, nous pouvons voir à quel point les pseudo-résidus diffèrent fortement; à l'itération initiale, ils ressemblent presque au cosinus d'origine. Deuxièmement, la partie gauche du graphique de la fonction était souvent ignorée au profit de la droite, qui avait des poids plus importants. Troisièmement, la fonction que nous avons obtenue à la troisième itération a reçu suffisamment d’attention et a commencé à ressembler au cosinus original (elle a également légèrement sur-appris)\n\nLes poids sont un outil puissant mais risqué que nous pouvons utiliser pour contrôler les propriétés de notre modèle. Si vous souhaitez optimiser votre fonction de perte, essayez d'abord de résoudre un problème plus simple en ajoutant des pondérations aux observations, à votre discrétion.\n\n# 4. Conclusion\n\nAujourd'hui, nous avons appris la théorie derrière le Gradient Boosting. GBM n'est pas seulement un algorithme spécifique, mais une méthodologie commune pour la construction d'ensembles de modèles. De plus, cette méthodologie est suffisamment flexible et extensible - il est possible de former un grand nombre de modèles en tenant compte de différentes fonctions de perte avec une variété de fonctions de pondération.\n\nLa pratique et les compétitions ML montrent que, dans les problèmes classiques (à l’exception des images, de l’audio et des données très éparses), la GBM est souvent l’algorithme le plus efficace (pour ne pas mentionner les ensembles superposés et de haut niveau, où la GBM fait presque toujours partie intégrante). En outre, il existe de nombreuses adaptations de GBM [pour l'apprentissage par renforcement](https://arxiv.org/abs/1603.04119) (Minecraft, ICML 2016). En passant, l'algorithme Viola-Jones, qui est encore utilisé en vision par ordinateur, est basé sur [AdaBoost](https://en.wikipedia.org/wiki/Viola%E2%80%93Jones_object_detection_framework#Learning_algorithm).\n\nDans cet article, nous avons volontairement omis de poser des questions sur la régularisation, la stochasticité et les hyper-paramètres de GBM. Ce n'est pas par hasard que nous avons utilisé un petit nombre d'itérations $\\large M = 3$. Si nous utilisions 30 arbres au lieu de 3 et formions le GBM comme décrit, le résultat ne serait pas prévisible :\n\n\n\n\n\n\n\n[Démo interactive](http://arogozhnikov.github.io/2016/07/05/gradient_boosting_playground.html)\n\n# 5. Mission de démonstration\nVotre tâche consiste à battre les bases de référence dans le cadre de la compétition \"Flight delays\" de [Kaggle Inclass](https://www.kaggle.com/c/flight-delays-fall-2018). Vous recevez un [démarreur CatBoost](https://www.kaggle.com/kashnitsky/mlcourse-ai-fall-2019-catboost-starter), l'astuce consiste à proposer de bonnes caractéristiques (features).\n\n# 6. Ressources utiles\n- Liste des cours [site](https://mlcourse.ai), [course repo](https://github.com/Yorko/mlcourse.ai), and YouTube [channel](https://www.youtube.com/watch?v=QKTuw4PNOsU&list=PLVlY_7IJCMJeRfZ68eVfEcu-UcN9BbwiX)\n- Course materials as a [Kaggle Dataset](https://www.kaggle.com/kashnitsky/mlcourse)\n- mlcourse.ai lectures on gradient boosting: [theory](https://youtu.be/g0ZOtzZqdqk) and [practice](https://youtu.be/V5158Oug4W8)\n- [Original article](https://statweb.stanford.edu/~jhf/ftp/trebst.pdf) about GBM from Jerome Friedman\n- “Gradient boosting machines, a tutorial”, [paper](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3885826/) by Alexey Natekin, and Alois Knoll\n- [Chapter in Elements of Statistical Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/printings/ESLII_print10.pdf) from Hastie, Tibshirani, Friedman (page 337)\n- [Wiki](https://en.wikipedia.org/wiki/Gradient_boosting) article about Gradient Boosting\n- [Introduction to boosted trees (Xgboost docs)](https://xgboost.readthedocs.io/en/latest/tutorials/model.html)\n- [Video-lecture by Hastie](https://www.youtube.com/watch?v=wPqtzj5VZus) about GBM at h2o.ai conference\n- [CatBoost vs. Light GBM vs. XGBoost](https://towardsdatascience.com/catboost-vs-light-gbm-vs-xgboost-5f93620723db) on \"Towards Data Science\"\n- [Benchmarking and Optimization of\nGradient Boosting Decision Tree Algorithms](https://arxiv.org/abs/1809.04559), [XGBoost: Scalable GPU Accelerated Learning](https://arxiv.org/abs/1806.11248) - benchmarking CatBoost, Light GBM, and XGBoost (no 100% winner)\n", "meta": {"hexsha": "1c3155e06f78ea3a25926b7ff513edf7b08edcb1", "size": 52578, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter_french/topic10_boosting/topic10_gradient_boosting-fr_def.ipynb", "max_stars_repo_name": "salman394/AI-ml--course", "max_stars_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter_french/topic10_boosting/topic10_gradient_boosting-fr_def.ipynb", "max_issues_repo_name": "salman394/AI-ml--course", "max_issues_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter_french/topic10_boosting/topic10_gradient_boosting-fr_def.ipynb", "max_forks_repo_name": "salman394/AI-ml--course", "max_forks_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 97.0073800738, "max_line_length": 2282, "alphanum_fraction": 0.6978013618, "converted": true, "num_tokens": 12763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.2254166210386804, "lm_q1q2_score": 0.09438124254629754}} {"text": "\n\n\n\n## Data-driven Design and Analyses of Structures and Materials (3dasm)\n\n## Lecture 1\n\n### Miguel A. Bessa | M.A.Bessa@tudelft.nl | Associate Professor\n\n## Introduction\n\n**What:** A lecture of the \"3dasm\" course\n\n**Where:** This notebook comes from this [repository](https://github.com/bessagroup/3dasm_course)\n\n**Reference for entire course:** Murphy, Kevin P. *Probabilistic machine learning: an introduction*. MIT press, 2022. Available online [here](https://probml.github.io/pml-book/book1.html)\n\n**How:** We try to follow Murphy's book closely, but the sequence of Chapters and Sections is different. The intention is to use notebooks as an introduction to the topic and Murphy's book as a resource.\n* If working offline: Go through this notebook and read the book.\n* If attending class in person: listen to me (!) but also go through the notebook in your laptop at the same time. Read the book.\n* If attending lectures remotely: listen to me (!) via Zoom and (ideally) use two screens where you have the notebook open in 1 screen and you see the lectures on the other. Read the book.\n\n**Optional reference (the \"bible\" by the \"bishop\"... pun intended 😆) :** Bishop, Christopher M. *Pattern recognition and machine learning*. Springer Verlag, 2006.\n\n**References/resources to create this notebook:**\n* [Figure (Car stopping distance)](https://korkortonline.se/en/theory/reaction-braking-stopping/)\n* Snippets of code from this awesome [repo](https://github.com/gerdm/prml) by Gerardo Duran-Martin that replicates many figures in Bishop's book\n\nApologies in advance if I missed some reference used in this notebook. Please contact me if that is the case, and I will gladly include it here.\n\n## **OPTION 1**. Run this notebook **locally in your computer**:\n1. Install miniconda3 [here](https://docs.conda.io/en/latest/miniconda.html)\n2. Open a command window and create a virtual environment called \"3dasm\":\n```\nconda create -n 3dasm python=3 numpy scipy jupyter nb_conda matplotlib pandas scikit-learn rise tensorflow -c conda-forge\n```\n3. Install [git](https://github.com/git-guides/install-git), open command window & clone the repository to your computer:\n```\ngit clone https://github.com/bessagroup/3dasm_course\n```\n4. Load jupyter notebook by typing in (anaconda) command window (it will open in your internet browser):\n```\nconda activate 3dasm\njupyter notebook\n```\n5. Open notebook (3dasm_course/Lectures/Lecture1/3dasm_Lecture1.ipynb)\n\n**Short note:** My personal environment also has other packages that help me while teaching.\n\n> conda install -n 3dasm -c conda-forge jupyter_contrib_nbextensions hide_code\n\nThen in the 3dasm conda environment:\n\n> jupyter nbextension install --py hide_code --sys-prefix\n>\n> jupyter nbextension enable --py hide_code\n>\n> jupyter serverextension enable --py hide_code\n>\n> jupyter nbextension enable splitcell/splitcell\n\n## **OPTION 2**. Use **Google's Colab** (no installation required, but times out if idle):\n\n1. go to https://colab.research.google.com\n2. login\n3. File > Open notebook\n4. click on Github (no need to login or authorize anything)\n5. paste the git link: https://github.com/bessagroup/3dasm_course\n6. click search and then click on the notebook (*3dasm_course/Lectures/Lecture1/3dasm_Lecture1.ipynb*)\n\n\n```python\n# Basic plotting tools needed in Python.\n\nimport matplotlib.pyplot as plt # import plotting tools to create figures\nimport numpy as np # import numpy to handle a lot of things!\n\n%config InlineBackend.figure_format = \"retina\" # render higher resolution images in the notebook\nplt.style.use(\"seaborn\") # style for plotting that comes from seaborn\nplt.rcParams[\"figure.figsize\"] = (8,4) # rescale figure size appropriately for slides\n```\n\n## Outline for today\n\n* Introduction\n - Taking a probabilistic perspective on machine learning\n* Basics of univariate statistics\n - Continuous random variables\n - Probabilities vs probability densities\n - Moments of a probability distribution\n* The mindblowing Bayes' rule\n - The rule that spawns almost every ML model (even when we don't realize it)\n\n**Reading material**: This notebook + Chapter 2 until Section 2.3\n\n## Get hyped about Artificial Intelligence...\n\n\n```python\nfrom IPython.display import display, YouTubeVideo, HTML\nYouTubeVideo('RNnZwvklwa8', width=512, height=288) # show that slides are interactive:\n # rescale video to 768x432 and back to 512x288\n```\n\n\n\n\n\n\n\n\n\n\n**Well...** This class *might* not make you break the world (yet!). Let's focus on the fundamentals:\n\n* Probabilistic perspective on machine learning\n* Supervised learning (especially regression)\n\n## Machine learning (ML)\n\n* **ML definition**: A computer program that learns from experience $E$ wrt tasks $T$ such that the performance $P$ at those tasks improves with experience $E$.\n\n* We'll treat ML from a **probabilistic perspective**:\n - Treat all unknown quantities as **random variables**\n \n* What are random variables?\n - Variables endowed with probability distributions!\n\n## The car stopping distance problem\n\n\n\n

\nCar stopping distance ${\\color{red}y}$ as a function of its velocity ${\\color{green}x}$ before it starts braking:\n\n${\\color{red}y} = {\\color{blue}z} x + \\frac{1}{2\\mu g} {\\color{green}x}^2 = {\\color{blue}z} x + 0.1 {\\color{green}x}^2$\n\n- ${\\color{blue}z}$ is the driver's reaction time (in seconds)\n- $\\mu$ is the road/tires coefficient of friction (assume $\\mu=0.5$)\n- $g$ is the acceleration of gravity (assume $g=10$ m/s$^2$).\n\n## The car stopping distance problem\n\n### How to obtain this formula?\n\n$y = d_r + d_{b}$\n\nwhere $d_r$ is the reaction distance, and $d_b$ is the braking distance.\n\n### Reaction distance $d_r$\n\n$d_r = z x$\n\nwith $z$ being the driver's reaction time, and $x$ being the velocity of the car at the start of braking.\n\n## The car stopping distance problem\n\n### Braking distance $d_b$\n\nKinetic energy of moving car:\n\n$E = \\frac{1}{2}m x^2$       where $m$ is the car mass.\n\nWork done by braking:\n\n$W = \\mu m g d_b$       where $\\mu$ is the coefficient of friction between the road and the tire, $g$ is the acceleration of gravity, and $d_b$ is the car braking distance.\n\nThe braking distance follows from $E=W$:\n\n$d_b = \\frac{1}{2\\mu g}x^2$\n\nTherefore, if we add the reacting distance $d_r$ to the braking distance $d_b$ we get the stopping distance $y$:\n\n$$y = d_r + d_b = z x + \\frac{1}{2\\mu g} x^2$$\n\n## The car stopping distance problem\n\n\n\n$y = {\\color{blue}z} x + 0.1 x^2$\n\nThe driver's reaction time ${\\color{blue}z}$ is a **random variable (rv)**\n\n* Every driver has its own reaction time $z$\n\n* Assume the distribution associated to $z$ is Gaussian with **mean** $\\mu_z=1.5$ seconds and **variance** $\\sigma_z^2=0.5$ seconds$^2$\n\n$$\nz \\sim \\mathcal{N}(\\mu_z=1.5,\\sigma_z^2=0.5^2)\n$$\n\nwhere $\\sim$ means \"sampled from\", and $\\mathcal{N}$ indicates a Gaussian **probability density function (pdf)**\n\n## Univariate Gaussian pdf \n\nThe gaussian pdf is defined as:\n\n$$\n \\mathcal{N}(z | \\mu_z, \\sigma_z^2) = \\frac{1}{\\sqrt{2\\pi\\sigma_z^2}}e^{-\\frac{1}{2\\sigma_z^2}(z - \\mu_z)^2}\n$$\n\nAlternatively, we can write it using the **precision** term $\\lambda_z := 1 / \\sigma_z^2$ instead of using $\\sigma_z^2$:\n\n$$\n \\mathcal{N}(z | \\mu_z, \\lambda_z^{-1}) = \\frac{\\lambda_z^{1/2}}{\\sqrt{2\\pi}}e^{-\\frac{\\lambda_z}{2}(z - \\mu_z)^2}\n$$\n\nAnyway, recall how this pdf looks like...\n\n\n```python\ndef norm_pdf(z, mu_z, sigma_z2): return 1 / np.sqrt(2 * np.pi * sigma_z2) * np.exp(-(z - mu_z)**2 / (2 * sigma_z2))\nzrange = np.linspace(-8, 4, 200) # create a list of 200 z points between z=-8 and z=4\nfig, ax = plt.subplots() # create a plot\nax.plot(zrange, norm_pdf(zrange, 0, 1), label=r\"$\\mu_z=0; \\ \\sigma_z^2=1$\") # plot norm_pdf(z|0,1)\nax.plot(zrange, norm_pdf(zrange, 1.5, 0.5**2), label=r\"$\\mu_z=1.5; \\ \\sigma_z^2=0.5^2$\") # plot norm_pdf(z|1.5,0.5^2)\nax.plot(zrange, norm_pdf(zrange, -1, 2**2), label=r\"$\\mu_z=-1; \\ \\sigma_z^2=2^2$\") # plot norm_pdf(z|-1,2^2)\nax.set_xlabel(\"z\", fontsize=20) # create x-axis label with font size 20\nax.set_ylabel(\"probability density\", fontsize=20) # create y-axis label with font size 20\nax.legend(fontsize=15) # create legend with font size 15\nax.set_title(\"Three different Gaussian pdfs\", fontsize=20); # create title with font size 20\n```\n\nThe green curve shows the Gaussian pdf of the rv $z$ **conditioned** on the mean $\\mu_z=1.5$ and variance $\\sigma_z^2=0.5^2$ for the car stopping distance problem.\n\n## Univariate Gaussian pdf \n\n$$\n p(z) = \\mathcal{N}(z | \\mu_z, \\sigma_z^2) = \\frac{1}{\\sqrt{2\\pi\\sigma_z^2}}e^{-\\frac{1}{2\\sigma_z^2}(z - \\mu_z)^2}\n$$\n\nThe output of this expression is the **PROBABILITY DENSITY** of $z$ **given** (or conditioned to) a particular $\\mu_z$ and $\\sigma_z^2$.\n\n* **Important**: Probability Density $\\neq$ Probability\n\nSo, what is a probability?\n\n## Probability\n\nThe probability of an event $A$ is denoted by $\\text{Pr}(A)$.\n\n* $\\text{Pr}(A)$ means the probability with which we believe event A is true\n\n* An event $A$ is a binary variable saying whether or not some state of the world holds.\n\nProbability is defined such that: $0 \\leq \\text{Pr}(A) \\leq 1$\n\nwhere $\\text{Pr}(A)=1$ if the event will definitely happen and $\\text{Pr}(A)=0$ if it definitely will not happen.\n\n## Joint probability\n\n**Joint probability** of two events: $\\text{Pr}(A \\wedge B)= \\text{Pr}(A, B)$\n\nIf $A$ and $B$ are **independent**: $\\text{Pr}(A, B)= \\text{Pr}(A) \\text{Pr}(B)$\n\nFor example, suppose $z_1$ and $z_2$ are chosen uniformly at random from the set $\\mathcal{Z} = \\{1, 2, 3, 4\\}$.\n\nLet $A$ be the event that $z_1 \\in \\{1, 2\\}$ and $B$ be the event that **another** rv denoted as $z_2 \\in \\{3\\}$.\n\nThen we have: $\\text{Pr}(A, B) = \\text{Pr}(A) \\text{Pr}(B) = \\frac{1}{2} \\cdot \\frac{1}{4}$.\n\n## Probability of a union of two events\n\nProbability of event $A$ or $B$ happening is: $\\text{Pr}(A \\vee B)= \\text{Pr}(A) + \\text{Pr}(B) - \\text{Pr}(A \\wedge B)$\n\nIf these events are mutually exclusive (they can't happen at the same time):\n\n$$\n\\text{Pr}(A \\vee B)= \\text{Pr}(A) + \\text{Pr}(B)\n$$\n\nFor example, suppose an rv denoted as $z_1$ is chosen uniformly at random from the set $\\mathcal{Z} = \\{1, 2, 3, 4\\}$.\n\nLet $A$ be the event that $z_1 \\in \\{1, 2\\}$ and $B$ be the event that the **same** rv $z_1 \\in \\{3\\}$.\n\nThen we have $\\text{Pr}(A \\vee B) = \\frac{2}{4} + \\frac{1}{4}$.\n\n## Conditional probability of one event given another\n\nWe define the **conditional probability** of event $B$ happening given that $A$ has occurred as follows:\n\n$$\n\\text{Pr}(B | A)= \\frac{\\text{Pr}(A,B)}{\\text{Pr}(A)}\n$$\n\nThis is not defined if $\\text{Pr}(A) = 0$, since we cannot condition on an impossible event.\n\n## Conditional independence of one event given another\n\nWe say that event $A$ is conditionally independent of event $B$ if we have $\\text{Pr}(A | B)= \\text{Pr}(A)$\n\nThis implies $\\text{Pr}(B|A) = \\text{Pr}(B)$. Hence, the joint probability becomes $\\text{Pr}(A, B) = \\text{Pr}(A) \\text{Pr}(B)$\n\nThe book uses the notation $A \\perp B$ to denote this property.\n\n## Coming back to our car stopping distance problem\n\n\n\n$y = {\\color{blue}z} x + 0.1 x^2$\n\nwhere $z$ is a **continuous** rv such that $z \\sim \\mathcal{N}(\\mu_z=1.5,\\sigma_z^2=0.5^2)$.\n\n* What is the probability of an event $Z$ defined by a reaction time $z \\leq 0.52$ seconds?\n\n$$\n\\text{Pr}(Z)=\\text{Pr}(z \\leq 0.52)= P(z=0.52)\n$$\n\nwhere $P(z)$ denotes the **cumulative distribution function (cdf)**. Note that cdf is denoted with a capital $P$.\n\nLikewise, we can compute the probability of being in any interval as follows:\n\n$\\text{Pr}(a \\leq z \\leq b)= P(z=b)-P(z=a)$\n\n* But how do we compute the cdf at a particular value $b$, e.g. $P(z=b)$?\n\n## Cdf's result from pdf's\n\nA pdf $p(z)$ is defined as the derivative of the cdf $P(z)$:\n\n$$\np(z)=\\frac{d}{d z}P(z)\n$$\n\nSo, given a pdf $p(z)$, we can compute the following probabilities:\n\n$$\\text{Pr}(z \\leq b)=\\int_{-\\infty}^b p(z) dz = P(b)$$\n$$\\text{Pr}(z \\geq a)=\\int_a^{\\infty} p(z) dz = 1 - P(a)$$\n$$\\text{Pr}(a \\leq z \\leq b)=\\int_a^b p(z) dz = P(b) - P(a)$$\n\n**IMPORTANT**: $\\int_{-\\infty}^{\\infty} p(z) dz = 1$\n\n### Some notes about pdf's\n\nThe integration to unity is important!\n\n$$\\int_{-\\infty}^{\\infty} p(z) dz = 1$$\n\n**Remember:** the integral of a pdf leads to a probability, and probabilities cannot be larger than 1.\n\nFor example, from this property we can derive the following:\n\n$$\n\\int_{-\\infty}^{\\infty} p(z) dz = \\int_{-\\infty}^{a} p(z) dz + \\int_{a}^{\\infty} p(z) dz\n$$\n\n$$\n\\Rightarrow \\text{Pr}(z \\geq a)= 1 - \\text{Pr}(z \\leq a) = 1 - \\text{P}(a) = 1 - \\int_{-\\infty}^a p(z) dz\n$$\n\nIn some cases we will work with probability distributions that are **unnormalized**, so this comment is important!\n\n* Being unnormalized means that the probability density of the distribution does not integrate to 1.\n* In this case, we cannot call such function a pdf, even though its output is a probability density.\n\n## Cdf's result from pdf's\n\nKey point?\n\n* Given a pdf $p(z)$, we can compute the probability of a continuous rv $z$ being in a finite interval as follows:\n\n$$\n\\text{Pr}(a \\leq z \\leq b)=\\int_a^b p(z) dz = P(b) - P(a)\n$$\n\nAs the size of the interval gets smaller, we can write\n\n$$\n\\text{Pr}\\left(z - \\frac{dz}{2} \\leq z \\leq z + \\frac{dz}{2}\\right) \\approx p(z) dz\n$$\n\nIntuitively, this says the probability of $z$ being in a small interval around $z$ is the density at $z$ times\nthe width of the interval.\n\n\n```python\nfrom scipy.stats import norm # import from scipy.stats the normal distribution\n\nzrange = np.linspace(-3, 3, 100) # 100 values for plot\nfig_std_norm, (ax1, ax2) = plt.subplots(1, 2) # create a plot with 2 subplots side-by-side\nax1.plot(zrange, norm.cdf(zrange, 0, 1), label=r\"$\\mu_z=0; \\ \\sigma_z=1$\") # plot cdf of standard normal\nax1.set_xlabel(\"z\", fontsize=20)\nax1.set_ylabel(\"probability\", fontsize=20)\nax1.legend(fontsize=15)\nax1.set_title(\"Standard Gaussian cdf\", fontsize=20)\n\nax2.plot(zrange, norm.pdf(zrange, 0, 1), label=r\"$\\mu_z=0; \\ \\sigma_z=1$\") # plot pdf of standard normal\nax2.set_xlabel(\"z\", fontsize=20)\nax2.set_ylabel(\"probability density\", fontsize=20)\nax2.legend(fontsize=15)\nax2.set_title(\"Standard Gaussian pdf\", fontsize=20)\nfig_std_norm.set_size_inches(25, 5) # scale figure to be wider (since there are 2 subplots)\n```\n\n## Note about scipy.stats\n\n[scipy](https://docs.scipy.org/doc/scipy/index.html) is an open-source software for mathematics, science, and engineering. It's brilliant and widely used for many things!\n\n**In particular**, [scipy.stats](https://docs.scipy.org/doc/scipy/reference/stats.html) is a simple module within scipy that has statistical functions and operations that are very useful. This way, we don't need to code all the functions ourselves. That's why we are using it to plot the cdf and pdf of the Gaussian distribution from now on, and we will use it for other things later.\n\n* In case you are interested, scipy.stats has a nice [tutorial](https://docs.scipy.org/doc/scipy/tutorial/stats.html)\n\n## Coming back to our car stopping distance problem\n\n\n\n$y = {\\color{blue}z} x + 0.1 x^2$\n\nwhere $z$ is a continuous rv such that $p(z)= \\mathcal{N}(z | \\mu_z=1.5,\\sigma_z^2=0.5^2)$.\n\n* What is the probability of an event $Z$ defined by a reaction time $z \\leq 0.52$ seconds?\n\n$$\n\\text{Pr}(Z) = \\text{Pr}(z \\leq 0.52) = P(z=0.52) = \\int_{-\\infty}^{0.52} p(z) dz\n$$\n\n\n```python\nPr_Z = norm.cdf(0.52, 1.5, 0.5) # using scipy norm.cdf(z=0.52 | mu_z=1.5, sigma_z=0.5)\n\nprint(\"The probability of event Z is: Pr(Z) = \",round(Pr_Z,3))\n```\n\n The probability of event Z is: Pr(Z) = 0.025\n\n\n\n```python\nz_value = 0.52 # z = 0.52 seconds\nzrange = np.linspace(0, 3, 200) # 200 values for plot\nfig_car_norm, (ax1, ax2) = plt.subplots(1, 2) # create subplot (two figures in 1)\nax1.plot(zrange, norm.cdf(zrange, 1.5, 0.5), label=r\"$\\mu_z=1.5; \\ \\sigma_z=0.5$\") # Figure 1 is cdf\nax1.plot(z_value, norm.cdf(z_value, 1.5, 0.5), 'r*',markersize=15, linewidth=2,\n label=u'$P(z=0.52~|~\\mu_z=1.5, \\sigma_z^2=0.5^2)$')\nax1.set_xlabel(\"z\", fontsize=20)\nax1.set_ylabel(\"probability\", fontsize=20)\nax1.legend(fontsize=15)\nax1.set_title(\"Gaussian cdf of $z$ for car problem\", fontsize=20)\nax2.plot(zrange, norm.pdf(zrange, 1.5, 0.5), label=r\"$\\mu_z=1.5; \\ \\sigma_z=0.5$\") # figure 2 is pdf\nax2.plot(z_value, norm.pdf(z_value, 1.5, 0.5), 'r*', markersize=15, linewidth=2,\n label=u'$p(z=0.52~|~\\mu_z=1.5, \\sigma_z^2=0.5^2)$')\nax2.set_xlabel(\"z\", fontsize=20)\nax2.set_ylabel(\"probability density\", fontsize=20)\nax2.legend(fontsize=15)\nax2.set_title(\"Gaussian pdf of $z$ for car problem\", fontsize=20)\nfig_car_norm.set_size_inches(25, 5) # scale figure to be wider (since there are 2 subplots)\n```\n\n### Why is the Gaussian distribution so widely used?\n\nSeveral reasons:\n\n1. It has two parameters which are easy to interpret, and which capture some of the most basic properties of a distribution, namely its mean and variance.\n2. The central limit theorem (Sec. 2.8.6 of the book) tells us that sums of independent random variables have an approximately Gaussian distribution, making it a good choice for modeling residual errors or “noise”.\n3. The Gaussian distribution makes the least number of assumptions (has maximum entropy), subject to the constraint of having a specified mean and variance (Sec. 3.4.4 of the book); this makes it a good default choice in many cases.\n4. It has a simple mathematical form, which results in easy to implement, but often highly effective, methods.\n\n## Car stopping distance problem\n\n\n\n$y = {\\color{blue}z} x + 0.1 x^2$\n\nwhere $z$ is a continuous rv such that $z \\sim \\mathcal{N}(\\mu_z=1.5,\\sigma_z^2=0.5^2)$.\n\n* What is the **expected** value for the reaction time $z$?\n\nThis is not a trick question! It's the mean $\\mu_z$, of course!\n\n* But how do we compute the expected value for any distribution?\n\n## Moments of a distribution\n\n### First moment: Expected value or mean\n\nThe expected value (mean) of a distribution is the **first moment** of the distribution:\n\n$$\n\\mathbb{E}[z]= \\int_{\\mathcal{Z}}z p(z) dz\n$$\n\nwhere $\\mathcal{Z}$ indicates the support of the distribution (the $z$ domain). \n\n* Often, $\\mathcal{Z}$ is omitted as it is usually between $-\\infty$ to $\\infty$\n* The expected value $\\mathbb{E}[z]$ is often denoted by $\\mu_z$\n\nAs you might expect (pun intended 😆), the expected value is a linear operator:\n\n$$\n\\mathbb{E}[az+b]= a\\mathbb{E}[z] + b\n$$\n\nwhere $a$ and $b$ are fixed variables (NOT rv's).\n\nAdditionally, for a set of $n$ rv's, one can show that the expectation of their sum is as follows:\n\n$\\mathbb{E}\\left[\\sum_{i=1}^n z_i\\right]= \\sum_{i=1}^n \\mathbb{E}[z_i]$\n\nIf they are **independent**, the expectation of their product is given by\n\n$\\mathbb{E}\\left[\\prod_{i=1}^n z_i\\right]= \\prod_{i=1}^n \\mathbb{E}[z_i]$\n\n## Moments of a distribution\n\n### Second moment (and relation to Variance)\n\nThe 2nd moment of a distribution $p(z)$ is:\n\n$$\n\\mathbb{E}[z^2]= \\int_{\\mathcal{Z}}z^2 p(z) dz\n$$\n\n#### Variance can be obtained from the 1st and 2nd moments\n\nThe variance is a measure of the “spread” of the distribution:\n\n$$\n\\mathbb{V}[z] = \\mathbb{E}[(z-\\mu_z)^2] = \\int (z-\\mu_z)^2 p(z) dz = \\mathbb{E}[z^2] - \\mu_z^2\n$$\n\n* It is often denoted by the square of the standard deviation, i.e. $\\sigma_z^2 = \\mathbb{V}[z] = \\mathbb{E}[(z-\\mu_z)^2]$\n\n#### Elaboration of the variance as a result of the first two moments of a distribution\n\n$$\n\\begin{align}\n\\mathbb{V}[z] & = \\mathbb{E}[(z-\\mu_z)^2] \\\\\n& = \\int (z-\\mu_z)^2 p(z) dz \\\\\n& = \\int z^2 p(z) dz + \\mu_z^2 \\int p(z) dz - 2\\mu_z \\int zp(z) dz \\\\\n& = \\mathbb{E}[z^2] - \\mu_z^2\n\\end{align}\n$$\n\nwhere $\\mu_z = \\mathbb{E}[z]$ is the first moment, and $\\mathbb{E}[z^2]$ is the second moment.\n\nTherefore, we can also write the second moment of a distribution as\n\n$$\\mathbb{E}[z^2] = \\sigma_z^2 + \\mu_z^2$$\n\n#### Variance and standard deviation properties\n\nThe standard deviation is defined as\n\n$ \\sigma_z = \\text{std}[z] = \\sqrt{\\mathbb{V}[z]}$\n\nThe variance of a shifted and scaled version of a random variable is given by\n\n$\\mathbb{V}[a z + b] = a^2\\mathbb{V}[z]$\n\nwhere $a$ and $b$ are fixed variables (NOT rv's).\n\nIf we have a set of $n$ independent rv's, the variance of their sum is given by the sum of their variances\n\n$$\n\\mathbb{V}\\left[\\sum_{i=1}^n z_i\\right] = \\sum_{i=1}^n \\mathbb{V}[z_i]\n$$\n\nThe variance of their product can also be derived, as follows:\n\n$$\n\\begin{align}\n\\mathbb{V}\\left[\\prod_{i=1}^n z_i\\right] & = \\mathbb{E}\\left[ \\left(\\prod_i z_i\\right)^2 \\right] - \\left( \\mathbb{E}\\left[\\prod_i z_i \\right]\\right)^2\\\\\n & = \\mathbb{E}\\left[ \\prod_i z_i^2 \\right] - \\left( \\prod_i\\mathbb{E}\\left[ z_i \\right]\\right)^2\\\\\n & = \\prod_i \\mathbb{E}\\left[ z_i^2 \\right] - \\prod_i\\left( \\mathbb{E}\\left[ z_i \\right]\\right)^2\\\\\n & = \\prod_i \\left( \\mathbb{V}\\left[ z_i \\right] +\\left( \\mathbb{E}\\left[ z_i \\right]\\right)^2 \\right)- \\prod_i\\left( \\mathbb{E}\\left[ z_i \\right]\\right)^2\\\\\n & = \\prod_i \\left( \\sigma_{z,\\,i}^2 + \\mu_{z,\\,i}^2 \\right)- \\prod_i\\mu_{z,\\,i}^2 \\\\\n\\end{align}\n$$\n\n## Note about higher-order moments\n\n* The $k$-th moment of a distribution $p(z)$ is defined as the expected value of the $k$-th power of $z$, i.e. $z^k$:\n\n$$\n\\mathbb{E}[z^k]= \\int_{\\mathcal{Z}}z^k p(z) dz\n$$\n\n## Mode of a distribution\n\nThe mode of an rv $z$ is the value of $z$ for which $p(z)$ is maximum.\n\nFormally, this is written as,\n\n$$ \\mathbf{z}^* = \\underset{z}{\\mathrm{argmax}}~p(z)$$\n\nIf the distribution is multimodal, this may not be unique:\n* That's why $\\mathbf{z}^*$ is in **bold**, to denote that in general it is a vector that is retrieved!\n* However, if the distribution is unimodal (one maximum), like the univariate Gaussian distribution, then it retrieves a scalar $z^*$\n\nNote that even if there is a unique mode, this point may not be a good summary of the distribution.\n\n## Mean vs mode for a non-symmetric distribution\n\n\n```python\n# 1. Create a gamma pdf with parameter a = 2.0\n\nfrom scipy.stats import gamma # import from scipy.stats the Gamma distribution\n\na = 2.0 # this is the only input parameter needed for this distribution\n\n# Define the support of the distribution (its domain) by using the\n# inverse of the cdf (called ppf) to get the lowest z of the plot that\n# corresponds to Pr = 0.01 and the highest z of the plot that corresponds\n# to Pr = 0.99:\nzrange = np.linspace(gamma.ppf(0.01, a), gamma.ppf(0.99, a), 200) \n\nmu_z, var_z = gamma.stats(2.0, moments='mv') # This computes the mean and variance of the pdf\n\nfig_gamma_pdf, ax = plt.subplots() # a trick to save the figure for later use\nax.plot(zrange, gamma.pdf(zrange, a), label=r\"$\\Gamma(z|a=2.0)$\")\nax.set_xlabel(\"z\", fontsize=20)\nax.set_ylabel(\"probability density\", fontsize=20)\nax.legend(fontsize=15)\nax.set_title(\"Gamma pdf for $a=2.0$\", fontsize=20)\nplt.close(fig_gamma_pdf) # do not plot the figure now. We will show it in a later cell\n```\n\n\n```python\n# 2. Plot the expected value (mean) for this pdf\nax.plot(mu_z, gamma.pdf(mu_z, a), 'r*', markersize=15, linewidth=2, label=u'$\\mu_z = \\mathbb{E}[z]$')\n```\n\n\n\n\n []\n\n\n\n\n```python\n# 3. Calculate the mode and plot it\nfrom scipy.optimize import minimize # import minimizer\n\n# Finding the maximum of the gamma pdf can be done by minimizing\n# the negative gamma pdf. So, we create a function that outputs\n# the negative of the gamma pdf given the parameter a=2.0:\ndef neg_gamma_given_a(z): return -gamma.pdf(z,a)\n\n# Use the default optimizer of scipy (L-BFGS) to find the\n# maximum (by minimizing the negative gamma pdf). Note\n# that we need to give an initial guess for the value of z,\n# so we can use, for example, z=mu_z:\nmode_z = minimize(neg_gamma_given_a,mu_z).x\n\nax.plot(mode_z, np.max(gamma.pdf(mode_z, a)),'g^', markersize=15,\n linewidth=2,label=u'mode $\\mathbf{z}^*=\\mathrm{argmax}~p(z)$')\nax.legend() # show legend\n```\n\n\n\n\n \n\n\n\n\n```python\n# Code to generate this Gamma distribution hidden during presentation (it's shown as notes)\n\nprint('The mean is ',mu_z) # print the mean calculated for this gamma pdf\nprint('The mode is approximately ',mode_z) # print the mode\nfig_gamma_pdf # show figure of this gamma pdf\n```\n\n## The amazing Bayes' rule\nBayesian inference definition:\n* Inference means “the act of passing from sample data to generalizations, usually with calculated degrees of certainty”.\n* Bayesian is used to refer to inference methods that represent “degrees of certainty” using probability theory, and which leverage Bayes’ rule to update the degree of certainty given data.\n\n**Bayes’ rule** is a formula for computing the probability distribution over possible values of an unknown (or hidden) quantity $z$ given some observed data $y$:\n\n$$\np(z|y) = \\frac{p(y|z) p(z)}{p(y)}\n$$\n\nBayes' rule follows automatically from the identity: $p(z|y) p(y) = p(y|z) p(z) = p(y,z) = p(z,y)$\n\n## The amazing Bayes' rule\n\n* I know... You don't find it very amazing (yet!).\n* Wait until you realize that almost all ML methods can be derived from this simple formula\n\n$$\np(z|y) = \\frac{p(y|z) p(z)}{p(y)}\n$$\n\n### See you next class\n\nHave fun!\n\n\n", "meta": {"hexsha": "4a1d17452ee091093759237660eba501b4e16d1c", "size": 551563, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures/Lecture1/3dasm_Lecture1.ipynb", "max_stars_repo_name": "shushu-qin/3dasm_course", "max_stars_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-07T18:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T21:45:27.000Z", "max_issues_repo_path": "Lectures/Lecture1/3dasm_Lecture1.ipynb", "max_issues_repo_name": "shushu-qin/3dasm_course", "max_issues_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "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": "Lectures/Lecture1/3dasm_Lecture1.ipynb", "max_forks_repo_name": "shushu-qin/3dasm_course", "max_forks_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2022-02-07T18:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T19:30:17.000Z", "avg_line_length": 369.4326858674, "max_line_length": 159916, "alphanum_fraction": 0.9294550215, "converted": true, "num_tokens": 8363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.09434630105316053}} {"text": "```python\n## This code cell will not be shown in the HTML version of this notebook\n#### some helpful imports ####\n# import autograd functionality\nimport autograd.numpy as np\n\n# import testing libraries\nimport sys\nsys.path.append('../')\nfrom mlrefined_libraries import time_series_lib as timelib\nfrom mlrefined_libraries import pid_lib as pidlib\n\n# import dataset path\ndatapath = '../datasets/'\n\n# import various other libraries e.g., for plotting, deep copying\nimport copy\nimport matplotlib.pyplot as plt\n\n# this is needed to compensate for %matplotl+ib notebook's tendancy to blow up images when plotted inline\nfrom matplotlib import rcParams\nrcParams['figure.autolayout'] = True\n%matplotlib notebook\n\n# autoreload function - so if anything behind the scenes is changeed those changes\n# are reflected in the notebook without having to restart the kernel\n%load_ext autoreload\n%autoreload 2\n```\n\n# Principles of PID control\n\nToggle code on and off in this presentation by clicking the 'Toggle code' button below.\n\n\n```python\nfrom IPython.display import display\nfrom IPython.display import HTML\nimport IPython.core.display as di # Example: di.display_html('

%s:

' % str, raw=True)\n\n# This line will hide code by default when the notebook is eåxported as HTML\ndi.display_html('', raw=True)\n\n# This line will add a button to toggle visibility of code blocks, for use with the HTML export version\ndi.display_html('''''', raw=True)\n```\n\n\n\n\n\n\n\n\n\n# The standard PID Control Model\n\n- with a trained Imitator or System Model in hand, we can now look at automatically controlling this Imitator to perform desired tasks\n\n\n- the simplest kind of behavior we make a system obey (like e.g., temperature control and cruise control): is to make the system match a series of **training** *set points* $x_1,\\,x_2,\\,...,x_T$ as closely as possible\n\n\n- examples of set points:\n - for cruise control / autonomous driving: speed levels to have the car drive\n - for temperature control: different temperature levels throughout the day\n - for an industrial process like water level: keep a certain level in a tank that can change throughout the day\n\n- this involves putting our Imitator model under the authority of a Controller (or - you can say - we pass our Imitator model through a Control model that selects optimal actions for it)\n\n\n- once trained the Control Model should be able to choose actions automatically so that the Imitator matches desired set points \n\n\n- that is, our Controller will choose actions $a_t$ for optimally for our Imitator so that its output $s_{t+1} = f_{\\text{imitator}}\\left(s_t,a_t\\right)$ matches the desired set points as closely as possible (as the system allows), or that \n\n$$s_t \\approx x_t \\,\\,\\,\\,\\, \\text{for} \\,\\,\\,\\,\\, t=2,...,T$$\n\n(often the initial state $s_1$ is determined by the problem, or set to a reasonable reference value) \n\n\n- once tuned properly a Control Model is often referred to as a *Control Law* or *Optimal Policy* \n\n- how does the Controller choose optimal actions to meet a series of set points? \n\n\n- *one way* is to train a Controller to choose actions optimally **looking backwards** to decide on the best choice of action in the present\n\n\n- this is based on the desire to always be correcting for previous mistakes / *historical errors*, or how well $s_t \\approx x_t$ previously\n\n\n- this most popular control approach is called *Proportional Integral Derivative or PID* ontrol \n\n\n- this is a simple *parameterized dynamic system with unlimited memory* that captures historical *error* between our sequence of training set points and the corresponding states of our system\n\n\n- as a graphical model it looks like this\n\n
\n

\n\n

\n
\n\n
\n

\n\n

\n
\n\n- here we have used the *signed error* $e_t = x_t - s_t$ as historical feedback to the Controller Model: $f_{\\text{controller}}\\left(e_t\\right)$\n\n\n- using the signed error is a convention, you could use another (e.g., absolute value of the error)\n\n\n- we uses a linear combination of this (and its history and/or its derivatives) to learn how to choose actions optimally\n\n\n- the simplest parameterized controller (a *Proportional controller*) uses a linear combination of this (signed) error to determine the next action to take\n\n\\begin{equation}\nf_{\\text{controller}}\\left(e_t;\\Theta_{\\text{controller}}\\right) = a_t = w_0 + w_1e_t\n\\end{equation}\n\n\n- this is a function with weights we need to tune properly in order for the controller to properly choose actions\n\n\n- it is called a *Proportional controller* because the action $a_t$ is literally being made proportional to the signed error of the system at the prior state\n\n
\n

\n\n

\n
\n\n- a common extension of this idea: use a summary statistic of the history of the error as well as well \n\n\n- this is usually chosen to be the *integral of the error*\n\n\\begin{equation}\nh^e_t = h^e_t + \\frac{1}{D}e_t\n\\end{equation}\n\nwhere $\\frac{1}{D}$ is the gap between steps, but in principle any dynamic system with unlimited memory will work\n\n\n- adding the integral (or history) of the error gives the controller *context*, as the integral summarizes how the error has changed in the past\n\n\n- this is what we mean when we say that a PID Controller 'looks backward' to decide on the best choice of action in the present\n\n- adding the history $h^e_t$ term to our parameterized action function / control model gives the parameterized update\n\n\\begin{equation}\na_t = w_0 + w_1e_t + w_2h^e_t\n\\end{equation}\n\n- this is a so-called *Proportional Integral* controller - one of the most common automatic controller used today in practice (for set-point matching automatic control problems)\n\n\n- notice: this history of the error is now an explicit input to our Controller \n\n\\begin{equation}\nf_{\\text{control}}\\left(e_t,h^e_t ; \\Theta_{\\text{controller}} \\right) = a_t = w_0 + w_1e_t + w_2h^e_t\n\\end{equation}\n\n- one final common addition: the derivative of the error: $\\frac{e_t - e_{t-1}}{D}$\n\n\n- proportional information derivative or *local difference* of the error can be added as well, tacking on another term as to the action update\n\n\n\\begin{equation}\na_t = w_0 + w_1e_t + w_2h_t + w_3\\frac{e_t - e_{t-1}}{D}\n\\end{equation}\n\n- using this update in a Control Model we have the so-called *Proportional Inegral Derivative* (PID) controller.\n\n\n- our Control Model now takes in two prior error terms \n\n# Tuning the weights of a PID Control Model\n\n- how do we tune these weights properly - so that our controller learns how to produce the best actions to lead our system model to match our training set points?\n\n\n- traditional (non machine-learning) approaches PID controller tuning involve \"voodoo\" and a lot of human trial and error \n\n\n- see e.g., the recommendations for tuning on stackoverflow and youtube (note here: $w_1 = K_p$, $w_2 = K_i$, and $w_3 = K_d$)\n\nhttps://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops\n\nhttps://www.youtube.com/watch?v=VVOi2dbtxC0&t=1050s\n\n\n- note: 'traditional' does not mean that 'old' - this is how many people tune their controllers today\n\n- why so much 'voo-doo' and human trial and error for PID tuning?\n\n\n- because the traditional way of doing PID control already involves one understand an enormous amount of specialized information\n\n - for Imitator / System modeling: the traditional way is to use 'first principles' differential equations modeling\n \n - this can lead to system models that are - by their very nature - highly unstable\n \n - this involves building up not only a steep mathematical knowledge stack, but expert knowledge in a particular domain (e.g., physics, chemistry, robotics, etc.,)\n \n \n- things often not included in traditional automatic control pedagogy\n\n - programming / basic CS\n - machine learning / deep learning basics (as an alternative to differential equations modeling)\n - mathematical optimization (although there is some emphasis on this for advanced students of automatic control, the approaches taken are very limiting = only special structures like QP are studied)\n\n# The ML perspective on PID tuning\n\n- but 'automatic parameter tuning' is the 'bread and butter' for machine learning folks - so what do we need to do to auto-tune our PID parameters?\n\n\n- Like everything else: we need to form a cost function (whose minimum recovers correctly tuned parameters)!\n\n\n- to design a proper cost, lets look at our entire controller pipeline- including our system model\n\n\n- to keep things simple we will perform these derivations using the simplest Proportional (P) controller, but everything that follows is the same for PI and PID controllers as well\n\n
\n

\n\n

\n
\n\n- our basic Proportional controller takes in the current (signed) error $e_t = x_t - s_t$ and returns the action $a_t$ \n\n\n\\begin{equation}\nf_{\\text{control}}\\left(e_t\\right) = a_t\n\\end{equation}\n\n\n- we then feed this action into our Imitator model to get our next state $s_{t+1}$\n\n\n\\begin{equation}\nf_{\\text{imitator}}\\left(s_t, a_t \\right) = f_{\\text{imitator}}\\left(s_t,\\, f_{\\text{control}}\\left(e_t\\right) \\right) = s_{t+1} \n\\end{equation}\n\n\n- now ideally - we want these actions made *so that this next state matches the input set point*, that is\n\n\\begin{equation}\ns_{t+1} \\approx x_{t+1}\n\\end{equation}\n\n\n- in other words, we want the *error* $e_{t+1} = x_{t+1} - s_{t+1}$ to be small in magnitude\n\n- so why not tune $\\Theta_{\\text{controller}}$ to minimize the average e.g., squared error over the entire sequence of *training set points* $x_1,...,x_T$ \n\n\n\\begin{equation}\n\\frac{1}{T-1}\\sum_{t=1}^{T-1}\\left(e_{t+1}\\right)^2 = \\frac{1}{T-1}\\sum_{t=1}^T\\left(s_{t+1} - x_{t+1}\\right)^2\n\\end{equation}\n\n\n- we ignore the error on our initial state $s_1$ since we cannot adjust it (its given by the problem at hand! e.g., with cruise control the car starts with 0 velocity)\n\n\n- if unwravel the definition of $s_{t+1}$ and express it in terms of our system and control model this is equivalently\n\n\n\\begin{equation}\n\\frac{1}{T-1}\\sum_{t=1}^{T-1}\\left(f_{\\text{imitator}}\\left(s_t,\\, f_{\\text{control}}\\left(e_t;\\Theta_{\\text{controller}}\\right) \\right) - x_{t+1}\\right)^2\n\\end{equation}\n\n\n- note here: we are minimizing over the *Controller parameters* $\\Theta_{\\text{controller}}$, **not** the parameters of our Imitator model\n\n\n- the weights of our imitator have already been tuned as necessary to real action/state data (another way to think about it: they are regularized so that the system matches a real set of input/output data)\n\n\n- our goal in optimizing our Controller parameters is to solidify our *Optimal Control Law* so that we learn an entire sequence of optimal actions $a_1,\\,a_2,\\,...,a_{T-1}$\n\n\n- thus we are getting at our optimal set of actions indirectly (via a parameterized function)\n\n- Lets look at a simple implementation of a PID controller\n\n\n```python\n# a simple implementation of a PID controller\ndef PID_controller(e_t,h_t,d_t,w): \n # note here in terms of inputs\n # e_t = current error\n # h_t = integral of error\n # d_t = derivative of error\n return w[0] + w[1]*e_t + w[2]*h_t + w[3]*d_t\n```\n\n\n```python\n# loop for evaluating control model over all input/output action/state pairs\n# Our inputs here:\n# s_1 - the initial condition state\n# x - sequence of training set points\n# w - the control model parameters\ndef control_loop(x,w):\n # initialize key variables and containers\n s_t = copy.deepcopy(s_1)\n h_t = 0\n d_t = 0\n frac = 1/float(np.size(x))\n action_history = []\n state_history = [s_t]\n error_history = []\n \n # loop over training set points and run through controller, then \n # system models\n for t in range(np.size(x) - 1):\n # get current set point\n x_t = x[:,t]\n\n # update error\n e_t = x_t - s_t\n error_history.append(e_t)\n \n # update integral of error\n h_t = h_t + frac*e_t\n \n # update derivative of error \n if t > 0:\n d_t = frac*(error_history[-1] - error_history[-2])\n \n # send error, integral, and derivative to PID controller\n a_t = PID_controller(e_t,h_t,d_t,w)\n \n # clip a_t to match system specifications?\n \n # send action to system model\n s_t = tuned_system_model(s_t,a_t)\n \n # store state output, and actions (for plotting)\n state_history.append(s_t)\n action_history.append(a_t)\n\n # transition to arrays\n state_history = np.array(state_history)[np.newaxis,:]\n action_history = np.array(action_history)[np.newaxis,:]\n \n # return velocities and control history\n return state_history,action_history\n```\n\n\n```python\n# an implementation of the least squares cost for PID controller tuning\n# note here: s is an (1 x T) array and a an (1 x T-1) array\ndef least_squares(w,x):\n # system_loop - runs over all action-state pairs and produces entire\n # state prediction set\n state_history,action_history = control_loop(x,w)\n\n # compute least squares error between real and predicted states\n cost = np.sum((state_history[:,1:] - x[:,1:])**2)\n return cost/float(x.shape[1]-1)\n```\n\n#### Example: 1 Cruise control\n\n- a `Python` implementation of our `control_model` for the *cruise control* problem. Notice at each update step the action is clipped to lie in the range $[-50,100]$ - which is the angle of the pedal against the floor of the car.\n\n\n- because here we are using a 'true model' of the automobile we need to use a zero order optimization method - since we cannot compute the gradient of `system_model` with respect to our PID weights.\n\n\n```python\n# create tuned system model for the car\nind = np.argmin(mylib1.train_cost_histories[0]) \nw_best = mylib1.weight_histories[0][ind]\n# a_norm = mylib1.x_norm\n# s_norm = mylib1.y_norm\n# s_invnorm = mylib1.y_invnorm\n# a_invnorm = mylib1.x_invnorm\n# tuned_system_model = lambda state,action: s_invnorm(system_model(s_norm(state),a_norm(action),w_best))\n\ntuned_system_model = lambda state,action: system_model(state,action,w_best)\ns_1 = 0.0\n```\n\n\n```python\n# loop for evaluating control model over all input/output action/state pairs\n# Our inputs here:\n# s_1 - the initial condition state\n# x - sequence of training set points\n# w - the control model parameters\ndef control_loop(x,w):\n # initialize key variables and containers\n s_t = copy.deepcopy(s_1)\n h_t = 0\n d_t = 0\n frac = 1/float(np.size(x))\n action_history = []\n state_history = [s_t]\n error_history = []\n \n # loop over training set points and run through controller, then \n # system models\n for t in range(np.size(x) - 1):\n # get current set point\n x_t = x[:,t]\n\n # update error\n e_t = x_t - s_t\n error_history.append(e_t)\n \n # update integral of error\n h_t = h_t + frac*e_t\n \n # update derivative of error \n if t > 0:\n d_t = frac*(error_history[-1] - error_history[-2])\n \n # send error, integral, and derivative to PID controller\n a_t = PID_controller(e_t,h_t,d_t,w)\n \n # clip action range to realistic machine standard?\n # clip inputs to -50% to 100% for car\n if a_t >= 100.0:\n a_t = 100.0\n if a_t <= -50.0:\n a_t = -50.0\n \n # send action to system model\n s_t = tuned_system_model(s_t,a_t)\n\n # store state output, and actions (for plotting)\n state_history.append(s_t)\n action_history.append(a_t)\n\n # transition to arrays\n state_history = np.array(state_history)[np.newaxis,:]\n action_history = np.array(action_history)[np.newaxis,:]\n \n # return velocities and control history\n return state_history,action_history\n```\n\n\n```python\n# an implementation of the least squares cost for PID controller tuning\n# note here: s is an (1 x T) array and a an (1 x T-1) array\ndef least_absolute(w,x):\n # system_loop - runs over all action-state pairs and produces entire\n # state prediction set\n state_history,action_history = control_loop(x,w)\n\n # compute least squares error between real and predicted states\n cost = np.sum(np.abs(state_history[:,1:] - x[:,1:]))\n return cost/float(x.shape[1]-1)\n```\n\n\n```python\n# create an instance of the car simulator\ndemo = pidlib.car_simulator.MyCar()\n\n# create a training sequence of *set points* for trying out the true simulator, and for learning a controller\nx_car = demo.create_set_points()\n```\n\n\n```python\n# This code cell will not be shown in the HTML version of this notebook\n# initialize with input/output data\nmylib5 = pidlib.rnn_pid_lib.super_setup.Setup(x_car)\n\n# normalize?\nmylib5.preprocessing_steps(normalizer_name = 'none')\n\n# split into training and validation sets\nmylib5.make_train_val_split(train_portion = 1)\n\n# choose cost\nmylib5.choose_cost(control_loop,cost = least_absolute)\n\n# fit an optimization\nw = 0.1*np.random.randn(4,1)\n# mylib5.fit(max_its = 59,alpha_choice = 10**(0),optimizer = 'gradient_descent',w_init = w,verbose = False)\n\nmylib5.fit(max_its = 50,alpha_choice = 10**(0),optimizer = 'zero_order',w_init = w,verbose = False)\n\n# show cost function history\nmylib5.show_histories(start = 1)\n```\n\n\n \n\n\n\n\n\n\n\n```python\n# This code cell will not be shown in the HTML version of this notebook\n# Plot the standard normalized series and its training fit\npidlib.variable_order_plotters.plot_setpoint_train_val_sequences(mylib5)\n```\n\n\n \n\n\n\n\n\n\n- these actions are crazy when the desired speed ramps up and down - we can fix this by *regularizing*\n\n#### Example: 2 PID controller for two tank example\n\n\n```python\n# This code cell will not be shown in the HTML version of this notebook\ndef two_tank_control_model(x,w):\n #### simulate vehicle response to set points ####\n s_t = [0.0,0.0]\n action_history = []\n state_history = [s_t]\n h = 0.0\n for t in range(np.size(x) - 1):\n # get current set point\n x_t = x[:,t]\n\n # update error\n e_t = x_t - s_t[1]\n \n # update integral of error\n h = h + e_t*0.1\n\n # set action based on PI linear combination\n a_t = w[0] + w[1]*e_t + w[2]*h \n \n if t > 0:\n a_t += w[3]*(s_t[1] - state_history[-2][1])\n\n # clip inputs to -50% to 100%\n if a_t >= 100.0:\n a_t = 100.0\n if a_t <= 0.0:\n a_t = 0.0\n \n # cap off condition\n #if s_t[1] > x_t:\n # a_t = 0\n \n # run pid controller\n s_t = demo_3.tank_model(a_t,s_t)\n \n # store results\n action_history.append(a_t)\n state_history.append(s_t)\n\n # transition to arrays\n state_history = np.array(state_history).T\n action_history = np.array(action_history)[np.newaxis,:]\n \n # return velocities and control history\n return state_history,action_history\n```\n\n\n```python\n# This code cell will not be shown in the HTML version of this notebook\n# an implementation of the least squares cost function for linear regression\ndef least_squares(w,x):\n states,actions = control_model(x,w)\n # compute cost over batch\n cost = np.sum((states[1,1:] - x[:,1:])**2)\n return cost/float(x.shape[1]-1)\n\n# a compact least absolute deviations cost function\ndef least_absolute_deviations(w,x):\n states,actions = control_model(x,w)\n # compute cost over batch\n cost = np.sum(np.abs(states[1,1:] - x[:,1:]))\n return cost/float(x.shape[1]-1)\n```\n\n\n```python\n# This code cell will not be shown in the HTML version of this notebook\n# initialize with input/output data\nmylib6 = pidlib.rnn_pid_lib.super_setup.Setup(x_tank2)\n\n# split into training and validation sets\nmylib6.make_train_val_split(train_portion = 1)\n\n# choose cost\ncontrol_model = two_tank_control_model\nmylib6.choose_cost(model = control_model,cost = least_absolute_deviations)\n\n# fit an optimization\nw = 0.1*np.random.randn(4,1)\nmylib6.fit(max_its = 10,alpha_choice = 'diminishing',optimizer = 'zero_order',w_init = w,verbose = False)\n\n# show cost function history\nmylib6.show_histories(start = 5)\n```\n\n\n \n\n\n\n\n\n\n\n```python\n# This code cell will not be shown in the HTML version of this notebook\n# plot results\npidlib.two_tank_plotter.plot_results(mylib6)\n```\n\n\n \n\n\n\n\n\n", "meta": {"hexsha": "5527d4c17765f1dded46c7025df3e60eb6b184cf", "size": 551316, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "presentations/pid_control/pid_control_part_1.ipynb", "max_stars_repo_name": "jermwatt/blog", "max_stars_repo_head_hexsha": "3dd0d464d7a17c1c7a6508f714edc938dc3c03e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-04-17T23:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T02:18:49.000Z", "max_issues_repo_path": "presentations/pid_control/pid_control_part_1.ipynb", "max_issues_repo_name": "jermwatt/blog", "max_issues_repo_head_hexsha": "3dd0d464d7a17c1c7a6508f714edc938dc3c03e9", "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": "presentations/pid_control/pid_control_part_1.ipynb", "max_forks_repo_name": "jermwatt/blog", "max_forks_repo_head_hexsha": "3dd0d464d7a17c1c7a6508f714edc938dc3c03e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-10T22:46:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-06T09:16:30.000Z", "avg_line_length": 131.0473021155, "max_line_length": 178387, "alphanum_fraction": 0.8126301431, "converted": true, "num_tokens": 5339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.19436780401867254, "lm_q1q2_score": 0.094147893291297}} {"text": "

Table of Contents

\n\n\n# $\\LaTeX$\n\n>_LaTeX, which is pronounced «Lah-tech» or «Lay-tech» (to rhyme with «blech» or «Bertolt Brecht»), is a document preparation system for high-quality typesetting. It is most often used for medium-to-large technical or scientific documents but it can be used for almost any form of publishing.\\\n $~~~~$ - https://www.latex-project.org/about/_\n\n\nThis git is designed to be a primer in using $\\LaTeX$ in Jupyter notebooks with the intention of improving presentation.\n\n$\\LaTeX$ is a powerful tool in making your markdowns cells look more professional and stand out. One can introduce $\\LaTeX$ into the Jupyter Notebooks markdown cells using imported libraries, however, Jupyter Notebook natively leverages JavaScripts library MathJax to allow rendering of special characters and formatting. Its intended to allow for displaying mathematical functions and text in a more legible format and is widely used in academia.\n\nThis notebook aims to act like a cheat sheet for commonly used formatting examples. As we get progress along in the notebook, explanations will be limited to expounding on usage idiosyncrasies of the function in question. In other words, sections later in the book rely on knowledge of previous sections.\n\n## Getting Started \nLets start with the basics. To insert $\\LaTeX$ formatted text in Jupyter notebook is enclose the text in '$' to get started. Eg: here is the letter 'A' before and after\n\nA : A\\\n\\\\$A\\\\$ : $A$\n\nEasy enough. However, if all we wanted to bold and italicize our text, we can do that with builtin markdown shortcuts. The real power of $\\LaTeX$ comes with introducing special characters. This is done using the escape character '\\'. In this example, to get the alpha symbol we prefix it with the backspace character.\n\n\\\\$alpha\\\\$ : $alpha$\\\n\\\\$\\\\alpha\\\\$ : $\\alpha$\n\n\n### Spacing\n\n$\\LaTeX$ doesn't care for white space and displays text with standardized spacing regardless of how many whitespace characters are there. To allow for better separation and control one can use '~'\n\n$A B$ (10 spaces separating the characters)\\\n$A~~B$ (2 '~' between characters)\n\n### Justification\n#### Centering\nBy default, Markdowns are left justified and so are $\\LaTeX$ entries. Enclose text in '\\$$' instead of a single '\\$' centers the $\\LaTeX$ text. eg:\n\n$$A = B$$\n\n#### Multiline formatting for math\nIf you are typing a multi line mathematical process or derivation, it can be convenient to wrap the entire block in a \\\\begin and \\\\end. This allows us to forgo the '$' at the beginning and end of each line. A few things to keep in mind,\n\n- Every line should end with a '\\\\\\\\'. \n- By default the block right aligned, however one can provide an ***&*** at every line to specify point of alignment\n\n\n\n$$\n\\begin{align}\nx &= 10 + 5 +2 \\\\\nx &= 10 + 7\\\\\nx &= 17\\\\\nx - 17 &= 0\\\\\n\\end{align}\n$$\n\n## The Greeks\nThe greek alphabets are all represented. Note that some letters have a capitalized version. Letters exempt are the ones which resemble their alphabet equivalent, such as a capital $\\alpha$ is ***A***. To access the capital variations, capitalize the first letter\n\n\n$$\n\\begin{align}\nAlpha&: \\alpha\\\\\nBeta&: \\beta\\\\\nGamma&: \\gamma~\\Gamma\\\\\nDelta&: \\delta~\\Delta\\\\\nEpsilon&: \\epsilon\\\\\nZeta&: \\zeta\\\\\nEta&: \\eta\\\\\nTheta&: \\theta~\\Theta\\\\\nIota&: \\iota\\\\\nKappa&: \\kappa\\\\\nLambda&: \\lambda~\\Lambda\\\\\nMu&: \\mu\\\\\nNu&: \\nu\\\\\nXi&: \\xi~\\Xi\\\\\nOmicron&: \\omicron\\\\\nPi&: \\pi~\\Pi\\\\\nSigma&: \\sigma~\\Sigma\\\\\nTau&: \\tau\\\\\nUpsilon&: \\upsilon~\\Upsilon\\\\\nPhi&: \\phi~\\Phi\\\\\nChi&: \\chi\\\\\nPsi&: \\psi~\\Psi\\\\\nOmega&: \\omega~\\Omega\n\\end{align}\n$$\n\n\n## Mathematical Symbols\nThere is a plethora of mathematical symbols available for use as well, however, due to their verbose nature, we won't be going over every single one. Here are a few divided by subsections\n\n### Superscript and Subscript\nSuperscipts and Subscripts are easily accessible using the '^' and '\\_' symbols. This symbol needs to be prefixed to the exponent or the subscript. \n\n$$ a_b $$ \n$$ x^2 $$ \n\n### Grouping\nGrouping allows us to group a set of symbols together so they are always presented together. Lets use a superscript to illustrate this example. By default the superscript symbol only captures the first character to superscript. So if I wanted to write anything a little more complicated I'd have to group characters together using the _{ }_ symbols. In the following example we get two very different outcomes depending upon whether we grouped y+z\n\n$$\n\\begin{align}\nNo~grouping &:x ^ y + z\\\\\nGrouping &:x ^ {y + z}\n\\end{align}\n$$\n\n### Sets & Probability\n\nOperators for showing set relationship\n\n$$\n\\begin{align}\nUnion &: \\cup\\\\\nIntersection &: \\cap\\\\\nSubset &: \\subset\\\\\nSuperset &: \\supset\\\\\n\\end{align}\n$$\n\n### Mathematical comparators\nThese symbols and their usage are fairly self explanatory. Some symbols which have a dedicated spot on the keyboard don't need any special effort. For eg:\n$$ = ~ < ~ >$$\n\nHowever, for others that do not have a dedicated keyboard spot they can be accessed with the escape character,\n\n$$\n\\begin{align}\n\\approx ~ \\leq~ \\geq \\\\\n\\equiv ~ \\ll~ \\gg \\\\\n\\neq ~ \\leq~ \\geq \\\\\n\\end{align}\n$$\n\n### Mathematical operators\n$$\\pm ~\\times~\\cdot$$\n\n### Fractions\nFractions can be presented using the _'\\\\dfrac'_ or _'\\\\tfrac'_ command. Depending upon need either can be utilized.\n\nDfrac: $\\dfrac x y$\n\nTfrac: $\\tfrac x y$\n\nThis can be combined with grouping to display complex math in a legible form\n\n$$ \\dfrac {x^{exp}} {y_{sub}^{exp}} $$\n\n## A few examples of using $\\LaTeX$\nLets use what we've learned so far and write some famous and some more obscure equations\n\n#### Einstein's mass-energy equivalence\n\n\n$$ E = mc^2$$\n\n#### Equations of motion\n\n$$\n\\begin{align}\nv &= u + at \\\\\ns &= ut + \\dfrac {a t^2}{2} \\\\\ns &= \\dfrac {(u+v)t}{2} \\\\\nv^2 &= u^2 + 2as\n\\end{align}\n$$\n\n#### Quadratic Equation\nFor, \n\n$$\n\\begin{align}\na x^2 + b x + c &= 0 \\\\ \nx &= \\dfrac {-b \\pm \\sqrt{b^2 - 4 ac}}{2a} \n\\end{align}\n$$\n\n#### Some calculus for good measure\n\n##### Derivation\n\n$$\n\\begin{align}\n \\dfrac{d}{dx} x^n &= n x^{n-1} \\\\ \n \\dfrac{d}{dx} (f(x)\\cdot g(x)) &= \\dfrac{d}{dx} (f(x))\\cdot g(x) + \\dfrac{d}{dx} (g(x))\\cdot f(x)\\\\\n\\end{align}\n$$\n\n##### Integration\n\n$$\n\\begin{align}\n \\int x^n \\cdot dx &= \\dfrac{x^{n+1}}{n+1} + C \\\\\n \\int f(x)\\cdot g'(x)\\cdot dx &= f(x)\\cdot g(x) - \\int g(x)\\cdot f'(x)\\cdot dx\n\\end{align}\n$$\n\n## Using in visualizations\n\nThese rules can also be applied to your visualizations if needed. All labels and titles can utilize $\\LaTeX$ formatting as long as they are inserted as _rstrings_. This allows the use of the backslash escape character. As an example, here we plot a sine function and its differentiation cosine. Take note of the title and legend and the x ticks\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt \n\n# Generate x values\nx = np.arange(0, 4*np.pi, 0.1); \n\n# Get y values for sine wave and its differentiation cosine\ny = np.sin(x) \ndy = np.cos(x)\n\n# Plot waves\nplt.figure(figsize = (10,8))\nplt.plot(x, y) \nplt.plot(x, dy)\n\n# Give a title for the sine wave plot\nplt.title(r'Plot of $sin(x)$ & $\\dfrac {d}{dx} sin(x)$') \n\n# Give x axis label for the plot\nplt.xlabel('x') \n\n# Give y axis label for the plot\nplt.ylabel('f (x)') \n\nplt.xticks(np.arange(0, 9*(np.pi/2),(np.pi)),\n [r'0$\\pi$', r'$1\\pi$', r'2$\\pi$',r'3$\\pi$', r'4$\\pi$'])\n\n\nplt.grid(True, alpha =0.2)\nplt.axhline(y=0, color='k')\n\nplt.legend([r'$sin(x)$',r'$\\dfrac {d}{dx} sin(x) = cos(x)$'],loc = 1)\nplt.show();\n```\n\nAs you can see the possibilities are limitless and learning and leveraging $\\LaTeX$ is a must to improve on your presentations\n", "meta": {"hexsha": "9dbb490d4952f370ce255e82d7019c438e1d4b6c", "size": 77387, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter_Workbook.ipynb", "max_stars_repo_name": "ssaeed85/UsingLatexInJupyterNB", "max_stars_repo_head_hexsha": "34006d0406415fd1b4b43d6edf5dd51e46985788", "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": "Jupyter_Workbook.ipynb", "max_issues_repo_name": "ssaeed85/UsingLatexInJupyterNB", "max_issues_repo_head_hexsha": "34006d0406415fd1b4b43d6edf5dd51e46985788", "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": "Jupyter_Workbook.ipynb", "max_forks_repo_name": "ssaeed85/UsingLatexInJupyterNB", "max_forks_repo_head_hexsha": "34006d0406415fd1b4b43d6edf5dd51e46985788", "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": 150.2660194175, "max_line_length": 59480, "alphanum_fraction": 0.8741132232, "converted": true, "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.18952108217423458, "lm_q1q2_score": 0.09402023942128886}} {"text": "\n\nGiulio Tesei
\nQDETAILSS WS3
\n2019-10-24, Lund University\n\n### LAYOUT\n

\n- What is a Jupyter notebook?\n

\n- How can it improve my workflow?\n

\n- How to get started\n

\n- How to share my notebook to help other scientists to reproduce my analysis\n\n### What is it?\nInteractive document that integrates:\n- code:\n - A long list of available programming languages:\n - Python, Java, R, Julia, Matlab, Octave, Scala, Spark, PHP, C#, C++, etc.\n

\n- command-line tools:\n - copying / deleting / moving files with `cp` / `rm` / `mv`\n - navigate in the directory tree with `cd`\n - create a new folder with `mkdir` \n

\n- narrative text:\n - equations\n - tables\n - links\n

\n- visualizations\n\n### Code\n\nDocumentation accessible within the notebook.\n- How can I call this function?\n- Which arguments does it have?\n- What attributes does this object have?\n\n\n```python\nnames = ['marie_curie','amedeo_avogadro','rosalind_franklin']\nprint(type(names), names[0], type(names[0]))\n```\n\n marie_curie \n\n\n\n```python\nfor name in names:\n first_last = name.split('_')\n print('first_last is ',first_last)\n first = first_last[0]\n last = first_last[1]\n print(first.capitalize()+' '+last.swapcase())\n```\n\n first_last is ['marie', 'curie']\n Marie CURIE\n first_last is ['amedeo', 'avogadro']\n Amedeo AVOGADRO\n first_last is ['rosalind', 'franklin']\n Rosalind FRANKLIN\n\n\n### Command-Line Tools:\nNo need to use the terminal or file managers.\n- copy / delete / move files or folders with `cp` / `rm` / `mv`\n- navigate in the directory tree with `cd`\n- create a new folder with `mkdir` \n- check the pth of the current directory with `pwd`\n\n\n```python\n%pwd\n```\n\n\n\n\n '/Users/giulio/jc/qdetailss'\n\n\n\n\n```python\n%mkdir data\n%ls\n```\n\n \u001b[34maux\u001b[m\u001b[m/ \u001b[34mdata\u001b[m\u001b[m/ jupyter_slides.pdf\r\n custom.css jupyter.ipynb \u001b[34mreveal.js\u001b[m\u001b[m/\r\n\n\n\n```python\n%rm -r data\n%ls\n```\n\n \u001b[34maux\u001b[m\u001b[m/ jupyter.ipynb \u001b[34mreveal.js\u001b[m\u001b[m/\r\n custom.css jupyter_slides.pdf\r\n\n\n### Narrative Text\n[Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) markup language:\n- equations\n- tables\n- links\n\n```\n###### Free Induction Decay\n\nThe oscillating voltage, $V(t)$, has an initial amplitude $V(0)$ which freely decays in time, $t$. The dampened signal can be modeled as a sine function of frequency $\\nu$, decaying exponentially with decay constant $T_2$:\n\n\\begin{equation}\nV(t)=V(0)\\,\\exp{(-t/T_2)}\\,\\sin{(2 \\pi \\nu t)}.\n\\end{equation}\n\n| Variable | Description | Unit |\n|---------------| ---------------|-------|\n| $t$ | time | ms |\n| $V$ | voltage | V |\n| $\\nu$ | frequency | Hz |\n| $T_2$ | decay constant | ms |\n\n###### References\n1. [Wikipedia](http://tiny.cc/r9r0ez)\n2. [Merriam-Webster](http://tiny.cc/uas0ez)\n```\n\n##### Free Induction Decay\n\nThe oscillating voltage, $V(t)$, has an initial amplitude $V(0)$ which freely decays in time, $t$. The dampened signal can be modeled as a sine function of frequency $\\nu$, decaying exponentially with decay constant $T_2$:\n\n\\begin{equation}\nV(t)=V(0)\\,\\exp{(-t/T_2)}\\,\\sin{(2 \\pi \\nu t)}.\n\\end{equation}\n\n| Variable | Description | Unit |\n|---------------| ---------------|-------|\n| $t$ | time | ms |\n| $V$ | voltage | V |\n| $\\nu$ | frequency | Hz |\n| $T_2$ | decay constant | ms |\n\n###### References\n1. [Wikipedia](http://tiny.cc/r9r0ez)\n2. [Merriam-Webster](http://tiny.cc/uas0ez)\n\n### How can it improve my workflow?\nAll the steps of your data analysis and visualization in a single document. \n- Interactive data exploration and analysis\n

\n- Immediate access to documentation: learn coding, readily use new libraries!\n

\n- Facilitates iteration: \n - once the notebook is set up, the analysis can be repeated effortlessly with new variables / data sets\n

\n- A large set of freely available tools:\n - Python libraries for linear algebra, fitting data, plotting, handling tabular data, image analysis, bioinformatics, spectroscopy, molecular visualization\n

\n- [Examples](https://github.com/jupyter/jupyter/wiki/A-gallery-of-interesting-Jupyter-Notebooks)\n\n\n\n```\n\n```\n\n\n```python\nimport numpy as np\nx = np.linspace(0,np.pi/2.,10)\nx\n```\n\n\n\n\n array([0. , 0.17453293, 0.34906585, 0.52359878, 0.6981317 ,\n 0.87266463, 1.04719755, 1.22173048, 1.3962634 , 1.57079633])\n\n\n\n\n```python\nnp.mean(x) # np.std() to compute the standard deviation\n```\n\n\n\n\n 0.7853981633974483\n\n\n\n\n```python\ny = np.cos(x) # np.sin(), np.tan(), np.log(), np.exp() etc.\ny\n```\n\n\n\n\n array([1.00000000e+00, 9.84807753e-01, 9.39692621e-01, 8.66025404e-01,\n 7.66044443e-01, 6.42787610e-01, 5.00000000e-01, 3.42020143e-01,\n 1.73648178e-01, 6.12323400e-17])\n\n\n\n\n\n\n```python\n!head -n 1 aux/pmf.dat\n```\n\n 1.525000000000000000e+01 2.086592750614395442e+01 1.224484592940475874e-01\r\n\n\n\n```python\n# Load data file\nx,y,z = np.loadtxt('aux/pmf.dat',unpack=True)\n```\n\n\n```python\n# Integrate along the given axis using the composite trapezoidal rule.\nnp.trapz(y,x)\n```\n\n\n\n\n 940.9132634027817\n\n\n\n\n```python\n# Return the derivative of an array.\ndy = np.gradient(y,x)\n# Save the gradient to a text file\nnp.savetxt('aux/gradient.dat',y)\n```\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'figure.dpi': 70})\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nx = np.linspace(0,10*np.pi,200)\ny = np.cos(x)\nplt.plot(x,y)\nplt.ylabel('Cosine')\nplt.xlabel('Angle / rad')\nplt.show()\n```\n\n$$\nP(x) = \\frac{1}{\\sqrt{2 \\pi \\sigma}} \\exp{\\left ( \\frac{-(x-\\mu)^2}{2\\sigma^2} \\right)}\n$$\n\n\n```python\nx = np.linspace(0,9,1000)\nfor u in range(1,8):\n y = np.exp(-(u-x)**2/(2*0.2**2)) / np.sqrt(2*np.pi*0.2**2)\n plt.plot(x,y,label=str(u))\nplt.legend(frameon=False, title='$\\mu$ / nm')\nplt.xlim(0,9)\nplt.xlabel('Distance, $x$ / nm'); plt.ylabel('Probabilty, $P(x)$')\nplt.savefig('aux/normal.pdf') # png, jpg, eps\nplt.show()\n```\n\n\n```python\nplt.rcParams.update({'figure.dpi': 300})\n```\n\n\n```python\nimport matplotlib.image as mpimg\nimg = mpimg.imread('aux/protein.png')\nprint(img.shape)\nfig = plt.figure(figsize=(1.2, 1.2))\nplt.imshow(img, interpolation='bilinear')\nplt.axis('off')\nplt.show()\n```\n\n\n```python\nplt.rcParams.update({'figure.dpi': 75})\n```\n\n\n```python\nfrom matplotlib.collections import LineCollection\nx = np.linspace(0,10,1000)\ny = np.exp(-(2.6-x)**2) / np.sqrt(4*np.pi) + np.exp(-(7-x)**2/2) / np.sqrt(8*np.pi)\npoints = np.array([x, y]).T.reshape(-1, 1, 2)\nsegments = np.concatenate([points[:-1], points[1:]], axis=1)\nnorm = plt.Normalize(x.min(), x.max())\nlc = LineCollection(segments, cmap='plasma', norm=norm)\nlc.set_array(x); lc.set_linewidth(4); plt.gca().add_collection(lc)\nplt.ylabel(r'Probability, $P(x)$'); plt.xlabel(r'Distance, $x$ / nm')\nplt.xlim(0,10); plt.ylim(0,.3)\nplt.show()\n```\n\nQ: How can I plot a gradient-colored line?\n\nA: Google [\"matplotlib gradient color line\"](https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html)\n\nYou can google very specific questions and quickly find excellent answers, generally on matplolib.org or stackoverflow.com\n\n### Multiple Subplots\n\n\n```python\nfig, axes = plt.subplots(nrows=3,ncols=2,figsize=(7, 6))\nx = np.arange(10)\naxes[0,0].plot(x, x**2, 'bo')\naxes[2,1].plot(x, -x**2, 'r^')\naxes[2,1].yaxis.set_ticks_position('right') # yticks on the right side\n```\n\n\n```python\ndef plotQCM(): \n fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2,ncols=2)\n\n colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n ax1 = plt.subplot2grid((11, 5), (5, 0), rowspan=6, colspan=3)\n ax3 = plt.subplot2grid((11, 5), (0, 0), rowspan=5, colspan=3)\n ax2 = plt.subplot2grid((11, 5), (5, 3), rowspan=6, colspan=2)\n ax4 = plt.subplot2grid((11, 5), (0, 3), rowspan=5, colspan=2)\n\n a = np.linspace(0,np.pi,100)\n\n for ax in [ax2,ax4]:\n for i,c in zip(range(1,13,2),colors):\n ax.plot(np.cos(a*i)+i*2,a,lw=2,color=c)\n ax.plot(-np.cos(a*i)+i*2,a,lw=2,ls=':',color=c)\n\n ax.set_xticks(np.arange(1,13,2)*2)\n ax.set_xticklabels(np.arange(1,13,2))\n ax.tick_params(axis='both',which='both',bottom=False,right=False,labelbottom=True,labelright=False,\n left=False,labelleft=False,pad=-.5)\n ax.set_frame_on(False)\n\n ax2.set_ylim(0-0.06/1.3*np.pi,np.pi+0.06/1.3*np.pi)\n ax4.set_ylim(0-0.06*np.pi,np.pi+0.06*np.pi)\n\n x0 = 2; y0 = 0; x1 = 1.7;\n\n c=7\n\n ax1.fill([x1,x1+2,x1+2.6,x1+.6], [y0,y0,y0+1,y0+1], colors[c], alpha=0.3, \n edgecolor=colors[c],ls='--',lw=0)\n ax1.fill([x1+.6,x1+2.6,x1+2.6,x1+.6], [y0+1,y0+1,y0+1.3,y0+1.3], colors[c], alpha=0.6, \n edgecolor=colors[c],ls='--',lw=0)\n\n ax1.fill([x0,x0+2,x0+2,x0], [y0+1,y0+1,y0+1.3,y0+1.3], colors[9], alpha=0.6, edgecolor=colors[9],ls='-',lw=0)\n ax1.fill([x0,x0+2,x0+2,x0], [y0,y0,y0+1,y0+1], colors[9], alpha=0.3, edgecolor=colors[9],ls='-',lw=0)\n\n ax3.fill([x1,x1+2,x1+2.6,x1+.6], [y0,y0,y0+1,y0+1], colors[c], alpha=0.3, \n edgecolor=colors[c],ls='--',lw=0)\n ax3.fill([x0,x0+2,x0+2,x0], [y0,y0,y0+1,y0+1], colors[9], alpha=0.3, edgecolor=colors[9],ls='-',lw=0)\n\n for ax in [ax1,ax3]: \n ax.axis('off')\n ax.plot([2.3,2.3],[0,1],marker='o',lw=0,color='k')\n ax.hlines(y=[0,1],xmin=[.9925,.9925],xmax=[2.3,2.3],lw=1,color='k')\n ax.annotate(r'$\\bigcirc$',xy=(1,0.5),fontsize=24,color='k',horizontalalignment='center',\n verticalalignment='center')\n ax.annotate(u'\\u223F',xy=(1,0.5),fontsize=16,color='k',horizontalalignment='center',\n verticalalignment='center')\n ax.vlines(x=[1,1],ymin=[0,0.61],ymax=[.4,1],lw=1,color='k')\n\n ax1.set_xlim(.7,4.5)\n ax3.set_xlim(.7,4.5)\n ax3.set_ylim(-.05,1.05)\n ax1.set_ylim(-.05,1.35)\n\n ax3.annotate('QCR', xy=(3,0.5),fontsize=14,color='k',horizontalalignment='center', verticalalignment='center')\n ax1.annotate('QCR', xy=(3,0.5),fontsize=14,color='k',horizontalalignment='center', verticalalignment='center')\n ax1.annotate('Film', xy=(3,1.15),fontsize=14,color='k',horizontalalignment='center', verticalalignment='center')\n\n plt.gcf().text(.6, 0.58, '$n$ = ', fontsize=12)\n plt.gcf().text(.6, 0.058, '$n$ = ', fontsize=12)\n\n plt.tight_layout(w_pad=2.5,h_pad=1)\n plt.show()\n```\n\n\n```python\ndef plotFourier(): \n fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2,figsize=(7, 3.5))\n \n colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n gamma = 2e-1\n fr = 5\n t = np.arange(0,10,.001)\n cos = np.cos(2*np.pi*fr*t)\n exp = np.exp(-t*2*np.pi*gamma)\n func = exp*cos\n ax1.plot(t,func,color=colors[0])\n ax1.set_xlim(0,4)\n\n fs = np.linspace(0,10,1000)\n curr = []\n for f in fs:\n curr.append( np.trapz( func*np.cos(2*np.pi*f*t),t) )\n curr = np.array(curr)\n ax2.plot(fs,curr,lw=2,color=colors[0]) \n ax2.yaxis.set_label_position('right'); ax2.yaxis.set_ticks_position('right')\n ax2.set_xlim(0,7)\n ax2.set_ylim(-.05,.55)\n\n ax1.hlines(y=-np.exp(-1),xmin=0,xmax=1/(2*np.pi*gamma))\n ax1.hlines(y=.7,xmin=4/5,xmax=1)\n ax1.hlines(y=.7,xmin=1,xmax=1.5,lw=1,linestyle=':')\n ax1.vlines(x=4/5,ymin=np.exp(-4/5*2*np.pi*gamma),ymax=.7,lw=1,linestyle=':')\n ax1.vlines(x=1,ymin=np.exp(-2*np.pi*gamma),ymax=.7,lw=1,linestyle=':')\n ax1.vlines(x=1/(2*np.pi*gamma)-.01,ymin=-np.exp(-1),ymax=-.6,lw=1,linestyle=':')\n ax1.annotate('1 / ( 2 $\\pi$ $\\Gamma_r$ )',xy=(.67,-.8),fontsize=16)\n ax2.hlines(y=curr.max()/2.,xmin=5,xmax=5+gamma)\n ax2.hlines(y=curr.max()/2.,xmin=5,xmax=5+gamma+.7,lw=1,linestyle=':')\n ax2.vlines(x=fr,ymin=curr.max()/2.,ymax=curr.max()+.05,lw=1,linestyle=':')\n ax2.annotate('$\\Gamma_r$',xy=(6,.185),fontsize=16)\n ax2.annotate(\"$f_r$\",xy=(fr-.2,curr.max()+.07),fontsize=16)\n ax1.annotate('1 / $f_r$',xy=(1.6,.65),fontsize=16)\n ax1.text(x=4.16,y=.1,s='FT',fontsize=16)\n ax1.text(x=4.13,y=-.05,s='⟶',fontsize=16)\n\n gamma = 4e-1\n fr = 2\n t = np.arange(0,10,.001)\n cos = np.cos(2*np.pi*fr*t)\n exp = np.exp(-t*2*np.pi*gamma)\n func = exp*cos\n ax1.plot(t,func,color=colors[3],lw=1)\n\n fs = np.linspace(0,10,1000)\n curr = []\n for f in fs:\n curr.append( np.trapz( func*np.cos(2*np.pi*f*t),t) )\n curr = np.array(curr)\n ax2.plot(fs,curr,lw=1,color=colors[3]) \n ax2.yaxis.set_label_position('right'); ax2.yaxis.set_ticks_position('right')\n\n ax2.hlines(y=curr.max()/2.,xmin=fr,xmax=fr+gamma)\n ax2.hlines(y=curr.max()/2.,xmin=fr,xmax=fr+gamma+.7,lw=1,linestyle=':')\n ax2.vlines(x=fr,ymin=curr.max()/2.,ymax=curr.max()+.05,lw=1,linestyle=':')\n ax2.annotate(\"$\\Gamma$\",xy=(3.2,.08),fontsize=16)\n ax2.annotate(\"$f$\",xy=(fr-.2,curr.max()+.07),fontsize=16)\n ax1.tick_params(axis='both',which='both',left=False,bottom=False,labelbottom=False,labelleft=False)\n ax2.tick_params(axis='both',which='both',bottom=False,right=False,labelbottom=False,labelright=False)\n ax1.set_xlabel('Time',labelpad=6)\n ax2.set_xlabel('Frequency',labelpad=6)\n ax1.set_ylabel('Current, $I(t)$',labelpad=6)\n ax2.set_ylabel('Current, $I(t)$',labelpad=8)\n\n fig.tight_layout(w_pad=3)\n plt.show()\n```\n\n\n```python\nplt.rcParams.update({'figure.dpi': 60})\n```\n\n\n```python\nplotQCM()\nplotFourier()\n```\n\n### [Jupyter Widgets](https://ipywidgets.readthedocs.io/en/latest/)\nGain control and visualize changes in the data!\n\n\n```python\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom ipywidgets import interactive\n\ndef plot_cos_decay_FT(freq=1,gamma=.2):\n\n def cos_decay(time,freq,gamma):\n cos = np.cos(2*np.pi*freq*time)\n exp = np.exp(-time*2*np.pi*gamma)\n return exp*cos\n \n def FT(time,freq,gamma):\n fourier = []\n for f in np.linspace(0,freq*2,1000):\n cos = np.cos(2*np.pi*f*time)\n fourier.append( np.trapz( cos_decay(time,freq,gamma)*cos,time) )\n return np.array(fourier)\n\n time = np.arange(0,10,.001)\n\n fig = plt.figure(figsize=(3.5,4))\n ax = plt.axes()\n ax.plot(time,cos_decay(time,freq,gamma),color=plt.get_cmap('tab10')(3), lw=1)\n \n axins = inset_axes(ax, width='60%', height='30%', loc='upper right', borderpad=1.1)\n axins.plot(np.linspace(0,freq*2,1000),FT(time,freq,gamma),color=plt.get_cmap('tab10')(0), lw=1)\n \n axins.set_xlabel(r'Frequency, $f$',color=plt.get_cmap('tab10')(0),fontsize=10,labelpad=1)\n axins.set_ylabel(r'$I(f)$',fontsize=10,labelpad=1)\n \n ax.set_ylabel('$I(t)$',fontsize=12)\n ax.set_xlabel(r'Time, $t$',color=plt.get_cmap('tab10')(3),fontsize=12)\n ax.set_xlim(0,10)\n```\n\n\n```python\ninteractive_plot = interactive(plot_cos_decay_FT, freq=(1, 5, .1), gamma=(.08,.14,.01) )\ninteractive_plot.children[0].description=r'$f$' # slide bar\ninteractive_plot.children[1].description=r'$\\Gamma$' # slide bar\ninteractive_plot\n```\n\n\n interactive(children=(FloatSlider(value=1.0, description='$f$', max=5.0, min=1.0), FloatSlider(value=0.14, des…\n\n\n\n\n\n```python\nimport pandas as pd\nfrom IPython.display import display\n```\n\nLibrary to handle tabular data: a convenient alternative to Excel!\n\n### Size-Exclusion Chromatography\nData from the purification of $\\alpha$-synuclein monomers kindly provided by **Veronica Lattanzi**\n \n\n\n\n```bash\n%%bash\nhead -n 22 aux/191923_d_alphasyn.txt\n```\n\n Run Name,20191023 dasyn NIST\r\n Run Date,12:10:53 PM 10-23-19\r\n Method Name,Increase_pumpA\r\n Export Format Version, 1.00\r\n Method ID, 2059\r\n Points/Second, 5.00\r\n Number of Records, 11780\r\n Offset from Run Start Time,00:00:00\r\n Run End Time,00:39:17\r\n Time,Second\r\n UV,AU,\r\n Conductivity,mS/cm\r\n Gradient Pump,\r\n Trace 3,\r\n Trace 4,\r\n Trace 5,\r\n Trace 6,\r\n GP Pressure,\r\n Volume,ml\r\n Fraction,\r\n Time,UV,Conductivity,Volume\r\n 0.0,-0.000730, 1.040, 0.0\r\n\n\n\n```python\ndf = pd.read_csv('aux/191923_d_alphasyn.txt',header=20,sep=',',index_col=0)\ndisplay(df.head(2))\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
UVConductivityVolume
Time
0.0-0.0007301.040.0
0.2-0.0007241.040.0
\n
\n\n\n\n```python\nfig = plt.figure(figsize=(6, 2.5))\nplt.plot(df.index/60, df['UV'])\nplt.ylabel('Absorbance at 276 nm'); plt.xlabel('Time / min')\n```\n\n\n```python\nfig = plt.figure(); ax1 = plt.axes()\nax1.plot(df.index/60, df['UV'])\nax2 = ax1.twinx() # creates a new subplot identical to x1, with invisible x-axis and y-axis on the r.h.s\nax2.plot(df.index/60, df['Conductivity'],color=plt.cm.tab10(3))\nax1.tick_params(axis='y',colors=plt.cm.tab10(0))\nax1.set_xlabel('Time / min')\nax1.set_ylabel('Absorbance at 276 nm',color=plt.cm.tab10(0))\nax2.set_ylabel('Conductivity / mS cm$^{-1}$',color=plt.cm.tab10(3))\nax2.tick_params(axis='y',colors=plt.cm.tab10(3))\nplt.savefig('aux/chromatogram.png')\n```\n\n\n```python\nfig = plt.figure(figsize=(6, 2.5))\n\nplt.plot(df.index/60, df['UV'])\nplt.xlim(17,27)\nt1 = 19.8; t2 = 23.5\nplt.vlines([t1,t2],ymin=0,ymax=.25,linestyle=':')\n\nplt.ylabel('Absorbance at 276 nm'); plt.xlabel('Time / min'); plt.show()\n\nt1 = 19.8*60; t2 = 23.5*60 # convertion to seconds\nabs_avg = np.mean(df.loc[t1:t2]['UV']); epsilon = 5960 ;path_length = 0.5\nprint('Monomer concentration:','{:.3f} μM'.format(abs_avg/epsilon/path_length*1e6))\n```\n\n### Data Scraping: Importing an HTML Table from [Sigma Aldrich](https://www.sigmaaldrich.com/life-science/metabolomics/learning-center/amino-acid-reference-chart.html)\n\n\n```python\nurl = \"https://www.sigmaaldrich.com/life-science/metabolomics/learning-center/amino-acid-reference-chart.html\"\ndf = pd.read_html(url, header=0, index_col=0, na_values='–')[0]\ndf = df['Alanine':'Valine'] # select rows we are interested in\ndf = df.apply(pd.to_numeric,errors='ignore') # convert numbers from strings to numeric values\ndisplay( df.iloc[::3] ) # show every third amino acid\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 \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
Abbr.Abbr..1Molecular WeightMolecular FormulaResidue FormulaResidue Weight (-H2O)pKa1pKb2pKx3pl4
Name
AlanineAlaA89.10C3H7NO2C3H5NO71.082.349.69NaN6.00
Aspartic acidAspD133.11C4H7NO4C4H5NO3115.091.889.603.652.77
GlutamineGlnQ146.15C5H10N2O3C5H8N2O2128.132.179.13NaN5.65
HydroxyprolineHypO131.13C5H9NO3C5H7NO2113.111.829.65NaNNaN
LysineLysK146.19C6H14N2O2C6H12N2O128.182.188.9510.539.74
ProlineProP115.13C5H9NO2C5H7NO97.121.9910.60NaN6.30
ThreonineThrT119.12C4H9NO3C4H7NO2101.112.099.10NaN5.60
ValineValV117.15C5H11NO2C5H9NO99.132.329.62NaN5.96
\n
\n\n\n\n```python\ndisplay( df['Arginine':'Glutamic acid'][['pKa1','pKb2','pKx3']] )\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
pKa1pKb2pKx3
Name
Arginine2.179.0412.48
Asparagine2.028.80NaN
Aspartic acid1.889.603.65
Cysteine1.9610.288.18
Glutamic acid2.199.674.25
\n
\n\n\n\n```python\ndf['Arginine':'Glutamine']['Molecular Weight'].values\n```\n\n\n\n\n array([174.2 , 132.12, 133.11, 121.16, 147.13, 146.15])\n\n\n\n\n```python\ndf['Arginine':'Glutamine']['Molecular Weight'].values.mean()\n```\n\n\n\n\n 142.31166666666667\n\n\n\n\n```python\ndisplay(df[df['pl4']>7])\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 \n \n
Abbr.Abbr..1Molecular WeightMolecular FormulaResidue FormulaResidue Weight (-H2O)pKa1pKb2pKx3pl4
Name
ArginineArgR174.20C6H14N4O2C6H12N4O156.192.179.0412.4810.76
HistidineHisH155.16C6H9N3O2C6H7N3O137.141.829.176.007.59
LysineLysK146.19C6H14N2O2C6H12N2O128.182.188.9510.539.74
\n
\n\n\n\n```python\ndf[df['pl4']>7]['Molecular Weight'].values.mean()\n```\n\n\n\n\n 158.51666666666668\n\n\n\n\n```python\nnp.mean(df['Molecular Weight']-df['Residue Weight (-H2O)'])\n```\n\n\n\n\n 18.014545454545452\n\n\n\n[](https://jakevdp.github.io/PythonDataScienceHandbook/)\nhttps://jakevdp.github.io/PythonDataScienceHandbook/\n\n### [Jupyter Course in Lund](https://github.com/mlund/jupyter-course)\n\n#### Reproducible and Interactive Data Analysis and Modelling using Jupyter Notebooks (4 ECTS)\n\n- course developed by me, Caterina Doglioni, Mikael Lund and Benjamin Ragan-Kelley\n- [COMPUTE](http://cbbp.thep.lu.se/compute/Previous_courses.php) research school (Natural Science)\n- video lectures ([Intro & Widgets](https://api.kaltura.nordu.net/p/310/sp/31000/embedIframeJs/uiconf_id/23450585/partner_id/310/widget_id/0_vujap4by?iframeembed=true&playerId=kaltura_player_5bfdb69292c20&flashvars[playlistAPI.kpl0Id]=0_nc717bpa&flashvars[playlistAPI.autoContinue]=true&flashvars[playlistAPI.autoInsert]=true&flashvars[ks]=&flashvars[localizationCode]=en&flashvars[imageDefaultDuration]=30&flashvars[leadWithHTML5]=true&flashvars[forceMobileHTML5]=true&flashvars[nextPrevBtn.plugin]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true), [Libraries](https://www.youtube.com/playlist?list=PLto3nNV9nKZlXSWOAqmmn4J7csD4I6a2d), [ATLAS Dijet](https://api.kaltura.nordu.net/p/310/sp/31000/embedIframeJs/uiconf_id/23450585/partner_id/310/widget_id/0_hr5l2zj6?iframeembed=true&playerId=kaltura_player_5bfdb5d709908&flashvars[playlistAPI.kpl0Id]=0_pspvclw2&flashvars[playlistAPI.autoContinue]=true&flashvars[playlistAPI.autoInsert]=true&flashvars[ks]=&flashvars[localizationCode]=en&flashvars[imageDefaultDuration]=30&flashvars[leadWithHTML5]=true&flashvars[forceMobileHTML5]=true&flashvars[nextPrevBtn.plugin]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true)), hands-on sessions, and peer-reviewed project work \n- next event: December–January\n- contact: \n - Ross Church: ross@astro.lu.se\n - Caterina Doglioni: caterina.doglioni@hep.lu.se\n - Mikael Lund: mikael.lund@teokem.lu.se\n\n\n\n[](http://www.rdkit.org/)\n\n\n```python\nfrom rdkit import Chem\nfrom rdkit.Chem.Draw import IPythonConsole\nm1 = Chem.MolFromSmiles('n1c2C(=O)NC(N)=Nc2ncc1CNc3ccc(cc3)C(=O)N[C@H](C(O)=O)CCC(O)=O')\nm1\n```\n\n\n```python\nfrom rdkit.Chem import Draw\nDraw.MolToFile(m1,'aux/folate.svg')\n```\n\n\n```python\nm1.GetNumAtoms()\n```\n\n\n\n\n 32\n\n\n\n\n```python\nChem.MolToSmiles(m1)\n```\n\n\n\n\n 'Nc1nc2ncc(CNc3ccc(C(=O)N[C@@H](CCC(=O)O)C(=O)O)cc3)nc2c(=O)[nH]1'\n\n\n\n\n```python\nm2 = Chem.AddHs(m1) # add hydrogens\nm2\n```\n\n\n```python\nfrom rdkit.Chem import AllChem\nChem.AllChem.EmbedMolecule(m2) # make it 3D using ETKDG method\nm2\n```\n\n\n```python\nimport nglview as nv\nview = nv.show_rdkit(m2)\nview\n```\n\n\n NGLWidget()\n\n\n\n```python\nprint(Chem.MolToMolBlock(m2),file=open('aux/folate.mol','w+'))\n```\n\n\n```python\n\nview = nv.show_file('aux/folate.mol')\nview\n```\n\n\n NGLWidget()\n\n\n\n\n\n```python\nimport mdtraj as md\ns = md.load('aux/4mqj.pdb')\nprint('Number of atoms:', s.n_atoms)\nprint('Number of residues:', s.n_residues)\nchains = [chain for chain in s.top.chains]\nn_chains = len(chains)\nprint('Number of chains:', n_chains)\ns14 = s.atom_slice(s.top.select('all and chainid < 4'))\nprint('Radius of gyration:',md.compute_rg(s14)[0],'nm')\n```\n\n Number of atoms: 10369\n Number of residues: 2386\n Number of chains: 24\n Radius of gyration: 2.3107479678330973 nm\n\n\n\n```python\nimport nglview as nv\nview = nv.show_pdbid('4mqj')\nview\n```\n\n\n NGLWidget()\n\n\n\n```python\nimport matplotlib as mpl\nview = nv.show_mdtraj(s)\nview.clear_representations(component=0)\nfor i in range(4):\n chain = [a.index for a in s.top.chain(i).atoms]\n view.add_representation('spacefill', selection=chain, color=mpl.colors.to_hex(plt.cm.tab20(i)))\nview\n```\n\n\n NGLWidget()\n\n\n\n```python\ndef viewColorScheme(molecule,dataframe):\n dataframe = dataframe.copy()\n dataframe['Abbr.'] = dataframe['Abbr.'].str.upper()\n dataframe.set_index('Abbr.', drop=True, inplace=True)\n dd = dataframe.dropna()\n dataframe = dataframe.fillna(0)\n preg = (dd['pKx3']-dd['pKx3'].min()) / (dd['pKx3'].max() - dd['pKx3'].min())\n colorscheme = pd.Series([mpl.colors.to_hex(c) for c in plt.cm.rainbow_r(preg)],index=preg.index)\n view = nv.show_mdtraj(molecule)\n view.clear_representations(component=0)\n for res in [res for chain in chains[:4] for res in chain.residues ]:\n atoms = [a.index for a in res.atoms]\n if dataframe.loc[res.name]['pKx3'] == 0:\n view.add_spacefill(selection=atoms, color='#ffffff')\n else:\n view.add_spacefill(selection=atoms, color=colorscheme[res.name])\n view.camera = 'orthographic'\n return view\n```\n\n\n```python\nviewColorScheme(s,df)\n```\n\n\n NGLWidget()\n\n\n### How to get started\n\nThe installation is simple and quick!\n\n- Install [miniconda](https://docs.conda.io/en/latest/miniconda.html)\n- miniconda is the light version of anaconda, a package manager that runs on Windows, Mac and Linux\n\n\n\n#### On Mac or Linux\n\n- Download the installation script for your operating system\n - using the terminal: `curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh`\n- Install by running the script: \n - type and enter `bash Miniconda3-latest-MacOSX-x86_64.sh`\n- Create a `conda` environment with Python 3.7 (the latest version):\n - type and enter `conda create -n myenv python`, myenv is the name of the environment (any name works)\n- Activate the environment:\n - `source activate myenv`\n- Install notebook, numpy, pandas, matplotlib, scipy:\n - `conda install notebook numpy pandas matplotlib scipy`\n- Install RDkit, mdtraj, nglview, ipywidgets\n - we need to specify the channel: `conda install -c conda-forge rdkit mdtraj nglview ipywidgets`\n- launch Jupyter notebook: `jupyter-notebook`\n\n#### On Windows\n\n- Download the installation executable for your operating system\n- Install by running the `.exe` file\n- Create a new `conda` environment with Python 3.7 (the latest version):\n - open the anaconda prompt from the start menu and navigate to the folder where the course material has been unzipped (e.g. using cd to change directory and dir to list files in a folder)\n - type: `conda create -n myenv python`, myenv is the name of the environment (any name works)\n- Activate the environment:\n - `activate myenv`\n- Install notebook, numpy, pandas, matplotlib, scipy:\n - `conda install notebook numpy pandas matplotlib scipy`\n- Install RDkit, mdtraj, nglview\n - we need to specify the channel: `conda install -c conda-forge rdkit mdtraj nglview ipywidgets`\n- launch Jupyter notebook: `jupyter-notebook`\n\n\n```python\nfrom IPython.display import IFrame\nIFrame(src='https://www.youtube.com/embed/HW29067qVWk', width=640, height=400)\n```\n\n\n\n\n\n\n\n\n\n\n### How to share my notebooks to help other scientists to reproduce my analyses\n\n- [Ten simple rules for writing and sharing computational analyses in Jupyter Notebooks](https://doi.org/10.1371/journal.pcbi.1007007)\n

\n- Saved as an HTML file and provided as Supporting Information\n

\n- It is important to provide the list of packages needed to run the notebook:\n - create a conda environment for every project\n - export the conda environment to a yml file: `conda env export > environment.yml`\n - other scientists can quickly reproduce your environment: `conda env create -f environment.yml`\n

\n- `notebook.ipynb` + data + `environment.yml` in a zip file as Supporting Information\n

\n- Example: [refnx: neutron and X-ray reflectometry analysis in Python](http://scripts.iucr.org/cgi-bin/paper?rg5158)\n\n### How to share my notebooks to help other scientists to reproduce my analyses\n\n- [Create a GitHub repository](https://help.github.com/en/github/getting-started-with-github/create-a-repo)\n

\n- Upload your notebook and `environment.yml`\n

\n- [myBinder](https://mybinder.readthedocs.io/en/latest/introduction.html) allows you to run the notebook in the repository on a server: no need to download and install \n

\n- Example: [refnx: neutron and X-ray reflectometry analysis in Python](https://github.com/refnx/refnx)\n\n[](https://reproducible-science-curriculum.github.io/sharing-RR-Jupyter/01-sharing-github/)\n
\n\n\n\nTo convert a notebook into slides in pdf format:\n1. `jupyter nbconvert --to slides jupyter.ipynb --post serve`\n2. `conda install nodejs`\n3. `npm install -g decktape`\n4. copy `reveal.js/` and `custom.css` in the notebook directory (Developer Tools in Chrome)\n5. modify `reveal.js/js/reveal.js` so that: width: \"90%\", height: \"90%\", margin: 0, minScale: 1 and maxScale: 1\n6. convert html to pdf: `decktape jupyter.slides.html jupyter.pdf`\n", "meta": {"hexsha": "024c502524dd4ef80791c814b513513079df18ac", "size": 399589, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "qdetailss/jupyter.ipynb", "max_stars_repo_name": "urania277/jupyter-course", "max_stars_repo_head_hexsha": "20060173e7355fc4726148f00b61404d2613b74b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:41:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T21:24:04.000Z", "max_issues_repo_path": "qdetailss/jupyter.ipynb", "max_issues_repo_name": "urania277/jupyter-course", "max_issues_repo_head_hexsha": "20060173e7355fc4726148f00b61404d2613b74b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-12-08T20:12:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T09:28:07.000Z", "max_forks_repo_path": "lectures/qdetailss/jupyter.ipynb", "max_forks_repo_name": "mlund/jupyter-course", "max_forks_repo_head_hexsha": "d2e12d153febc6848a1ed80a2f3f29973a3bea73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2017-12-11T13:18:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T14:18:33.000Z", "avg_line_length": 160.3487158909, "max_line_length": 59136, "alphanum_fraction": 0.8836229226, "converted": true, "num_tokens": 11410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.2146914090629578, "lm_q1q2_score": 0.09399694394570265}} {"text": "\n
\n GEOS 639 Geodetic Imaging \n\n Lab 5: Volcano Source Modeling Using InSAR -- [20 Points] \n\n
\n Franz J Meyer; University of Alaska Fairbanks
\n Due Date: April 14, 2022 \n
\n\n This lab will introduce you to the intersection between Geodetic Displacement data created using InSAR and Geophysical Modeling. Radar Remote Sensing can provide you with geodetic observations of surface displacement. Inverse Modeling helps you understand the physical causes behind an observed displacement. \n \nTo illuminate the handoff from geodesy to geophysics, this lab will show how to use InSAR observations to determine the most likely parameters of a volcanic magma source underneath Okmok volcano, Alaska. You will use a Mogi source model to describe the physics behind observed surface displacement at Okmok. We will again use our **Jupyter Notebook** framework implemented within the Amazon Web Services (AWS) cloud to work on this exercise.

\n\nThis Lab is part of the UAF course GEOS639 Geodetic Imaging. It will introduce the following data analysis concepts:\n\n- A Mogi Source Model describing volcanic source geometry and physics\n- How to use the \"grid search\" method to perform a pseudo-inversion of a Mogi source model \n- How to solve for the best fitting source parameters using modeling with InSAR data\n
\n
\n\n\n
\n THIS NOTEBOOK INCLUDES THREE HOMEWORK ASSIGNMENTS. \n
\n Complete all assignments to achieve full score.
\n\n To submit your homework, please download your completed Jupyter Notebook from the server both asf PDF (*.pdf) and Notebook file (*.ipynb) and submit them as a ZIP bundle via the GEOS 639 Canvas page. To download, please select the following options in the main menu of the notebook interface:\n\n
    \n
  1. Save your notebook with all of its content by selecting File / Save and Checkpoint
  2. \n
  3. To export in Notebook format, click the radio button next to the notebook file in the main Jupyter Hub browser tab. Once clicked, a download field will appear near the top of the page.
  4. \n
  5. To export in PDF format, right-click on your browser window and print the browser content to PDF
  6. \n
\n\nContact me at fjmeyer@alaska.edu should you run into any problems.\n
\n
\n
\n\n\n```python\nimport url_widget as url_w\nnotebookUrl = url_w.URLWidget()\ndisplay(notebookUrl)\n```\n\n\n```python\nfrom IPython.display import Markdown\nfrom IPython.display import display\n\nnotebookUrl = notebookUrl.value\nuser = !echo $JUPYTERHUB_USER\nenv = !echo $CONDA_PREFIX\nif env[0] == '':\n env[0] = 'Python 3 (base)'\nif env[0] != '/home/jovyan/.local/envs/unavco':\n display(Markdown(f'WARNING:'))\n display(Markdown(f'This notebook should be run using the \"unavco\" conda environment.'))\n display(Markdown(f'It is currently using the \"{env[0].split(\"/\")[-1]}\" environment.'))\n display(Markdown(f'Select \"unavco\" from the \"Change Kernel\" submenu of the \"Kernel\" menu.'))\n display(Markdown(f'If the \"unavco\" environment is not present, use Create_OSL_Conda_Environments.ipynb to create it.'))\n display(Markdown(f'Note that you must restart your server after creating a new environment before it is usable by notebooks.'))\n```\n\n# 0. Importing Relevant Python Packages\n\n First step in any notebook is to import the required Python libraries into the Jupyter environment. In this notebooks we use the following scientific libraries:\n
    \n
  1. NumPy is one of the principal packages for scientific applications of Python. It is intended for processing large multidimensional arrays.
  2. \n
  3. Matplotlib is a low-level library for creating two-dimensional diagrams and graphs. With its help, you can build diverse charts, from histograms and scatterplots to non-Cartesian coordinates graphs.
  4. \n
\n
\nThe first step is to import all required python modules:\n\n\n```python\nimport os # for chdir, getcwd, path.basename, path.exists\nimport copy\nimport subprocess # for check_call\n\nimport matplotlib.pylab as plt # for add_subplot, cm.jet, colorbar, figure, grid, imshow, rcParams.update, savefig,\n # set_bad, set_clim, set_title, set_xlabel, set_ylabel\nimport numpy as np # for arange, arctan, concatenate, cos, fromfile, isnan, ma.masked_value, min, pi, power, reshape,\n # sqrt, square, sin, sum, tile, transpose, where, zeros \n```\n\nset up matplotlib plotting inside the notebook:\n\n\n```python\n%matplotlib inline\n```\n\n
\n\n# 1. Introduction to the Study Site: Okmok Volcano, Alaska\n\n Okmok is one of the more active volcanoes in Alaska’s Aleutian Chain. Its last (confirmed) eruption was in the summer of 2008. Okmok is interesting from an InSAR perspective as it inflates and deflates heavily as magma moves around in its magmatic source located roughly 2.5 km underneath the surface. To learn more about Okmok volcano and its eruptive history, please visit the very informative site of the Alaska Volcano Observatory.\n\nThis lab uses a pair of C-band ERS-2 SAR images acquired on Aug 18, 2000 and Jul 19, 2002 to analyze the properties of a volcanic source that was responsible for an inflation of Okmok volcano of more than 3 cm near its summit. The figure to the right shows the Okmok surface displacement as measured by GPS data from field campaigns conducted in 2000 and 2002. The plots show that the displacement measured at the site is consistent with that created by an inflating point (Mogi) source.
\n\nThe primary goal of the problem set is to estimate values for four unknown model parameters describing a source process beneath a volcano. The lab uses real InSAR data from Okmok volcano, so you should get some sense for how remote sensing can be used to infer physical processes at volcanoes. We will assume that the source can be modeled as an inflating point source (a so-called Mogi source) and will use a grid-search method to find the source model parameters (3D source location and volume of magma influx) that best describe our InSAR-observed surface displacement.\n
\n
\n
\n\n# 2. Downloading and Visualizing the InSAR Data\n\n## 2.1 Download Data from AWS S3 Storage Bucket and Prep for Further Processing\n\nWe are using a pre-calculated displacement map created from C-band ERS-2 SAR images acquired on Aug 18, 2000 and Jul 19, 2002. We will pull the displacement map from an Amazon Web Services (AWS) S3 storage bucket: \n\nCreate and move to a directory in which to store our Lab 5 files:\"\n\n\n```python\npath = f\"{os.getcwd()}/lab_6_data\"\nif not os.path.exists(path):\n os.makedirs(path)\nos.chdir(path)\nprint(f\"Current working directory: {os.getcwd()}\")\n```\n\nDownload the displacement map from the AWS-S3 bucket:\n\n\n```python\ndisplacement_map_path = 's3://asf-jupyter-data-west/E451_20000818_20020719.unw'\ndisplacement_map = os.path.basename(displacement_map_path)\n!aws --region=us-west-2 --no-sign-request s3 cp $displacement_map_path $displacement_map\n```\n\nDefine some variables:\n\n\n```python\nsample = 1100\nline = 980\nposting = 40.0\nhalf_wave = 28.3\n```\n\nRead the dataset into the notebook, storing our observed displacement map in the variable \"observed_displacement_map\": \n\n\n```python\nif os.path.exists(displacement_map):\n with open (displacement_map, 'rb') as f: \n coh = np.fromfile(f, dtype='>f', count=-1)\n observed_displacement_map = np.reshape(coh, (line, sample))\n```\n\nNow we scale the measured and unwrapped InSAR phase into surface displacement in *cm* units and replace all ```nans``` with 0\n\n\n```python\nobserved_displacement_map = observed_displacement_map*half_wave/2.0/np.pi\nwhere_are_NaNs = np.isnan(observed_displacement_map)\nobserved_displacement_map[where_are_NaNs] = 0\n```\n\n Create a mask that removes invalid samples (low coherence) from the displacement map: \n\n\n```python\nobserved_displacement_map_m = np.ma.masked_where(observed_displacement_map==0, observed_displacement_map)\n```\n\n
\n\n## 2.2 Visualize The Surface Displacement Map\n\n We will visualize the displacement map both in units of [cm] and as a rewrapped interferogram.\n

\nWrite a function that calculates the bounding box.
\n\n\n```python\ndef extents(vector_component):\n delta = vector_component[1] - vector_component[0]\n return [vector_component[0] - delta/2, vector_component[-1] + delta/2]\n```\n\nCreate a directory in which to store the plots we are about to make, and move into it: \n\n\n```python\nos.chdir(path)\nproduct_path = 'plots'\nif not os.path.exists(product_path):\n os.makedirs(product_path)\nif os.path.exists(product_path) and os.getcwd() != f\"{path}/{product_path}\":\n os.chdir(product_path)\nprint(f\"Current working directory: {os.getcwd()}\")\n```\n\nWrite a plotting function:\n\n\n```python\ndef plot_model(infile, line, sample, posting, output_filename=None, dpi=72):\n # Calculate the bounding box\n extent_xvec = extents((np.arange(1, sample*posting, posting)) / 1000)\n extent_yvec = extents((np.arange(1, line*posting, posting)) / 1000)\n extent_xy = extent_xvec + extent_yvec\n \n plt.rcParams.update({'font.size': 14})\n inwrapped = (infile/10 + np.pi) % (2*np.pi) - np.pi\n cmap = copy.copy(plt.cm.get_cmap(\"jet\"))\n cmap.set_bad('white', 1.)\n \n # Plot displacement\n fig = plt.figure(figsize=(16, 8))\n ax1 = fig.add_subplot(1, 2, 1)\n im = ax1.imshow(infile, interpolation='nearest', cmap=cmap, extent=extent_xy, origin='upper')\n cbar = ax1.figure.colorbar(im, ax=ax1, orientation='horizontal')\n ax1.set_title(\"Displacement in look direction [mm]\")\n ax1.set_xlabel(\"Easting [km]\")\n ax1.set_ylabel(\"Northing [km]\")\n plt.grid()\n \n # Plot interferogram\n im.set_clim(-30, 30)\n ax2 = fig.add_subplot(1, 2, 2)\n im = ax2.imshow(inwrapped, interpolation='nearest', cmap=cmap, extent=extent_xy, origin='upper')\n cbar = ax2.figure.colorbar(im, ax=ax2, orientation='horizontal')\n ax2.set_title(\"Interferogram phase [rad]\")\n ax2.set_xlabel(\"Easting [km]\")\n ax2.set_ylabel(\"Northing [km]\")\n plt.grid()\n \n if output_filename:\n plt.savefig(output_filename, dpi=dpi)\n```\n\nCall plot_model() to plot our observed displacement map: \n\n\n```python\nplot_model(observed_displacement_map_m, line, sample, posting, output_filename='Okmok-inflation-observation.png', dpi=200)\n```\n\n
\n\n# 3. The Mogi Source Forward Model for InSAR Observations\n\n## 3.1 The Mogi Equation\n\nThe Mogi model provides the 3D ground displacement, $u(x,y,z)$, due to an inflating source at location $(x_s,y_s,z_s)$ with volume change $V$:\n\n\\begin{equation}\nu(x,y,z)=\\frac{1}{\\pi}(1-\\nu)\\cdot V\\Big(\\frac{x-x_s}{r(x,y,z)^3},\\frac{y-y_s}{r(x,y,z)^3},\\frac{z-z_s}{r(x,y,z)^3}\\Big)\n\\end{equation}\n
\n\\begin{equation}\nr(x,y,z)=\\sqrt{(x-x_s)^2+(y-y_s)^2+(z-z_s)^2}\n\\end{equation}\n\nwhere $r$ is the distance from the Mogi source to $(x,y,z)$, and $\\nu$ is the Poisson's ratio of the halfspace. The Poisson ratio describes how rocks react when put under stress (e.g., pressure). It is affected by temperature, the quantity of liquid to solid, and the composition of the soil material. In our problem, we will assume that $\\nu$ is fixed. \n
\n\n## 3.2 Projecting Mogi Displacement to InSAR Line-of-Sight\n\nIn our example, the $x$-axis points east, $y$ points north, and $z$ points up. However, in the code the input values for $z$ are assumed to be depth, such that the Mogi source is at depth $z_s > 0$. The observed interferogram is already corrected for the effect of topography, so the observations can be considered to be at $z = 0$.\n \n\nThe satellite “sees” a projection of the 3D ground displacement, $u$, onto the look vector, $\\hat{L}$, which points from the satellite to the target. Therefore, we are actually interested in the (signed magnitude of the) projection of $u$ onto $\\hat{L}$ (right). This is given by\n\n\\begin{array}{lcl} proj_{\\hat{L}}u & = & (u^T\\hat{L})\\hat{L} \\\\ u^T\\hat{L} & = & u \\cdot \\hat{L} = |u||\\hat{L}|cos(\\alpha) = |u|cos(\\alpha) \\\\ & = & u_x\\hat{L}_x+ u_y\\hat{L}_y + u_z\\hat{L}_z \\end{array}\n\nwhere the look vector is given by $\\hat{L}=(sin(l) \\cdot cos(t), -sin(l) \\cdot sin(t), -cos(l))$, where $l$ is the look angle measured from the nadir direction and $t$ is the satellite track angle measured clockwise from geographic north. All vectors are represented in an east-north-up basis.\n\nOur forward model takes a Mogi source, $(x_s,y_s,z_s,V)$, and computes the look displacement at any given $(x, y, z)$ point. If we represent the ith point on our surface grid by $x_i = (x_i,y_i,z_i)$ the the displacement vector is $u_i = u(x_i, y_i, z_i)$, and the look displacement is\n\n\\begin{equation}\nd_i = u_i \\cdot \\hat{L}\n\\end{equation}\n\n\n\n## 3.3 Defining the Mogi Forward Model\n\nWe can now represent the Mogi forward problem as \n\n\\begin{equation}\ng(m) = d\n\\end{equation}\n\nwhere $g(·)$ describes the forward model in the very first equation in this notebook, $m$ is the (unknown) Mogi model, and $d$ is the predicted interferogram. The following code cells calculate the Mogi forward model according to the equations given above:\n\n\nWrite a function to calculate a forward model for a Mogi source. \n\n\n```python\ndef calc_forward_model_mogi(n1, e1, depth, delta_volume, northing, easting, plook):\n \n # This geophysical coefficient is needed to describe how pressure relates to volume change\n displacement_coefficient = (1e6*delta_volume*3)/(np.pi*4)\n \n # Calculating the horizontal distance from every point in the displacement map to the x/y source location\n d_mat = np.sqrt(np.square(northing-n1) + np.square(easting-e1))\n \n # denominator of displacement field for mogi source\n tmp_hyp = np.power(np.square(d_mat) + np.square(depth),1.5)\n \n # horizontal displacement\n horizontal_displacement = displacement_coefficient * d_mat / tmp_hyp\n \n # vertical displacement\n vertical_displacement = displacement_coefficient * depth / tmp_hyp\n \n # azimuthal angle\n azimuth = np.arctan2((easting-e1), (northing-n1))\n \n # compute north and east displacement from horizontal displacement and azimuth angle\n east_displacement = np.sin(azimuth) * horizontal_displacement\n north_displacement = np.cos(azimuth) * horizontal_displacement\n \n # project displacement field onto look vector\n temp = np.concatenate((east_displacement, north_displacement, vertical_displacement), axis=1)\n delta_range = temp.dot(np.transpose([plook]))\n delta_range = -1.0 * delta_range\n return delta_range\n```\n\nWrite a function to create simulated displacement data based on Mogi Source Model parameters: \n\n\n```python\ndef displacement_data_from_mogi(x, y, z, volume, iplot, imask):\n # Organizing model parameters\n bvc = [x, y, z, volume, 0, 0, 0, 0]\n bvc = np.asarray(bvc, dtype=object)\n bvc = np.transpose(bvc)\n \n # Setting acquisition parameters\n track = -13.3*np.pi / 180.0\n look = 23.0*np.pi / 180.0\n plook = [-np.sin(look)*np.cos(track), np.sin(look)*np.sin(track), np.cos(look)]\n \n # Defining easting and northing vectors\n northing = np.arange(0, (line)*posting, posting) / 1000\n easting = np.arange(0, (sample)*posting, posting) / 1000\n northing_mat = np.tile(northing, (sample, 1))\n easting_mat = np.transpose(np.tile(easting, (line, 1)))\n northing_vec = np.reshape(northing_mat, (line*sample, 1))\n easting_vec = np.reshape(easting_mat, (line*sample, 1))\n \n # Handing coordinates and model parameters over to the rngchg_mogi function\n calc_range = calc_forward_model_mogi(bvc[1], bvc[0], bvc[2], bvc[3], northing_vec, easting_vec, plook)\n \n # Reshaping surface displacement data derived via calc_forward_model_mogi()\n surface_displacement = np.reshape(calc_range, (sample,line))\n \n # return rotated surface displacement\n return np.transpose(np.fliplr(surface_displacement))\n```\n\n
\n\n## 3.4 Plotting The Mogi Forward Model\n\nThe cell below plots several Mogi forward models by varying some of the four main Mogi modeling parameters $(x_s,y_s,z_s,V)$.\n \nThe examples below fix the depth parameter to $z_s = 2.58 km$ and the volume change parameter to $volume = 0.0034 km^3$. We then vary the easting and northing parameters $x_s$ and $y_s$ to demonstrate how the model predictions vary when model parameters are changed.\n

\nRun the first example: \n\n\n```python\nplt.rcParams.update({'font.size': 14})\nextent_x = extents((np.arange(1, sample*posting, posting))/1000)\nextent_y = extents((np.arange(1, line*posting, posting))/1000)\nextent_xy = extent_x + extent_y\nxs = np.arange(18, 24.2, 0.4)\nys = np.arange(20, 24.2, 0.4)\n\nzs = 2.58;\nvolume = 0.0034;\nxa = [0, 7, 15]\nya = [0 ,5, 10]\n\nfig = plt.figure(figsize=(18, 18))\ncmap = copy.copy(plt.cm.get_cmap(\"jet\"))\nsubplot_index = 1\n\nfor k in xa:\n for l in ya: \n ax = fig.add_subplot(3, 3, subplot_index)\n predicted_displacement_map = displacement_data_from_mogi(xs[k], ys[l], zs, volume, 0, 0)\n predicted_displacement_map_m = np.ma.masked_where(observed_displacement_map==0, predicted_displacement_map)\n im = ax.imshow(predicted_displacement_map_m, interpolation='nearest', cmap=cmap, extent=extent_xy)\n cbar = ax.figure.colorbar(im, ax=ax, orientation='horizontal')\n plt.grid()\n im.set_clim(-30, 30)\n ax.plot(xs[k],ys[l], 'k*', markersize=25, markerfacecolor='w')\n ax.set_title('Source: X=%4.2fkm; Y=%4.2fkm' % (xs[k], ys[l]))\n ax.set_xlabel(\"Easting [km]\")\n ax.set_ylabel(\"Northing [km]\")\n subplot_index += 1\n \nplt.savefig('Model-samples-3by3.png', dpi=200, transparent='false')\n```\n\n
\n\n# Homework Assignment #1 \n\n
\n ASSIGNMENT #1: Experiment with the Mogi Forward Model -- [8 Points] \n\n To get a feeling for the Mogi forward model, please run the following forward model experiments using the Python Function displacement_data_from_mogi and plot the results (using the code cell above):\n\n
    \n
  1. Run a reference simulation using the code cell above by specifying the following model parameters for source depth $x_s$ and volume change $V$: $z_{s1} = 2.5 km$; $V_1 = 0.01 km^3$. The script will visualize the resulting simulated surface displacement maps. Change the name of the output figure (last line of the script) to something that you will recognize later on (e.g., ReferenceRun.png). -- [2 Points]
  2. \n
    \n
  3. Change the depth of the source by a factor of three ($z_{s2} = 7.5 km$) while leaving the other model parameters unchanged. Modify name of the output figure in the last line of the script. Visualize the results. Discuss changes to the reference run. Describe how the strength and shape of the displacement signal has changed and provide a physical explanation. -- [2 Points]
  4. \n
    \n
  5. Now change the source volume by a factor of three ($V_2 = 0.03 km^3$ – also reset source depth to $z_{s1} = 2.5 km$). Visualize the results and compare them to the reference run. -- [2 Points]
  6. \n
    \n
  7. Finally change both source volume and depth by a factor of three ($z_{s2} = 7.5 km$ and $V_2 = 0.03 km^3$). Compare this result to the results of experiments 1–3. -- [2 Points]
  8. \n
\n\n
\n
\n\n
\n
\n Question 1.1 [2 Points]: Experiment no. 1: Perform reference run in code cell above using source model parameters to $z_{s1} = 2.5 km$; $V_1 = 0.01 km^3$. Plot results. \n\nADD DISCUSSION HERE:\n\n
\n\n
\n
\n Question 1.2 [2 Points]: Experiment no. 2: Set source model parameters to $z_{s2} = 7.5 km$; $V_1 = 0.01 km^3$. Plot and discuss the results in comparison to reference run. \n\nADD DISCUSSION HERE:\n\n
\n\n
\n
\n Question 1.3 [2 Points]: Experiment no. 3: Set source model parameters to $V_2 = 0.03 km^3$ and $z_{s1} = 2.5 km$. Plot and discuss the results in comparison to reference run. \n\nADD DISCUSSION HERE:\n\n
\n\n
\n
\n Question 1.4 [2 Points]: Experiment no. 4: Set source model parameters to $V_2 = 0.03 km^3$ and $z_{s2} = 7.5 km$. Plot and discuss the results in comparison to reference run. \n\nADD DISCUSSION HERE:\n\n
\n
\n\nModify the example script below to answer questions 1.2 - 1.4: \n\n\n```python\nplt.rcParams.update({'font.size': 14})\nextent_x = extents((np.arange(1, sample*posting, posting))/1000)\nextent_y = extents((np.arange(1, line*posting, posting))/1000)\nextent_xy = extent_x + extent_y\nxs = np.arange(18, 24.2, 0.4)\nys = np.arange(20, 24.2, 0.4)\n\n# ------------ Change Variables HERE --------------- #\nzs = 2.58;\nvolume = 0.0034;\n# ------------------------------------------------- #\n\nxa = [0, 7, 15]\nya = [0 ,5, 10]\n\nfig = plt.figure(figsize=(18, 18))\ncmap = copy.copy(plt.cm.get_cmap(\"jet\"))\nsubplot_index = 1\n\nfor k in xa:\n for l in ya: \n ax = fig.add_subplot(3, 3, subplot_index)\n predicted_displacement_map = displacement_data_from_mogi(xs[k], ys[l], zs, volume, 0, 0)\n predicted_displacement_map_m = np.ma.masked_where(observed_displacement_map==0, predicted_displacement_map)\n im = ax.imshow(predicted_displacement_map_m, interpolation='nearest', cmap=cmap,extent=extent_xy)\n cbar = ax.figure.colorbar(im, ax=ax, orientation ='horizontal')\n plt.grid()\n im.set_clim(-30, 30)\n ax.plot(xs[k],ys[l], 'k*', markersize=25, markerfacecolor='w')\n ax.set_title(f\"Source: X={xs[k]:.2f}km; Y={ys[l]:.2f}km\")\n ax.set_xlabel(\"Easting [km]\")\n ax.set_ylabel(\"Northing [km]\")\n subplot_index += 1\n\n# CHANGE THE NAME OF THE IMAGE THAT IS BEING SAVED TO YOUR CLOUD INSTANCE!!\nplt.savefig('Model-samples-3by3.png', dpi=200, transparent='false')\n```\n\n
\n\n# 4. Solving the Inverse Model\n\n The inverse problem seeks to determine the optimal parameters $(\\hat{x_s},\\hat{y_s},\\hat{z_s},\\hat{V})$ of the Mogi model $m$ by minimizing the misfit between predictions, $g(m)$, and observations $d^{obs}$ according to\n \n\\begin{equation}\n\\sum{\\Big[g(m) - d^{obs}\\Big]^2}\n\\end{equation}\n\nThis equation describes misfit using the method of least-squares, a standard approach to approximate the solution of an overdetermined equation system. We will use a grid-search approach to find the set of model parameters that minimize the the misfit function. The approach is composed of the following processing steps: \n
    \n
  1. Loop through the mogi model parameters,
  2. \n
  3. Calculate the forward model for each set of parameters,
  4. \n
  5. Calculate the misfit $\\sum{[g(m) - d^{obs}]^2}$, and
  6. \n
  7. Find the parameter set that minimizes this misfit.
  8. \n
\n
\n\n## 4.1 Experimenting with Misfit\n\nLet's look at the misfit $\\sum{[g(m) - d^{obs}]^2}$ for a number of different model parameter sets $(x_s,y_s,z_s,V)$: \n\n\n\n\n```python\nplt.rcParams.update({'font.size': 14})\nextent_x = extents((np.arange(1, sample*posting, posting))/1000)\nextent_y = extents((np.arange(1, line*posting, posting))/1000)\nextent_xy = extent_x + extent_y\nxs = np.arange(18, 24.2, 0.4)\nys = np.arange(20, 24.2, 0.4)\n\nzs = 2.58;\nvolume = 0.0034;\nxa = [0, 7, 15]\nya = [0 ,5, 10]\n\nfig = plt.figure(figsize=(18, 18))\ncmap = copy.copy(plt.cm.get_cmap(\"jet\"))\nsubplot_index = 1\n\nfor k in xa:\n for l in ya: \n ax = fig.add_subplot(3, 3, subplot_index)\n predicted_displacement_map = displacement_data_from_mogi(xs[k], ys[l], zs, volume, 0, 0)\n predicted_displacement_map_m = np.ma.masked_where(observed_displacement_map==0, predicted_displacement_map)\n im = ax.imshow(observed_displacement_map_m-predicted_displacement_map_m, interpolation='nearest', cmap=cmap, extent=extent_xy)\n cbar = ax.figure.colorbar(im, ax=ax, orientation='horizontal')\n plt.grid()\n im.set_clim(-30, 30)\n ax.plot(xs[k], ys[l], 'k*', markersize=25, markerfacecolor='w')\n ax.set_title('Source: X=%4.2fkm; Y=%4.2fkm' % (xs[k], ys[l]))\n ax.set_xlabel(\"Easting [km]\")\n ax.set_ylabel(\"Northing [km]\")\n subplot_index += 1\nplt.savefig('Misfit-samples-3by3.png', dpi=200, transparent='false')\n```\n\n
\n\n## 4.2 Running Grid-Search to find Best Fitting Model Parameter $(\\hat{x}_s,\\hat{y}_s)$\n\nThe following code cell runs a grid-search approach to find the best fitting Mogi source parameters for the 2000-2002 displacement event at Okmok. To keep things simple, we will fix the depth $z_s$ and volume change $V$ parameters close to their \"true\" values and search only for the correct east/north source location ($x_s,y_s$).\n

\nWrite a script using the grid-search approach in Python:\n\n\n```python\n# FIX Z AND dV, SEARCH OVER X AND Y\n\n# Setting up search parameters\nxs = np.arange(19, 22.2, 0.2)\nys = np.arange(21, 23.2, 0.2)\nzs = 2.58;\nvolume = 0.0034;\n\nnx = xs.size\nny = ys.size\nng = nx * ny;\n\nprint(f\"fixed z = {zs}km, dV = {volume}, searching over (x,y)\")\n\nmisfit = np.zeros((nx, ny))\nsubplot_index = 0\n\n# Commence grid-search for best model parameters\nfor k, xv in enumerate(xs):\n for l, yv in enumerate(ys):\n subplot_index += 1\n predicted_displacement_map = displacement_data_from_mogi(xs[k], ys[l], zs, volume, 0, 0)\n predicted_displacement_map_m = np.ma.masked_where(observed_displacement_map==0, predicted_displacement_map)\n misfit[k,l] = np.sum(np.square(observed_displacement_map_m - predicted_displacement_map_m))\n print(f\"Source {subplot_index:3d}/{ng:3d} is x = {xs[k]:.2f} km, y = {ys[l]:.2f} km\")\n\n# Searching for the minimum in the misfit matrix\nmmf = np.where(misfit == np.min(misfit))\nprint(f\"\\n----------------------------------------------------------------\")\nprint('Best fitting Mogi Source located at: X = %5.2f km; Y = %5.2f km' % (xs[mmf[0]], ys[mmf[1]]))\nprint(f\"----------------------------------------------------------------\")\n```\n\n
\n\n## 4.3 Plot and Inspect the Misfit Function\n\nThe code cell below plots the misfit function ($\\sum{[g(m) - d^{obs}]^2}$) describing the fit of different Mogi source parameterizations to the observed InSAR data. You should notice a clear minimum in the misfit plot at the location of the best fitting source location estimated above. \n \nYou may notice that, even for the best fitting solution, the misfit does not become zero. This could be due to other signals in the InSAR data (e.g., atmospheric effects or residual topography). Alternatively, it could also indicate that the observed displacement doesn't fully comply with Mogi theory. \n\n

\nPlot the misfit function ($\\sum{[g(m) - d^{obs}]^2}$):\n\n\n```python\nplt.rcParams.update({'font.size': 18})\nextent_xy = extents(xs) + extents(ys)\nfig = plt.figure(figsize=(10, 10))\ncmap = copy.copy(plt.cm.get_cmap(\"jet\"))\nax1 = fig.add_subplot(1, 1 ,1)\nim = ax1.imshow(np.transpose(misfit), origin='lower', interpolation='nearest', cmap=cmap, extent=extent_xy)\n# USE THIS COMMAND TO CHANGE COLOR SCALING: im.set_clim(-30, 30)\nax1.set_aspect('auto')\ncbar = ax1.figure.colorbar(im, ax=ax1, orientation='horizontal')\nax1.plot(xs[mmf[0]], ys[mmf[1]], 'k*', markersize=25, markerfacecolor='w')\nax1.set_title(\"Misfit Function for Mogi-Source Approximation\")\nax1.set_xlabel(\"Easting [km]\")\nax1.set_ylabel(\"Northing [km]\")\nplt.savefig('Misfit-function.png', dpi=200, transparent='false')\n```\n\n
\n\n## 4.4 Plot Best-Fitting Mogi Forward Model and Compare to Observations\n\nWith the best-fitting model parameters defined, you can now analyze how well the model fits the InSAR-observed surface displacement. The best way to do that is to look at both the observed and predicted displacement maps and compare their spatial patterns. Additionally, we will also plot the residuals (observed_displacement_map - observed_displacement_map) to determine if there are additional signals in the data that are not modeled using Mogi theory. \n\n

\nCompare the observed and predicted displacement maps:\n\n\n```python\n# Calculate predicted displacement map for best-fitting Mogi parameters:\npredicted_displacement_map = displacement_data_from_mogi(xs[mmf[0]], ys[mmf[1]], zs, volume, 0, 0)\n\n# Mask the predicted displacement map to remove pixels incoherent in the observations:\npredicted_displacement_map_m = np.ma.masked_where(observed_displacement_map==0, predicted_displacement_map)\n\n# Plot observed displacement map\nplot_model(observed_displacement_map_m, line, sample, posting)\n\n# Plot simulated displacement map\nplot_model(predicted_displacement_map_m, line, sample, posting)\n\nplt.savefig('BestFittingMogiDefo.png', dpi=200, transparent='false')\n\n# Plot simulated displacement map without mask applied\nplot_model(predicted_displacement_map, line, sample, posting)\n```\n\nDetermine if there are additional signals in the data that are not modeled using Mogi theory:\n\n\n```python\n# Plot residual between observed and predicted displacement maps\nplot_model(observed_displacement_map_m-predicted_displacement_map_m, line, sample, posting)\nplt.savefig('Residuals-ObsMinusMogi.png', dpi=200, transparent='false')\n```\n\n# Homework Assignment #2 \n\n
\n ASSIGNMENT #2: Run 2nd Grid-Search to Find Model Parameters $(\\hat{z}_s,\\hat{V})$ -- [8 Points] \n\n For this second grid-search run, we now switch out the model parameters we are trying to estimate. We will assume that the lateral location of the Mogi source is now fixed to its estimated value ($\\hat{x}_s = 20.6 km$; $\\hat{y}_s = 21.8 km$). \n\nTo perform a grid search for the best fitting model parameters $\\hat{z}_s$ and $\\hat{V}$, please complete the following steps:\n\n
    \n
    \n
  1. Using the previous grid-search script as a template, write a new grid-search script to search for the best fitting source model depth ($z_s$) and volume change ($V$). -- [3 Points]
  2. \n
    \n
  3. Provide a plot of the misfit function and provide the best-fitting values for $\\hat{z}_s$ and $\\hat{V}$. When plotting the misfit function, put $z_s$ on the vertical axis. You may want to adjust the color scale, in order to better see the shape of the misfit function. -- [2 Points]
  4. \n
    \n
  5. Compare the $z_s$ vs. $V$ misfit function (misfit function 2) to the $y_s$ vs. $x_s$ misfit function (misfit function 1). You should see that the shape of the function is different. Misfit function 1 is largely of circular shape while misfit function 2 appears elongated. Interpret this pattern. -- [3 Points]
  6. \n
\n\n
\n
\n\n
\n
\n Question 2.1 [3 Points]: Provide code to perform grid search over $z_s$ and $V$. \n\nPROVIDE SCRIPT BY MODIFYING THE CODE IN THE CODE CELL BELOW:\n\n
\n\n\n```python\n# !!!! MODIFY THIS SCRIPT TO PERFORM A GRID SEARCH OVER zs AND V: !!!!\n\n# Setting up search parameters\nxs = np.arange(19, 22.2, 0.2)\nys = np.arange(21, 23.2, 0.2)\nzs = 2.58;\nvolume = 0.0034;\n\nnx = xs.size\nny = ys.size\nng = nx * ny;\n\n#print('fixed z = ',zs,' km, dV = ',volume, ' searching over (x,y)')\nprint(f\"fixed z = {zs}km, dV = {volume}, searching over (x,y)\")\n\nmisfit=np.zeros((nx,ny))\nsubplot_index = 0\n\n# Commence grid-search for best model parameters\nfor k, xv in enumerate(xs):\n for l, yv in enumerate(ys):\n subplot_index = subplot_index+1\n predicted_displacement_map = displacement_data_from_mogi(xs[k],ys[l],zs,volume,0,0)\n predicted_displacement_map_m = np.ma.masked_where(observed_displacement_map == 0, predicted_displacement_map)\n misfit[k,l] = np.sum(np.square(observed_displacement_map_m - predicted_displacement_map_m))\n print(f\"Source {subplot_index:3d}/{ng:3d} is x = {xs[k]:.2f} km, y = {ys[l]:.2f} km\")\n\n# Searching for the minimum in the misfit matrix\nmmf = np.where(misfit == np.min(misfit))\nprint('')\nprint(f\"\\n----------------------------------------------------------------\")\nprint('Best fitting Mogi Source located at: X = %5.2f km; Y = %5.2f km' % (xs[mmf[0]], ys[mmf[1]]))\nprint(f\"----------------------------------------------------------------\")\n```\n\n
\n
\n Question 2.2-A [1 Points]: Provide the best fitting values for source depth ($\\hat{z}_s$) and volume change ($\\hat{V}$) according to your grid-search results. \n\nPROVIDE ESTIMATES FOR $\\hat{z}_s$ and $\\hat{V}$ HERE:\n\n
\n\n
\n
\n Question 2.2-B [1 Points]: Provide plot of $z_s$ on $V$ misfit function. \n\nPROVIDE PLOT HERE:\n\n
\n\n
\n
\n Question 2.3 [3 Points]: Compare the $z_s$ vs. $V$ misfit function (misfit function 2) to the initial $y_s$ vs. $x_s$ misfit function (misfit function 1). Interpret their difference in spatial pattern. \n\nPROVIDE DISCUSSION HERE:\n\n
\n\n
\n\n# Homework Assignment #3 \n\n
\n ASSIGNMENT #3: Error Discussion -- [4 Points] \n\n In a perfect world where data are noise-free and geophysical models perfectly represent reality, there should be a set of model parameters that reduces the misfit function to zero. In our case, however, the misfit function still shows large values, even for the best fitting model parameters. Provide and explain three reasons for why the differences between the model and the data are not zero.\n

\nPROVIDE DISCUSSION HERE:\n
\n
\n
\n\n# 5. Version Log\n\n GEOS 639 Geodetic Imaging - Version 1.3.3 - March 2022 \n
\n Version Changes:\n
    \n
  • remove obsolete asf_notebook functions
  • \n
  • url_widget
  • \n
  • Adjust some of the language in the notebook
  • \n
\n
\n
\n", "meta": {"hexsha": "088d12e38825fed81e22bdce2f05f60e86355693", "size": 53932, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week-9/GEOS639-Lab5-VolcanoSourceModelingfromInSAR.ipynb", "max_stars_repo_name": "uafgeoteach/GEOS639-InSARGeoImaging", "max_stars_repo_head_hexsha": "2f0804f875fe3dbc4972c1dfc785dc585ebbd482", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-22T06:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T19:09:31.000Z", "max_issues_repo_path": "Week-9/GEOS639-Lab5-VolcanoSourceModelingfromInSAR.ipynb", "max_issues_repo_name": "uafgeoteach/GEOS639-InSARGeoImaging", "max_issues_repo_head_hexsha": "2f0804f875fe3dbc4972c1dfc785dc585ebbd482", "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": "Week-9/GEOS639-Lab5-VolcanoSourceModelingfromInSAR.ipynb", "max_forks_repo_name": "uafgeoteach/GEOS639-InSARGeoImaging", "max_forks_repo_head_hexsha": "2f0804f875fe3dbc4972c1dfc785dc585ebbd482", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4267869535, "max_line_length": 709, "alphanum_fraction": 0.5857375955, "converted": true, "num_tokens": 10736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.22541660542786954, "lm_q1q2_score": 0.09352508941544874}} {"text": "# SNLP Assignment 3\n\nName 1: Sangeet Sagar
\nStudent id 1: 7009050
\nEmail 1: sasa00001@stud.uni-saarland.de
\n\n\nName 2: Nikhil Paliwal
\nStudent id 2: 7009915
\nEmail 2: nipa00002@stud.uni-saarland.de
\n\n**Instructions:** Read each question carefully.
\nMake sure you appropriately comment your code wherever required. Your final submission should contain the completed Notebook and the respective Python files for exercises 2 and 3. There is no need to submit the data files.
\nUpload the zipped folder in Teams. Make sure to click on \"Turn-in\" after you upload your submission, otherwise the assignment will not be considered as submitted. Only one member of the group should make the submisssion.\n\n---\n\n## Exercise 1: Entropy Intuition (2 points)\n\n### 1.1 (0.5 points)\n\nOrder the following three snippets by entropy (highest to lowest). Justify your answer (view it more intuitively rather than by using a specific character-level language model, though you would probably reach the same conclusion).\n\n```\n1: A B A A A A B B A A A B A B B B B B A\n2: A B A B A B A B A B A B A B A B A B A\n3: A B A A A B A B A B A B A B A B A B A\n```\n\n**Answer**
\nCorrect order: $2 > 3 > 1$
\n*Explanation*: Looking intuitively, Entropy is a measure of randomness in a probability distribution. We compare the entorpy in the above sequences by comparing radomness. **2** has the highest degre of randomness for the reason that no consecutive letters are same. This is followed by **3** as it has a repition of `A A A` in the beginning. This is observation is more prevelant in **1**, hence it has least entropy among all.\n\n### 1.2 (0.5 point)\n\nWords in natural language do not have the maximum entropy given the available alphabet. This creates a redundancy (e.g. the word `maximum` could be uniquely replaced by `mxmm` and everyone would still understand). If the development of natural languages leads to somewhat optimal solutions, why is it beneficial to have such redundancies in communication?\n\nIf you're uncertain, please refer to this well-written article: [www-math.ucdenver.edu/~wcherowi/courses/m5410/m5410lc1.html](http://www-math.ucdenver.edu/~wcherowi/courses/m5410/m5410lc1.html).\n\n**Answer**
\nHaving redundancies diminishes the uncertainty in communication. With more information on the goal of communication, more certain we become what the speaker refers.\n\n### 1.3 (1 point)\n\n1. Assume you were given a perfect language model that would always assign probability of $1$ to the next word. What would be the cross-entropy on any text? Motivate your answer with formal derivation. (0.5 points)\n2. How does cross-entropy relate to perplexity? Is there a reason why would one be preferred over the other? (0.5 points)\n\n**Answer**
\nCross-entropy\n$$ H(P, Q) = \\quad –\\sum_{x \\in X} P(x) * \\log(Q(x)) $$\n1. In the given situation, $P(x) = Q(x) = 1$. Hence,\n$$ H(P, Q) = \\quad –\\sum_{x \\in X} 1 * \\log(1) $$\n$$ H(P, Q) = 0 $$\nIntuitively, if the probablity of the next word is 1, we are always certain about the subsequent outcomes, hence there is no un-certainity and the Entropy is $0$.\n\n2. Perplexity($M$) is given as $M = 2^{H(P, Q)}$. Hence it is equivalent to the exponentiation of the cross-entropy. Generally, perplexity is preferred over cross-entropy as it is easy to interpret (for the reason that perplexity is the avergae de-facto size of vocabluary).\n\n\n## Exercise 2: Harry Potter and the Measure of Uncertainty (4 points)\n\n#### 2.1 (2.5 points)\n\nHarry, Hermione, and Ron are trying to save the Philosopher's Stone. To do this, they have to cross a series of hurdles to reach the room where the stone is kept. Currently, they are trapped in a chamber whose exit is blocked by fire. On a table before them are 7 potions.\n\n|P1|P2|P3|P4|P5|P6|P7|\n|---|---|---|---|---|---|---|\n\nOf these, 6 potions are poisons and only one is the antidote that will get them through the exit. Drinking the poison will not kill them, but will weaken them considerably. \n\n1. There is no way of knowing which potion is a poison and which an antidote. How many potions must they sample *on an average* to pick the antidote? (1 point)\n\n**Answer**
\nWe have $X$ = no. of potion sampled before picking up an antidote.
\n\n$P(X=1) = \\frac{1}{7} \\quad \\quad \\quad$ (antidote is picked up in the first sampling)
\n$P(X=2) = \\frac{6}{7}\\cdot\\frac{1}{6} = \\frac{1}{7}\\quad$ (1 poison, 1 antidote)
\n$P(X=3) = \\frac{6}{7} \\cdot \\frac{5}{6} \\cdot \\frac{1}{5} = \\frac{1}{7} $ (2 poison, 1 antidote)
\nSimilarly,
\n$P(X=4)= P(X=5)= P(X=6)= P(X=7) =\\frac{1}{7} $\n\n\n$$ E[x] = \\sum_{n=1}^{7} n\\cdot\\left(\\frac{1}{7}\\right)$$\n$$ E[x] = \\frac{1}{7}\\sum_{n=1}^{7} n$$\n$$ E[x] = 4$$\n\nTherefore, we must take sample 4 potions on an avergage to pick the antidote.\n\nHermione notices a scroll lying near the potions. The scroll contains an intricate riddle written by Professor Snape that will help them determine which potion is the antidote. With the help of the clues provided, Hermione cleverly deduces that each potion can be the antidote with a certain probability. \n\n|P1|P2|P3|P4|P5|P6|P7|\n|---|---|---|---|---|---|---|\n|1/16|1/4|1/64|1/2|1/64|1/32|1/8|\n\n2. In this situation, how many potions must they now sample *on an average* to pick the antidote correctly? (1 point)\n\n\n\n3. What is the most efficient sequence of potions they must sample to discover the antidote? Why do you claim that in terms of how uncertain you are about guessing right? (0.5 point)\n\n**Answer**
\n**P4 > P2 > P7 > P1 > P6 > {P3, P4}**
\nThe sequence of potion sampling given above diminishes the uncertainity (to maximum extent) as we take the potion with highest probablity of being an antidote at first.\n\n\n#### 2.2 (1.5 points)\n\n1. Extend your logic from 2.1 to a Shannon's Game where you have to correctly guess the next word in a sentence. Assume that a word is any possible permutation and combination of 26 letters of the alphabet, and all the words have a length of at most *n*. \nHow many guesses will one have to make to guess the correct word? (1 point)
\n(**Hint**: Think of how many words can exist in this scenario)\n\n**Answer**
\nLet $k$ be the total number of words of length atmost $n$ be present in the corpus:\n$$ k = \\sum_{n=1}^{26} 26^{n}$$\n\nSum of a GP
\n$$ k = \\frac{26}{25}(26^{n}-1)$$\n\nUsing similar logic form 2.1, we have
\n$E[X=1] = \\frac{1}{k} $ ; (expectation of a correct guess in the 1st sampling)
\n$E[X=2] = \\frac{k-1}{k} \\frac{1}{k-1} = \\frac{1}{k}$ ; (expectation of a correct guess in the 2nd sampling)
\nAnd so on,
\n$E[X=k] = \\frac{1}{k}$ ; (we sample as many times as we have totat number of words in the corpus)\n\n$$ E[x] = \\sum_{m=1}^{k} m\\cdot\\left(\\frac{1}{k}\\right)$$\n$$ E[x] = \\frac{1}{k}\\sum_{m=1}^{k} m$$\n$$ E[x] = \\frac{1}{k}\\cdot \\frac{k(k+1)}{2}$$\n\nTherefore, one has to make $\\frac{1}{k}\\cdot \\frac{k(k+1)}{2}$ (where $k = \\sum_{n=1}^{26} 26^{n}$) guesses to to guess the correct word.\n\n2. Why is the entropy lower in real-world languages? How do language models help to reduce the uncertainty of guessing the correct word? (2-3 sentences) (0.5 point)\n\n**Answer**
\nEntropy is lower for real-world languages for the reason that the language is defined under a particular set of rules (e.g. Grammatical rules) and is confined to follow them. We as a speaker or a writer of the language follow a specific sentence structure.
\nA statistical language model is learned from raw text and predicts the probability of the next word in the sequence given the words already present in the sequence. Hence, given a word the LM will have certain choices to choose\nfrom to make the next prediction and it will select the one with maximum probablity, thus reducing the uncertainity of guessing the correct word.\n\n## Exercise 3: Kullback-Leibler Divergence (4 points)\n\nAnother metric (besides perplexity and cross-entropy) to compare two probability distributions is the Kullback-Leibler Divergence $D_{KL}$. It is defined as:\n\n\\begin{equation}\nD_{KL}(P\\|Q) = \\sum_{x \\in X}P(x) \\cdot \\log \\frac{P(x)}{Q(x)}\n\\end{equation}\n\nWhere $P$ is the empirical or observed distribution, and Q is the estimated distribution over a common probabilitiy space $X$. \nAnswer the following questions:\n\n#### 3.1. (0.5 points)\n\nHow is $D_{KL}$ related to Cross-Entropy? Derive a mathematical expression that describes the relationship. \n\n**Answer**
\n$$ D_{KL}(P\\|Q) = \\sum_{x \\in X}P(x) \\cdot \\log \\frac{P(x)}{Q(x)} $$ \n$$ D_{KL}(P\\|Q) = -\\sum_{x \\in X}P(x)\\cdot \\log(Q(x)) + \\sum_{x \\in X}P(x)\\cdot \\log(Q(x)) $$ \n$$ D_{KL}(P\\|Q) = E_P[-\\log(Q)]- E_P[-\\log(P)]$$ \n$$ D_{KL}(P\\|Q) = H(P, Q)- H(P)$$ \n\nWhere:
\n$ H(P,Q)$ = cross entropy of distributions $P$ and $Q$
\n$ H(P)$ = entropy of distribution $P$\n\n#### 3.2. (0.5 points)\n\nIs minimizing $D_{KL}$ the same thing as minimizing Cross-Entropy? Support your answer using your answer to 1.\n\n\n\n**Answer**
\nYes, minimizing cross-entrpy is same as minimizing $D_{KL}$ becuase entropy remains unchanged for a true distribution. Changes in the distribution are reflected only in the cross-entropy.\n\n#### 3.3 (3 points)\n\nFor a function $d$ to be considered a distance metric, the following three properties must hold:\n\n$\\forall x,y,z \\in U:$\n\n1. $d(x,y) = 0 \\Leftrightarrow x = y$\n2. $d(x,y) = d(y,x)$\n3. $d(x,z) \\le d(x,y) + d(y,z)$\n\nIs $D_{KL}$ a distance metric? ($U$ in this case is the set of all distributions over the same possible states).\nFor each of the three points either prove that it holds for $K_{DL}$ or show a counterexample proving why it does not.\n\n**Answer**
\n1. Let $x=p$, $y=q$ \n$$ D(p \\|q) = H(p, q) - H(p) \\quad \\quad \\quad \\quad \\dots (1)$$\n$$ D(p \\|q) = H(p,p) - H(p)$$\n$$ D(p \\|q) = H(p) - H(p)$$\n$$ D(p \\|q) = 0$$\n$D_{KL}$ holds here.\n\n2. $$ D(q \\|p) = H(q, p) - H(q) \\quad \\quad \\quad \\quad \\dots (2)$$\nFrom 1 and 2, \n$$D(q \\|p) \\neq D(p \\|q)$$\n$D_{KL}$ does not hold here.
\nCounterexample:\n\\begin{align}\nD(x\\|y) &= \\frac{1}{3} \\log\\left(\\frac{1/3}{1/6}\\right) + \\frac{2}{3} \\log\\left(\\frac{2/3}{5/6}\\right) \\\\\nD(x\\|y) &= 0.035 \\\\\n\\\\\nD(y\\|x) &= \\frac{1}{6} \\log\\left(\\frac{1/6}{1/3}\\right) + \\frac{5}{6} \\log\\left(\\frac{5/6}{2/3}\\right) \\\\\nD(y\\|x) &= 0.03 \\\\\n\\end{align}\nHence\n$$D(x \\|y) \\neq D(y \\|x) $$\n\n3. $D_{KL}$ does not hold here.
\nCounterexample:\nSample space : ${0, 1}$
\n$x(0) = \\frac{1}{3}$
\n$y(0) = \\frac{1}{6}$
\n$z(0) = \\frac{1}{12}$
\n\n$$ D(p\\|q) = \\sum p_i \\log\\left(\\frac{p_i}{q_i}\\right) $$\n\\begin{align}\nD(x\\|z) &= \\sum x_i \\log\\left(\\frac{x_i}{z_i}\\right) \\\\\nD(x\\|z) &= x(0) \\log\\left(\\frac{x(0)}{z(0)}\\right) + x(1) \\log\\left(\\frac{x(1)}{z(1)}\\right) \\\\\nD(x\\|z) &= \\frac{1}{3} \\log\\left(\\frac{1/3}{1/12}\\right) + \\frac{2}{3} \\log\\left(\\frac{2/3}{11/12}\\right) \\\\\nD(x\\|z) &= 0.108 \\\\\n\\\\\nD(x\\|y) &= \\frac{1}{3} \\log\\left(\\frac{1/3}{1/6}\\right) + \\frac{2}{3} \\log\\left(\\frac{2/3}{5/6}\\right) \\\\\nD(x\\|y) &= 0.035 \\\\\n\\\\\nD(y\\|z) &= \\frac{1}{6} \\log\\left(\\frac{1/6}{1/12}\\right) + \\frac{5}{6} \\log\\left(\\frac{5/6}{1/12}\\right) \\\\\nD(x\\|z) &= 0.015 \\\\\n\\end{align}\n\nHence,\n$$D(x\\|z) \\ge D(x\\|y) + D(x\\|y)$$\n\nTherefore, $D_{KL}$ is not a distance metric.\n\n## Bonus (1.5 points)\n\n1. Compute $D_{KL}(Q_1\\|P_1)$ for the following pair of sentences based on a unigram language model (word level).\n\n```\np1: to be or not to be\nq1: to be or to be or not or to be be be\n```\n\n Do so by implementing the function `dkl` in `bonus.py`. You will also have to calculate the distributions $P_1$, $Q_1$; for this, you can either reuse your code from the last assignment or implement a new function in `bonus.py`. (1 point)\n\n2. Suppose the sentences in 1. would be replaced by the following sequences of symbols. You can imagine them to be sequences of nucleobases in a [coding](https://en.wikipedia.org/wiki/Coding_region) region of a gene in your genome.\n\n```\np2: ACTGACACTGAC\nq2: ACTACTGACCCACTACTGACCC\n```\n\nLet $P_2$, $Q_2$ be the character-level unigram LMs derived from these sequences. What values will $D_{KL}(P_1\\|P_2)$, $D_{KL}(Q_1\\|Q_2)$ take? Does the quantity hold any information? Would computing $D_{KL}$ between distributions over two different natural languages hold any information? (0.5 points)\n\nNo mathematical explanation nor coding required for the second part.\n\n\n```python\nfrom importlib import reload\nimport bonus\nbonus = reload(bonus)\n\n# TODO: estimate LMs\nP = \nQ = \n\n# TODO: DKL\nprint(bonus.dkl(p,q))\n```\n", "meta": {"hexsha": "097ef77b504e34bca9a8b9536f3c50d171ac5fb9", "size": 17709, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "snlp/hw3/Assignment3.ipynb", "max_stars_repo_name": "sangeet2020/ss-21", "max_stars_repo_head_hexsha": "c2dbcf9668cb82b27a76e766a977483dd5fae0d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T21:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:07:49.000Z", "max_issues_repo_path": "snlp/hw3/Assignment3.ipynb", "max_issues_repo_name": "sangeet2020/ss-21", "max_issues_repo_head_hexsha": "c2dbcf9668cb82b27a76e766a977483dd5fae0d4", "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": "snlp/hw3/Assignment3.ipynb", "max_forks_repo_name": "sangeet2020/ss-21", "max_forks_repo_head_hexsha": "c2dbcf9668cb82b27a76e766a977483dd5fae0d4", "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.6174496644, "max_line_length": 434, "alphanum_fraction": 0.5670562991, "converted": true, "num_tokens": 4096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.19930799790404563, "lm_q1q2_score": 0.09343372122905962}} {"text": "\n\n\n

Escuela de Ciencias Básicas, Tecnología e Ingeniería

\n
\n\n\n

ECBTI

\n
\n\n\n

Curso: Métodos Numéricos

\n
\n\n\n

Unidad 1: Error

\n
\n\n\n

Febrero 28 de 2020

\n
\n\n\n***\n\n> **Tutor:** Carlos Alberto Álvarez Henao, I.C. D.Sc.\n\n> **skype:** carlos.alberto.alvarez.henao\n\n> **Herramienta:** [Jupyter](http://jupyter.org/)\n\n> **Kernel:** Python 3.7\n\n\n***\n\n***Comentario:*** estas notas están basadas en el curso del profesor [Kyle T. Mandli](https://github.com/mandli/intro-numerical-methods) (en inglés)\n\n# Fuentes de error\n\nLos cálculos numéricos, que involucran el uso de máquinas (análogas o digitales) presentan una serie de errores que provienen de diferentes fuentes:\n\n- del Modelo\n- de los datos\n- de truncamiento\n- de representación de los números (punto flotante)\n- $\\ldots$\n\n***Meta:*** Categorizar y entender cada tipo de error y explorar algunas aproximaciones simples para analizarlas.\n\n# Error en el modelo y los datos\n\nErrores en la formulación fundamental\n\n- Error en los datos: imprecisiones en las mediciones o incertezas en los parámetros\n\nInfortunadamente no tenemos control de los errores en los datos y el modelo de forma directa pero podemos usar métodos que pueden ser más robustos en la presencia de estos tipos de errores.\n\n# Error de truncamiento\n\nLos errores surgen de la expansión de funciones con una función simple, por ejemplo, $sin(x) \\approx x$ para $|x|\\approx0$.\n\n# Error de representación de punto fotante\n\nLos errores surgen de aproximar números reales con la representación en precisión finita de números en el computador.\n\n# Definiciones básicas\n\nDado un valor verdadero de una función $f$ y una solución aproximada $F$, se define:\n\n- Error absoluto\n\n$$e_a=|f-F|$$\n\n- Error relativo\n\n$$e_r = \\frac{e_a}{|f|}=\\frac{|f-F|}{|f|}$$\n\n\n\n# Notación $\\text{Big}-\\mathcal{O}$\n\nsea $$f(x)= \\mathcal{O}(g(x)) \\text{ cuando } x \\rightarrow a$$\n\nsi y solo si\n\n$$|f(x)|\\leq M|g(x)| \\text{ cuando } |x-a| < \\delta \\text{ donde } M, a > 0$$\n\n\nEn la práctica, usamos la notación $\\text{Big}-\\mathcal{O}$ para decir algo sobre cómo se pueden comportar los términos que podemos haber dejado fuera de una serie. Veamos el siguiente ejemplo de la aproximación de la serie de Taylor:\n\n***Ejemplo:***\n\nsea $f(x) = \\sin x$ con $x_0 = 0$ entonces\n\n$$T_N(x) = \\sum^N_{n=0} (-1)^{n} \\frac{x^{2n+1}}{(2n+1)!}$$\n\nPodemos escribir $f(x)$ como\n\n$$f(x) = x - \\frac{x^3}{6} + \\frac{x^5}{120} + \\mathcal{O}(x^7)$$\n\nEsto se vuelve más útil cuando lo vemos como lo hicimos antes con $\\Delta x$:\n\n$$f(x) = \\Delta x - \\frac{\\Delta x^3}{6} + \\frac{\\Delta x^5}{120} + \\mathcal{O}(\\Delta x^7)$$\n\n# Reglas para el error de propagación basado en la notación $\\text{Big}-\\mathcal{O}$\n\nEn general, existen dos teoremas que no necesitan prueba y se mantienen cuando el valor de $x$ es grande:\n\nSea\n\n$$\\begin{aligned}\n f(x) &= p(x) + \\mathcal{O}(x^n) \\\\\n g(x) &= q(x) + \\mathcal{O}(x^m) \\\\\n k &= \\max(n, m)\n\\end{aligned}$$\n\nEntonces\n\n$$\n f+g = p + q + \\mathcal{O}(x^k)\n$$\n\ny\n\n\\begin{align}\n f \\cdot g &= p \\cdot q + p \\mathcal{O}(x^m) + q \\mathcal{O}(x^n) + O(x^{n + m}) \\\\\n &= p \\cdot q + \\mathcal{O}(x^{n+m})\n\\end{align}\n\nDe otra forma, si estamos interesados en valores pequeños de $x$, $\\Delta x$, la expresión puede ser modificada como sigue:\n\n\\begin{align}\n f(\\Delta x) &= p(\\Delta x) + \\mathcal{O}(\\Delta x^n) \\\\\n g(\\Delta x) &= q(\\Delta x) + \\mathcal{O}(\\Delta x^m) \\\\\n r &= \\min(n, m)\n\\end{align}\n\nentonces\n\n$$\n f+g = p + q + O(\\Delta x^r)\n$$\n\ny\n\n\\begin{align}\n f \\cdot g &= p \\cdot q + p \\cdot \\mathcal{O}(\\Delta x^m) + q \\cdot \\mathcal{O}(\\Delta x^n) + \\mathcal{O}(\\Delta x^{n+m}) \\\\\n &= p \\cdot q + \\mathcal{O}(\\Delta x^r)\n\\end{align}\n\n***Nota:*** En este caso, supongamos que al menos el polinomio con $k=max(n,m)$ tiene la siguiente forma:\n\n$$\n p(\\Delta x) = 1 + p_1 \\Delta x + p_2 \\Delta x^2 + \\ldots\n$$\n\no\n\n$$\n q(\\Delta x) = 1 + q_1 \\Delta x + q_2 \\Delta x^2 + \\ldots\n$$\n\npara que $\\mathcal{O}(1)$ \n\n\nde modo que hay un término $\\mathcal{O}(1)$ que garantiza la existencia de $\\mathcal{O}(\\Delta x^r)$ en el producto final.\n\nPara tener una idea de por qué importa más la potencia en $\\Delta x$ al considerar la convergencia, la siguiente figura muestra cómo las diferentes potencias en la tasa de convergencia pueden afectar la rapidez con la que converge nuestra solución. Tenga en cuenta que aquí estamos dibujando los mismos datos de dos maneras diferentes. Graficar el error como una función de $\\Delta x$ es una forma común de mostrar que un método numérico está haciendo lo que esperamos y muestra el comportamiento de convergencia correcto. Dado que los errores pueden reducirse rápidamente, es muy común trazar este tipo de gráficos en una escala log-log para visualizar fácilmente los resultados. Tenga en cuenta que si un método fuera realmente del orden $n$, será una función lineal en el espacio log-log con pendiente $n$.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndx = np.linspace(1.0, 1e-4, 100)\n\nfig = plt.figure()\nfig.set_figwidth(fig.get_figwidth() * 2.0)\naxes = []\naxes.append(fig.add_subplot(1, 2, 1))\naxes.append(fig.add_subplot(1, 2, 2))\n\nfor n in range(1, 5):\n axes[0].plot(dx, dx**n, label=\"$\\Delta x^%s$\" % n)\n axes[1].loglog(dx, dx**n, label=\"$\\Delta x^%s$\" % n)\n\naxes[0].legend(loc=2)\naxes[1].set_xticks([10.0**(-n) for n in range(5)])\naxes[1].set_yticks([10.0**(-n) for n in range(16)])\naxes[1].legend(loc=4)\nfor n in range(2):\n axes[n].set_title(\"Crecimiento del Error vs. $\\Delta x^n$\")\n axes[n].set_xlabel(\"$\\Delta x$\")\n axes[n].set_ylabel(\"Error Estimado\")\n axes[n].set_title(\"Crecimiento de las diferencias\")\n axes[n].set_xlabel(\"$\\Delta x$\")\n axes[n].set_ylabel(\"Error Estimado\")\n\nplt.show()\n```\n\n# Error de truncamiento\n\n***Teorema de Taylor:*** Sea $f(x) \\in C^{m+1}[a,b]$ y $x_0 \\in [a,b]$, para todo $x \\in (a,b)$ existe un número $c = c(x)$ que se encuentra entre $x_0$ y $x$ tal que\n\n$$ f(x) = T_N(x) + R_N(x)$$\n\ndonde $T_N(x)$ es la aproximación del polinomio de Taylor\n\n$$T_N(x) = \\sum^N_{n=0} \\frac{f^{(n)}(x_0)\\times(x-x_0)^n}{n!}$$\n\ny $R_N(x)$ es el residuo (la parte de la serie que obviamos)\n\n$$R_N(x) = \\frac{f^{(n+1)}(c) \\times (x - x_0)^{n+1}}{(n+1)!}$$\n\nOtra forma de pensar acerca de estos resultados consiste en reemplazar $x - x_0$ con $\\Delta x$. La idea principal es que el residuo $R_N(x)$ se vuelve mas pequeño cuando $\\Delta x \\rightarrow 0$.\n\n$$T_N(x) = \\sum^N_{n=0} \\frac{f^{(n)}(x_0)\\times \\Delta x^n}{n!}$$\n\ny $R_N(x)$ es el residuo (la parte de la serie que obviamos)\n\n$$ R_N(x) = \\frac{f^{(n+1)}(c) \\times \\Delta x^{n+1}}{(n+1)!} \\leq M \\Delta x^{n+1}$$\n\n***Ejemplo 1:***\n\n$f(x) = e^x$ con $x_0 = 0$\n\nUsando esto podemos encontrar expresiones para el error relativo y absoluto en función de $x$ asumiendo $N=2$.\n\nDerivadas:\n$$\\begin{aligned}\n f'(x) &= e^x \\\\\n f''(x) &= e^x \\\\ \n f^{(n)}(x) &= e^x\n\\end{aligned}$$\n\nPolinomio de Taylor:\n$$\\begin{aligned}\n T_N(x) &= \\sum^N_{n=0} e^0 \\frac{x^n}{n!} \\Rightarrow \\\\\n T_2(x) &= 1 + x + \\frac{x^2}{2}\n\\end{aligned}$$\n\nRestos:\n$$\\begin{aligned}\n R_N(x) &= e^c \\frac{x^{n+1}}{(n+1)!} = e^c \\times \\frac{x^3}{6} \\quad \\Rightarrow \\\\\n R_2(x) &\\leq \\frac{e^1}{6} \\approx 0.5\n\\end{aligned}$$\n\nPrecisión:\n$$\n e^1 = 2.718\\ldots \\\\\n T_2(1) = 2.5 \\Rightarrow e \\approx 0.2 ~~ r \\approx 0.1\n$$\n\n¡También podemos usar el paquete `sympy` que tiene la capacidad de calcular el polinomio de *Taylor* integrado!\n\n\n```python\nimport sympy\nx = sympy.symbols('x')\nf = sympy.symbols('f', cls=sympy.Function)\n\nf = sympy.exp(x)\nf.series(x0=0, n=5)\n```\n\n\n\n\n$\\displaystyle 1 + x + \\frac{x^{2}}{2} + \\frac{x^{3}}{6} + \\frac{x^{4}}{24} + O\\left(x^{5}\\right)$\n\n\n\nGraficando\n\n\n```python\nx = np.linspace(-1, 1, 100)\nT_N = 1.0 + x + x**2 / 2.0\nR_N = np.exp(1) * x**3 / 6.0\n\nplt.plot(x, T_N, 'r', x, np.exp(x), 'k', x, R_N, 'b')\nplt.plot(0.0, 1.0, 'o', markersize=10)\nplt.grid(True)\nplt.xlabel(\"x\")\nplt.ylabel(\"$f(x)$, $T_N(x)$, $R_N(x)$\")\nplt.legend([\"$T_N(x)$\", \"$f(x)$\", \"$R_N(x)$\"], loc=2)\nplt.show()\n```\n\n***Ejemplo 2:***\n\nAproximar\n\n$$ f(x) = \\frac{1}{x} \\quad x_0 = 1,$$\n\nusando $x_0 = 1$ para el tercer termino de la serie de Taylor.\n\n$$\\begin{aligned}\n f'(x) &= -\\frac{1}{x^2} \\\\\n f''(x) &= \\frac{2}{x^3} \\\\\n f^{(n)}(x) &= \\frac{(-1)^n n!}{x^{n+1}}\n\\end{aligned}$$\n\n$$\\begin{aligned}\n T_N(x) &= \\sum^N_{n=0} (-1)^n (x-1)^n \\Rightarrow \\\\\n T_2(x) &= 1 - (x - 1) + (x - 1)^2\n\\end{aligned}$$\n\n$$\\begin{aligned}\n R_N(x) &= \\frac{(-1)^{n+1}(x - 1)^{n+1}}{c^{n+2}} \\Rightarrow \\\\\n R_2(x) &= \\frac{-(x - 1)^{3}}{c^{4}}\n\\end{aligned}$$\n\n\n```python\nx = np.linspace(0.8, 2, 100)\nT_N = 1.0 - (x-1) + (x-1)**2\nR_N = -(x-1.0)**3 / (1.1**4)\n\nplt.plot(x, T_N, 'r', x, 1.0 / x, 'k', x, R_N, 'b')\nplt.plot(1.0, 1.0, 'o', markersize=10)\nplt.grid(True)\nplt.xlabel(\"x\")\nplt.ylabel(\"$f(x)$, $T_N(x)$, $R_N(x)$\")\n\nplt.legend([\"$T_N(x)$\", \"$f(x)$\", \"$R_N(x)$\"], loc=8)\nplt.show()\n```\n\n# En esta celda haz tus comentarios\n\n\nEsta cosa con esta vaina quizas tal vez-.-.--\n\n\n\n\n\n\n\n\n\n## Error de punto flotante\n\nErrores surgen de aproximar 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### Sistemas de punto flotante\n\nLos números en sistemas de punto flotante se representan como una serie de bits que representan diferentes partes de un número. En los sistemas de punto flotante normalizados, existen algunas convenciones estándar para el uso de estos bits. En general, los números se almacenan dividiéndolos en la forma\n\n$$F = \\pm d_1 . d_2 d_3 d_4 \\ldots d_p \\times \\beta^E$$\n\ndonde\n\n1. $\\pm$ es un bit único y representa el signo del número.\n\n\n2. $d_1 . d_2 d_3 d_4 \\ldots d_p$ es la *mantisa*. observe que, técnicamente, el decimal se puede mover, pero en general, utilizando la notación científica, el decimal siempre se puede colocar en esta ubicación. Los digitos $d_2 d_3 d_4 \\ldots d_p$ son llamados la *fracción* con $p$ digitos de precisión. Los sistemas normalizados específicamente ponen el punto decimal en el frente y asume $d_1 \\neq 0$ a menos que el número sea exactamente $0$.\n\n\n3. $\\beta$ es la *base*. Para el sistema binario $\\beta = 2$, para decimal $\\beta = 10$, etc.\n\n\n4. $E$ es el *exponente*, un entero en el rango $[E_{\\min}, E_{\\max}]$\n\nLos puntos importantes en cualquier sistema de punto flotante es\n\n1. Existe un conjunto discreto y finito de números representables.\n\n\n2. Estos números representables no están distribuidos uniformemente en la línea real\n\n\n3. La aritmética en sistemas de punto flotante produce resultados diferentes de la aritmética de precisión infinita (es decir, matemática \"real\")\n\n### Propiedades de los sistemas de punto flotante\n\nTodos los sistemas de punto flotante se caracterizan por varios números importantes\n\n- Número normalizado reducido (underflow si está por debajo, relacionado con números sub-normales alrededor de cero)\n\n\n- Número normalizado más grande (overflow)\n\n\n- Cero\n\n\n- $\\epsilon$ o $\\epsilon_{mach}$\n\n\n- `Inf` y `nan`\n\n***Ejemplo: Sistema de juguete***\n\nConsidere el sistema decimal de 2 digitos de precisión (normalizado)\n\n$$f = \\pm d_1 . d_2 \\times 10^E$$\n\ncon $E \\in [-2, 0]$.\n\n**Numero y distribución de números**\n\n\n1. Cuántos números pueden representarse con este sistema?\n\n\n2. Cuál es la distribución en la línea real?\n\n\n3. Cuáles son los límites underflow y overflow?\n\nCuántos números pueden representarse con este sistema?\n\n$$f = \\pm d_1 . d_2 \\times 10^E ~~~ \\text{with} E \\in [-2, 0]$$\n\n$$2 \\times 9 \\times 10 \\times 3 + 1 = 541$$\n\nCuál es la distribución en la línea real?\n\n\n```python\nd_1_values = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nd_2_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nE_values = [0, -1, -2]\n\nfig = plt.figure(figsize=(10.0, 1.0))\naxes = fig.add_subplot(1, 1, 1)\n\nfor E in E_values:\n for d1 in d_1_values:\n for d2 in d_2_values:\n axes.plot( (d1 + d2 * 0.1) * 10**E, 0.0, 'r+', markersize=20)\n axes.plot(-(d1 + d2 * 0.1) * 10**E, 0.0, 'r+', markersize=20)\n \naxes.plot(0.0, 0.0, '+', markersize=20)\naxes.plot([-10.0, 10.0], [0.0, 0.0], 'k')\n\naxes.set_title(\"Distribución de Valores\")\naxes.set_yticks([])\naxes.set_xlabel(\"x\")\naxes.set_ylabel(\"\")\naxes.set_xlim([-0.1, 0.1])\nplt.show()\n```\n\nCuáles son los límites superior (overflow) e inferior (underflow)?\n\n- El menor número que puede ser representado (underflow) es: $1.0 \\times 10^{-2} = 0.01$\n\n\n\n- El mayor número que puede ser representado (overflow) es: $9.9 \\times 10^0 = 9.9$\n\n### Sistema Binario\n\nConsidere el sistema en base 2 de 2 dígitos de precisión\n\n$$f=\\pm d_1 . d_2 \\times 2^E \\quad \\text{with} \\quad E \\in [-1, 1]$$\n\n\n#### Numero y distribución de números**\n\n\n1. Cuántos números pueden representarse con este sistema?\n\n\n2. Cuál es la distribución en la línea real?\n\n\n3. Cuáles son los límites underflow y overflow?\n\nCuántos números pueden representarse en este sistema?\n\n\n$$f=\\pm d_1 . d_2 \\times 2^E ~~~~ \\text{con} ~~~~ E \\in [-1, 1]$$\n\n$$ 2 \\times 1 \\times 2 \\times 3 + 1 = 13$$\n\nCuál es la distribución en la línea real?\n\n\n```python\nd_1_values = [1]\nd_2_values = [0, 1]\nE_values = [1, 0, -1]\n\nfig = plt.figure(figsize=(10.0, 1.0))\naxes = fig.add_subplot(1, 1, 1)\n\nfor E in E_values:\n for d1 in d_1_values:\n for d2 in d_2_values:\n axes.plot( (d1 + d2 * 0.5) * 2**E, 0.0, 'r+', markersize=20)\n axes.plot(-(d1 + d2 * 0.5) * 2**E, 0.0, 'r+', markersize=20)\n \naxes.plot(0.0, 0.0, 'r+', markersize=20)\naxes.plot([-4.5, 4.5], [0.0, 0.0], 'k')\n\naxes.set_title(\"Distribución de Valores\")\naxes.set_yticks([])\naxes.set_xlabel(\"x\")\naxes.set_ylabel(\"\")\naxes.set_xlim([-3.5, 3.5])\nplt.show()\n```\n\nCuáles son los límites superior (*overflow*) e inferior (*underflow*)?\n\n- El menor número que puede ser representado (*underflow*) es: $1.0 \\times 2^{-1} = 0.5$\n\n\n\n\n- El mayor número que puede ser representado (*overflow*) es: $1.1 \\times 2^1 = 3$\n\nObserve que estos números son en sistema binario. \n\nUna rápida regla de oro:\n\n$$2^3 2^2 2^1 2^0 . 2^{-1} 2^{-2} 2^{-3}$$\n\ncorresponde a\n\n8s, 4s, 2s, 1s . mitades, cuartos, octavos, $\\ldots$\n\n### Sistema real - IEEE 754 sistema binario de punto flotante\n\n#### Precisión simple\n\n- Almacenamiento total es de 32 bits\n\n\n- Exponente de 8 bits $\\Rightarrow E \\in [-126, 127]$\n\n\n- Fracción 23 bits ($p = 24$)\n\n\n```\ns EEEEEEEE FFFFFFFFFFFFFFFFFFFFFFF\n0 1 8 9 31\n```\n\nOverflow $= 2^{127} \\approx 3.4 \\times 10^{38}$\n\nUnderflow $= 2^{-126} \\approx 1.2 \\times 10^{-38}$\n\n$\\epsilon_{\\text{machine}} = 2^{-23} \\approx 1.2 \\times 10^{-7}$\n\n\n#### Precisión doble\n\n- Almacenamiento total asignado es 64 bits\n\n- Exponenete de 11 bits $\\Rightarrow E \\in [-1022, 1024]$\n\n- Fracción de 52 bits ($p = 53$)\n\n```\ns EEEEEEEEEE FFFFFFFFFF FFFFFFFFFF FFFFFFFFFF FFFFFFFFFF FFFFFFFFFF FF\n0 1 11 12 63\n```\nOverflow $= 2^{1024} \\approx 1.8 \\times 10^{308}$\n\nUnderflow $= 2^{-1022} \\approx 2.2 \\times 10^{-308}$\n\n$\\epsilon_{\\text{machine}} = 2^{-52} \\approx 2.2 \\times 10^{-16}$\n\n### Acceso de Python a números de la IEEE\n\nAccede a muchos parámetros importantes, como el epsilon de la máquina\n\n```python\nimport numpy\nnumpy.finfo(float).eps\n```\n\n\n```python\nimport numpy\nnumpy.finfo(float).eps\n\nprint(numpy.finfo(numpy.float16))\nprint(numpy.finfo(numpy.float32))\nprint(numpy.finfo(float))\nprint(numpy.finfo(numpy.float128))\n```\n\n## Por qué debería importarnos esto?\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### 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### 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 = numpy.array([10**(-n) for n in range(1, 16)])\nx = 1.0 + dx\ny = -numpy.ones(x.shape)\nerror = numpy.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### 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\nx = numpy.linspace(-1e-3, 1e-3, 100, dtype=numpy.float32)\nerror = (0.5 - (1.0 - numpy.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### 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 = numpy.linspace(0.988, 1.012, 1000, dtype=numpy.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### 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 = numpy.linspace(0.5, 1.5, 101, dtype=numpy.float16)\nf_hat = (x**2 - 1.0) / (x - 1.0)\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.plot(x, numpy.abs(f_hat - (x + 1.0)))\naxes.set_xlabel(\"$x$\")\naxes.set_ylabel(\"Error Absoluto\")\nplt.show()\n```\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### 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 = numpy.linspace(1e-20, 5.0, 100)\ndelta_x = numpy.array([2.0**(-n) for n in range(1, 60)])\nx = 1.0\nf_hat_1 = (numpy.exp(x + delta_x) - numpy.exp(x)) / (delta_x)\nf_hat_2 = (numpy.exp(x + delta_x) - numpy.exp(x - delta_x)) / (2.0 * delta_x)\n\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\naxes.loglog(delta_x, numpy.abs(f_hat_1 - numpy.exp(1)), 'o-', label=\"Unilateral\")\naxes.loglog(delta_x, numpy.abs(f_hat_2 - numpy.exp(1)), 's-', label=\"Centrado\")\naxes.legend(loc=3)\naxes.set_xlabel(\"$\\Delta x$\")\naxes.set_ylabel(\"Error Absoluto\")\nplt.show()\n```\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\nimport scipy.special\n\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 = numpy.linspace(-2, 2, 100, dtype=numpy.float32)\nfor N in range(1, 50):\n error = numpy.abs((numpy.exp(x) - my_exp(x, N=N)) / numpy.exp(x))\n if numpy.all(error < 8.0 * numpy.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### 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## 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### 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### 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### Algoritmo\n\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\n```python\n\n```\n", "meta": {"hexsha": "129885372fc1774cb414bc1497c4b632f8558a18", "size": 197004, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Cap_01_Error.ipynb", "max_stars_repo_name": "UNADCdD/M-todos-Num-ricos", "max_stars_repo_head_hexsha": "539838f7f72c365e515d6fe81e91296f6e8826ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-04T00:26:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-04T00:26:35.000Z", "max_issues_repo_path": "Cap_01_Error.ipynb", "max_issues_repo_name": "UNADCdD/M-todos-Num-ricos", "max_issues_repo_head_hexsha": "539838f7f72c365e515d6fe81e91296f6e8826ea", "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": "Cap_01_Error.ipynb", "max_forks_repo_name": "UNADCdD/M-todos-Num-ricos", "max_forks_repo_head_hexsha": "539838f7f72c365e515d6fe81e91296f6e8826ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-08T01:36:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T01:36:50.000Z", "avg_line_length": 114.0069444444, "max_line_length": 49936, "alphanum_fraction": 0.8389981929, "converted": true, "num_tokens": 11499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.2450850131323717, "lm_q1q2_score": 0.0934311989562584}} {"text": "#
Econometrics HW_08
\n\n**
11510691 程远星$\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\plim}{plim}\n\\newcommand{\\using}[1]{\\stackrel{\\mathrm{#1}}{=}}\n\\newcommand{\\ffrac}{\\displaystyle \\frac}\n\\newcommand{\\asim}{\\overset{\\text{a}}{\\sim}}\n\\newcommand{\\space}{\\text{ }}\n\\newcommand{\\bspace}{\\;\\;\\;\\;}\n\\newcommand{\\QQQ}{\\boxed{?\\:}}\n\\newcommand{\\void}{\\left.\\right.}\n\\newcommand{\\Tran}[1]{{#1}^{\\mathrm{T}}}\n\\newcommand{\\d}[1]{\\displaystyle{#1}}\n\\newcommand{\\CB}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\SB}[1]{\\left[ #1 \\right]}\n\\newcommand{\\P}[1]{\\left( #1 \\right)}\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\n\\newcommand{\\norm}[1]{\\left\\| #1 \\right\\|}\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\Exp}{\\mathrm{E}}\n\\newcommand{\\RR}{\\mathbb{R}}\n\\newcommand{\\EE}{\\mathbb{E}}\n\\newcommand{\\NN}{\\mathbb{N}}\n\\newcommand{\\ZZ}{\\mathbb{Z}}\n\\newcommand{\\QQ}{\\mathbb{Q}}\n\\newcommand{\\AcA}{\\mathscr{A}}\n\\newcommand{\\FcF}{\\mathscr{F}}\n\\newcommand{\\Var}[2][\\,\\!]{\\mathrm{Var}_{#1}\\left[#2\\right]}\n\\newcommand{\\Avar}[2][\\,\\!]{\\mathrm{Avar}_{#1}\\left[#2\\right]}\n\\newcommand{\\Cov}[2][\\,\\!]{\\mathrm{Cov}_{#1}\\left(#2\\right)}\n\\newcommand{\\Corr}[2][\\,\\!]{\\mathrm{Corr}_{#1}\\left(#2\\right)}\n\\newcommand{\\I}[1]{\\mathrm{I}\\left( #1 \\right)}\n\\newcommand{\\N}[1]{\\mathcal{N} \\left( #1 \\right)}\n\\newcommand{\\ow}{\\text{otherwise}}\n\\void^\\dagger$
**\n\n## Question 5\n\n$\\P{1}$\n\n$\\bspace$The two set of standard errors are so close and there's really no needs to distinguish them from each other.\n\n$\\P{2}$\n\n$\\bspace$Holding all other variables fixed, the probability of smoking changes by about $-0.029\\times4=-0.116$.\n\n$\\P{3}$\n\n$$\\abs{\\ffrac{0.02} {2\\times 0.00026}}\\approx 38.46153846153846$$\n\n$\\P{4}$\n\n$\\bspace$Holding other factors in the equation fixed, the probability to smoke will decrease $0.101$ for a person in a state with restaurant smoking restrictions.\n\n$\\P{5}$\n\n$$\\begin{align}\\widehat{\\text{smoke}} &= 0.656-0.069\\times\\log\\P{67.44} + 0.012\\times\\log\\P{6500} - 0.029 \\times 16\\\\\n&\\bspace+ 0.0207\\times77 -0.00026\\times77^2 -0.101\\times0-0.026\\times 0\\\\\n&\\approx 0.0052\n\\end{align}$$\n\n## Question 6\n\n$\\P{1}$\n\n$\\bspace$The numerator has $k+1$ regressors, and that's the $df$ for it. For the denominator, its $df$ is $n-\\P{k-2}$\n\n$\\P{2}$\n\n$\\bspace$In BP test, there's one more regressor thus it's got a higher $R$-squared. In White test, the model has more restrictions and thus the $R$-squared will be higher.\n\n$\\P{3}$\n\n$\\bspace$For $t$ test statistic will be a little bit smaller however the change of $F$ statistic is unpredictable. The $\\text{SSR}$s will be larger while $df$s also do.\n\n$\\P{4}$\n\n$\\bspace$Collinearity. Since the estimated equation will be a linear combination of all variables.\n\n## Question 7\n\n$\\P{1}$\n\n$\\bspace$Since the two are uncorrelated, we have $\\Var{u_{i,e}} = \\Var{f_i} + \\Var{v_{i,e}} = \\sigma_f^2 + \\sigma_v^2$\n\n$\\P{2}$\n\n$$\\begin{align}\n\\Cov{u_{i,e},u_{i,g}} &= \\Cov{f_i + v_{i,e},f_i + v_{i,g}}\\\\\n&= \\Cov{f_i,f_i} + \\Cov{f_i,v_{i,g}} + \\Cov{v_{i,e},f_i} + \\Cov{v_{i,e},v_{i,g}}\\\\\n&= \\Cov{f_i,f_i} + 0 + 0 + 0 = \\Var{f_i}\n\\end{align}$$\n\n$\\P{3}$\n\n$$\\begin{align}\n\\Var{\\bar u_i} &= \\Var{\\ffrac{1} {m_i}\\sum_{e=1}^{m_i} u_{i,e}} \\\\\n&= \\Var{f_i + \\ffrac{1} {m_i}\\sum_{e=1}^{m_i} v_{i,e}}\\\\\n&= \\Var{f_i} + \\Var{\\ffrac{1} {m_i}\\sum_{e=1}^{m_i} v_{i,e}}\\\\\n&= \\sigma_f^2 + \\ffrac{\\sigma_v^2} {m_i}\n\\end{align}$$\n\n$\\P{4}$\n\n$\\bspace$From the weighted OLS method, our target is to find some specific weight so that $\\Var{\\bar u_i} = \\ffrac{\\sigma_f^2} {m_i}$. If we take the weight so that the data are simply averaged, then like the preceding problem, we failed.\n", "meta": {"hexsha": "c7a0be2eac61335b17ffedc98005f62b79ceca82", "size": 6099, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FinMath/Econometrics/HW/HW_08.ipynb", "max_stars_repo_name": "XavierOwen/Notes", "max_stars_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-27T10:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T03:11:58.000Z", "max_issues_repo_path": "FinMath/Econometrics/HW/HW_08.ipynb", "max_issues_repo_name": "XavierOwen/Notes", "max_issues_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "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": "FinMath/Econometrics/HW/HW_08.ipynb", "max_forks_repo_name": "XavierOwen/Notes", "max_forks_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:57:23.000Z", "avg_line_length": 34.4576271186, "max_line_length": 249, "alphanum_fraction": 0.5158222659, "converted": true, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.18952109132967757, "lm_q1q2_score": 0.09328003262132463}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n#####Version 0.1\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the projects [homepage](camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$.:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n####Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computational-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%pylab inline\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n##Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n###Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n###Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\")\n```\n\n\n###But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```\nimport pymc as pm\n\nalpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = pm.Exponential(\"lambda_1\", alpha)\nlambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\ntau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```\nprint \"Random output:\", tau.random(), tau.random(), tau.random()\n```\n\n Random output: 52 2 26\n\n\n\n```\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. \n\n\n```\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo*, which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```\n### Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n [****************100%******************] 40000 of 40000 complete\n\n\n\n```\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n###Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\")\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```\n#type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. .\n- [2] Norvig, Peter. 2009. [*The Unreasonable Effectiveness of Data*](http://www.csee.wvu.edu/~gidoretto/courses/2011-fall-cp/reading/TheUnreasonable EffectivenessofData_IEEE_IS2009.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "dea3e4b810865f8738e02a4a005d12cca4fb1df1", "size": 412277, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_stars_repo_name": "sielizondo/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "9e4c4efd6fbc21e7ff49a7147489f844b8a962f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-01-22T23:03:58.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-06T15:37:24.000Z", "max_issues_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_issues_repo_name": "claudiamihai/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "9e4c4efd6fbc21e7ff49a7147489f844b8a962f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_forks_repo_name": "claudiamihai/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "9e4c4efd6fbc21e7ff49a7147489f844b8a962f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-01T11:35:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T11:35:00.000Z", "avg_line_length": 379.6289134438, "max_line_length": 109855, "alphanum_fraction": 0.9037491783, "converted": true, "num_tokens": 11110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.09271650302259124}} {"text": "```python\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n```\n\n##### Exercise 7.1\n\nWhy do you think a larger random walk task (19 states instead of 5) was used in the examples of this chapter? Would a smaller walk have shifted the advantage to a different value of n? How about the change in left-side outcome from 0 to -1? Would that have made any difference in the best value of n?\n\nA small random walk would truncate large n-step to their total returns since episodes will be shorter (i.e. large n would just result in alpha MC methods). Therefore we should expect the advantage at lower n for smaller random walks. \n\nWith values initialized at 0, if the left-most value terminated in 0 reward, we would need longer episodes for an agent to assign the correct values to the states left of center, since episodes that terminate to the left will not cause any updates initially, only the episodes that terminate to the right end with non-zero reward. Thus I would expect the best value of n to increase.\n\n---------\n\n##### Exercise 7.2\n\nWhy do you think on-line methods worked better than off-line methods on the example task?\n\nOff-line methods generally take random actions with some small probability $\\epsilon$. We would expect at least 1-2 random actions in an environment with a minimum of 10 states to termination, depending on $\\epsilon$ (assuming $\\epsilon$ is between 10-20%). Therefore, even after finding the optimal action-values, these random actions will attribute erroneous rewards to certain actions, leading to higher RMSEs compared to on-line methods; we also see that larger n is more optimal for off-line methods compared to on-line, presumably because larger n reduces noise from the $\\epsilon$ greedy actions.\n\n-----------\n\n##### Exercise 7.3\n\nIn the lower part of Figure 7.2, notice that the plot for n=3 is different from the others, dropping to low performance at a much lower value of $\\alpha$ than similar methods. In fact, the same was observed for n=5, n=7, and n=9. Can you explain why this might have been so? In fact, we are not sure ourselves.\n\nMy hypothesis is that odd values of n have higher RMSE because of the environment. It takes at a minimum, an odd number of steps to reach termination from the starting state. For off-line methods, even after finding the optimal action-values, an agent may still not terminate in an odd number of steps. Therefore my hypothesis is that odd n-step methods are more likely to cause erroneous updates to the $\\epsilon$ greedy actions compared to even n-step methods. A quick way to test this, would be to create a random-walk where an agent will terminate at a minimum in an even number of steps, and then to observe the same plots as in Figure 7.2. \n\n----------\n\n#### Exercise 7.4 \n\nThe parameter $\\lambda $ characterizes how fast the exponential weighting in Figure 7.4 falls off, and thus how far into the future the $\\lambda $-return algorithm looks in determining its backup. But a rate factor such as $\\lambda $ is sometimes an awkward way of characterizing the speed of the decay. For some purposes it is better to specify a time constant, or half-life. What is the equation relating $\\lambda $ and the half-life, $\\tau$, the time by which the weighting sequence will have fallen to half of its initial value?\n\nThe half life occurs when weighting drops in half:\n\n$ \\lambda^{n} = 0.5 $,\n\nwhich occurs at,\n$n = -ln(2) / ln(\\lambda) = \\tau$\n\n\n-----\nGetting (7.3) from the equation above it:\n\n$R_t^\\lambda = (1 - \\lambda) \\sum_{n=1}^\\infty \\lambda^{n-1} R^{(n)}_t$,\n\nafter $T-t-1$, we sum to infinity but with $R^{T-t-1}_t$, which is just the total return $R_t$, so:\n\n$R_t^\\lambda = (1 - \\lambda) \\sum_{n=1}^{T-t-1} \\lambda^{n-1} R^{(n)}_t + (1 - \\lambda) R_t \\sum_{n=T-t-1}^{\\infty} \\lambda^{n} $\n\nWe can remove $\\lambda^{T-t-1}$ from the last sum to get $ (1 - \\lambda) R_t \\lambda^{T-t-1} \\sum_{n=0}^\\infty \\lambda^n = (1 - \\lambda) R_t \\lambda^{T-t-1} \\frac{1}{1 - \\lambda}$, so that: \n\n$R_t^\\lambda = (1 - \\lambda) \\sum_{n=1}^{T-t-1} \\lambda^{n} R^{(n)}_t + \\lambda^{T-t-1} R_t $\n\n----------\n\n##### Exercise 7.5\n\nIn order to get TD($\\lambda$) to be equivalent to the $\\lambda$-return algorithm in the online case, the proposal is that $\\delta_t = r_{t+1} + \\gamma V_t(s_{t+1}) - V_{t-1}(s_t) $ and the n-step return is $R_t^{(n)} = r_{t+1} + \\dots + \\gamma^{n-1} r_{t+n} + \\gamma^n V_{t+n-1}(s_{t+n}) $. To show that this new TD method is equivalent to the $\\lambda$ return, it suffices to show that $\\Delta V_t(s_t)$ for the $\\lambda$ return is equivalent to the new TD with modified $\\delta_t$ and $R_t^{(n)}$.\n\nAs such, we expand the $\\lambda$ return:\n\n$\n\\begin{equation}\n\\begin{split}\n\\frac{1}{\\alpha} \\Delta V_t(s_t) =& -V_{t-1}(s_t) + R_t^\\lambda\\\\\n=& -V_{t-1}(s_t) + (1 - \\lambda) \\lambda^0 [r_{t+1} + \\gamma V_t(s_{t+1})] + (1-\\lambda) \\lambda^1 [r_{t+1} + \\gamma r_{t+2} + \\gamma^2 V_{t+1}(s_{t+2})] + \\dots\\\\\n=& -V_{t-1}(s_t) + (\\gamma \\lambda)^0 [r_{t+1} + \\gamma V_t(s_{t+1}) - \\gamma \\lambda V_t(s_{t+1})] + (\\gamma \\lambda)^1 [r_{t+2} + \\gamma V_{t+1}(s_{t+2}) - \\gamma \\lambda V_{t+1}(s_{t+2})] + \\dots\\\\\n=& (\\gamma \\lambda)^0 [r_{t+1} + \\gamma V_t(s_{t+1}) - V_{t-1}(s_t)] + (\\gamma \\lambda) [r_{t+2} + \\gamma V_{t+1}(s_{t+2}) - V_t(s_t+1)] + \\dots\\\\\n=& \\sum_{k=t}^\\infty (\\gamma \\lambda)^{k-t} \\delta_k\n\\end{split}\n\\end{equation}\n$\n\nwhere $\\delta_k = r_k + \\gamma V_k(s_{k+1}) - V_{k-1}(s_k)$ as defined in the problem. Therefore, for online TD as defined above, the $\\lambda$ return is exactly equivalent.\n\n\n-------------\n\n##### Exercise 7.6\n\nIn Example 7.5, suppose from state s the wrong action is taken twice before the right action is taken. If accumulating traces are used, then how big must the trace parameter $\\lambda $ be in order for the wrong action to end up with a larger eligibility trace than the right action?\n \nThe eligibility trace update is $e_t(s) \\leftarrow 1 + \\gamma \\lambda e_{t-1}(s)$ if $s = s_t$ and $e_t(s) \\leftarrow \\gamma \\lambda e_{t-1}(s)$ if $s \\neq s_t$. For two wrong actions, then one right action, $e_t(wrong) = (1 + \\gamma \\lambda) \\gamma \\lambda $, and $e_t(right) = 1$. If we want $e_t(wrong) \\gt e_t(right)$, we need $(1 + \\gamma \\lambda) \\gamma \\lambda \\gt 1$, or $\\gamma \\lambda \\gt \\frac{1}{2} (\\sqrt(5) - 1)$.\n\n-----------\n\n##### Exercise 7.7\n\n\n\n```python\nclass LoopyEnvironment(object):\n def __init__(self):\n self._terminal_state = 5\n self._state = 0\n self._num_actions = 2\n \n @property\n def state(self):\n return self._state\n \n @state.setter\n def state(self, state):\n assert isinstance(state, int)\n assert state >= 0 and state <= self._terminal_state\n self._state = state\n \n @property\n def terminal_state(self):\n return self._terminal_state\n\n def reinit_state(self):\n self._state = 0\n \n def get_states_list(self):\n return range(self._terminal_state + 1)\n \n def get_actions_list(self):\n return range(self._num_actions)\n \n def is_terminal_state(self):\n return self._state == self._terminal_state\n \n def take_action(self, action):\n \"\"\"\n action int: 0 or 1\n if action is 0 = wrong, then don't change the state\n if action is 1 = right, then go to the next state\n\n returns int: reward\n \"\"\"\n assert action in [0, 1]\n assert self.is_terminal_state() == False\n if action == 1:\n self._state += 1\n if self._state == self._terminal_state:\n return 1\n return 0\n```\n\n\n```python\nimport random\nfrom itertools import product\n\nclass SARSA_lambda(object):\n def __init__(self, environment):\n states = environment.get_states_list()\n actions = environment.get_actions_list()\n \n self.environment = environment\n self.state_actions = list(product(states, actions))\n self.Q = np.random.random([len(states), len(actions)])\n self.e = np.zeros([len(states), len(actions)])\n \n def _get_epsilon_greedy_action(self, epsilon, p):\n if random.random() <= epsilon:\n action = random.randint(0, len(p) - 1)\n return action\n actions = np.where(p == np.amax(p))[0]\n action = np.random.choice(actions)\n return action\n \n def learn(self, num_episodes=100, Lambda=.9, gamma=.9, epsilon=.05, alpha=0.05,\n replace_trace=False):\n \"\"\"\n Args:\n num_episodes (int): Number of episodes to train\n Lambda (float): TD(lambda) parameter \n (if lambda = 1 we have MC or if lambda = 0 we have 1-step TD)\n gamma (float): decay parameter for Bellman equation\n epsilon (float): epsilon greedy decisions\n alpha (float): determines how big should TD update be\n \n Returns:\n list (int): the number of time steps it takes for each episode to terminate\n \"\"\"\n \n time_steps = []\n for n in xrange(num_episodes):\n time_idx = 0\n self.e = self.e * 0\n self.environment.reinit_state()\n s = self.environment.state\n a = random.randint(0, self.Q.shape[1] - 1)\n while not self.environment.is_terminal_state():\n r = self.environment.take_action(a)\n time_idx += 1\n\n s_prime = self.environment.state\n a_prime = self._get_epsilon_greedy_action(epsilon, self.Q[s_prime, :])\n delta = r + gamma * self.Q[s_prime, a_prime] - self.Q[s, a]\n\n if replace_trace:\n self.e[s, a] = 1\n else:\n self.e[s, a] = self.e[s, a] + 1\n \n for s, a in self.state_actions:\n self.Q[s, a] = self.Q[s, a] + alpha * delta * self.e[s, a]\n self.e[s, a] = gamma * Lambda * self.e[s, a]\n \n s = s_prime\n a = a_prime\n \n time_steps.append(time_idx)\n return time_steps\n\n```\n\n\n```python\nenv = LoopyEnvironment()\ns = SARSA_lambda(env)\n```\n\nRun both the replace-trace and the SARSA($\\lambda$) regular trace methods for X episodes, and repeat N times. Get the average time length over all X episodes for each iteration for each alpha. In the environment in Figure 7.18, it takes at a minimum, 5 time steps to terminate. This is our baseline.\n\n\n```python\n\ndef get_results(replace_trace, num_trials, num_episodes):\n alphas = np.linspace(.2, 1, num=10)\n results = np.array([])\n for alpha in alphas:\n res = []\n for i in xrange(num_trials):\n sarsa_lambda = SARSA_lambda(env)\n t = sarsa_lambda.learn(num_episodes=num_episodes, alpha=alpha, \n replace_trace=replace_trace, gamma=0.9,\n epsilon=0.05, Lambda=0.9)\n res.append(np.mean(t))\n\n if results.shape[0] == 0:\n results = np.array([alpha, np.mean(res)])\n else:\n results = np.vstack([results, [alpha, np.mean(res)]])\n return results\n\nnum_trials = 100\nnum_episodes = 20\nreplace_trace = get_results(True, num_trials, num_episodes)\nregular_trace = get_results(False, num_trials, num_episodes)\n \n```\n\n\n```python\nplt.plot(replace_trace[:, 0], replace_trace[:, 1], label='replace')\nplt.plot(regular_trace[:, 0], regular_trace[:, 1], label='regular')\n\nplt.legend()\nplt.title('Exercise 7.7: First %d episodes averaged %d times' %(num_episodes, num_trials))\nplt.xlabel('alpha')\nplt.ylabel('Time-steps')\n```\n\nWe see that on average, the replace trace method for $\\gamma = 0.9$, $\\lambda=0.9$, $\\epsilon=0.05$ takes less time to terminate. With lower $\\gamma$, the advantage of replace-trace seems to disappear.\n\n-----------\n\n##### Exercise 7.8\n\nsarsa($\\lambda$) with replacing traces, has a backup which is equivalent to sarsa($\\lambda$) until the first repeated state-action pair. If we use the replace-trace formula in Figure 7.17, the replace-trace backup diagram terminates at the first repeated state-action pair. For the replace-trace formula in Figure 7.16, the backup diagram after the first repeated-state action pair is some hybrid of sarsa($\\lambda$) with weights changed only for the repeated state-actions. I'm not sure how to draw that.\n\n-------\n\n##### Exercise 7.9\n\nWrite pseudocode for an implementation of TD($\\lambda $) that updates only value estimates for states whose traces are greater than some small positive constant.\n \n\nYou can use a hash-map of traces to update, and if the update reduces the value of the trace below some constant, remove the trace from the hash-map. Traces get added to the hash-map as they get visited. If you want to write the pseudo code or real code, feel free to make a pull-request!\n\n-------\n\n##### Exercise 7.10\n\nProve that the forward and backward views of off-line TD($\\lambda $) remain equivalent under their new definitions with variable $\\lambda $ given in this section. Follow the example of the proof in Section 7.4.\n\n\nAs given in the book, the backward view is:\n\n$\n e_t(s)=\\left\\{\n \\begin{array}{ll}\n \\gamma \\lambda_t e_{t-1}(s), & \\mbox{ if } s \\neq s_t\\\\\n \\gamma \\lambda_t e_{t-1}(s) + 1, & \\mbox{ if } s = s_t\n \\end{array}\n \\right.\n$\n\nand the forward view is:\n\n$R_t^\\lambda = \\sum_{k=t+1}^{T-1} R_t^{(k-t)} (1 - \\lambda_k) \\prod_{i=t+1}^{k-1} \\lambda_i + R_t \\prod_{i=t+1}^{T-1} \\lambda_i$.\n\nThe proof is almost identical to 7.4. For the backward view we need to express the eligibility trace nonrecursively:\n\n$e_t(s) = \\gamma \\lambda_t e_{t-1}(s) + I_{ss_t} = \\gamma \\lambda_t [\\gamma \\lambda_{t-1} e_{t-2}(s) + I_{ss_{t-1}}] + I_{ss_t} = \\sum_{k=0}^t I_{ss_k}\\gamma^{t-k} \\prod_{i=k+1}^t \\lambda_i$\n\nso that the sum of all updates to a given state is:\n\n$\\sum_{t=0}^{T-1}\\alpha I_{ss_t} \\sum_{k=t}^{T-1} \\gamma^{k-t} \\prod_{i=t+1}^k \\lambda_i \\delta_k$\n\nwhich was obtained by following the same algebra as in 7.9 to 7.12.\n\n\nThe next step is to show that the sum of all updates of the forward view is equivalent to the previous equation above. We start with:\n\n\n$\n\\begin{equation}\n\\begin{split}\n\\frac{1}{\\alpha} \\Delta V_t(s_t) =& -V_{t}(s_t) + R_t^\\lambda\\\\\n=& -V_t(s_t) + (1 - \\lambda_{t+1}) [r_{t+1} + \\gamma V_t(s_{t+1})] + (1 - \\lambda_{t+2})\\lambda_{t+1} [r_{t+1} + \\gamma r_{t+2} + \\gamma^2 V_t(s_{t+2})] + \\dots\\\\\n=& -V_{t}(s_t) + [r_{t+1} + \\gamma V_t(s_{t+1}) - \\lambda_{t+1} \\gamma V_t(s_{t+1})] + \\gamma \\lambda_{t+1} [r_{t+2} + \\gamma V_t(s_{t+2}) - \\gamma \\lambda_{t+2} V_t(s_{t+2})] + \\dots\\\\\n=& [r_{t+1} + \\gamma V_t(s_{t+1}) - V_t(s_t)] + (\\gamma \\lambda_{t+1})[r_{t+2} + \\gamma V_t(s_{t+2}) - V_t(s_{t+1})] + (\\gamma^2 \\lambda_{t+1}\\lambda_{t+2}) \\delta_{t+3} + \\dots\\\\\n\\approx& \\sum_{k=t}^{T-1} \\gamma^{k-t} \\delta_k \\prod_{i=t+1}^{k} \\lambda_i\n\\end{split}\n\\end{equation}\n$\n\nwhich is equivalent to the backward case, and becomes an equality for offline updates.\n\n\n------\n\n** \"Eligibility traces are the first line of defense against both long-delayed rewards and non-Markov tasks.\"**\n\n\"In the future it may be possible to vary the trade-off between TD and Monte Carlo methods more finely by using variable $\\lambda $, but at present it is not clear how this can be done reliably and usefully.\"\n", "meta": {"hexsha": "504ccbb9859a7ad2f0ef2e2aef7ca83300954e43", "size": 44358, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/chapter7.ipynb", "max_stars_repo_name": "btaba/intro-to-rl", "max_stars_repo_head_hexsha": "b65860cd81ce43ac344d4f618a6364c000ea971b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2016-10-02T19:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-30T18:10:37.000Z", "max_issues_repo_path": "notebooks/chapter7.ipynb", "max_issues_repo_name": "btaba/intro-to-rl", "max_issues_repo_head_hexsha": "b65860cd81ce43ac344d4f618a6364c000ea971b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-07-08T08:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-03T01:38:33.000Z", "max_forks_repo_path": "notebooks/chapter7.ipynb", "max_forks_repo_name": "btaba/intro-to-rl", "max_forks_repo_head_hexsha": "b65860cd81ce43ac344d4f618a6364c000ea971b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2016-10-02T20:12:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T20:30:57.000Z", "avg_line_length": 91.4597938144, "max_line_length": 23488, "alphanum_fraction": 0.7602687227, "converted": true, "num_tokens": 4328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.22541660542786957, "lm_q1q2_score": 0.09267121984962469}} {"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, symbols, Matrix\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Orthogonal vectors and subspaces\n# Rowspace orthogonal to nullspace and columnspace to nullspace of AT\n# N(ATA) = N(A)\n\n## Orthogonal vectors\n\n* Two vectors are orthogonal if their dot product is zero\n* If they are written as column vectors **x** and **y**, their dot product is **x**T**y**\n * For orthogonal (perpendicular) vectors **x**T**y** = 0\n* From the Pythagorean theorem they are orthogonal if\n$$ { \\left\\| \\overline { x } \\right\\| }^{ 2 }+{ \\left\\| \\overline { y } \\right\\| }^{ 2 }={ \\left\\| \\overline { x } +\\overline { y } \\right\\| }^{ 2 }\\\\ { \\left\\| \\overline { x } \\right\\| }=\\sqrt { { x }_{ 1 }^{ 2 }+{ x }_{ 2 }^{ 2 }+\\dots +{ x }_{ b }^{ 2 } } $$\n\n* The length squared of a (column) vector **x** can be calculated by **x**T**x**\n* This achieves exactly the same as the sum of the squares of each element in the vector\n$$ { x }_{ 1 }^{ 2 }+{ x }_{ 2 }^{ 2 }+\\dots +{ x }_{ n }^{ 2 }$$\n\n* Following from the Pythagorean theorem we have\n$$ { \\left\\| \\overline { x } \\right\\| }^{ 2 }+{ \\left\\| \\overline { y } \\right\\| }^{ 2 }={ \\left\\| \\overline { x } +\\overline { y } \\right\\| }^{ 2 }\\\\ { \\underline { x } }^{ T }\\underline { x } +{ \\underline { y } }^{ T }\\underline { y } ={ \\left( \\underline { x } +\\underline { y } \\right) }^{ T }\\left( \\underline { x } +\\underline { y } \\right) \\\\ { \\underline { x } }^{ T }\\underline { x } +{ \\underline { y } }^{ T }\\underline { y } ={ \\underline { x } }^{ T }\\underline { x } +{ \\underline { x } }^{ T }\\underline { y } +{ \\underline { y } }^{ T }\\underline { x } +{ \\underline { y } }^{ T }\\underline { y } \\\\ \\because \\quad { \\underline { x } }^{ T }\\underline { y } ={ \\underline { y } }^{ T }\\underline { x } \\\\ { \\underline { x } }^{ T }\\underline { x } +{ \\underline { y } }^{ T }\\underline { y } ={ \\underline { x } }^{ T }\\underline { x } +2{ \\underline { x } }^{ T }\\underline { y } +{ \\underline { y } }^{ T }\\underline { y } \\\\ 2{ \\underline { x } }^{ T }\\underline { y } =0\\\\ { \\underline { x } }^{ T }\\underline { y } =0 $$\n* This states that the dot product of orthogonal vectors equal zero\n\n* The zero vector is orthogonal to all other similar dimensional vectors\n\n## Orthogonality of subspaces\n\n* Consider two subspaces *S* and *T*\n* To be orthogonal every vector in *S* must be orthogonal to any vector in *T*\n\n* Consider the *XY* and *YZ* planes in 3-space\n* They are not orthogonal, since many combinations of vectors (one in each plane) are not orthogonal\n* Vectors in the intersection, even though, one each from each plane can indeed be the same vector\n* We can say that any planes that intersect cannot be orthogonal to each other\n\n## Orthogonality of the rowspace and the nullspace\n\n* The nullspace contains vectors **x** such that A**x** = **0**\n* Now remembering that **x**T**y** = 0 for orthogonal column vectors and considering each row in A as a transposed column vector and **x** (indeed a column vector) and their product being zero meaning that they are orthogonal, we have:\n$$ \\begin{bmatrix} { { a }_{ 11 } } & { a }_{ 12 } & \\dots & { a }_{ 1n } \\\\ { a }_{ 21 } & { a }_{ 22 } & \\dots & { a }_{ 2n } \\\\ \\vdots & \\vdots & \\vdots & \\vdots \\\\ { a }_{ m1 } & { a }_{ m2 } & \\dots & { a }_{ mn } \\end{bmatrix}\\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ \\vdots \\\\ { x }_{ n } \\end{bmatrix}=\\begin{bmatrix} 0 \\\\ 0 \\\\ \\vdots \\\\ 0 \\end{bmatrix}\\\\ \\begin{bmatrix} { a }_{ 11 } & { a }_{ 12 } & \\dots & { a }_{ 1n } \\end{bmatrix}\\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ \\vdots \\\\ { x }_{ n } \\end{bmatrix}=0\\\\ \\dots $$\n\n* The rows (row vectors) in A are NOT the only vectors in the rowspace, since we also need to show that ALL linear combinations of them are also orthogonal to **x**\n* This is easy to see by the structure above\n\n## Orthogonality of the columnspace and the nullspace of AT\n\n* The proof is the same as above\n\n* The orthogonality of the rowspace and the nullspace is creating two orthogonal subspaces in ℝn\n* The orthogonality of the columnspace and the nullspace of AT is creating two orthogonal subspaces in ℝm\n\n* Note how the dimension add up to the degree of the space ℝ\n * The rowspace (a fundamental subspace in ℝn) is of dimension *r*\n * The dimension of the nullspace (a fundamental subspace in ℝn) is of dimension *n* - *r*\n * Addition of these dimensions gives us the dimension of the total space *n* as in ℝn\n * AND\n * The columnspace is of dimension *r* and the nullspace of AT is of dimension *m* - *r*, which adds to *m* as in ℝm\n\n* This means that two lines that may be orthogonal in ℝ3 cannot be two orthogonal subspaces of ℝ3 since the addition of the dimensions of these two subspaces (lines) is not 3 (as in ℝ3)\n\n* We call this complementarity, i.e. the nullspace and rowspace are orthogonal *complements* in ℝn\n\n## ATA\n\n* We know that\n * The result is square\n * The result is symmetric, i.e. (*n*×*m*)(*m*×*n*)=*n*×*n*\n * (ATA)T = ATATT = ATA\n\n* When A**x** = **b** is not solvable we use ATA**x** = AT**b**\n* **x** in the first instance did not have a solution, but after multiplying both side with AT, we hope that the second **x** has an solution, now called\n$$ {A}^{T}{A}\\hat{x} = {A}^{T}{b} $$\n\n\n* Consider the matrix below with *m* = 4 equation in *n* = 2 unknowns\n* The only **b** solutions must be linear combinations of the columnspace of A\n\n\n```python\nA = Matrix([[1, 1], [1, 2], [1, 5]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 1\\\\1 & 2\\\\1 & 5\\end{matrix}\\right]$$\n\n\n\n$$ {x}_{1} \\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\end{bmatrix} + {x}_{2} \\begin{bmatrix} 1 \\\\ 2 \\\\ 5 \\end{bmatrix} = \\begin{bmatrix} {b}_{1} \\\\ {b}_{2} \\\\ {b}_{3} \\end{bmatrix} $$\n\n\n```python\nA.transpose() * A\n```\n\n\n\n\n$$\\left[\\begin{matrix}3 & 8\\\\8 & 30\\end{matrix}\\right]$$\n\n\n\n* Note how the nullspace of ATA is equal to the nullspace of A\n\n\n```python\n(A.transpose() * A).nullspace() == A.nullspace()\n```\n\n\n\n\n True\n\n\n\n* The same goes for the rank\n\n\n```python\nA.rref(), (A.transpose() * A).rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\begin{pmatrix}\\left[\\begin{matrix}1 & 0\\\\0 & 1\\\\0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}\\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right], & \\begin{bmatrix}0, & 1\\end{bmatrix}\\end{pmatrix}\\end{pmatrix}$$\n\n\n\n* ATA is not always invertible\n* In fact it is only invertible if the nullspace of A only contains the zero vector (has independent columns)\n\n\n```python\n\n```\n", "meta": {"hexsha": "94607e4da580d6972243c6e49fa333b042126e17", "size": 15461, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_14_Orthogonality_of_vectors_and_subspaces.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_14_Orthogonality_of_vectors_and_subspaces.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_14_Orthogonality_of_vectors_and_subspaces.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": 32.6181434599, "max_line_length": 1149, "alphanum_fraction": 0.4976392213, "converted": true, "num_tokens": 3019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.19436782035217448, "lm_q1q2_score": 0.09263174800144658}} {"text": "#### 10.\n\n\n\n\n**HW Review:**\n\n

Diffraction and crystallography

\n\n\n

11.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\n

See Page 420 for phase problem, See Page 421 for the way the problem can be addressed.

\n\n\n\n

11.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\n
\n\n\n\n
\n\n\n\n\n**Chapter 12**\n\n**12.12 A swimmer enters a gloomier world (in one sense) on diving to greater depths. Given that the mean molar absorption coefficient of seawater in the visible region is $6.2x10^{−5}$ $dm^{3}$ $mol^{−1}$ $cm^{−1}$, calculate the depth at which a diver will experience (a) half the surface intensity of light and (b) one-tenth that intensity.**\n\n\n### Derivation of Beer's Law:\n\nHere is an image of the situation we wish to model:\n\n\n\nThe density of particles, $\\rho$ and the absorption coefficient, $\\alpha$ multiplied by the intensity, I shown in the 1st order differential equation:\n$$ -\\frac{\\partial{I}}{\\partial{x}} = I \\alpha \\rho $$\n\nCombine like-terms to each side of the equation:\n\n$$\\int_{I_{0}}^{I} \\frac{\\partial{I}}{I} = -\\int_{0}^{x} \\alpha \\rho \\partial{x} $$\n\n\nWe know that $\\int \\frac{1}{x}dx = ln(x)$, so\n\n$$ln(\\frac{I}{I_{0}}) = - \\alpha \\rho x, $$\n\n\n-----------------\n\nTo get the general solution of the D.E we can take the exponential of both sides \n\n$$\\frac{I}{I_{0}} = e^{-\\alpha \\rho x} $$\n\n**General Solution to the D.E**:\n\n$$I (x) = I_{0} e^{-\\alpha \\rho x}$$\n\n--------------------------\n\nOtherwise, to continue deriving Beer's Law we can use the property of logarithms:\n\n$$-ln(\\frac{I}{I_{0}}) = ln(\\frac{I_{0}}{I}) = \\alpha \\rho x, $$\n\n\nand since we know the following\n\n$$log_{10}(x) = \\frac{ln(x)}{ln(10)},$$\n\nthen we can say\n\n$$ log_{10}(\\frac{I_{0}}{I}) = \\frac{\\alpha \\rho x}{ln(10)}$$\n\n\nFinally, we can say that $\\rho \\propto c$. We can also simplify further by saying $\\epsilon =\\frac{\\alpha}{ln(10)}$, which has units of $M^{-1}cm^{-1}$ and $x = b$, where b is in cm.\n\n$$ A = log(\\frac{I_{0}}{I}) = \\epsilon b c$$\n\nNow, solving for the path length $b$ gives the following expression with $c_{H_{2}O} = \\rho/MW$ and $I = 0.5I_{0}$.\n\n\n$$ b = \\frac{log(\\frac{I_{0}}{0.5I_{0}})}{\\epsilon (\\rho/MW)} = \\frac{0.301}{(6.2 x 10^{-5} dm^{3}. mol^{-1}.cm^{-1}) (55.5 mol.dm^{-3})} = 87 cm $$\n\n**Note**, since the information regarding salt water concentration is not provided in the question we approximated the concentration by with values for $H_{2}O$.\n\n\n\n\n\n**12.25 How many normal modes of vibration are there for (a) $NO_{2}$, (b) $N_{2}O$, (c) cyclohexane, and (d) hexane?**\n\nThere are $3N-6$ and $3N-5$ vibrational modes (in which N is the number of atoms in molecule) for non-linear and linear molecules; respectively.\n\n\n**(a)** $NO_{2}$, Non-linear; $3N-6 = 3(3)-6 = 3$\n\n**(b)** $N_{2}O$, linear; $3N-5 = 3(3)-5 = 4$\n\n**(c)** cyclohexane, non-linear; $3N-6 = 3(18)-6 = 48$\n\n**(d)** hexane, non-linear; $3N-6 = 3(20)-6 = 54$\n\n\n\n\n-----------------------------------------\n\n**SIDE NOTES:**\n\n### Rates of various processes\n\n| $\\text{Process}$ | $\\text{Timescales (s)}$ | $\\text{Radiative}$ | $\\text{Transition}$ |\n| :--: | :--: | :--: | :--: |\n| IC | $10^{-14}-10^{-11}$ | N | $S_{n} \\to S_{1}$ |\n| Vib Relax | $10^{-14}-10^{-11}$ | N | ${S_{n}}^{*} \\to S_{n}$ |\n| Abs | $10^{-15}$ | Y | $S_{0} \\to S_{n}$ |\n| Fluor | $10^{-9}-10^{-7}$ | Y | $S_{1} \\to S_{0}$ |\n| ISC | $10^{-8}-10^{-3}$ | N | $S_{1} \\to T_{1}$ |\n| Phos | $10^{-4}-10^{0}$ | Y | $T_{1} \\to S_{0}$ |\n\n\n- timescale of FRET are typically in ns \n\n\n-----------------------------------------\n\n\n\n**12.37 When benzophenone is illuminated with ultraviolet radiation, it is excited into a singlet state. This singlet changes rapidly into a triplet, which phosphoresces. Triethylamine acts as a quencher for the triplet. In an experiment in methanol as solvent, the phosphorescence intensity Iphos varied with amine concentration as shown below. A time-resolved laser spectroscopy experiment had also shown that the half-life of the fluorescence in the absence of quencher is 29 ms. What is the value of $k_{Q}$?**\n\n\n| $Species$ | $\\text{}$ | $\\text{}$ | $\\text{}$ |\n| :--: | :--: | :--: | :--: |\n| $[Q]/(mol\\space dm^{−3})$ | 0.0010 | 0.0050 | 0.0100 |\n| $I_{phos}/(A.U.)$ | 0.41 | 0.25 | 0.16|\n\n\nFirst, we need to write out the mechanism that is given in the question:\n\n>When benzophenone is illuminated with ultraviolet radiation, it is excited into a singlet state. \n\n$$ M + h\\nu_{i} \\rightarrow M^{*} \\tag{1}$$\n\n>This singlet changes rapidly into a triplet, which phosphoresces.\n\n$$ M^{*} \\rightarrow M + h\\nu_{phos} \\tag{2}$$\n\n>Triethylamine acts as a quencher for the triplet.\n\n$$ M^{*} + Q \\rightarrow M + Q \\tag{3}$$\n\n\n
\n\nTo model this process, we apply the steady state approximation on $[M^{*}]$ to obtain $I_{phos}$... (Do this to get your own \"stern-volmer\" equation that models what the questions provides).\n\n**Steady State** is an assumption that the rate of (production/destruction) is equal to zero i.e., at equilibrium. \n\n$$\\frac{d[M^{*}]}{dt} = I_{abs} - k_{Q}[Q][M^{*}]-k_{phos}[M^{*}]=0$$\n\n$$ \\implies (-k_{Q}[Q]-k_{phos})[M^{*}] = -I_{abs} \\implies [M^{*}] = \\frac{I_{abs}}{k_{Q}[Q]+k_{phos}},$$\n\nand we know that $I_{phos} = k_{phos}[M^{*}]$, so \n\n$$ I_{phos} = k_{phos} \\frac{I_{abs}}{k_{Q}[Q]+k_{phos}}$$\n\nWe can take the inverse of $I_{phos}$ to get the equation in the form of a line:\n\n$$ \\frac{1}{I_{phos}} = \\frac{1}{I_{abs}} + \\frac{k_{Q}[Q]}{k_{phos}I_{abs}}$$\n\nNow, we plot the data that was given and extract the slope...\n\n\n```python\n%matplotlib inline\nimport plot as p\nimport numpy as np\nQ = np.array([0.0010,0.0050, 0.0100])\nIphos = np.array([0.41, 0.25, 0.16])\nx,y = Q,1/Iphos\np.simple_plot(x,y,xlabel=r'$[Q]$',ylabel=r'${I_{phos}}^{-1}$',Type='scatter',color=False,fig_size=(8,4),\n fit=True, order=1, annotate_text=r\"$slope=k_{Q}/(k_{phos}I_{abs})$\",annotate_x=-0.005, annotate_y=5.5)\n```\n\nTherefore, the linear fit gives:\n$$I_{phos}^{-1}=(424.5302 dm^{3} mol )[Q]+(1.966), $$\n\nwhere $\\frac{k_{Q}}{k_{phos}I_{abs}} = 424.5302 dm^{3} mol $. \n\nTherefore,\n\n$$k_{Q} = \\frac{(24.5302 dm^{3} mol)(2.39x10^{4} s^{-1})}{1.97} = 5.2x10^{6} dm^{3} mol^{-1} s^{-1} $$\n\n\n\n\n\n\n\n\n\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n
\n\n\n\n

What kind of information can be obtained using FRET spectroscopy? What is the distance dependence of the FRET effect?

\n\n

Fö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\n**12.39 The Förster theory of resonance energy transfer and the basis for the FRET technique can be tested by performing fluorescence measurements on a series of compounds in which an energy donor and an energy acceptor are covalently linked by a rigid molecular linker of variable and known length. L. Stryer and R.P. Haugland, Proc. Natl. Acad. Sci. USA 58, 719 (1967), collected the following data on a family of compounds with the general composition dansyl-(l-prolyl)n-naphthyl, in which the distance R between the naphthyl donor and the dansyl acceptor was varied by increasing the number of prolyl units in the linker:**\n\n\n| $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ |\n| :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | \n| $R/nm$ | 1.2 | 1.5 | 1.8 | 2.8 | 3.1 | 3.4 | 3.7 | 4.0 | 4.3 | 4.6 |\n| $\\eta_{T}$ | 0.99 | 0.94 | 0.97 | 0.82 | 0.74 | 0.65 | 0.40 | 0.28 | 0.24 | 0.16 |\n\n\n\n**Are the data described adequately by the Förster theory (eqns 12.26 and 12.27)? If so, what is the value of $R_{0}$ for the naphthyl–dansyl pair?**\n\n\n
Förster theory:
\n\nStates that the efficiency of resonance energy transfer is related to the distance $R$ between donor-acceptor pairs by\n\n$$\\eta_{T} = \\frac{{R_{0}}^{6}}{{R_{0}}^{6} + {R}^{6}}, $$\n\nwhere $R_{0}$ is the distance at which $50 \\%$ of the energy is transfered from donor to acceptor, and $R$ is the distance between donor and acceptor.\n\nFirst, we need to rearrange the Förster theory equation into a linearized form. \n\n$$ \\frac{1}{\\eta_{T}} = \\frac{{R_{0}}^{6} + {R}^{6}}{{R_{0}}^{6}} = 1 + (\\frac{R}{R_{0}})^{6}$$\n\nNow, we are able to plot the data:\n\n\n\n\n```python\n%matplotlib inline\nimport plot as p\nimport numpy as np\nR = np.array([1.2, 1.5, 1.8, 2.8, 3.1, 3.4, 3.7, 4.0, 4.3, 4.6])\nnT = np.array([0.99, 0.94, 0.97, 0.82, 0.74, 0.65, 0.40, 0.28, 0.24, 0.16])\nx,y = R**6,1/nT\np.simple_plot(x,y,xlabel=r'$(R/(nm))^{6}$',ylabel=r'${\\eta_{T}}^{-1}$',Type='scatter',\n color=False,fig_size=(8,4),fit=True, order=1)\n```\n\nUsing the slope of the line $y=0.000550*x+(0.971320)$, where the slope is $0.000550 = (\\frac{1}{R_{0}})^{6}$.\n\n$$R_{0} = (\\frac{1}{0.000550 nm^{-6}})^{1/6} = 3.5 nm$$\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8d990f9f13cff07ca8ee44c0d5c933429653b990", "size": 69020, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "CHEM3405_Physical_Chemistry_Bio/HW_Review_03-25-20.ipynb", "max_stars_repo_name": "robraddi/tu_chem", "max_stars_repo_head_hexsha": "18b8247d6c00e33f15f040a57a32b5fc2372137a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-29T04:26:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T04:26:42.000Z", "max_issues_repo_path": "CHEM3405_Physical_Chemistry_Bio/HW_Review_03-25-20.ipynb", "max_issues_repo_name": "robraddi/tu_chem", "max_issues_repo_head_hexsha": "18b8247d6c00e33f15f040a57a32b5fc2372137a", "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": "CHEM3405_Physical_Chemistry_Bio/HW_Review_03-25-20.ipynb", "max_forks_repo_name": "robraddi/tu_chem", "max_forks_repo_head_hexsha": "18b8247d6c00e33f15f040a57a32b5fc2372137a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-03T17:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-03T17:47:05.000Z", "avg_line_length": 162.4, "max_line_length": 26628, "alphanum_fraction": 0.8598377282, "converted": true, "num_tokens": 3985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.09257336505959532}} {"text": "# Practical Session 1: Data exploration and regression algorithms\n\n*Notebook by Ekaterina Kochmar*\n\n## 0.1. Dataset\n\nThe California House Prices Dataset is originally obtained from the StatLib repository. This dataset contains the collected information on the variables (e.g., median income, number of households, precise geographical position) using all the block groups in California from the 1990 Census. A block group is the smallest geographical unit for which the US Census Bureau publishes sample data, and on average it includes $1425.5$ individuals living in a geographically compact area. The [original data](http://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html) contains $20640$ observations on $9$ variables, with the *median house value* being the dependent variable (or *target attribute*). The [modified dataset](https://www.kaggle.com/camnugent/california-housing-prices) from Aurelien Geron, *Hands-On Machine Learning with Scikit-Learn and TensorFlow* contains an additional categorical variable.\n\nFor more information on the original data, please refer to Pace, R. Kelley and Ronald Barry, *Sparse Spatial Autoregressions*, Statistics and Probability Letters, 33 (1997) 291-297. For the information on the modified dataset, please refer to Aurelien Geron, *Hands-On Machine Learning with Scikit-Learn and TensorFlow*, O′Reilly (2017), ISBN: 978-1491962299.\n\n## 0.2. Understanding your task\n\nYou are given a dataset that contains a range of attributes describing the houses in California. Your task is to predict the median price of a house based on its attributes. That is, you should train a machine learning (ML) algorithm on the available data, and the next time you get new information on some housing in California, you can use your trained algorithm to predict its price.\n\nThe questions to ask yourself before starting a new ML project:\n- Does the task suggest a supervised or an unsupervised approach?\n- Are you trying to predict a discrete or a continuous value?\n- Which ML algorithm is most suitable?\n\nTry to answer these questions before you start working on this task, using the following hints:\n- *Supervised* approaches rely on the availability of target label annotation in data; examples include regression and classification approaches. *Unsupervised* approaches don't use annotated data; clustering is a good example of such approach.\n- *Discrete* variables are associated with classes and imply classification approach. *Continuous* variables are associated with regression.\n\n## 0.3. Machine Learning check-list\n\nIn a typical ML project, you need to:\n\n- Get the dataset\n- Understand the data, the attributes and their correlations\n- Split the data into training and test set\n- Apply normalisation, scaling and other transformations to the attributes if needed\n- Build a machine learning model\n- Evaluate the model and investigate the errors\n- Tune your model to improve performance\n\nThis practical will show you how to implement the above steps.\n\n## 0.4. Prerequisites\n\nSome of you might have used Jupiter notebooks with the following libraries before in the [CL 1A Scientific Computing course](https://www.cl.cam.ac.uk/teaching/1920/SciComp/materials.html).\n\nTo run the notebooks on your machine, check if `Python 3` is installed. In addition, you will need the following libraries:\n\n- `Pandas` for easy data uploading and manipulation. Check installation instructions at https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html\n- `Matplotlib`: for visualisations. Check installation instructions at https://matplotlib.org/users/installing.html\n- `NumPy` and `SciPy`: for scietinfic programming. Check installation instruction at https://www.scipy.org/install.html\n- `Scikit-learn`: for machine learning algorithms. Check installation instructions at http://scikit-learn.org/stable/install.html\n\nAlternatively, a number of these libraries can be installed in one go through [Anaconda](https://www.anaconda.com/products/individual) distribution. \n\n## 0.5. Learning objectives\n\nIn this practical you will learn how to:\n\n- upload and explore a dataset\n- visualise and explore the correlations between the variables\n- structure a machine learning project\n- select the training and test data in a random and in a stratified way\n- handle missing values\n- handle categorical values\n- implement a custom data transformer\n- build a machine learning pipeline\n- implement a regression algorithm\n- evaluate a regression algorithm performance\n\nIn addition, you will learn about such common machine learning concepts as:\n- data scaling and normalisation\n- overfitting and underfitting\n- cross-validation\n- hyperparameter setting with grid search\n\n\n## Step 1: Uploading and inspecting the data\n\nFirst let's upload the dataset using `Pandas` and defining a function pointing to the location of the `housing.csv` file:\n\n\n```python\nimport pandas as pd\nimport os\n\ndef load_data(housing_path):\n csv_path = os.path.join(housing_path, \"housing.csv\")\n return pd.read_csv(csv_path)\n```\n\nNow, let's run `load_data` using the path where you stored your `housing.csv` file. This function will return a `Pandas` DataFrame object containing all the data. It is always a good idea to take a quick look into the uploaded dataset and make sure you understand the data you are working with. For example, you can check the top rows of the uploaded data and get the general information about the dataset using `Pandas` functionality as follows:\n\n\n```python\nhousing = load_data(\"housing/\")\nhousing.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_valueocean_proximity
0-122.2337.8841.0880.0129.0322.0126.08.3252452600.0NEAR BAY
1-122.2237.8621.07099.01106.02401.01138.08.3014358500.0NEAR BAY
2-122.2437.8552.01467.0190.0496.0177.07.2574352100.0NEAR BAY
3-122.2537.8552.01274.0235.0558.0219.05.6431341300.0NEAR BAY
4-122.2537.8552.01627.0280.0565.0259.03.8462342200.0NEAR BAY
\n
\n\n\n\nRemember that each row in this table represents a block group (housing district), and each column an attribute. How many attributes does the dataset contain? \n\nAnother way to get the summary information about the number of instances and attributes in the dataset is using `info` function. It also shows each attribute's type and number of non-null values:\n\n\n```python\nhousing.info()\n```\n\n \n RangeIndex: 20640 entries, 0 to 20639\n Data columns (total 10 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 20640 non-null float64\n 1 latitude 20640 non-null float64\n 2 housing_median_age 20640 non-null float64\n 3 total_rooms 20640 non-null float64\n 4 total_bedrooms 20433 non-null float64\n 5 population 20640 non-null float64\n 6 households 20640 non-null float64\n 7 median_income 20640 non-null float64\n 8 median_house_value 20640 non-null float64\n 9 ocean_proximity 20640 non-null object \n dtypes: float64(9), object(1)\n memory usage: 1.6+ MB\n\n\nBefore proceeding further, think about the following: \n- How is the data represented? \n- What do the attribute types suggest? \n- Are there any missing values in the dataset? If so, should you do anything about them? \n\nYou must have worked with numerical values before, and the data types like `float64` should look familiar. However, *ocean\\_proximity* attribute has values of a different type. You can inspect the values of a particular attribute in the DataFrame using the following code:\n\n\n```python\nhousing[\"ocean_proximity\"].value_counts()\n```\n\n\n\n\n <1H OCEAN 9136\n INLAND 6551\n NEAR OCEAN 2658\n NEAR BAY 2290\n ISLAND 5\n Name: ocean_proximity, dtype: int64\n\n\n\nThe above suggests that the values are categorical: there are $5$ categories that define ocean proximity. ML algorithms prefer to work with numerical data, besides all the other attributes are represented using numbers. Keep that in mind, as this suggests that you will need to cast the categorical data as numerical.\n\nFor now, let's have a general overview of the attributes and distribution of their values (note *ocean_proximity* is excluded from this summary):\n\n\n```python\nhousing.describe()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \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
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_value
count20640.00000020640.00000020640.00000020640.00000020433.00000020640.00000020640.00000020640.00000020640.000000
mean-119.56970435.63186128.6394862635.763081537.8705531425.476744499.5396803.870671206855.816909
std2.0035322.13595212.5855582181.615252421.3850701132.462122382.3297531.899822115395.615874
min-124.35000032.5400001.0000002.0000001.0000003.0000001.0000000.49990014999.000000
25%-121.80000033.93000018.0000001447.750000296.000000787.000000280.0000002.563400119600.000000
50%-118.49000034.26000029.0000002127.000000435.0000001166.000000409.0000003.534800179700.000000
75%-118.01000037.71000037.0000003148.000000647.0000001725.000000605.0000004.743250264725.000000
max-114.31000041.95000052.00000039320.0000006445.00000035682.0000006082.00000015.000100500001.000000
\n
\n\n\n\nTo make sure you understand the structure of the dataset, try answering the following questions: \n- How can you interpret the values in the table above?\n- What do the percentiles (e.g., $25\\%$ or $50\\%$) tell you about the distribution of values in this dataset (you can select one particular attribute to explain)? \n- How are the missing values handled?\n\nRemember that you can always refer to [`Pandas`](https://pandas.pydata.org/pandas-docs/stable/reference/index.html) documentation.\n\nAnother good way to get an overview of the values distribution is to plot histograms. This time, you'll need to use `matplotlib`:\n\n\n```python\n%matplotlib inline \n#so that the plot will be displayed in the notebook\nimport matplotlib.pyplot as plt\n\nhousing.hist(bins=50, figsize=(20,15))\nplt.show()\n```\n\nTwo observations about this graphs are worth making:\n- the *median_income*, *housing_median_age* and the *median_house_value* have been capped by the team that collected the data: that is, the values for the *median_income* are scaled by dividing the income by \\\\$10000 and capped so that they range between $[0.4999, 15.0001]$ with the incomes lower than $0.4999$ and higher than $15.0001$ binned together; similarly, the *housing_median_age* values have been scaled and binned to range between $[1, 52]$ years and the *median_house_value* – to range between $[14999, 500001]$. Data manipulations like these are not unusual in data science but it's good to be aware of how the data is represented;\n- several other attributes are \"tail heavy\" – they have a long distribution tail with many decreasingly rare values to the right of the mean. In practice that means that you might consider using the logarithms of these values rather than the absolute values.\n\n## Step 2: Splitting the data into training and test sets\n\nIn this practical, you are working with a dataset that has been collected and thoroughly labelled in the past. Each instance has a predefined set of values and the correct price label assigned to it. After training the ML model on this dataset you hope to be able to predict the prices for new houses, not contained in this dataset, based on their characteristics such as geographical position, median income, number of rooms and so on. How can you check in advance whether your model is good in making such predictions?\n\nThe answer is: you set part of your dataset, called *test set*, aside and use it to evaluate the performance of your model only. You train and tune your model using the rest of the dataset – *training set* – and evaluate the performance of the model trained this way on the test set. Since the model doesn't see the test set during training, this perfomance should give you a reasonable estimate of how well it would perform on new data. Traditionally, you split the data into $80\\%$ training and $20\\%$ test set, making sure that the test instances are selected randomly so that you don't end up with some biased selection leading to over-optimistic or over-pessimistic results on your test set.\n\nFor example, you can select your test set as the code below shows. To ensure random selection of the test items, use `np.random.permutation`. However, if you want to ensure that you have a stable test set, and the same test instances get selected from the dataset in a random fashion in different runs of the program, select a random seed, e.g. using `np.random.seed(42)`.\n\n\n```python\nimport numpy as np\nnp.random.seed(42)\n\ndef split_train_test(data, test_ratio): \n shuffled_indices = np.random.permutation(len(data))\n test_set_size = int(len(data) * test_ratio)\n test_indices = shuffled_indices[:test_set_size]\n train_indices = shuffled_indices[test_set_size:]\n return data.iloc[train_indices], data.iloc[test_indices]\n\ntrain_set, test_set = split_train_test(housing, 0.2)\nprint(len(train_set), \"training instances +\", len(test_set), \"test instances\")\n```\n\n 16512 training instances + 4128 test instances\n\n\nNote that `scikit-learn` provides a similar functionality to the code above with its `train_test_split` function. Morevoer, you can pass it several datasets with the same number of rows each, and it will split them into training and test sets on the same indices (you might find it useful if you need to pass in a separate DataFrame with labels):\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\nprint(len(train_set), \"training instances +\", len(test_set), \"test instances\")\n```\n\n 16512 training instances + 4128 test instances\n\n\nSo far, you have been selecting your test set using random sampling methods. If your data is representative of the task at hand, this should help ensure that the results of the model testing are informative. However, if your dataset is not very large and the data is skewed on some of the attributes or on the target label (as is often the case with the real-world data), random sampling might introduce a sampling bias. *Stratified sampling* is a technique that helps make sure that the distributions of the instance attributes or labels in the training and the test sets are similar, meaning that the proportion of instances drawn from each *stratum* in the dataset is similar in the training and test data.\n\nSampling bias may express itself both in the distribution of labels and in the distribution of the attribute values. For instance, take a look at the *median_income* attribute value distribution. Suppose for now (and you might find a confirmation to that later in the practical) that this attribute is predictive of the house price, however its values are unevenly distributed across the range of $[0.4999, 15.0001]$ with a very long tail. If random sampling doesn't select enough instances for each *stratum* (each range of incomes) the estimate of the under-represented strata's importance will be biased. \n\nFirst, to limit the number of income categories (strata), particularly at the long tail, let's apply further binning to the income values: e.g., you can divide the income by $1.5$, round up the values using `ceil` to have discrete categories (bins), and merge all the categories greater than $5$ into category $5$. The latter can be achieved using `Pandas`' `where` functionality, keeping the original values when they are smaller than $5$ and converting them to $5$ otherwise:\n\n\n```python\nhousing[\"income_cat\"] = np.ceil(housing[\"median_income\"] / 1.5)\nhousing[\"income_cat\"].where(housing[\"income_cat\"] < 5, 5.0, inplace = True)\n\nhousing[\"income_cat\"].hist()\nplt.show()\n```\n\nNow you have a much smaller number of categories of income, with the instances more evenly distributed, so you can hope to get enough data to represent the tail. Next, let's split the dataset into training and test sets making sure both contain similar proportion of instances from each income category. You can do that using `scikit-learn`'s `StratifiedShuffleSplit` specifying the condition on which the data should be stratified (in this case, income category):\n\n\n```python\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\nfor train_index, test_index in split.split(housing, housing[\"income_cat\"]):\n strat_train_set = housing.loc[train_index]\n strat_test_set = housing.loc[test_index]\n```\n\nLet's compare the distribution of the income values in the randomly selected train and test sets and the stratified train and test sets against the full dataset. To better understand the effect of random sampling versus stratified sampling, let's also estimate the error that would be introduced in the data by such splits:\n\n\n```python\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\n\ndef income_cat_proportions(data):\n return data[\"income_cat\"].value_counts() / len(data)\n\ncompare_props = pd.DataFrame({\n \"Overall\": income_cat_proportions(housing),\n \"Stratified tr\": income_cat_proportions(strat_train_set),\n \"Random tr\": income_cat_proportions(train_set),\n \"Stratified ts\": income_cat_proportions(strat_test_set),\n \"Random ts\": income_cat_proportions(test_set),\n})\ncompare_props[\"Rand. tr %error\"] = 100 * compare_props[\"Random tr\"] / compare_props[\"Overall\"] - 100\ncompare_props[\"Rand. ts %error\"] = 100 * compare_props[\"Random ts\"] / compare_props[\"Overall\"] - 100\ncompare_props[\"Strat. tr %error\"] = 100 * compare_props[\"Stratified tr\"] / compare_props[\"Overall\"] - 100\ncompare_props[\"Strat. ts %error\"] = 100 * compare_props[\"Stratified ts\"] / compare_props[\"Overall\"] - 100\n\ncompare_props.sort_index()\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 \n \n \n \n \n \n \n \n \n \n \n
OverallStratified trRandom trStratified tsRandom tsRand. tr %errorRand. ts %errorStrat. tr %errorStrat. ts %error
1.00.0398260.0398500.0397290.0397290.040213-0.2433090.9732360.060827-0.243309
2.00.3188470.3188590.3174660.3187980.324370-0.4330651.7322600.003799-0.015195
3.00.3505810.3505940.3485950.3505330.358527-0.5666112.2664460.003455-0.013820
4.00.1763080.1762960.1785370.1763570.1673931.264084-5.056334-0.0068700.027480
5.00.1144380.1144020.1156730.1145830.1094961.079594-4.318374-0.0317530.127011
\n
\n\n\n\nAs you can see, the distributions in the stratified training and test sets are much closer to the original distribution of categories as well as being much closer to each other. \n\nNote, that to help you split the data, you had to introduce a new category – *income_cat* – which contains the same information as the original attribute *median_income* binned in a different way:\n\n\n```python\nstrat_train_set.info()\n```\n\n \n Int64Index: 16512 entries, 17606 to 15775\n Data columns (total 11 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 16512 non-null float64\n 1 latitude 16512 non-null float64\n 2 housing_median_age 16512 non-null float64\n 3 total_rooms 16512 non-null float64\n 4 total_bedrooms 16354 non-null float64\n 5 population 16512 non-null float64\n 6 households 16512 non-null float64\n 7 median_income 16512 non-null float64\n 8 median_house_value 16512 non-null float64\n 9 ocean_proximity 16512 non-null object \n 10 income_cat 16512 non-null float64\n dtypes: float64(10), object(1)\n memory usage: 1.5+ MB\n\n\nBefore proceeding further let's remove the *income_cat* attribute so the data is back to its original state. Here is how you can do that:\n\n\n```python\nfor set_ in (strat_train_set, strat_test_set):\n set_.drop(\"income_cat\", axis=1, inplace=True)\n\nstrat_train_set.info()\n```\n\n \n Int64Index: 16512 entries, 17606 to 15775\n Data columns (total 10 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 16512 non-null float64\n 1 latitude 16512 non-null float64\n 2 housing_median_age 16512 non-null float64\n 3 total_rooms 16512 non-null float64\n 4 total_bedrooms 16354 non-null float64\n 5 population 16512 non-null float64\n 6 households 16512 non-null float64\n 7 median_income 16512 non-null float64\n 8 median_house_value 16512 non-null float64\n 9 ocean_proximity 16512 non-null object \n dtypes: float64(9), object(1)\n memory usage: 1.4+ MB\n\n\n## Step 3: Exploring the attributes\n\nThe next step is to look more closely into the attributes and gain insights into the data. In particular, you should try to answer the following questions: \n- Which attributes look most informative? \n- How do they correlate with each other and the target label?\n- Is any further normalisation or scaling needed?\n\nThe most informative ways in which you can answer the questions above are by *visualising* the data and by *collecting additional statistics* on the attributes and their relations to each other.\n\nFirst, remember that from now on you're only looking into and gaining insights from the training data. You will use the test data at the evaluation step only, thus ensuring no data leakage between the training and test sets occurs and the results on the test set are a fair evaluation of your algorithm's performance. Let's make a copy of the training set that you can experiment with without a danger of overwriting or changing the original data: \n\n\n```python\nhousing = strat_train_set.copy()\n```\n\n### Visualisations\n\nThe first two attributes describe the geographical position of the houses. Let's apply further visualisations and look into the geographical area that is covered: for that, use a scatter plot plotting longitude against latitude coordinates. To make the scatter plot more informative, use `alpha` option to highlight high density points:\n\n\n```python\nhousing.plot(kind='scatter', x='longitude', y='latitude', alpha=0.2)\n```\n\nYou can experiment with `alpha` values to get a better understanding, but it should be obvious from these plots that the areas in the south and along the coast of California are more densely populated (roughly corresponding to the Bay Area, Los Angeles, San Diego, and the Central Valley). \n\nNow, what does geographical position suggest about the housing prices? In the following code, the size of the circles represents the size of the population, and the color represents the price, ranging from blue for low prices to red for high prices (this color scheme is specified by the preselected `cmap` type):\n\n\n```python\nhousing2 = strat_train_set.copy()\n\n```\n\n\n```python\nhousing2[\"ocean_proximity\"].value_counts()\n\n# housing2.loc(\"ocean_proximity\")\n#TODO COME BACK TO THIS \nhousing2[\"ocean_proximity\"].value_counts()\n\n```\n\n\n\n\n <1H OCEAN 7276\n INLAND 5263\n NEAR OCEAN 2124\n NEAR BAY 1847\n ISLAND 2\n Name: ocean_proximity, dtype: int64\n\n\n\n\n```python\nhousing.plot(kind='scatter', x='longitude', y='latitude', alpha=0.5,\n s=housing[\"population\"]/100, label=\"population\", figsize=(10,7), \n c=housing[\"median_house_value\"], cmap=plt.get_cmap(\"jet\"), colorbar=\"True\",\n )\nplt.legend()\n```\n\nThis plot suggests that the housing prices depend on the proximity to the ocean and on the population size. What does this suggest about the informativeness of the attributes for your ML task?\n\n### Correlations\n\nLet's also look into how the attributes correlate with each other:\n\n\n```python\ncorr_matrix = housing.corr()\ncorr_matrix\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 \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
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_value
longitude1.000000-0.924478-0.1058480.0488710.0765980.1080300.063070-0.019583-0.047432
latitude-0.9244781.0000000.005766-0.039184-0.072419-0.115222-0.077647-0.075205-0.142724
housing_median_age-0.1058480.0057661.000000-0.364509-0.325047-0.298710-0.306428-0.1113600.114110
total_rooms0.048871-0.039184-0.3645091.0000000.9293790.8551090.9183920.2000870.135097
total_bedrooms0.076598-0.072419-0.3250470.9293791.0000000.8763200.980170-0.0097400.047689
population0.108030-0.115222-0.2987100.8551090.8763201.0000000.9046370.002380-0.026920
households0.063070-0.077647-0.3064280.9183920.9801700.9046371.0000000.0107810.064506
median_income-0.019583-0.075205-0.1113600.200087-0.0097400.0023800.0107811.0000000.687160
median_house_value-0.047432-0.1427240.1141100.1350970.047689-0.0269200.0645060.6871601.000000
\n
\n\n\n\nSince you are trying to predict the house value, the last column in this table is the most informative. Let's make the output clearer:\n\n\n```python\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n```\n\n\n\n\n median_house_value 1.000000\n median_income 0.687160\n total_rooms 0.135097\n housing_median_age 0.114110\n households 0.064506\n total_bedrooms 0.047689\n population -0.026920\n longitude -0.047432\n latitude -0.142724\n Name: median_house_value, dtype: float64\n\n\n\nThis makes it clear that the *median_income* is most strongly positively correlated with the price. There is small positive correlation of the price with *total_rooms* and *housing_median_age*, and small negative correlation with *latitude*, which suggests that the prices go up with the increase in income, number of rooms and house age, and go down when you go north. `Pandas`' `scatter_matrix` function allows you to visualise the correlation of attributes with each other (note that since the correlation of an attribute with itself will result in a straight line, `Pandas` uses a histogram instead – that's what you see along the diagonal):\n\n\n```python\nfrom pandas.plotting import scatter_matrix\n# If the above returns an error, use the following:\n#from pandas.tools.plotting import scatter_matrix\n\nattributes = [\"median_house_value\", \"median_income\", \"total_rooms\", \"housing_median_age\", \"latitude\"]\nscatter_matrix(housing[attributes], figsize=(12,8))\n```\n\nThese plots confirm that the income attribute is the most promising one for predicting house prices, so let's zoom in on this attribute:\n\n\n```python\nhousing.plot(kind=\"scatter\", x=\"median_income\", y=\"median_house_value\", alpha=0.3)\n```\n\nThere are a couple of observations to be made about this plot:\n- The correlation is indeed quite strong: the values follow the upward trend and are not too dispersed otherwise;\n- You can clearly see a line around $500000$ which covers a full range of income values and is due to the fact that the house prices above that value were capped in the original dataset. However, the plot suggests that there are also some other less obvious groups of values, most visible around $350000$ and $450000$, that also cover a range of different income values. Since your ML algorithm will learn to reproduce such data quirks, you might consider looking into these matters further and removing these districts from your dataset (after all, in any real-world application, one can expect a certain amount of noise in the data and clearing the data is one of the steps in any practical application). \n\nThe next thing to notice is that a number of attributes from the original dataset, including *total_rooms*, \t*total_bedrooms* and *population*, do not actually describe each house in particular but rather represent the cumulative counts for *all households* in the block group. At the same time, the task at hand requires you to predict the house price for *each individual household*. In addition, an attribute that measures the proportion of bedrooms against the total number of rooms might be informative. Therefore, the following transformed attributes might be more useful for the prediction:\n\n\n```python\nhousing[\"rooms_per_household\"] = housing[\"total_rooms\"] / housing[\"households\"]\nhousing[\"bedrooms_per_household\"] = housing[\"total_bedrooms\"] / housing[\"households\"]\nhousing[\"bedrooms_per_rooms\"] = housing[\"total_bedrooms\"] / housing[\"total_rooms\"]\nhousing[\"population_per_household\"] = housing[\"population\"] / housing[\"households\"]\n```\n\nA good way to check whether these transformations have any effect on the task is to check attributes correlations again:\n\n\n```python\ncorr_matrix = housing.corr()\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n```\n\n\n\n\n median_house_value 1.000000\n median_income 0.687160\n rooms_per_household 0.146285\n total_rooms 0.135097\n housing_median_age 0.114110\n households 0.064506\n total_bedrooms 0.047689\n population_per_household -0.021985\n population -0.026920\n bedrooms_per_household -0.043343\n longitude -0.047432\n latitude -0.142724\n bedrooms_per_rooms -0.259984\n Name: median_house_value, dtype: float64\n\n\n\nYou can see that the number of rooms per household is more strongly correlated with the house price – the more rooms the more expensive the house, while the proportion of bedrooms is more strongly correlated with the price than either the number of rooms or bedrooms in the household – since the correlation is negative, the lower the bedroom-to-room ratio, the more expensive the property.\n\n## Step 4: Data preparation and transformations for machine learning algorithms\n\nNow you are almost ready to implement a regression algorithm for the task at hand. However, there are a couple of other things to address, in particular:\n- handle missing values if there are any;\n- convert all attribute values (e.g. categorical, textual) into numerical format;\n- scale / normalise the feature values if necessary.\n\nFirst, let's separate the labels you're trying to predict (*median_house_value*) from the attributes in the dataset that you will use as *features*. The following code will keep a copy of the labels and the rest of the attributes separate (note that `drop()` will create a copy of the data and will not affect `strat_train_set` itself): \n\n\n```python\nhousing = strat_train_set.drop(\"median_house_value\", axis=1) #drop makes a copy!\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n```\n\nYou can add the transformed features that you found useful before with the additional function as shown below. Then you can run `add_features(housing)` to add the features:\n\n\n```python\ndef add_features(data):\n # add the transformed features that you found useful before\n data[\"rooms_per_household\"] = data[\"total_rooms\"] / data[\"households\"]\n data[\"bedrooms_per_household\"] = data[\"total_bedrooms\"] / data[\"households\"]\n data[\"bedrooms_per_rooms\"] = data[\"total_bedrooms\"] / data[\"total_rooms\"]\n data[\"population_per_household\"] = data[\"population\"] / data[\"households\"]\n \n# add_features(housing)\n```\n\nYou will learn shortly about how to implement your own *data transformers* and will be able to re-implement addition of these features as a data transfomer.\n\n### Handling missing values\n\nIn Step 1 above, when you took a quick look into the dataset, you might have noticed that all attributes but one have $20640$ values in the dataset; *total_bedrooms* has $20433$, so some values are missing. ML algorithms cannot deal with missing values, so you'll need to decide how to replace these values. There are three possible solutions:\n\n1. remove the corresponding housing blocks from the dataset (i.e., remove the rows in the dataset)\n2. remove the whole attribute (i.e., remove the column)\n3. set the missing values to some predefined value (e.g., zero value, the mean, the median, the most frequent value of the attribute, etc.)\n\nThe following `Pandas` functionality will help you implement each of these options:\n\n\n```python\nhousing\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 \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 \n \n \n \n \n \n \n \n \n
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomeocean_proximity
17606-121.8937.2938.01568.0351.0710.0339.02.7042<1H OCEAN
18632-121.9337.0514.0679.0108.0306.0113.06.4214<1H OCEAN
14650-117.2032.7731.01952.0471.0936.0462.02.8621NEAR OCEAN
3230-119.6136.3125.01847.0371.01460.0353.01.8839INLAND
3555-118.5934.2317.06592.01525.04459.01463.03.0347<1H OCEAN
..............................
6563-118.1334.2046.01271.0236.0573.0210.04.9312INLAND
12053-117.5633.8840.01196.0294.01052.0258.02.0682INLAND
13908-116.4034.099.04855.0872.02098.0765.03.2723INLAND
11159-118.0133.8231.01960.0380.01356.0356.04.0625<1H OCEAN
15775-122.4537.7752.03095.0682.01269.0639.03.5750NEAR BAY
\n

16512 rows × 9 columns

\n
\n\n\n\n\n```python\n## option 1:\nhousing.dropna(subset=[\"total_bedrooms\"])\n## option 2:\n# housing.drop(\"total_bedrooms\", axis=1)\n# option 3:\n# median = housing[\"total_bedrooms\"].median()\n# housing[\"total_bedrooms\"].fillna(median, inplace=True)\nhousing\n\n\n# I would have chossen to repalce over droping them!\n# I think replacing will cause more harm than use.?\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 \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 \n \n \n \n \n \n \n \n \n
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomeocean_proximity
17606-121.8937.2938.01568.0351.0710.0339.02.7042<1H OCEAN
18632-121.9337.0514.0679.0108.0306.0113.06.4214<1H OCEAN
14650-117.2032.7731.01952.0471.0936.0462.02.8621NEAR OCEAN
3230-119.6136.3125.01847.0371.01460.0353.01.8839INLAND
3555-118.5934.2317.06592.01525.04459.01463.03.0347<1H OCEAN
..............................
6563-118.1334.2046.01271.0236.0573.0210.04.9312INLAND
12053-117.5633.8840.01196.0294.01052.0258.02.0682INLAND
13908-116.4034.099.04855.0872.02098.0765.03.2723INLAND
11159-118.0133.8231.01960.0380.01356.0356.04.0625<1H OCEAN
15775-122.4537.7752.03095.0682.01269.0639.03.5750NEAR BAY
\n

16512 rows × 9 columns

\n
\n\n\n\nAlthough, all three options are possible, keep in mind that in the first two cases you are throwing away either some valuable attributes (e.g., as you've seen earlier, *bedrooms_per_rooms* correlates well with the label you're trying to predict) or a number of valuable training examples. Option 3, therefore, looks more promising. Note, that for that you estimate a mean or median based on the training set only (as, in general, your ML algorithm has access to the training data only during the training phase), and then store the mean / median values to replace the missing values in the test set (or any new dataset, to that effect). In addition, you might want to calculate and store the mean / median values for all attributes as in a real-life application you can never be sure if any of the attributes will have missing values in the future.\n\nHere is how you can calculate and store median values using `sklearn` (note that you'll need to exclude `ocean_proximity` attribute from this calculation since it has non-numerical values):\n\n\n```python\n# for earlier versions of sklearn use:\n#from sklearn.preprocessing import Imputer \n#imputer = Imputer(strategy=\"median\")\n\nfrom sklearn.impute import SimpleImputer\n\nimputer = SimpleImputer(strategy=\"median\")\nhousing_num = housing.drop(\"ocean_proximity\", axis=1)\nimputer.fit(housing_num)\n```\n\n\n\n\n SimpleImputer(add_indicator=False, copy=True, fill_value=None,\n missing_values=nan, strategy='median', verbose=0)\n\n\n\nYou can check the median values stored in the `imputer` as follows:\n\n\n```python\nimputer.statistics_\n```\n\n\n\n\n array([-1.1849e+02, 3.4260e+01, 2.9000e+01, 2.1270e+03, 4.3500e+02,\n 1.1660e+03, 4.0900e+02, 3.5348e+00, 1.7970e+05])\n\n\n\nand also make sure that they exactly coincide with the median values for all numerical attributes:\n\n\n```python\nhousing_num.median().values\n```\n\n\n\n\n array([-1.1849e+02, 3.4260e+01, 2.9000e+01, 2.1270e+03, 4.3500e+02,\n 1.1660e+03, 4.0900e+02, 3.5348e+00, 1.7970e+05])\n\n\n\nFinally, let's replace the missing values in the training data:\n\n**WHAT does this do!!!**\n\n\n```python\nX = imputer.transform(housing_num)\nhousing_tr = pd.DataFrame(X, columns=housing_num.columns)\nhousing_tr.info()\n```\n\n \n RangeIndex: 20640 entries, 0 to 20639\n Data columns (total 9 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 20640 non-null float64\n 1 latitude 20640 non-null float64\n 2 housing_median_age 20640 non-null float64\n 3 total_rooms 20640 non-null float64\n 4 total_bedrooms 20640 non-null float64\n 5 population 20640 non-null float64\n 6 households 20640 non-null float64\n 7 median_income 20640 non-null float64\n 8 median_house_value 20640 non-null float64\n dtypes: float64(9)\n memory usage: 1.4 MB\n\n\n### Handling textual and categorical attributes\n\nAnother aspect of the dataset that should be handled is the textual / categorical values of the *ocean_proximity* attribute. ML algorithms prefer working with numerical data, so let's use `sklearn`'s functionality and cast the categorical values as numerical values as follows:\n\n\n```python\nfrom sklearn.preprocessing import LabelEncoder\n\nencoder = LabelEncoder()\nhousing_cat_encoded = encoder.fit_transform(housing[\"ocean_proximity\"])\nhousing_cat_encoded\n```\n\n\n\n\n array([3, 3, 3, ..., 1, 1, 1])\n\n\n\nThe code above mapped the categories to numerical values. You can check what the numerical values correspond to in the original data using:\n\n\n```python\nencoder.classes_\n```\n\n\n\n\n array(['<1H OCEAN', 'INLAND', 'ISLAND', 'NEAR BAY', 'NEAR OCEAN'],\n dtype=object)\n\n\n\nOne problem with the encoding above is that the ML algorithm will automatically assume that the numerical values that are close to each other encode similar concepts, which for this data is not quite true: for example, value $0$ corresponding to *$<$1H OCEAN* category is actually most similar to values $3$ and $4$ (*NEAR BAY* and *NEAR OCEAN*) and not to value $1$ (*INLAND*).\n\nAn alternative to this encoding is called *one-hot encoding* and it runs as follows: for each category, it creates a separate binary attribute which is set to $1$ (hot) when the category coincides with the attribute, and $0$ (cold) otherwise. So, for instance, *$<$1H OCEAN* will be encoded as a one-hot vector $[1, 0, 0, 0, 0]$ and *NEAR OCEAN* will be encoded as $[0, 0, 0, 0, 1]$. The following `sklearn`'s functionality allows to convert categorical values into one-hot vectors:\n\n\n```python\nfrom sklearn.preprocessing import OneHotEncoder\n\nencoder = OneHotEncoder()\n# fit_transform expects a 2D array, but housing_cat_encoded is a 1D array.\n# Reshape it using NumPy's reshape functionality where -1 simply means \"unspecified\" dimension \nhousing_cat_1hot = encoder.fit_transform(housing_cat_encoded.reshape(-1,1))\nhousing_cat_1hot\n```\n\n\n\n\n <20640x5 sparse matrix of type ''\n \twith 20640 stored elements in Compressed Sparse Row format>\n\n\n\nNote that the data format above says that the output is a sparse matrix. This means that the data structure only stores the location of the non-zero elements, rather than the full set of vectors which are mostly full of zeros. You can check the [documentation on sparse matrices](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html) if you'd like to learn more. If you'd like to see how the encoding looks like you can also convert it back into a dense NumPy array using:\n\n\n```python\nhousing_cat_1hot.toarray()\n```\n\n\n\n\n array([[0., 0., 0., 1., 0.],\n [0., 0., 0., 1., 0.],\n [0., 0., 0., 1., 0.],\n ...,\n [0., 1., 0., 0., 0.],\n [0., 1., 0., 0., 0.],\n [0., 1., 0., 0., 0.]])\n\n\n\nThe steps above, including casting text categories to numerical categories and then converting them into 1-hot vectors, can be performed using `sklearn`'s `LabelBinarizer`:\n\n\n```python\nfrom sklearn.preprocessing import LabelBinarizer\n\nencoder = LabelBinarizer()\nhousing_cat_1hot = encoder.fit_transform(housing[\"ocean_proximity\"])\nhousing_cat_1hot\n```\n\n\n\n\n array([[0, 0, 0, 1, 0],\n [0, 0, 0, 1, 0],\n [0, 0, 0, 1, 0],\n ...,\n [0, 1, 0, 0, 0],\n [0, 1, 0, 0, 0],\n [0, 1, 0, 0, 0]])\n\n\n\nThe above produces dense array as an output, so if you'd like to have a sparse matrix instead you can specify it in the `LabelBinarizer` constructor:\n\n\n```python\nencoder = LabelBinarizer(sparse_output=True)\nhousing_cat_1hot = encoder.fit_transform(housing[\"ocean_proximity\"])\nhousing_cat_1hot\n```\n\n\n\n\n <20640x5 sparse matrix of type ''\n \twith 20640 stored elements in Compressed Sparse Row format>\n\n\n\n### Data transformers\n\nA useful functionality of `sklearn` is [data transformers](http://scikit-learn.org/stable/data_transforms.html): you will see them used in preprocessing very often. For example, you have just used one to impute the missing values. In addition, you can implement your own custom data transformers. In general, a transformer class needs to implement three methods:\n- a constructor method;\n- a `fit` method that learns parameters (e.g. mean and standard deviation for a normalization transformer) or returns `self`; and\n- a `transform` method that applies the learned transformation to the new data.\n\nWhenever you see `fit_transform` method, it means that the method uses an optimised combination of `fit` and `transform`. Here is how you can implement a data transformer that will convert categorical values into 1-hot vectors:\n\n\n```python\nfrom sklearn.base import TransformerMixin # TransformerMixin allows you to use fit_transform method\n\nclass CustomLabelBinarizer(TransformerMixin):\n def __init__(self, *args, **kwargs):\n self.encoder = LabelBinarizer(*args, **kwargs)\n def fit(self, X, y=0):\n self.encoder.fit(X)\n return self\n def transform(self, X, y=0):\n return self.encoder.transform(X)\n```\n\nSimilarly, here is how you can wrap up adding new transformed features like bedroom-to-room ratio with a data transformer:\n\n\n```python\nfrom sklearn.base import BaseEstimator, TransformerMixin \n# BaseEstimator allows you to drop *args and **kwargs from you constructor\n# and, in addition, allows you to use methods set_params() and get_params()\n\nrooms_id, bedrooms_id, population_id, household_id = 3, 4, 5, 6\n\nclass CombinedAttributesAdder(BaseEstimator, TransformerMixin):\n def __init__(self, add_bedrooms_per_rooms = True): # note no *args and **kwargs used this time\n self.add_bedrooms_per_rooms = add_bedrooms_per_rooms\n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n rooms_per_household = X[:, rooms_id] / X[:, household_id]\n bedrooms_per_household = X[:, bedrooms_id] / X[:, household_id]\n population_per_household = X[:, population_id] / X[:, household_id]\n if self.add_bedrooms_per_rooms:\n bedrooms_per_rooms = X[:, bedrooms_id] / X[:, rooms_id]\n return np.c_[X, rooms_per_household, bedrooms_per_household, \n population_per_household, bedrooms_per_rooms]\n else:\n return np.c_[X, rooms_per_household, bedrooms_per_household, \n population_per_household]\n \nattr_adder = CombinedAttributesAdder()\nhousing_extra_attribs = attr_adder.transform(housing.values)\n# print(housing_extra_attribs.info)\n```\n\nIf you'd like to explore the new attributes, you can convert the `housing_extra_attribs` into a `Pandas` DataFrame and apply the functionality as before:\n\n\n```python\nhousing_extra_attribs = pd.DataFrame(housing_extra_attribs, columns=list(housing.columns)+\n [\"rooms_per_household\", \"bedrooms_per_household\", \n \"population_per_household\", \"bedrooms_per_rooms\"])\nprint(housing.info)\n\nhousing_extra_attribs.info()\n\n```\n\n \n \n RangeIndex: 16512 entries, 0 to 16511\n Data columns (total 13 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 16512 non-null object\n 1 latitude 16512 non-null object\n 2 housing_median_age 16512 non-null object\n 3 total_rooms 16512 non-null object\n 4 total_bedrooms 16512 non-null object\n 5 population 16512 non-null object\n 6 households 16512 non-null object\n 7 median_income 16512 non-null object\n 8 ocean_proximity 16512 non-null object\n 9 rooms_per_household 16512 non-null object\n 10 bedrooms_per_household 16512 non-null object\n 11 population_per_household 16512 non-null object\n 12 bedrooms_per_rooms 16512 non-null object\n dtypes: object(13)\n memory usage: 1.6+ MB\n\n\n\n```python\nhousing_extra_attribs.info()\n```\n\n### Feature scaling\n\nFinally, ML algorithms do not typically perform well when the feature values cover significantly different ranges of values. For example, in the dataset at hand, the income ranges from $0.4999$ to $15.0001$, while population ranges from $3$ to $35682$. Taken at the same scale, these values are not directly comparable. The data transformation that should be applied to these values is called *feature scaling*.\n\nOne of the most common ways to scale the data is to apply *min-max scaling* (also often referred to as *normalisaton*). Min-max scaling puts all values on the scale of $[0, 1]$ making the ranges directly comparable. For that, you need to subtract the min from the actual value and divide by the difference between the maximum and minimum values, i.e.:\n\n\\begin{equation}\nf_{scaled} = \\frac{f - F_{min}}{F_{max} - F_{min}}\n\\end{equation}\n\nwhere $f \\in F$ is the actual feature value of a feature type $F$, and $F_{min}$ and $F_{max}$ are the minumum and maximum values for the feature of type $F$.\n\nAnother common approach is *standardisation*, which subtracts the mean value (so the standardised values have a zero mean) and divides by the variance (so the standardised values have unit variance). Standardisation does not impose a specific range on the values and is more robust to the outliers: i.e., a noisy input or an incorrect income value of $100$ (when the rest of the values lie within the range of $[0.4999, 15.0001]$) will introduce a significant skew in the data after min-max scaling. At the same time, standardisation does not bind values to the same range of $[0, 1]$, which might be problematic for some algorithms.\n\n`Scikit-learn` has an implementation for the `MinMaxScaler`, `StandardScaler`, as well as [other scaling approaches](http://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler), i.e.:\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\n\nscaler = StandardScaler()\nhousing_tr_scaled = scaler.fit_transform(housing_tr)\n```\n\n### Putting all the data transformations together\n\nAnother useful functionality of `sklearn` is pipelines. These allow you to stack several separate transformations together. For example, you can apply the numerical transformations such as missing values handling and data scaling as follows:\n\n\n```python\nfrom sklearn.pipeline import Pipeline\n\nnum_pipeline = Pipeline([\n #('imputer', Imputer(strategy=\"median\")),\n ('imputer', SimpleImputer(strategy=\"median\")),\n ('std_scaler', StandardScaler()),\n])\n\nhousing_num_tr = num_pipeline.fit_transform(housing_num)\nhousing_num_tr.shape\n```\n\nPipelines are useful because they help combining several steps together, so that the output of one data transformer (e.g., `Imputer`) is passed on as an input to the next one (e.g., `StandardScaler`) and so you don't need to worry about the intermediate steps. Besides, it makes the code look more concise and readable. However:\n- the code above doesn't handle categorical values;\n- we started with `Pandas` DataFrames because they are useful for data uploading and inspection, but the `Pipeline` expects `NumPy` arrays as input, and at the moment, `sklearn`'s `Pipeline` cannot handle `Pandas` DataFrames.\n\nIn fact, there is a way around the two issues above. Let's implement another custom data transformer that will allow you to select specific attributes from a `Pandas` DataFrame:\n\n\n```python\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n# Create a class to select numerical or categorical columns \n# since Scikit-Learn doesn't handle DataFrames yet\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attribute_names):\n self.attribute_names = attribute_names\n def fit(self, X, y=None):\n return self\n def transform(self, X):\n return X[self.attribute_names].values\n```\n\nThe transformer above allows you to select a predefined set of attributes from a DataFrame, dropping the rest and converting the selected ones into a `NumPy` array. This is quite useful because now you can select the numerical attributes and apply one set of transformations to them, and then select categorical attributes and apply another set of transformation to them, i.e.:\n\n\n```python\nnum_attribs = list(housing_num)\ncat_attribs = [\"ocean_proximity\"]\n\nnum_pipeline = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n #('imputer', Imputer(strategy=\"median\")),\n ('imputer', SimpleImputer(strategy=\"median\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', StandardScaler()),\n ])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', CustomLabelBinarizer()),\n ])\n```\n\nFinally, to merge the output of the two separate data transformers back together, you can use `sklearn`'s `FeatureUnion` functionality: it runs the two pipelines' `fit` methods and the two `transform` methods in parallel, and then concatenates the output. I.e.:\n\n\n```python\nfrom sklearn.pipeline import FeatureUnion\n\nfull_pipeline = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\n\nhousing = strat_train_set.drop(\"median_house_value\", axis=1)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\nhousing_prepared = full_pipeline.fit_transform(housing)\nprint(housing_prepared.shape)\nhousing_prepared\n```\n\n## Step 5: Implementation, evaluation and fine-tuning of a regression model\n\nNow that you've explored and prepared the data, you can implement a regression model to predict the house prices on the test set. \n\n### Training and evaluating the model\n\nLet's train a [Linear Regression](http://scikit-learn.org/stable/modules/linear_model.html) model first. During training, a Linear Regression model tries to find the optimal set of weights $w=(w_{1}, w_{2}, ..., w_{n})$ for the features (attributes) $X=(x_{1}, x_{2}, ..., x_{n})$ by minimising the residual sum of squares between the responses predicted by such linear approximation $Xw$ and the observed responses $y$ in the dataset, i.e. trying to solve:\n\n\\begin{equation}\nmin_{w} ||Xw - y||_{2}^{2}\n\\end{equation}\n\n\n```python\nfrom sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(housing_prepared, housing_labels)\n```\n\nFirst, let's try the model on some instances from the training set itself:\n\n\n```python\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\n# note the use of transform, as you'd like to apply already learned (fitted) transformations to the data\nsome_data_prepared = full_pipeline.transform(some_data)\n\nprint(\"Predictions:\", list(lin_reg.predict(some_data_prepared)))\nprint(\"Actual labels:\", list(some_labels))\n```\n\nThe above shows that the model is able to predict some price values, however they don't seem to be very accurate. How can you measure the performance of your model in a more comprehensive way?\n\nTypically, the output of the regression model is measured in terms of the error in prediction. There are two error measures that are commonly used. *Root Mean Square Error (RMSE)* measures the average deviation of the model's prediction from the actual label, but note that it gives a higher weight for large errors:\n\n\\begin{equation}\nRMSE(X, h) = \\sqrt{\\frac{1}{m} \\sum_{i=1}^{m} (h(x^{(i)}) - y^{(i)})^{2}}\n\\end{equation}\n\nwhere $m$ is the number of instances, $h$ is the model (hypothesis), $X$ is the matrix containing all feature values, $x^{(i)}$ is the feature vector describing instance $i$, and $y^{(i)}$ is the actual label for instance $i$.\n\nBecause *RMSE* is highly influenced by the outliers (i.e., large errors), in some situations *Mean Absolute Error (MAE)* is preferred. You may note that its estimation is somewhat similar to the estimation of *RMSE*:\n\n\\begin{equation}\nMAE(X, h) = \\frac{1}{m} \\sum_{i=1}^{m} |h(x^{(i)}) - y^{(i)}|\n\\end{equation}\n\nLet's measure the performance of the linear regression model using these error estimations:\n\n\n```python\nfrom sklearn.metrics import mean_squared_error\n\nhousing_predictions = lin_reg.predict(housing_prepared)\nlin_mse = mean_squared_error(housing_labels, housing_predictions)\nlin_rmse = np.sqrt(lin_mse)\nlin_rmse\n```\n\nGiven that the majority of the districts' housing values lie somewhere between $[\\$100000, \\$300000]$ an estimation error of over \\\\$68000 is very high. This shows that the regression model *underfits* the training data: it doesn't capture the patterns in the training data well enough because it lacks the descriptive power either due to the features not providing enough information to make a good prediction or due to the model itself being not complex enough. The ways to fix this include:\n- using more features and/or more informative features, for example applying log to some of the existing features to address the long tail distributions;\n- using more complex models;\n- reducing the constraints on the model.\n\nThe model that you used above is not constrained (or, *regularised* – more on this in later lectures), so you should try using more powerful models or work on the feature set.\n\nFor example, *polynomial regression* models the relationship between the $X$ and $y$ as an $n$-th degree polynomial. Polynomial regression extends simple linear regression by constructing polynomial features from the existing ones. For simplicity, assume that your data has only $2$ features rather than $8$, i.e. $X=[x_{1}, x_{2}]$. The linear regression model above tries to learn the coefficients (weights) $w=[w_{0}, w_{1}, w_{3}]$ for the linear prediction (a plane) $\\hat{y} = w_{0} + w_{1}x_{1} + w_{2}x_{2}$ that minimises the residual sum of squares between the prediction and actual label as you've seen above. \n\nIf you want to fit a paraboloid to the data instead of a plane, you can combine the features in second-order polynomials, so that the model looks like this: \n\n\\begin{equation}\n\\hat{y} = w_{0} + w_{1}x_{1} + w_{2}x_{2} + w_{3}x_{1}x_{2} + w_{4}x_{1}^2 + w_{5}x_{2}^2\n\\end{equation}\n\nThis time, the model tries to learn an optimal set of weights $w=[w_{0}, ..., w_{5}]$ (note that $w_{0}$ is called an intercept).\n\nNote that polynomial regression still employs a linear model. For instance, you can define a new variable $z = [x_1, x_2, x_1x_2, x_1^2, x_2^2]$ and rewrite the polynomial above as:\n\n\\begin{equation}\n\\hat{y} = w_{0} + w_{1}z_{0} + w_{2}z_{1} + w_{3}z_{2} + w_{4}z_{3} + w_{5}z_{4}\n\\end{equation}\n\nFor that reason, the polynomial regression in `sklearn` is addressed at the `preprocessing` steps – that is, first the second-order polynomials are estimated on the features, and then the same `LinearRegression` model as above is applied. For instance, use a second- and third-order polynomials and compare the results (feel free to use higher order polynomials, though keep in mind that as the complexity of the model increases, so does the processing time, the number of weights to be learned, and the chance that the model *overfits* to the training data). For more information, refer to `sklearn` [documentation](http://scikit-learn.org/stable/auto_examples/linear_model/plot_polynomial_interpolation.html):\n\n\n```python\nfrom sklearn.preprocessing import PolynomialFeatures\n\nmodel = Pipeline([('poly', PolynomialFeatures(degree=3)),\n ('linear', LinearRegression())])\n\nmodel = model.fit(housing_prepared, housing_labels)\nhousing_predictions = model.predict(housing_prepared)\nlin_mse = mean_squared_error(housing_labels, housing_predictions)\nlin_rmse = np.sqrt(lin_mse)\nlin_rmse\n```\n\nHow does the performance of the polynomial regression model compare to the first-order linear regression? You see that the performance improves as the complexity of the feature space increases. However, note that the more complex the model becomes, the more accurately it learns to replicate the training data, and the less likely it will generalise to the new pattern, i.e. in the test data. This phenomenon of learning to replicate the patterns from the training data too closely is called *overfitting*, and it is an opposite of *underfitting* when the model does not learn enough about the pattern from the training data due to its simplicity.\n\nJust to give you a flavor of the problem, here is an example of a complex model from the `sklearn` suite called `DecisionTreeRegressor` (Decision Trees are outside of the scope of this course, so don't worry if this looks unfamiliar to you. `sklearn` has implementation for a wide range of ML algorithms, so do check the [documentation](http://scikit-learn.org/stable/auto_examples/tree/plot_tree_regression.html) if you want to learn more). Note that the `DecisionTreeRegressor` learns to predict the values in the training data perfectly well (resulting in the error of $0$!) which usually means that it won't work well on the new data – e.g., check this later on the test data:\n\n\n```python\nfrom sklearn.tree import DecisionTreeRegressor\n\ntree_reg = DecisionTreeRegressor()\ntree_reg = tree_reg.fit(housing_prepared, housing_labels)\nhousing_predictions = tree_reg.predict(housing_prepared)\ntree_mse = mean_squared_error(housing_labels, housing_predictions)\ntree_mse = np.sqrt(tree_mse)\ntree_mse\n```\n\n### Learning to better evaluate you model using cross-validation\n\nObviously, one of the problems with overfitting above is caused by the fact that you're training and testing on the same (training) set (remember, that you should do all model tuning and optimisation on the training data, and only then apply the best model to the test data). So how can you measure the level of overfitting *before* you apply this model to the test data?\n\nThere are two possible solutions. You can either reapply `train_test_split` function from Step 2 to set aside part of the training set as a *development* (or *validation*) set, and then train the model on the smaller training set and tune it on the development set, before applying your best model to the test set. Or you can use *cross-validation*.\n\nWith *K-fold cross-validation* strategy, the training data gets randomly split into $k$ distinct subsets (*splits*). Then the model gets trained $10$ times, in each run being tested on a different fold and trained on the other $9$ folds. That way, the algorithm is evaluated on each data point in the training set, but during training is not exposed to the data points that it gets tested on later. The result is an array of $10$ evaluation scores, which can be averaged for better understanding and model comparison, i.e.:\n\n\n```python\nfrom sklearn.model_selection import cross_val_score\n \ndef analyse_cv(model): \n scores = cross_val_score(model, housing_prepared, housing_labels,\n scoring = \"neg_mean_squared_error\", cv=10)\n\n # cross-validation expects utility function (greater is better)\n # rather than cost function (lower is better), so the scores returned\n # are negative as they are the opposite of MSE\n sqrt_scores = np.sqrt(-scores) \n print(\"Scores:\", sqrt_scores)\n print(\"Mean:\", sqrt_scores.mean())\n print(\"Standard deviation:\", sqrt_scores.std())\n \nanalyse_cv(tree_reg)\n```\n\nThis shows that the `DecisionTreeRegression` model does not actually perform well when tested on a set different from the one it was trained on. What about the other models? E.g.:\n\n\n```python\nanalyse_cv(lin_reg)\n```\n\nLet's try one more model – [`RandomForestRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) that implements many Decision Trees (similar to above) on random subsets of the features. This type of models are called *ensemble learning* models and they are very powerful because they benefit from combining the decisions of multiple algorithms:\n\n\n```python\nfrom sklearn.ensemble import RandomForestRegressor\n\nforest_reg = RandomForestRegressor()\nanalyse_cv(forest_reg)\n```\n\n### Fine-tuning the model\n\nSome learning algorithms have *hyperparameters* – the parameters of the algorithms that should be set up prior to training and don't get changed during training. Such hyperparameters are usually specified for the `sklearn` algorithms in brackets, so you can always check the list of parameters specified in the documentation. For example, whether the [`LinearRegression`](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model should calculate the intercept or not should be set prior to training and does not depend on the training itself, and so does the number of helper algorithms (decision trees) that should be combined in a [`RandomForestRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) for the final prediction. `RandomForestRegressor` has $16$ parameters, so if you want to find the *best* setting of the hyperparametes for `RandomForestRegressor`, it will take you a long time to try out all possible combinations.\n\nThe code below shows you how the best hyperparameter setting can be automatically found for an `sklearn` ML algorithm using a `GridSearch` functionality. Let's use the example of `RandomForestRegressor` and focus on specific hyperparameters: the number of helper algorithms (decision trees in the forest, or `n_estimators`) and the number of features the regressor considers in order to find the most informative subsets of instances to each of the helper algorithms (`max_features`):\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\n\n# specify the range of hyperparameter values for the grid search to try out \nparam_grid = {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]}\n\nforest_reg = RandomForestRegressor()\ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5,\n scoring=\"neg_mean_squared_error\")\ngrid_search.fit(housing_prepared, housing_labels)\n\ngrid_search.best_params_\n```\n\nYou can also monitor the intermediate results as shown below. Note also that if the best results are achieved with the maximum value for each of the parameters specified for exploration, you might want to keep experimenting with even higher values to see if the results improve any further:\n\n\n```python\ncv_results = grid_search.cv_results_\nfor mean_score, params in zip(cv_results[\"mean_test_score\"], cv_results[\"params\"]):\n print(np.sqrt(-mean_score), params)\n```\n\nOne more insight you can gain from the best estimator is the importance of each feature (expressed in the weight the best estimator learned to assign to each of the features). Here is how you can do that:\n\n\n```python\nfeature_importances = grid_search.best_estimator_.feature_importances_\nfeature_importances\n```\n\nIf you also want to display the feature names, you can do that as follows:\n\n\n```python\nextra_attribs = ['rooms_per_household', 'bedrooms_per_household', 'population_per_household', 'bedrooms_per_rooms']\ncat_one_hot_attribs = ['<1H OCEAN', 'INLAND', 'ISLAND', 'NEAR BAY', 'NEAR OCEAN']\nattributes = num_attribs + extra_attribs + cat_one_hot_attribs\nsorted(zip(feature_importances, attributes), reverse=True)\n```\n\nHow do these compare with the insights you gained earlier (e.g., during data exploration in Step 1, or during attribute exporation in Step 3)?\n\n\n### At last, evaluating your best model on the test set!\n\nFinally, let's take the best model you built and tuned on the training set and apply in to the test set:\n\n\n```python\nfinal_model = grid_search.best_estimator_\n\nX_test = strat_test_set.drop(\"median_house_value\", axis=1)\ny_test = strat_test_set[\"median_house_value\"].copy()\n\nX_test_prepared = full_pipeline.transform(X_test)\nfinal_predictions = final_model.predict(X_test_prepared)\n\nfinal_mse = mean_squared_error(y_test, final_predictions)\nfinal_rmse = np.sqrt(final_mse)\n\nfinal_rmse\n```\n\n# Assignments\n\n**For the tick session**:\n\n\n**It seems to be very slow to run the RandomForestRegressor. How can I speed this up?**\n## 1. \nFamiliarise yourself with the code in this practical. During the tick session, be prepared to discuss the different steps and answer questions (as well as ask questions yourself).\n\n## 2.\nExperiment with the different steps in the ML pipeline:\n- try dropping less informative features from the feature set and test whether it improves performance\n- use other options in preprocessing: e.g., different imputer strategies, min-max rather than standardisation for scaling, feature scaling vs. no feature scaling, and compare the results\n- evaluate the performance of the simple linear regression model on the test set. What is the `final_rmse` for this model?\n- estimate different feature importance weights with the simple linear regression model (if unsure how to extract the feature weights, check [documentation](http://scikit-learn.org/stable/modules/linear_model.html)). How do these compare to the (1) feature importance weights with the best estimator, and (2) feature correlation scores with the target value from Step 3?\n- [`RandomizedSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html), as opposed to the `GridSearchCV` used in the practical, does not try out each parameter values combination. Instead it only tries a fixed number of parameter settings sampled from the specified distributions. As a result, it allows you to try out a wider range of parameter values in a less expensive way than `GridSearchCV`. Apply `RandomizedSearchCV` and compare the best estimator results.\n\nFinally, if you want to have more practice with regression tasks, you can **work on the following optional task**:\n\n## 3. (Optional)\n\nUse the bike sharing dataset (`./bike_sharing/bike_hour.csv`, check `./bike_sharing/Readme.txt` for the description), apply the ML steps and gain insights from the data. What data transformations should be applied? Which attributes are most predictive? What additional attributes can be introduced? Which regression model performs best?\n\nWith dropping the na values I got 48120.666286373504 as the final value and some how get the same 48120.666286373504 for replacing with median?\n\n\n```python\nimport pandas as pd\nimport os\n\ndef load_data(housing_path):\n csv_path = os.path.join(housing_path, \"housing.csv\")\n return pd.read_csv(csv_path)\nhousing = load_data(\"housing/\") #pandas\n```\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\nprint(len(train_set), \"training instances +\", len(test_set), \"test instances\")\n\n#splitting\n```\n\n 13209 training instances + 3303 test instances\n\n\n\n```python\nhousing = strat_train_set.copy()\n```\n\n\n```python\ncorr_matrix = housing.corr()\ncorr_matrix\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 \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
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_value
longitude1.000000-0.924478-0.1058480.0488710.0765980.1080300.063070-0.019583-0.047432
latitude-0.9244781.0000000.005766-0.039184-0.072419-0.115222-0.077647-0.075205-0.142724
housing_median_age-0.1058480.0057661.000000-0.364509-0.325047-0.298710-0.306428-0.1113600.114110
total_rooms0.048871-0.039184-0.3645091.0000000.9293790.8551090.9183920.2000870.135097
total_bedrooms0.076598-0.072419-0.3250470.9293791.0000000.8763200.980170-0.0097400.047689
population0.108030-0.115222-0.2987100.8551090.8763201.0000000.9046370.002380-0.026920
households0.063070-0.077647-0.3064280.9183920.9801700.9046371.0000000.0107810.064506
median_income-0.019583-0.075205-0.1113600.200087-0.0097400.0023800.0107811.0000000.687160
median_house_value-0.047432-0.1427240.1141100.1350970.047689-0.0269200.0645060.6871601.000000
\n
\n\n\n\n\n```python\nhousing = strat_train_set.drop(\"median_house_value\", axis=1) #drop makes a copy!\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n```\n\n\n```python\nfrom sklearn.impute import SimpleImputer\n\nimputer = SimpleImputer(strategy=\"median\")\nhousing_num = housing.drop(\"ocean_proximity\", axis=1)\nimputer.fit(housing_num)\n```\n\n\n\n\n SimpleImputer(add_indicator=False, copy=True, fill_value=None,\n missing_values=nan, strategy='median', verbose=0)\n\n\n\n\n```python\nX = imputer.transform(housing_num)\nhousing_tr = pd.DataFrame(X, columns=housing_num.columns)\n# housing_tr.info()\n```\n\n\n```python\nfrom sklearn.preprocessing import LabelBinarizer\n\nencoder = LabelBinarizer(sparse_output=True)\nhousing_cat_1hot = encoder.fit_transform(housing[\"ocean_proximity\"])\nhousing_cat_1hot\n```\n\n\n\n\n <16512x5 sparse matrix of type ''\n \twith 16512 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\nfrom sklearn.base import BaseEstimator, TransformerMixin \n# BaseEstimator allows you to drop *args and **kwargs from you constructor\n# and, in addition, allows you to use methods set_params() and get_params()\n\nrooms_id, bedrooms_id, population_id, household_id = 3, 4, 5, 6\n\nclass CombinedAttributesAdder(BaseEstimator, TransformerMixin):\n def __init__(self, add_bedrooms_per_rooms = True): # note no *args and **kwargs used this time\n self.add_bedrooms_per_rooms = add_bedrooms_per_rooms\n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n rooms_per_household = X[:, rooms_id] / X[:, household_id]\n bedrooms_per_household = X[:, bedrooms_id] / X[:, household_id]\n population_per_household = X[:, population_id] / X[:, household_id]\n if self.add_bedrooms_per_rooms:\n bedrooms_per_rooms = X[:, bedrooms_id] / X[:, rooms_id]\n return np.c_[X, rooms_per_household, bedrooms_per_household, \n population_per_household, bedrooms_per_rooms]\n else:\n return np.c_[X, rooms_per_household, bedrooms_per_household, \n population_per_household]\n \nattr_adder = CombinedAttributesAdder()\nhousing_extra_attribs = attr_adder.transform(housing.values)\n# print(housing_extra_attribs.info)\n```\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\n\nscaler = StandardScaler()\nhousing_tr_scaled = scaler.fit_transform(housing_tr)\n```\n\n\n```python\nfrom sklearn.base import TransformerMixin # TransformerMixin allows you to use fit_transform method\n\nclass CustomLabelBinarizer(TransformerMixin):\n def __init__(self, *args, **kwargs):\n self.encoder = LabelBinarizer(*args, **kwargs)\n def fit(self, X, y=0):\n self.encoder.fit(X)\n return self\n def transform(self, X, y=0):\n return self.encoder.transform(X)\n```\n\n\n```python\n\nfrom sklearn.pipeline import Pipeline\nnum_attribs = list(housing_num)\ncat_attribs = [\"ocean_proximity\"]\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attribute_names):\n self.attribute_names = attribute_names\n def fit(self, X, y=None):\n return self\n def transform(self, X):\n return X[self.attribute_names].values\n\nnum_pipeline = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n #('imputer', Imputer(strategy=\"median\")),\n ('imputer', SimpleImputer(strategy=\"median\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', StandardScaler()),\n ])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', CustomLabelBinarizer()),\n ])\n```\n\n\n```python\nfrom sklearn.pipeline import FeatureUnion\n\nfull_pipeline = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\n\nhousing = strat_train_set.drop(\"median_house_value\", axis=1)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\nhousing_prepared = full_pipeline.fit_transform(housing)\nprint(housing_prepared.shape)\nhousing_prepared\n```\n\n (16512, 17)\n\n\n\n\n\n array([[-1.15604281, 0.77194962, 0.74333089, ..., 0. ,\n 0. , 0. ],\n [-1.17602483, 0.6596948 , -1.1653172 , ..., 0. ,\n 0. , 0. ],\n [ 1.18684903, -1.34218285, 0.18664186, ..., 0. ,\n 0. , 1. ],\n ...,\n [ 1.58648943, -0.72478134, -1.56295222, ..., 0. ,\n 0. , 0. ],\n [ 0.78221312, -0.85106801, 0.18664186, ..., 0. ,\n 0. , 0. ],\n [-1.43579109, 0.99645926, 1.85670895, ..., 0. ,\n 1. , 0. ]])\n\n\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.linear_model import LinearRegression\n\n\n\n\n# specify the range of hyperparameter values for the grid search to try out \nparam_grid = {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]}\n\nforest_reg = RandomForestRegressor()\ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5,\n scoring=\"neg_mean_squared_error\")\ngrid_search.fit(housing_prepared, housing_labels)\n\ngrid_search.best_params_\n```\n", "meta": {"hexsha": "ab37f436b1a87057095d871947c9628acfeb7077", "size": 804022, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DSPNP_practical1/.ipynb_checkpoints/DSPNP_notebook1-checkpoint.ipynb", "max_stars_repo_name": "marcus800/cl-datasci-pnp-2021", "max_stars_repo_head_hexsha": "aea4a1e1aaeac895c595d67f328485157f1e2b39", "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": "DSPNP_practical1/.ipynb_checkpoints/DSPNP_notebook1-checkpoint.ipynb", "max_issues_repo_name": "marcus800/cl-datasci-pnp-2021", "max_issues_repo_head_hexsha": "aea4a1e1aaeac895c595d67f328485157f1e2b39", "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": "DSPNP_practical1/.ipynb_checkpoints/DSPNP_notebook1-checkpoint.ipynb", "max_forks_repo_name": "marcus800/cl-datasci-pnp-2021", "max_forks_repo_head_hexsha": "aea4a1e1aaeac895c595d67f328485157f1e2b39", "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": 221.4326631782, "max_line_length": 333824, "alphanum_fraction": 0.888566482, "converted": true, "num_tokens": 24895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462564, "lm_q2_score": 0.20946968873287058, "lm_q1q2_score": 0.09251710701828052}} {"text": "```python\n%matplotlib inline\n\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"font.size\"] = 18\n```\n\n# Radiation Interatctions with Matter\n\n### Learning Objectives\n\n- Define uncollided flux\n- Define linear interaction coefficient\n- Apply linear interaction coefficients to a slab problem\n- Identify the units of intensity, flux density, fluence, reaction rate\n- Compare linear interaction coefficient and cross section\n- Calculate uncollided flux in a medium \n- Calculate mean free path of a particle in a medium\n- Define the half thickness in a medium\n- Apply the concept of buildup factor to attenuation in a slab\n- Define microscopic cross section\n- Calculate macroscopic cross sections, given a microscopic cross section\n- Calculate the mass interaction coefficients of mixtures\n- Calculate flux density\n- Calculate Reaction Rate Density\n- Recognize the dependence of flux on energy, position, and time\n- Define radiation fluence\n- Calculate uncollided flux density from isotropic point sources\n- Apply the Kelin-Nishina formula to Compton Scattering\n- Compare energy dependence of photon interaction cross sections\n- Describe energy dependence of neutron interaction cross sections\n- Recognize the comparative range of heavy vs. light particles \n- Recognize the comparative range of charged particles\n\n## Linear Interaction Coefficient\n\n- The interaction of radiation with matter is always statistical in nature, and, therefore, must be described in probabilistic terms. \n\nConsider a particle travelling through a homogeneous material.\n\n\\begin{align}\nP_i(\\Delta x) &= \\mbox{probability the particle, causes a reaction of type i in distance }\\Delta x\\\\\n\\end{align}\n\nEmpirically, we find that this probability becomes constant as $\\Delta x \\longrightarrow 0$. Thus:\n\n\n\\begin{align}\n\\mu_i &= \\lim_{\\Delta x \\rightarrow 0}\\frac{P_i(\\Delta x)}{\\Delta x}\\\\\n\\end{align}\n\nFacts about $\\mu_𝑖$:\n\n- $\\mu_i$ is an *intrinsic* property of the material for a given incident particle and interaction. \n- $\\mu_i$ is independent of the path length traveled prior to the interaction. \n- $\\mu_i$ may represent many types of interaction (scattering: $\\mu_s$, absorption: $\\mu_a$, ...)\n- $\\mu_i$ typically depends on particle energy\n\n\nThe probability, per unit path length, that a neutral particle undergoes some sort of reaction, is the sum of the probabilities, per unit path length of travel, for each type :\n\n\\begin{align}\n\\mu_t(E) = \\sum_i \\mu_i(E)\n\\end{align}\n\n## Think Pair Share:\n\nWhat are the units of the linear interaction coefficient?\n\n### Attenuation of Uncollided Flux\n\nImagine a plane of neutral particles strike a slab of some material, normal to the surface. \n\nWe can describe this using $\\mu_t$ or, equivalently, the macroscopic total cross section $\\Sigma_t$. \n\n\n\\begin{align}\nI(x) &= I_0e^{-\\mu_t x}\\\\\nI(x) &= I_0e^{-\\Sigma_t x}\\\\\n\\end{align}\n\nwhere\n\n\\begin{align}\n I(x) &= \\mbox{uncollided intensity at distance x}\\\\\n I_0 &= \\mbox{initial uncollided intensity}\\\\\n \\mu_t &= \\mbox{total linear interaction coefficient} \\\\\n \\Sigma_t &= \\mbox{macroscopic total cross section} \\\\\n x &= \\mbox{distance into material [m]}\\\\\n\\end{align}\n\n\n\n```python\nimport math\ndef attenuation(distance, initial=100, sig_t=1):\n \"\"\"This function describes neutron attenuation into the slab\"\"\"\n return initial*math.exp(-sig_t*distance)\n\n```\n\nRather than intensity, one can find the probability density:\n\nWe have a strong analogy between decay and attenuation, as above. In the case of decay the probability of decay in a time interval dt is:\n\n\\begin{align}\nP(t)dt &= \\lambda e^{-\\lambda t}dt\\\\\n &= \\mbox{probability of decay in interval dt}\n\\end{align}\n\nFrom this, one can find the mean lifetime of a neutron before decay:\n\n\\begin{align}\n\\bar{t} &= \\int_0^\\infty t'P(t')dt'\\\\\n &= \\int_0^\\infty t'\\lambda e^{-\\lambda t'}dt'\\\\ \n &= \\frac{1}{\\lambda}\n\\end{align}\n\nIn the case of attenuation:\n\\begin{align}\nP(x)dx &= \\Sigma_te^{-\\Sigma_tx}dx\n\\end{align}\n\nSuch that: \n\n\\begin{align}\nP(x)dx &= \\mu_t e^{-\\mu_t x}dx\\\\\n &= \\Sigma_t e^{-\\Sigma_t x}dx\\\\\n &= \\mbox{probability of interaction in interval dx}\n\\end{align}\n\n\nSo, the mean free path is:\n\n\\begin{align}\n\\bar{l} &= \\int_0^\\infty x'P(x')dx'\\\\\n &= \\int_0^\\infty x'\\Sigma_te^{-\\Sigma_t x'}dx'\\\\ \n &= \\frac{1}{\\Sigma_t}\n\\end{align}\n\n\nOr, equivalently in $\\mu_t$ notation:\n\n\\begin{align}\n\\bar{x} &= \\int_0^\\infty x'P(x')dx'\\\\\n &= \\int_0^\\infty x'\\mu_te^{-\\mu_t x'}dx'\\\\ \n &= \\frac{1}{\\mu_t}\n\\end{align}\n\n\n\n```python\ndef prob_dens(distance, initial=100, sig_t=1):\n return sig_t*attenuation(distance, initial=100, sig_t=1)\n\n```\n\n\n```python\nsig_t = 0.2\ni_0 = 100\n\n# This code plots attenuation\nimport numpy as np\nz = np.arange(24)\ny = np.arange(24)\nx = np.arange(24)\nfor h in range(0,24):\n x[h] = h\n y[h] = attenuation(h, initial=i_0, sig_t=sig_t)\n z[h] = prob_dens(h, initial=i_0, sig_t=sig_t)\n\n# creates a figure and axes with matplotlib\nfig, ax = plt.subplots()\nscatter = plt.scatter(x, y, color='blue', s=y*20, alpha=0.4) \nax.plot(x, y, color='red') \nax.plot(x, z, color='green') \n\n\n# adds labels to the plot\nax.set_ylabel('Percent of Neutrons')\nax.set_xlabel('Distance into slab')\nax.set_title('Attenuation')\n\n# adds tooltips\nimport mpld3\nlabels = ['{0}% intensity'.format(i) for i in y]\ntooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)\nmpld3.plugins.connect(fig, tooltip)\n\nmpld3.display()\n```\n\n\n\n\n\n\n\n\n
\n\n\n\n\n## Half-thickness\n\nIn another analog to decay, the **half-thickness** of a material is the distance required for half of the incident radiation to interact with a medium:\n\n\\begin{align}\n\\frac{I(x_{1/2})}{I(0)} &= e^{-\\mu_t x_{1/2}}\\\\\n\\implies x_{1/2} &= \\frac{\\ln{2}}{\\mu_t}\n\\end{align}\n\n## Think pair share: \nWhat is the concept in the context of decay that is analogous to the half-thickness?\n\n\n## Microscopic Cross Sections\n\n- The microscopic cross section $\\sigma_i$ is the likelihood of the event per unit area. \n- The macroscopic cross section $\\Sigma_i$ is the likelihood of the event per unit area of a certain density of target isotopes.\n- The macroscopid cross section $\\Sigma_i$ is equivalent to the linear interaction coefficient $\\mu_i$, but we tend to use $\\Sigma_i$ in nuclear interactions, reserving $\\mu_i$ for photon interactions.\n\n\\begin{align}\n\\mu_i &= \\mbox{linear interaction coefficient}\\\\\n\\Sigma_i &= \\mbox{macroscopic cross section}\\\\\\\\\n &= \\sigma_i N\\\\\n &= \\sigma_i \\frac{\\rho N_a}{A}\\\\\n \\mbox{where }& \\\\\n N &= \\mbox{atom density of medium}\\\\\n \\rho &= \\mbox{mass density of the medium}\\\\\n N_a &= \\mbox{Avogadro's number}\\\\\n A &= \\mbox{atomic weight of the medium}\n\\end{align}\n\n\n\n```python\ndef macroscopic_xs(micro, N):\n \"\"\"Returns the macroscopic cross section [cm^2] or [barns]\n \n Parameters\n ----------\n micro: double\n microscopic cross section [cm^2] or [barns]\n N: double\n atom density in the medium [atoms/cm^3]\n \"\"\"\n return micro*N\n```\n\n\n```python\ndef NA():\n \"\"\"Returns Avogadro's number \n 6.022x10^23 atoms per mole\n \"\"\"\n return 6.022E23\n\ndef num_dens_from_rho(rho, na, a):\n \"\"\"The atomic number density. \n That is, the concentration of atoms or molecules per unit volume (V)\n \n Parameters\n -----------\n rho : double\n material density (in units like g/cm^3 or kg/m^3) of the sample\n na : double\n Avogadro's number\n a : double\n The atomic or molecular weight of the atom or molecule of interest \n \"\"\"\n return rho*na/a\n```\n\n## Example: \nImagine a beam of neutrons striking a body of water, $H_2O$. Many will be absorbed by the hydrogen in the water, particularly $^1H$. \n\n\n```python\n# Find the macroscpic absorption cross section \n# of the 1H in H2O\nsig_1h = 0.333 # barns\n\n# First, molecular density of water\nrho_h2o = 1 # g/cm^3\na_h2o = 18.0153 # g/mol\nn_h2o = num_dens_from_rho(rho_h2o, NA(), a_h2o) # molecules water / cm^3\nn_h2o_barn = n_h2o/10**(24) # 10^24 molecules water / cm^3\nprint('n_h2o [1/cm^3] = ', n_h2o)\nprint('n_h2o [10^(24)/cm^3] = ', n_h2o_barn)\n\n# Now, there are two Hydrogens in each molecule of water, so:\nmacroscopic_h1 = macroscopic_xs(sig_1h, 2*n_h2o_barn)\nprint('absorption in water from 1H = ', macroscopic_h1)\n```\n\n n_h2o [1/cm^3] = 3.342714248444378e+22\n n_h2o [10^(24)/cm^3] = 0.033427142484443784\n absorption in water from 1H = 0.02226247689463956\n\n\n### Mixtures\nIn a medium that is a mixture of isotopes (e.g. $H_2O$), we can calculate the total macroscopic cross section based on individual microscopic cross sections and number densities for each component of the mixture. We may need to include information about relative isotopic abundances (f).\n\nFor the same problem as above (neutrons striking a body of water) we can calculate the absorption by *all* isotopes in the $H_2O$.\n\n\n\\begin{align}\n\\mu^{H_2O} \\equiv \\Sigma^{H_2O} &= N^1\\sigma_a^1 + N^2\\sigma_a^2 + N^{16}\\sigma_a^{16}\n+ N^{17}\\sigma_a^{17} + N^{18}\\sigma_a^{18}\\\\\n&= f^1N^H\\sigma_a^1 + f^2N^H\\sigma_a^2 + f^{16}N^O\\sigma_a^{16} + f^{17}N^O\\sigma_a^{17} + f^{18}N^O\\sigma_a^{18}\n\\end{align}\n\nSuperscripts 1, 2, 16, 17, and 18 indicate isotopes $^1H$, $^2H$, $^{16}O$,$^{17}O$, and $^{18}O$. \n\n\\begin{align}\nN^H = 2N^{H_2O}\\\\\nN^{O} = N^{H_2O}\\\\\nN^{H_2O} = \\frac{\\rho^{H_2O}N_a}{A^{H_2O}}\n\\end{align}\n\nThus:\n\\begin{align}\n\\mu^{H_2O} \\equiv \\Sigma^{H_2O} &= N^{H_2O}\\left[2f^1\\sigma_a^1 + 2f^2\\sigma_a^2 + f^{16}\\sigma_a^{16} + f^{17}\\sigma_a^{17} + f^{18}\\sigma_a^{18}\\right]\n\\end{align}\n\n\n\n```python\n# We need a lot of data\n\n# Abundances\nf_1 = 0.99985\nf_2 = 0.00015\nf_16 = 0.99756\nf_17 = 0.00039\nf_18 = 0.00205\n\n# Then, microscopic absorption cross sections\nsig_1 = 0.333\nsig_2 = 0.000506\nsig_16 = 0.000190\nsig_17 = 0.239\nsig_18 = 0.000160\n\nmacroscopic_h2o = n_h2o_barn*(2*f_1*sig_1 \n + 2*f_2*sig_2\n + f_16*sig_16\n + f_17*sig_17 \n + f_18*sig_18) \nprint('absorption in water from all isos = ', macroscopic_h2o,\"\\n\",\n 'while absorption in water from 1H = ', macroscopic_h1,\"\\n\",\n 'Thus, absorption in water is mostly from 1H.')\n```\n\n absorption in water from all isos = 0.02226860496564809 \n while absorption in water from 1H = 0.02226247689463956 \n Thus, absorption in water is mostly from 1H.\n\n\n### Reaction Rates\n\n- The microscopic cross section is just the likelihood of the event per unit area. \n- The macroscopic cross section is just the likelihood of the event per unit area of a certain density of target isotopes.\n- The reaction rate is the macroscopic cross section times the flux of incident neutrons.\n\n\\begin{align}\nR_{i,j}(\\vec{r}) &= N_j(\\vec{r})\\int dE \\phi(\\vec{r},E)\\sigma_{i,j}(E)\\\\\nR_{i,j}(\\vec{r}) &= \\mbox{reactions of type i involving isotope j } [reactions/cm^3s]\\\\\nN_j(\\vec{r}) &= \\mbox{number of nuclei participating in the reactions } [\\#/cm^3]\\\\\nE &= \\mbox{energy} [MeV]\\\\\n\\phi(\\vec{r},E)&= \\mbox{flux of neutrons with energy E at position i } [\\#/cm^2s]\\\\\n\\sigma_{i,j}(E)&= \\mbox{cross section } [cm^2]\\\\\n\\end{align}\n\n\nThis can be written more simply as $R_x = \\Sigma_x I N$, where I is intensity of the neutron flux.\n\n\nUsing flux notation, the density of ith type of neutron interaction with isotope j, per unit time is:\n\n\n\\begin{align}\nR_{i,j}(\\vec{r}) = \\Sigma_{i,j}\\phi(\\vec{r})\n\\end{align}\n\n### Reaction Rate Example: Fission Source term\n\nAn example of an important use of reaction rates is the source of neutrons in a reactor are the neutrons from fission. \n\n\\begin{align}\ns &=\\nu \\Sigma_f \\phi\n\\end{align}\n\nwhere\n\n\\begin{align}\ns &= \\mbox{neutrons available for next generation of fissions}\\\\\n\\nu &= \\mbox{the number born per fission}\\\\\n\\Sigma_f &= \\mbox{the number of fissions in the material}\\\\\n\\phi &= \\mbox{initial neutron flux}\n\\end{align}\n\nThis can also be written as:\n\n\\begin{align}\ns =& \\nu\\Sigma_f\\phi\\\\\n =& \\nu\\frac{\\Sigma_f}{\\Sigma_{a,fuel}}\\frac{\\Sigma_{a,fuel}}{\\Sigma_a}{\\Sigma_a} \\phi\\\\\n =& \\eta f {\\Sigma_a} \\phi\\\\\n\\eta =& \\frac{\\nu\\Sigma_f}{\\Sigma_{a,fuel}} \\\\\n =& \\mbox{number of neutrons produced }\\\\\n & \\mbox{ per neutron absorbed by the fuel}\\\\\n =& \\mbox{\"neutron reproduction factor\"}\\\\\nf =& \\frac{\\Sigma_{a,fuel}}{\\Sigma_a} \\\\\n =& \\mbox{number of neutrons absorbed in the fuel}\\\\\n &\\mbox{ per neutron absorbed anywhere}\\\\\n =&\\mbox{\"fuel utilization factor\"}\\\\\n\\end{align}\n\nThis absorption and flux term at the end seeks to capture the fact that some of the neutrons escape. However, if we assume an infinite reactor, we know that all the neutrons are eventually absorbed in either the fuel or the coolant, so we can normalize by $\\Sigma_a\\phi$ and therefore:\n\n\n\\begin{align}\nk_\\infty &= \\frac{\\eta f \\Sigma_a\\phi}{\\Sigma_a \\phi}\\\\\n&= \\eta f\n\\end{align}\n\n## Flux density from Point Source\nFinding $\\phi(\\vec{r}0$ generally requires *particle transport calculations.*\n\nHowever, in some simple practical situations, the flux density can be approximated by the flux density of uncollided source particles.\n\n### Point Source in Vacuum\n\nConsider a source of particles:\n\n- it emits $S_p$ particles per unit time\n- all particles have energy E\n- and they are emitted radially outward into an infinite vacuum\n- isotropically (equally in all directions)\n- from a single point in space\n\n### Think-pair share: \n\n- How many interactions occur?\n\n\n### At a radius r: \nBecause the source is isotropic, each unit area on an imaginary spherical shell of radius $r$ has the same number of particles crossing it. Thus:\n\n\\begin{align}\n\\phi^o(r) &= \\mbox{uncollided flux at radius r in any direction}\\\\\n&= \\frac{S_p}{4\\pi r^2}\n\\end{align}\n\n\n```python\ndef phi_o_r(r, s):\n \"\"\"Returns the uncolided flux at radius r\n due to an isotropic point source in a vacuum\n \n Parameters\n -----------\n r : double\n radius away from the point [length]\n s : double\n point source strength [particles/time]\n \"\"\"\n return s/(4*math.pi*pow(r,2))\n```\n\n\n```python\ns=200\n\nplt.plot(range(1,10), [phi_o_r(r, s) for r in range(1,10)])\n```\n\nThe plot above, this $1/r^2$ reduction in flux and reaction rate, is occaisionally called \"geometric attenuation\".\n\n\n```python\n# The below IFrame displays Page 189 of your textbook:\n# Shultis, J. K. (2016). Fundamentals of Nuclear Science and Engineering Third Edition, \n# 3rd Edition. [Vitalsource]. Retrieved from https://bookshelf.vitalsource.com/#/books/9781498769303/\n# Please take note of Figure 7.2\n\nfrom IPython.display import IFrame\nIFrame(\"https://bookshelf.vitalsource.com/books/9781498769303/pageid/211\", width=1000, height=500)\n\n```\n\n\n\n\n\n\n\n\n\n\n## Point Source in an Attenuating Medium\nSo, the unollided flux is \n\\begin{align}\n\\phi^o(r) &= \\frac{S_p}{4\\pi r^2}\n\\end{align}\n\n### A small volume\n\nAt a distance r, we place a homogeneous mass with a volume $\\Delta V_d$. The interaction rate $R_d$ in the mass is: \n\n\\begin{align}\n&R^o(r)=\\mu_d(E)\\Delta V_d\\frac{S_p}{4\\pi r^2}\\\\\n\\mbox{where}&\\\\\n&\\mu_d(E)=\\mbox{linear interaction coefficient in the volume}\n\\end{align}\n\n### An inifinite volume\n\nFrom this, we can imagine the point source embeeded in an infinite medium of this material. A detector is at distance r in the volume:\n\n\\begin{align}\n&\\phi^o(r) = \\frac{S_p}{4\\pi r^2}e^{-\\mu r}\\\\\n\\mbox{where}&\\\\\n&e^{-\\mu r}=\\mbox{material attenuation}\n\\end{align}\n\n### A slab shield\n\nImagine a slab shield, thickness t, at a distance r, between the point source and a detector.\n\n\\begin{align}\n&\\phi^o(r) = \\frac{S_p}{4\\pi r^2}e^{-\\mu t}\\\\\n\\mbox{where}&\\\\\n&t=\\mbox{thickness of the slab}\n\\end{align}\n\nIf it were made of a series of materials $i$, with coefficients $\\mu_i$, and thicknesses $t_i$:\n\n\\begin{align}\n&\\phi^o(r) = \\frac{S_p}{4\\pi r^2}e^{\\sum_i -\\mu_i t_i}\\\\\n\\mbox{where}&\\\\\n&\\mu_i=\\mbox{linear interaction coefficient of ith slab}\\\\\n&t_i=\\mbox{thickness of ith slab}\n\\end{align}\n\n### Heterogeneous Medium\n\nAn arbitrary heterogeneous medium can be described as having an interaction coefficient $\\mu(\\vec{r})$ at any point $\\vec{r}$ in the medium, a funciton of position in the medium.\n\n\\begin{align}\n&\\phi^o(r) = \\frac{S_p}{4\\pi r^2}e^{\\left[-\\int_0^r \\mu(s) ds\\right]}\\\\\n\\end{align}\n\n## Polyenergetic Point Source\n\n- Previous examples assume a **monoenergetic** point source (particles of a single energy, E). \n- But, a single source can emit particles at several discrete energies, or even a continuum of energies.\n\nLet's define some variables:\n\n\\begin{align}\nf_i &= \\mbox{fraction of the source emitted with energy }E_i\\\\\nE_i &= \\mbox{discrete energy of }f_iS_p\\mbox{ particles}\\\\\nS_p &= \\mbox{still the number of particles emitted from the point source}\n\\end{align}\n\nThe total interaction rate caused by uncollided particles streaming through a small volume mass at distance r from the source is the following, **for some set of i discrete energies**.\n\n\\begin{align}\nR^o(r)=\\sum_i\\frac{S_p f_i\\mu_d(E_i) \\Delta V_d}{4\\pi r^2}e^{\\left[-\\int_0^r \\mu(s,E_i) ds\\right]}\\\\\n\\end{align}\n\nIf the source emits a continuum of energies, it's best to define the fraction $f_i$ as a differential probability:\n\n\\begin{align}\nN(E)dE\\mbox{the probability that a source particle is emitted with energy in dE about E}\n\\end{align}\n\n\nWith this definition, the sum over discrete energies becomes an integral.\n\n\\begin{align}\nR^o(r)=\\int_o^\\infty \\left[\\frac{S_p N(E)\\mu_d(E) \\Delta V_d}{4\\pi r^2}e^{\\left[-\\int_0^r \\mu(s,E) ds\\right]}\\right]dE\\\\\n\\end{align}\n\nPlease note, you may see many nuclear texts list the dE first in the integral... don't be bamboozled. This is equivalent to the above:\n\n\\begin{align}\nR^o(r)=\\int_o^\\infty dE\\frac{S_p N(E)\\mu_d(E) \\Delta V_d}{4\\pi r^2}e^{\\left[-\\int_0^r \\mu(s,E) ds\\right]}\n\\end{align}\n\n\n### Example 7.4 from your book (Shultis & Faw)\n\nA point source with an activity of 500 Ci emits 2-MeV photons with a frequency of 70% per decay. \n\n\\begin{align}\nS_p = 500 Ci\\\\\nf_2 = 0.7\\\\\n\\end{align}\n\nWhat is the flux density of 2-MeV photons 1 meter from the source? \n\n\n\n```python\ns_p = 500 # Ci\nf_2 = 0.7 # fraction emitted at 2MeV\nmu = 1.0/187.0 # mean free path of 2MeV photon in air is 187m\n\n# first, convert S_p is in number of particles per decay (Bq)\nbq_to_ci = 3.7e10 # Bq/Ci\ns_p = s_p*bq_to_ci \n\n# Now, find uncollided flux of 2MeV photons at 1 m\nr = 1.0 #m\ns = s_p*f_2 # just want 2MeV photons\nphi = phi_o_r(r, s)\nprint(\"Uncollided flux is : \", phi)\n\n# Uh oh, we forgot the material attenuation!\nphi = phi_o_r(r, s)*math.exp(-mu*r)\nprint(\"Uncollided flux with attenuation is : \", phi)\n```\n\n Uncollided flux is : 1030528256520.0223\n Uncollided flux with attenuation is : 1025032118881.2917\n\n\n### Think Pair Share\n\nWhat are the units of $\\phi^o$, above?\n\n\n# Photon Interactions\n\n**Recall:** \n \n\\begin{align}\nc &= \\mbox{speed of light}\\\\ \n &=2.9979\\times10^8\\left[\\frac{m}{s}\\right]\\\\\nE &= \\mbox{photon energy}\\\\\n &=h\\nu\\\\\n &=\\frac{hc}{\\lambda}\\\\\nh &= \\mbox{Planck's constant}\\\\\n &= 6.62608\\times10^{−34} [J\\cdot s] \\\\\n\\nu &=\\mbox{photon frequency}\\\\\n\\lambda &= \\mbox{photon wavelength}\n\\end{align}\n\n**Nota bene:**\n- **10eV - 20MeV** photons are important in radiation sheilding\n- At **10eV - 20MeV**, only photoelectric effect, pair production, and Compton Scattering are significant\n\n\n
Figure from: \"Radiation Interactions with Tissue.\" Radiology Key. Jan 8 2016.
\n\n\n\n
Figure from: Cullen, D. E. 1994. \"Photon and Electron Interaction Databases and Their Use in Medical Applications.\" UCRL-JC--117419. Lawrence Livermore National Lab. http://inis.iaea.org/Search/search.aspx?orig_q=RN:26035330.
\n\n\n\n## Klein Nishina\n\nThe total Compton cross section, per atom with Z electrons, based on the free-electron approximation, is given by the well-known Klein-Nishina formula [Evans 1955]:\n\n\\begin{align}\n\\sigma_c(E) =\\pi Zr_e^2\\lambda\\left[(-2\\lambda - 2\\lambda^2)\\ln{\\left(1+\\frac{2}{\\lambda}\\right)} + \\frac{2(1+9\\lambda + 8\\lambda^2 + 2\\lambda^3)}{(\\lambda + 2)^2}\\right]\n\\end{align}\n\nHere $\\lambda \\equiv \\frac{m_ec^2}{E}$, a dimensionless quantity, and $r_e$ is the classical electron radius. The value of $r_e$ is given by:\n\n\\begin{align}\nr_e &\\equiv \\frac{e^2}{4\\pi\\epsilon_om_ec^2}\\\\\n&= 2.8179\\times10^{-13}cm\n\\end{align}\n\n\n### Think pair share:\nConceptually, in the above equation:\n\n- what is $r_e$?\n- what is $e$?\n- what is $\\epsilon_o$?\n- what is $m_ec^2$?\n\n\n\n### Total Photon Cross Section\nVarious types of incoherent scattering, including Compton, are actually present in that intermediate energy range. It is occaisionally important to correct for all types of incoherent scattering, but it can typically be assumed to be primarily Compton scattering. \n\nFor photons, then $\\mu$ becomes:\n\n\\begin{align} \n\\mu(E)&\\equiv N\\left[\\sigma_{ph}(E) + \\sigma_{inc}(E) + \\sigma_{pp}(E)\\right]\\\\\n &\\simeq N\\left[\\sigma_{ph}(E) + \\sigma_{c}(E) + \\sigma_{pp}(E)\\right]\\\\\n N &= \\mbox{atom density}\\\\\n &= \\frac{\\rho N_a}{A} \n\\end{align}\n\nIt is common to denote this as the total mass interaction coefficient:\n\n\\begin{align}\n\\frac{\\mu}{\\rho} &= \\frac{N_a}{A}\\left[\\sigma_{ph}(E) + \\sigma_{c}(E) + \\sigma_{pp}(E)\\right]\\\\\n&= \\frac{N_a}{A}\\left[\\frac{\\mu_{ph}(E)}{\\rho} + \\frac{\\mu_{c}(E)}{\\rho} + \\frac{\\mu_{pp}(E)}{\\rho}\\right]\n\\end{align}\n\n## Neutron Interactions\n\nPhotons tend to interact with electrons in a target atom. **Neutrons tend to interact with the nucleus.**\n\nNeutron cross sections:\n\n- Vary rapidly with the incident neutron energy,\n- Vary erratically from one element to another \n- Even vary dramatically between isotopes of the same element.\n\nThere are lots of sources of neutron cross sections. The best place to start is the Brookhaven National Laboratory National Nuclear Data Center [https://www.nndc.bnl.gov/](https://www.nndc.bnl.gov/).\n\nYour book has a clever table (7.1) listing some of the data needed for high and low energy interaction calculations. These include:\n\n- Elastic scattering cross sections \n- Angular distribution of elastically scattered neutrons \n- Inelastic scattering cross sections \n- Angular distribution of inelastically scattered neutrons \n- Gamma-photon yields from inelastic neutron scattering \n- Resonance absorption cross sections \n- Thermal-averaged absorption cross sections \n- Yield of neutron-capture gamma photons\n- Fission cross sections and associated gamma-photon and neutron yields\n\n\n# Total cross sections\n\n**For light nuclei** ($A<25$) and $E<1keV$, the cross section typically varies as:\n\n\\begin{align}\n\\sigma_t = \\sigma_1 + \\frac{\\sigma_2}{\\sqrt{E}}\n\\end{align}\n\n**For solids** at energies less than about 0.01 eV, Bragg cutoffs apply. These are energies below which no coherent scattering is possible from the material's crystalline planes.\n\n\n**For heavy nuclei**, the total cross section has a $\\frac{1}{\\sqrt{E}}$ behavior with low energy, narrow resonances and high energy broad resonances:\n\n\\begin{align}\n\\sigma_t \\propto \\frac{1}{\\sqrt{E}}\n\\end{align}\n\n\n```python\n# The below IFrame displays Page 200 of your textbook:\n# Shultis, J. K. (2016). Fundamentals of Nuclear Science and Engineering Third Edition, \n# 3rd Edition. [Vitalsource]. Retrieved from https://bookshelf.vitalsource.com/#/books/9781498769303/\n# Please take note of Figure 7.2\n\nfrom IPython.display import IFrame\nIFrame(\"https://bookshelf.vitalsource.com/books/9781498769303/pageid/222\", width=1000, height=1000)\n\n```\n\n\n\n\n\n\n\n\n\n\n### Recall fission cross sections :\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7d8ae7a205160cc3915380a384e7ed8542fcff3e", "size": 68860, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "rad_interactions/00-rad-int-matter.ipynb", "max_stars_repo_name": "katyhuff/npr247", "max_stars_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T06:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T17:14:51.000Z", "max_issues_repo_path": "rad_interactions/00-rad-int-matter.ipynb", "max_issues_repo_name": "katyhuff/npr247", "max_issues_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-29T17:27:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T17:46:50.000Z", "max_forks_repo_path": "rad_interactions/00-rad-int-matter.ipynb", "max_forks_repo_name": "katyhuff/npr247", "max_forks_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-08-25T20:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T03:05:26.000Z", "avg_line_length": 58.5544217687, "max_line_length": 11764, "alphanum_fraction": 0.6192564624, "converted": true, "num_tokens": 7157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.184767510648, "lm_q1q2_score": 0.092383755324}} {"text": "```javascript\n%%javascript\nMathJax.Hub.Config({TeX: { equationNumbers: { autoNumber: \"AMS\" } }});\n```\n\n\n \n\n\n# Maximum Entropy Principle for inference methods\n\nThe inference method based on the maximum entropy principle (**MaxEnt principle**) \nasserts that the most suitable probability distribution compatible with a given set of constraints is the one with the largest entropy [Jaynes1957a, Jaynes1957b].\nThis method is considered as a powerful estimation technique in a wide range of probabilistic models since it brings a solution to the **universal problem** of trying to stract information from partial or incomplete data --which is usually what we have to work with--. That is the reason why it finds applications in various fields of research, beyond statistical physics, as biology [De Martino2018] and ecology [Tang2021], being also usefull for analyzing and understanding complex social or economic systems [Golan1997,Scharfenaker2020], and make financial predictions [Benedetto2015]. Problems arising from these systems are characterized by having many degrees of freedom and non-trivial interaction patterns between individual subsystems. Hence it must be dealt with\ninductive inference problems due to the insufficient amount of experimental data and the incomplete nature of the information that can be extracted from them. \n\nMoreover, the MaxEnt principle has been proven to be useful for a reasonable estimation of quantum states from incomplete data [Buzek2000,Goncalves2013,Gupta2021], where the amount of experimental resourses and time consuming make quantum tomography impractical even for an intermediate number of qubits, and therefore, approaches to validate quantum processing on these quantum devices are needed.\n\n[De Martino2018] De Martino A, De Martino D. An introduction to the maximum entropy approach and its application to inference problems in biology. Heliyon. 2018 Apr 13;4(4):e00596. https://doi.org/10.1016/j.heliyon.2018.e00596 \n\n[Tang2021] Maximum Entropy Modeling to Predict the Impact of Climate Change on Pine Wilt Disease in China, Xinggang Tang, Yingdan Yuan, Xiangming Li and Jinchi Zhang, Front. Plant Sci., 23 April 2021. https://doi.org/10.3389/fpls.2021.652500.\n\n[Golan1997] A. Golan, G. Judge, and D. Miller, *Maximum Entropy\nEconometrics: Robust Estimation with Limited Data* (John Wiley and Sons, Chichester, United Kingdom,\n1997).\n\n[Scharfenaker2020] Scharfenaker, E., Yang, J. Maximum entropy economics. Eur. Phys. J. Spec. Top. 229, 1577–1590 (2020). https://doi.org/10.1140/epjst/e2020-000029-4\n\n[Benedetto2015] A maximum entropy method to assess the predictability of financial and commodity prices, F.Benedetto, G.Giunta, L.Mastroeni, Digital Signal Processing\nVolume 46, November 2015, Pages 19-31. https://doi.org/10.1016/j.dsp.2015.08.001\n\n[Jaynes1957a] E. T. Jaynes, Information theory and statistical mechanics, Physical Review **106**, 620 (1957).\n\n[Jaynes1957b] E. T. Jaynes, Information theory and statistical mechanics. II, Physical Review **108**, 171 (1957).\n\n[Buzek2000] V. Buzek and G. Drobny, Quantum tomography via the maxent principle, Journal of Modern Optics47, 2823 (2000). https://doi.org/10.1080/09500340008232199\n\n[Goncalves2013] D. Goncalves, C. Lavor, M. Gomes-Ruggiero, A. Cesario,R. Vianna, and T. Maciel, Quantum state tomographywith incomplete data: Maximum entropy and variationalquantum tomography, Phys. Rev. A87, 052140 (2013). https://doi.org/10.1103/PhysRevA.87.052140\n\n\n[Gupta2021] Maximal Entropy Approach for Quantum State Tomography, Rishabh Gupta, Rongxin Xia, Raphael D. Levine, and Sabre Kais, PRX QUANTUM **2**, 010318 (2021). https://doi.org/10.1103/PRXQuantum.2.010318\n\n\n# Mathematical problem\n\nLet $X$ be a random variable in a sample space $\\Omega = \\{x_1, \\ldots, x_k\\}$ with **unknown** probabilities \\\\(p_i=P(X=x_i), x_i ∈ \\Omega\\\\) and $\\sum_{i=1}^k p_i=1$. Mathematically, the MaxEnt formalism with \\\\(m\\\\) constraints on the expectations values $E[g_j]=\\alpha_j$ of functions $g_j(x_i)$, can be expressed as a constrained optimization problem \n\n\\begin{equation}\n\\mathrm{max}\\;S(X)\\;\\;\n\\mathrm{s.t.}\n\\sum_{i=1}^k p_i g_j(x_i)=\\alpha_j, ~j=1,\\dots,m \\;\\;\\;\\;\\;\\;\\;\\;\\;\\;\\;\\;\\;\\;(1)\\nonumber\n\\end{equation}\n\nwere $S(X)$ is the entropy of the random variable $X$. Within the information theory, $S$ is usually taken as the Shannon entroypy and then the principle gives the less biased distribution, consistent with the available data. In such a case $S(X)= H \\equiv −k\n\\sum_{i=1}^k p_i \\mathrm{log}(p_i)$. The resulting maximum entropy probability is given by:\n\n\\begin{equation}\np_i =\n\\frac{1}\n{Z(λ_1, . . . , λ_m)}\nexp \\left[−λ_1 g_1(x_i) − · · · − λ_m g_m(x_i)\\right],\\;\\;\\;\\;\\;\\;\\;\\;\\;(2)\\nonumber\n\\end{equation}\n\nwith $Z(λ_1, . . . , λ_m) = \\sum_{i=1}^k exp [−λ_1g_1(x_i) − · · · − λ_mg_m(x_i)]$ and $λ_m$ is the Lagrangian multiplier for the $m$-th constraint given by the relation\n\\begin{equation}\\label{classical lagrange multipliers}\n\\alpha_{j}= \\frac{\\partial}{\\partial\\lambda_{j}}\\ln Z,\\quad 1\\leq j \\leq n.\\;\\;\\;\\;\\;\\;(3)\\nonumber\n\\end{equation}.\n\nHence, to find the MaxEnt probability distribution is considered a hard task due to the nonlinearities in the reconstruction algorithm. In fact, the relations in Ec. (3) represents a system of nonlinear differential equations to be solve. \n\n# MaxEnt inference in Biology \n\n## Inference of gene interaction networks\n\n \n\n**Fig. 1** Inference of gene interaction networks from empirical expression data. Figure extracted from \"Using the principle of entropy maximization to infer genetic interaction networks from gene expression patterns\", T.R. Lezon, J.R. Banavar, M. Cieplak, A. Maritan, N.V. Fedoroff, Proc. Natl. Acad. Sci. 103 (50) (2006) 19033–19038.\n\n\n\n\n\n\n# MaxEnt inference in Ecology\n\n## Predicting the distribution of pine species and the impact of climate change on forest diseases\n\n\n\n**Fig. 2** Habitat suitability maps showing the ocurrence of *P. desinflora* by 2050 and 2070 under two distinct climate change scenarios in China. Figure extracted from \"Maximum Entropy Modeling to Predict the Impact of Climate Change on Pine Wilt Disease in China\", Xinggang Tang, Yingdan Yuan, Xiangming Li and Jinchi Zhang, Front. Plant Sci., 23 April 2021.\n\n\n# Solving MaxEnt as a QUBO problem\n\nThe Quadratic Unconstrained Binary Optimization (QUBO) [Kochenberger2014] is a model for representing a wide range of combinatorial optimization problems. Moreover, due to its close connection to Ising models, QUBO constitutes a central problem class for Adiabatic quantum computation feasible to be solved through quantum annealing.\n\nIf $f_Q(x)=x^TQx$ is a quadratic polinomial over binary variables $x_i\\in B=\\{0,1\\}$, where $Q\\in \\mathbb {R} ^{n\\times n}$ is a symmetric $n\\times n$ matrix, the QUBO problem consists of finding a binary vector $x^{*}$ that minimize $f_Q$.\n\n\n## Goal\n\n\nWe have redefined the MaxEnt problem as a QUBO problem $\\left(P^TQP+C^TP\\right)$. For this purpose, the first step is to find an appropriate entropy function $S$ and codified the variables to be obtained as a result of the minimization process, in our case the probabilities $p_i$, as a binary vector. Expanding the Shannon's entropy $H$ to first order in the distribution $P=(p_1,p_1,\\dots,p_k)^T$, we obtain the quadratic entropy\n\n\\begin{equation}\nH(P) \\approx −k\n\\sum_{i=1}^k p_i \\mathrm{log}(p_i)=2 - 2 P^TP,\\;\\;\\;\\;\\;\\;\\;\\;\\;\\; (4)\\nonumber\n\\label{entropy}\n\\end{equation}\n\nwere we have take the value $k=2$ according to a random variable $X\\in\\Omega=\\{0,1\\}$.\nThen, we are interesting in to find the probability distribution $P$ that satisfies the constraints in Eq. $\\left(1\\right)$ and maximizes the quadratic entropy $\\left(4\\right)$.\n\n$1.$ We define the cost function $f(P)$ as:\n\\begin{equation}\nf(P) = -H(P) + \\sum_{j= 0}^{m} (G_j^T P - \\alpha_j) ^2.\\;\\;\\;\\;\\;\\;\\;\\;\\;\\; (5)\\nonumber\n\\end{equation}\n\nwhere $G_j=(g_j(x_1),g_j(x_2),\\dots,g_j(x_k))^T$ is the vector which contains the image of the function $g_j\\in \\{g_1,\\dots,g_m\\}$. After trivial algebra manipulation Eq. $(5)$ is reduced to \n\n\\begin{align}\nf(P)=-2 + \\sum_{j= 0}^{m} \\alpha_j^2 + \\left(\\sum_{j= 0}^{m}(-2) \\alpha_j G_j^T\\right) P + P^T \\left( 2I_k +\\sum_{j= 0}^{m} G_j G_j^T\\right) P \\;\\;\\;\\;\\;\\;\\;\\;\\;\\; (6)\\nonumber\n \\end{align}\n\n\n\n\nThen, $f(P)$ can be rewritten as\n\\begin{equation}\nf(P) = P^T Q P + C^T P + cte, \\;\\;\\;\\;\\;\\;\\;\\;\\;\\; (7)\\nonumber\n\\end{equation}\n\nwith $C^T = \\sum_{j= 0}^{m}(-2) \\alpha_j G_j^T$, and $Q = 2 I_n +\\sum_{j= 0}^{m} G_j G_j^T$.\n\n$2.$ Now we will express each entry $p_i$ of the probability distribution in a binary basis, i.e., \n\\begin{equation}\np_i = \\sum_{k=1}^d \\frac{a_{ik}}{2^k},\\;\\;\\;\\;\\;\\;\\;\\;\\;\\; (8)\\nonumber\n\\end{equation}\nwhere each $a_{ik}$ can be $0$ or $1$. For a given $d$ we have a restriction of the values that we able to represent $(0 \\leq p_i \\leq 1- 1/2^d$ with precision $1/2^d)$. Then,\n\n\\begin{align}\np_i &= (\\frac{1}{2}, \\ldots,\\frac{1}{2^d}) (a_{i1}, \\ldots, a_{id})^T\\;\\;\\;\\;\\;\\;\\;\\;\\;\\; (9)\\nonumber\\\\\n\\mathrm{or}\\;\\; P & = S a,\\nonumber\n\\end{align}\n\nwith $S$ an adequate matrix that performs the transformation.\n\nFinally, we obtain the cost function in a suitable form to be solve as a QUBO problem\n\n\\begin{equation}\nf(p) = cte + C^T S a + a^T S^TQS a.\n\\end{equation}\n\n[Kochenberger2014] Kochenberger, Gary; Hao, Jin-Kao (2014). \"The unconstrained binary quadratic programming problem: a survey\" (PDF). Journal of Combinatorial Optimization. **28**: 58–81. http://doi:10.1007/s10878-014-9734-0. \n\n\n# A puzzlelike problem\n\n\n\n\n\n\n\nThe following code finds the MaxEnt probability distribution given the appearance frequencies of the faces of a die as constraints. \n\n\n\n\n```python\nimport numpy as np\nimport function as f \n```\n\n\n```python\n#Example 1: Dice without constraints\nnb = 6 #Number of bits \nlam = 0.001 #Optimization constant\nnumreads = 10000 #number of reads\ny0= np.array ([[1.0],[1.0],[1.0],[1.0],[1.0], [1.0] ])\nalpha = np.array ([1.0 ])\ny = [y0]\nx,p,cost, cost_bin = f.solution(y, alpha, nb, lam,numreads )\nprint('Binary solution: ', x)\nprint('Probability: ', p, 'Sum: ', sum(p))\nprint('Cost: ', cost[0])\n```\n\n Binary solution: [0 0 1 0 1 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 1 0 0 1 0 1 0]\n Probability: [0.15625 0.1875 0.1875 0.171875 0.140625 0.15625 ] Sum: 1.0\n Cost: -0.9996630859375\n\n\n\n\n\n```python\n#Example 2: Dice with fair mean value\nnb = 6 #Number of bits \nlam = 0.001 #Optimization constant\nnumreads = 10000 #number of reads\ny0= np.array ([[1.0],[1.0],[1.0],[1.0],[1.0], [1.0] ])\ny1= np.array ([[1.0],[2.0],[3.0],[4.0],[5.0], [6.0] ])\nalpha = np.array ([1.0, 3.5 ])\ny = [y0, y1]\nx,p,cost, cost_bin = f.solution(y, alpha, nb, lam,numreads )\nprint('Binary solution: ', x)\nprint('Probability: ', p, 'Sum: ', sum(p))\nprint('Cost: ', cost[0])\n```\n\n Binary solution: [0 0 1 0 1 0 0 0 1 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 0 0 1 0 1 0]\n Probability: [0.15625 0.171875 0.171875 0.171875 0.171875 0.15625 ] Sum: 1.0\n Cost: -13.249666015625\n\n\n\n\n\n```python\n#Example 3: Loaded dice\nnb = 8 #Number of bits \nlam = 0.0001 #Optimization constant\nnumreads = 50000 #number of reads\ny0= np.array ([[1.0],[1.0],[1.0],[1.0],[1.0], [1.0] ])\ny1= np.array ([[1.0],[2.0],[3.0],[4.0],[5.0], [6.0] ])\nalpha = np.array ([1.0, 6 ])\ny = [y0, y1]\nx,p,cost, cost_bin = f.solution(y, alpha, nb, lam,numreads )\nprint('Binary solution: ', x)\nprint('Probability: ', p, 'Sum: ', sum(p))\nprint('Cost: ', cost[0])\n```\n\n Binary solution: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0\n 0 1 0 1 1 1 1 1 0 1 0]\n Probability: [0. 0. 0. 0.0234375 0.0078125 0.9765625] Sum: 1.0078125\n Cost: -36.99968707275391\n\n\n\n\n\n```python\n#Example 4: Dice with one face with fixed probability\nnb = 8 #Number of bits \nlam = 0.01 #Optimization constant\nnumreads = 10000 #number of reads\ny0= np.array ([[1.0],[1.0],[1.0],[1.0],[1.0], [1.0] ])\ny1= np.array ([[0.0],[1.0],[0.0],[0.0],[0.0], [0.0] ])\nalpha = np.array ([1.0, 0.8 ])\ny = [y0, y1]\nx,p,cost, cost_bin = f.solution(y, alpha, nb, lam,numreads )\nprint('Binary solution: ', x)\nprint('Probability: ', p, 'Sum: ', sum(p))\nprint('Cost: ', cost[0])\n```\n\n Binary solution: [0 0 0 0 1 1 0 0 1 1 0 0 1 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 1 0 0 0 0 1\n 0 1 0 0 0 0 0 1 1 0 0]\n Probability: [0.046875 0.78515625 0.0390625 0.04296875 0.0390625 0.046875 ] Sum: 1.0\n Cost: -1.6272644042968751\n\n\n\n\n\n```python\n#Example 5: Dice with two faces summing a fixed probability\nnb = 8 #Number of bits \nlam = 0.01 #Optimization constant\nnumreads = 10000 #number of reads\ny0= np.array ([[1.0],[1.0],[1.0],[1.0],[1.0], [1.0] ])\ny1= np.array ([[1.0],[1.0],[0.0],[0.0],[0.0], [0.0] ])\nalpha = np.array ([1.0, 0.7 ])\ny = [y0, y1]\nx,p,cost, cost_bin = f.solution(y, alpha, nb, lam,numreads )\nprint('Binary solution: ', x)\nprint('Probability: ', p, 'Sum: ', sum(p))\nprint('Cost: ', cost[0])\n```\n\n Binary solution: [0 1 0 1 1 0 0 1 0 1 0 1 1 0 0 1 0 0 0 1 0 0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 0\n 1 0 0 0 0 0 1 0 1 0 0]\n Probability: [0.34765625 0.34765625 0.07421875 0.07421875 0.078125 0.078125 ] Sum: 1.0\n Cost: -1.4846789550781248\n\n\n\n", "meta": {"hexsha": "9cd9e363adb14ce1e09bd3a3054ae4cb1e468cf1", "size": 19812, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Quantum Vision/QuantumVision.ipynb", "max_stars_repo_name": "stared/Hackathon2021", "max_stars_repo_head_hexsha": "69e2ba4345b311e62d09d02f6953b25614229e12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-07-26T13:45:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:15:23.000Z", "max_issues_repo_path": "Quantum Vision/QuantumVision.ipynb", "max_issues_repo_name": "stared/Hackathon2021", "max_issues_repo_head_hexsha": "69e2ba4345b311e62d09d02f6953b25614229e12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-26T19:33:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T08:32:20.000Z", "max_forks_repo_path": "Quantum Vision/QuantumVision.ipynb", "max_forks_repo_name": "stared/Hackathon2021", "max_forks_repo_head_hexsha": "69e2ba4345b311e62d09d02f6953b25614229e12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2021-07-26T13:10:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:23:48.000Z", "avg_line_length": 43.4473684211, "max_line_length": 781, "alphanum_fraction": 0.5747022007, "converted": true, "num_tokens": 4950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.23091975234373585, "lm_q1q2_score": 0.09232440506377616}} {"text": "```python\nGodfrey Beddard 'Applying Maths in the Chemical & Biomolecular Sciences an example-based approach' Chapter 9\n```\n\n\n```python\n# import all python add-ons etc that will be needed later on\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sympy import *\nfrom scipy.integrate import quad\ninit_printing() # allows printing of SymPy results in typeset maths format\nplt.rcParams.update({'font.size': 14}) # set font size for plots\n```\n\n# 7 Convolution\n\n## 7.1 Motivation and concept\n\nInstruments measure everything: for example, mass, energy, number of particles, wavelength of light, voltage, current, and images. However, every instrument distorts the data to a greater or lesser extent, and obviously we try to make these distortions insignificant but this is not always possible. In cases when a detector may not respond quickly enough to an event, when very wide slits have to be used in a spectrometer to detect a weak signal, or an electronic circuit does not respond in a linear manner to the input voltage, a distortion to the data is unavoidable. The effect is to _convolute_ the ideal response, as defined by the physics behind the experiment, with the instrumental response. Fortunately Fourier transforms can usually be used to unravel the effect of convolution, however, in some circumstances this may not be possible.\n\n**(i)** To be specific, suppose that the lifetime of electronically excited atoms or molecules is to be measured by exciting them with a pulse of light and their fluorescence measured as it decays with time. This fluorescence could be observed with a photodiode or photomultiplier, whose output voltage is measured with an oscilloscope. Before doing this experiment, two questions have to be answered; \n>(a) Is the laser used to excite the molecules of short enough duration that the molecules or atoms can be excited quickly enough before any significant number can decay back to the ground state? \n\n>(b) Is the detection equipment (photodiode, oscilloscope) used able to respond quickly enough to measure the decaying fluorescence properly? \n\n\n\nFigure 24. Top: A signal representing the ideal response of an experiment to a sudden impulse. Middle: The actual stimulation used in the experiment represented as the instrument response. Bottom: The measured signal, the convolution of the two upper curves.\n____\n\nIf either one or both of these conditions cannot be met, then the data will be distorted by the relatively slow response of the instrument. The convolution curve in fig 24 shows how this distortion affects some data. In this figure, the top curve is the ideal decay of the excited state, but it could represent any ideal response. This behaviour would be observed if the molecules could be excited with an infinitesimally narrow laser pulse and measured with a photo-detector with an unlimited time response. The second curve is the actual shape of the laser pulse, and/or detector response, and is the 'instrument response' drawn on the same timescale. Clearly, this has a width and a rise and decay time that is not so very different to that of the ideal response. The lower curve is the convolution of the ideal response with the instrument response, and is what would be measured experimentally and clearly has characteristics of both curves. A log plot of the data would show that only at long times does the convoluted response have the same slope as the ideal one. It makes no difference if the instrument response consists of a slow 'driving force' for the experiment, in this case a long-lived light-pulse, or a slowly responding detector or both, because the effect producing the convolution is the same. Fortunately, convolution can be calculated easily and rapidly using Fourier transforms.\n\n\nFigure 25. The convolution of a narrow spectral line with a wide slit in a spectrometer.\n\n____\n\n**(ii)** As a second example, consider measuring the width or position of one particular spectral line, such as from a star or a sample of molecules in the lab. The spectrometer has slits on its entrance and exit and these, with the number of grooves in the grating, control the resolution of the spectrometer. Typically, this is $0.1$ nm/mm of slit width for a moderately good spectrometer and 1 nm/mm for a general purpose one. If the slits cannot be closed to more than $0.1$ mm, then the resolution of the general purpose instrument will be approximately 0.1 nm and a narrow spectral line will appear to have this value even it is many times narrower. This is because the grating is rotated while measuring the spectrum and the spectral line is swept across the slits. The effect is to sequentially place a spectral line at all possible points, and hence wavelengths, across the slit. A signal is recorded at all these wavelengths rather than being measured only at its proper one, and the response measured is the convolution of the ideal width of the spectral line with the instrument response, which is the finite width of the slit. In many instruments, a CCD camera measures all wavelengths simultaneously, and a slit is not needed nor is the grating scanned. However, the same reasoning applies because the individual elements of the camera have a finite width, which therefore act as individual slits.\n\n**(iii)** A final use of convolution is to smooth data. Because convoluting one function with another involves integration, this has the effect of summing or averaging. The rolling or moving average method (Section 10.4) is in effect a convolution, and effectively smooths spiky data.\n\nIn the next sections, a convolution will be calculated by direct summation and by a Fourier transform. Convolution is related to the auto- and cross-correlations and these will also be described. How to go about estimating the true response from the convoluted response in real, that is experimental data, i.e. reversing the effects of convolution, is discussed in chapter 13 on numerical methods. This is usually done using iterative, non-linear least-squares methods, (See 13.6.7), because when using real data, which always contains noise, it is found that reverse transforming the convolution often results in a calculated ideal response that is so noisy as to be useless.\n\n\n\nFigure 26. Curves show the instrument response, as a series of impulses (dashed), which produce a response ($w$) at each point on its profile not all of which are shown. These are then added together in this time delayed manner, to produce the convoluted response.\n____\n\n## 7.2 How convolution works\n\nTo understand how convolution works, suppose that the overall instrument response is made up of a series of $\\delta$-function impulses. These can be infinitesimally narrow light pulses that excite a molecule. Suppose these impulses are made at ever shorter time intervals, then the effect is that of smoothly exciting the molecule. Each of the impulses elicits an ideal response but because there are many of them, their responses must be added together. The result is the convolution; the effect is shown in Fig. 26. It is always assumed in the convolution that the response is linear with the impulse, which simply means that doubling the impulse doubles the response and so forth.\n\nThe light pulses occur at each point in the dashed curve, Fig. 26. The response from each impulse is the decaying solid curve. To calculate the overall response at any given point along the x-axis, the effect of all previous impulses must be added into the calculation. Suppose that the pulse exciting the sample has a shape given by some function $f$, the ideal experimental response $w$, and the convolution $C$. The terms can be written down at each time if it is assumed, for the present, that the impulses are discrete and the data is represented as a series of points at times $1, 2, 3$, and so forth; $f$(6), for example, represents the value of $f$ at the sixth time position. The first point of the impulse is $f$(1) and this produces the response\n\n$$\\displaystyle f (1)[w(1) + w(2) + w(3) + \\cdots]$$\n\nThe second and third impulses produce\n\n$\\displaystyle f(2)[w(1) + w(2) + w(3) + \\cdots]$ and $f(3)[w(1) + w(2) + w(3) + \\cdots]$.\n\nThe convolution is the sum of these terms at times 1, 2, 3, and so on therefore;\n\n$$\\displaystyle\\begin{align}\nC(1)& = f (1)w(1)\\\\\nC(2)& = f (1)w(2) + f (2)w(1)\\\\\nC(3) &= f (1)w(3) + f (2)w(2) + f (3)w(1)\\\\\nC(4)& = f (1)w(4) + f (2)w(3) + f (3)w(2) + f (4)w(1)\\\\\n\\end{align}$$\n\nThese sums are shown in Fig. 27 by adding the products of $f$ and $w$ vertically. Clearly, only where both $f$ and $w$ are not zero, will this product have a value. The symmetry in these sums soon becomes apparent, each being the product of one series running to the right, and the other to the left; for instance, look at $C$(4). The name convolution arises from just this effect; the word also means 'folded' and this is shown in the form of the series where each function is folded back onto the other. Convolution is also the distribution of one function in accordance with a 'law' specified by another function (Steward 1987) because the whole of one function $w$, is multiplied with each ordinate of the other $f$, and the results added. The ideal response (the 'one function') is distributed, i.e. spread out according to the law or shape of the driving function $f$.\n\n\n\n\nFigure 27. Diagram showing the notation used to calculate a convolution.\n\n## 7.3 Convolution by summation\n\nWritten as a summation, the convolution at point $k$ is\n\n$$\\displaystyle C(k) = \\sum_{i=0}^k f(i)w(k - i ) \\tag{32}$$\n\nThis sum evaluates just one point; to calculate the whole convolution, the index $k$ must now be varied from 1 to $n$, which is the number of data points, making a double summation. One reason Fourier transforms are used to calculate convolutions is that the fast Fourier transform algorithm, FFT, is far quicker on the computer than calculating the convolution as a double summation, particularly for a large number of data points.\n\nThe algorithm to calculate the summation has a double loop to calculate all values of $k$ and to perform the summation in eqn. 32. The two functions used are those that produced Fig. 24, which are $\\displaystyle f(t) = e^{-t/100}$ and $\\displaystyle w(t) = e^{-(t-100)^2/1000}$, and $2^{10}$ points will be also be used to mimic the data produced by an instrument.\n\nFirst, because the data is discrete, arrays $f$ and $w$ are made; to hold the data points. Then two loops are made, one changes $k$ from 1 to $n$ the and inside one calculates $C(k)$. The indices are arranged as in equation 32. The variable $s$ accumulates the sum as the inner do loop progresses. This is a relatively slow calculation because of the double loop.\n\n\n```python\ndef do_convolution(f,w): # do by double summation \n # Sigma f(n-m)g(m) ; c(0) = f(0)w(0), c(1) = f(0)w(1) + f(1)w(0) etc \n n = len(f)\n c = [0.0 for i in range(n)]\n for k in range(n):\n s = 0.0\n for i in range(k):\n s = s + f[i]*w[k-i]\n pass\n c[k] = s\n return c\n\nn = 2**10\nf = [ np.exp(-i/100.0) for i in range(n)]\nw = [ np.exp(-(i-100)**2/1e3) for i in range(n)]\nt = [i for i in range(n)]\n\nC = do_convolution(f,w)\nmxc = max(C) # use to normalse\nplt.plot(t,C/mxc,color='red',label='C , convolution '+r'$f\\otimes w$')\nplt.plot(t,f,color='black',label='f(x)')\nplt.plot(t,w,color='blue',label='w(x)')\nplt.xlim([0,n])\nplt.legend()\nplt.show()\n```\n\n## 7.4 Convolution by Fourier transform\n\nThe convolution can also become an integral, by supposing that the points are separated by an infinitesimal amount, and therefore, the change $sum \\rightarrow \\int $ is allowable. The integral form of the convolution at time $u$, is\n\n$$\\displaystyle C(u)=\\int_0^\\infty f(t)w(u-t)dt \\tag{33}$$\n\nwhich represents the response at time $u$ to an impulse delivered at time $t$. The limits to the integral are often represented as $\\pm \\infty$. If the signal is zero at times less than zero, then the lower limit can be made zero as illustrated. The convolution integral is frequently written as,\n\n$$\\displaystyle C(t) = f (t) \\otimes w(t) \\qquad \\text{ or } \\qquad C = f \\otimes w. \\tag{34} $$\n\nThe convolution is performed by Fourier transforming functions $f$ and $w$ separately, multiplying the transforms together and then inverse transforming. The symbol $\\otimes$ represents all these calculations because the result is returned in the time domain. Sometimes, the convolution is written only as a conversion into the frequency domain as\n\n$$\\displaystyle f(t)\\otimes w(t) = \\sqrt{2\\pi} F(\\omega)W(\\omega)$$\n\nwhere $F$ and $W$ are the respective transforms of $f$ and $w$, $\\omega$ being angular frequency. Thus convolution in 'normal' space is multiplication in 'Fourier' space. \n\nIf $T$ represents the Fourier transform and $T[\\cdots]^{-1}$ the inverse transform the convolution is formally written as\n\n$$\\displaystyle C = T[T( f )T(w)]^{-1} \\tag{35} $$\n\nwhich is the same as equation 34. If the equations describing $f$ and $w$ are known, an exponential and a Gaussian for example, then the Fourier transform integral of each can be calculated as described in Section 6, the product of these multiplied and the inverse transform integral then calculated. The result is the convolution of the two functions. \n\nAs an example, consider convoluting a square pulse with two delta functions. Their convolution will produce two square pulses centred on the two delta functions, because, as the pulse is swept past the two deltas, only at their overlap will their product have a finite value. Three stages of the convolution are shown at the top of Fig. 28, and the result is shown below this.\n\n\n\nFigure 28. Convolution as Fourier transforms.\n____\n\nNext, the convolution is evaluated using Fourier transforms. The transforms of the two delta functions and the pulse have already been calculated, and are shown in Fig. 29. This product of the two transforms is then reverse transformed and two square pulses are produced.\n\nThis last convolution is, incidentally, another way of describing the interference due to a double slit, and if many delta functions are used then this describes the effect of a diffraction grating on light waves.\n\nThe data needed in a convolution is frequently a list of numbers because it comes from an experiment and in this case a numerical method has to be used to do the transform, which is then called a Discrete Fourier Transform. This is described further in Section 9, but here is an example some code to illustrate convolution using discrete Fourier transforms.\n\n\n\nFigure 29. Left: The two waveforms are the Fourier transform of a square pulse (top) and two delta functions (lower). When these are multiplied together and reverse transformed two pulses are produced which is the convolution of the delta functions and the single square pulse. The same method has been used to make Fig. 24, even though the functions differ.\n\n\n```python\n# convolution by fourier transform\n\nn = 2**10\nf = [ np.exp(-i/100.0) for i in range(n)]\nw = [ np.exp(-(i-100)**2/1e3) for i in range(n)]\nt = [i for i in range(n)]\n\nF = np.fft.rfft(f) # use rfft as input in only real \nW = np.fft.rfft(w)\nC = np.fft.irfft(F*W)\n\nmxc = max(C) # use to normalse\n\nplt.plot(t,C/mxc,color='red',label='C , convolution '+r'$f\\otimes w$')\nplt.plot(t,f,color='black',label='f')\nplt.plot(t,w,color='blue',label='w')\nplt.plot()\nplt.xlim([0,n])\nplt.legend()\nplt.show()\n```\n\n## 7.5 A warning\n\nFinally a warning about using Fourier transforms to perform convolution. The transform assumes that the function being transformed is periodic, this means that if the signal is not of the same size, such as zero, at its start and end there is a frequency associated with changing from end to start so that this will appear as an artefact in the convolution. THis occurs because the transform assumes that the signal is periodic. This does not arise in the case of the summation method and even though this may be slower to calculate, it is more robust. The difference is shown in the next figure 29A. On the left is shown the summation based convolution calculation using an exponential, with lifetime of 10000, and a Gaussian and on the right using the Fourier transform method. All is not lost, however, because by padding the data with zeros to double its length the correct result can be obtained. \n\n\n\nFigure 29A. The figure shows the difference between the correct convolution done by summation ( red curve left ) and the artefact introduced by using the Fourier method ( red curve right ) this is produced when the functions are not the same, preferably zero, at the end of the data.\n\n\n## 8 Autocorrelation and cross-correlation\n\n\nA correlation is a function that measures the similarity of one set of data to another. A cross-correlation is formed if the data are dissimilar, an autocorrelation if there is only one set of data. The data might be a voltage from a detector, it might be an image or residuals from fitting a set of data. In Fig. 30 part of a noisy sinusoidal curve is shown in black and labelled 1. The second curve (2, red) is displaced only a little from the first and is clearly only slightly different; the third (3, grey) which is displaced by more is clearly different from the first as it is positive at large $x$ when the first curve is negative. The right-hand figure shows the autocorrelation of the curve (1) shown on the left, and as this is an oscillating curve, the autocorrelation also oscillates but eventually reaches zero. The oscillation is a result of the fact that a sinusoidal curve is similar to itself after each period, and the autocorrelation measures this similarity by increasing and decreasing. The autocorrelation is also less noisy that the data because it involves summing or integrating over many data points. \n\nA random signal with an average of zero will have an autocorrelation that averages to zero at all points except the first, whereas the autocorrelation of an exponential and similar functions will be not be zero, but decay away in some manner. The autocorrelation is a likened to a measure of the 'memory' a function has, that is, how similar one part of the data is with an earlier or later part. A zero average random signal has no memory because it is random, and each point is independent of its predecessor; this is not true of any other signal. The correlation is therefore a process by which we can compare patterns in data. In data analysis, the residuals, which are the difference between the data and a fitted function, should be random if the fit is correct; the shape of the autocorrelation is therefore a way of testing this.\n\n\n\nFigure 30. A sketch showing the first $120$ points of a set of noisy data of $250$ points. The data is still somewhat similar to itself when displaced by only a few points but much less so, when displaced by many, dashed grey curve. The autocorrelation of all the data is shown on the right. Notice also how as autocorrelation integrates the data, the noise is reduced.\n____\n\nIn ultra-fast (femtosecond) laser spectroscopy, autocorrelations are used to measure the length of the laser pulse because no electronic device is fast enough to do this, as they are limited to a time resolution of a few tens of picoseconds at best, but laser pulses can be less than $10$ fs in duration. In single molecule spectroscopy, the correlation of the number of fluorescent photons detected in a given time interval is used to determine the diffusion coefficient of the molecules. In the study of the electronically excited states of molecules, the correlation of time resolved spectra, recorded as the molecule moves on its potential energy surface, is a measure of excited state and solvent dynamics.\n\nThe correlation function is similar to, but different from, convolution. The autocorrelation is always symmetrical about zero displacement or lag, the cross-correlation is not. In the convolution the two functions $f$ and $w$ are folded on one another, the first point of $f$ multiplying the last of $w$ and so on, until the last point of $f$ multiplies the first of $w$, equation 31. In the auto- and cross-correlation, one function is also moved past the other and the sum of the product of each term is made but with the indices running in the _same direction_, both increasing. \n\nA cross-correlation is shown in Fig. 31 using a triangle and a rectangle, each with a base line, and for clarity, defined with only six points. The first term in auto- or cross-correlation $A$ occurs when point $f$(6) overlaps with $w$(1), when $f$ is to the far left of $w$. The position at $-5$ to the left is shown in the figure as $A$(-5). The middle term in the correlation is at zero displacement, or lag, and there is total overlap of the two shapes and the correlation is at a maximum. The figure on the right shows the last overlap, consisting of just one point in common between the two shapes. There are six terms in the summation of $A$(0) down to one in each of $A$(-5) and $A$(5). The zero lag term is\n\n$$\\displaystyle A(0) = f (1)w(1) + f (2)w(2) + \\cdots + f (6)w(6)$$\n\nThe next term has one point displacement between $f$ and $w$ and five terms are summed,\n\n$$A(1) = f (1)w(2) + f (2)w(3) + f (3)w(4) + f (4)w(5) + f (5)w(6)$$\n\nWith two points displaced, there are four terms\n\n$$\\displaystyle A(2) = f (1)w(3) + f (2)w(4) + f (3)w(5) + f (4)w(6) $$\n\nand so forth for the other terms. The last overlap is\n\n$$\\displaystyle A(5) = f (1)w(6) \\tag{36}$$\n\nOn the negative side, the indices are interchanged, $f$ for $w$ and vice versa, and the first (far left) term is\n$A(-5) = f (6)w(1)$ and similarly for the other terms. There are 11 terms in all or, in general $2n - 1$, for data of $n$ points. In an autocorrelation, $f$ and $w$ are the same function and therefore the autocorrelation must be symmetrical and only terms from zero to five are needed, the others being known by symmetry.\n\n\n\nFigure 31. A pictorial description of cross-correlation of the signals (functions) $w$ and $f$.\n____\n\nThe formula for the autocorrelation for $n$ data points is\n\n$$\\displaystyle A_a(k)=\\sum_{i=0}^{n-k}f(i)f(k+i) \\qquad k=0,1,\\cdots \\rightarrow \\cdots n \\tag{37}$$\n\nwhere the first value of the displacement $k$ is zero, and the last $n$, and both functions are now labelled $f$. Very often the autocorrelation is normalized; this means dividing by $\\sum f(i)^2$, \n\n$$\\displaystyle A_a(k)=\\frac{\\sum\\limits_{i=0}^{n-k}f(i)f(k+i)}{\\sum f(i)^2} \\tag{38}$$\n\nThese last two formulae produce just half of the autocorrelation. To produce the full correlation, symmetrical about zero lag, the mirror image of equation (37) must be added as points $-n \\to -1$ to the left-hand part of the data.\n\nThe cross-correlation uses a similar formula\n\n$$\\displaystyle A_c(k)=\\sum\\limits_{i=0}^{n-k} f(i)w(k+i) \\qquad k=-n+1,\\cdots 0, \\cdots n-1 \\tag{39}$$\n\nbut now $k$ always ranges from $-n + 1 \\to n - 1$. This distinction is crucial, otherwise the whole of the cross-correlation is not calculated.\n\nIn calculating a correlation as a summation with a computer, as with a convolution, each term in the correlation is a sum, so this means that two nested 'loops' are needed to calculate the whole function; one loop sums each individual term, the other calculates the sum, $A(k)$.\n\nSome authors define the correlation up to a maximum of $n$ in the summation, not $n - k$. There is, however, a pitfall in doing this because, if the correlation is not zero above half the length of the data, then this folds round and what is calculated is the sum of the correlation plus its mirror image. The way to avoid this is to add $n$ zeros to the data and the summation continued until $2n$. This should be done routinely if Fourier transforms are used to calculate the correlation.\n\nCorrelations and convolution are not restricted to digitized data but apply also to normal functions. Written as an integral, the cross-correlation of a real, i.e. not complex, function is\n\n$$\\displaystyle A_c =\\int_{-\\infty}^{\\infty}f(t)w(u+t)dt \\tag{40}$$\n\nand the autocorrelation of $f$,\n\n$$\\displaystyle A_c =\\int_{-\\infty}^{\\infty}f(t)f(u+t)dt \\tag{41}$$\n\nNotice that the sign in the second term is positive in the correlation but negative in a convolution, equation (33). If the function contains a complex number, then the conjugate is always placed on the left,\n\n$$\\displaystyle A_c =\\int_{-\\infty}^{\\infty}f(t)^*f(u+t)dt \\tag{41}$$\n\nThe normalised autocorrelation is \n\n$$\\displaystyle G(u) = \\frac{\\int\\limits_{-\\infty}^{\\infty}f(t)^*f(u+t)dt}{\\int\\limits_{-\\infty}^{\\infty}f(t)^2dt} =\\frac{\\langle f(t)\\,f(u+t)\\rangle}{\\langle f(t)^2\\rangle} \\tag{42}$$\n\nand the bracket notation indicates that these are average value. The denominator is the normalization term and is also the value of the numerator with $u = 0$.\n\n## 8.1 Calculating an autocorrelation\n\n**(i)** If the function is periodic then the integration limits should cover one period. The normalized autocorrelation of a cosine $A\\cos(2\\pi\\nu t + \\varphi)$, where the period is $T = 1/\\nu$ and $\\varphi$ is the phase, is calculated as\n\n$$\\displaystyle G(u) = \\frac{\\int\\limits_0^T \\cos(2\\pi \\nu t+\\varphi)\\cos(2\\pi \\nu (u+t)+\\varphi)dt}{\\int\\limits_0^T \\cos^2(2\\pi \\nu t+\\varphi)dt}$$\n\nand the result will be independent of the phase. The normalisation integral is a standard one and can be looked up or converted to an exponential form to simplify integration. The result is $\\displaystyle \\int_0^T \\cos(2\\pi t/T+\\varphi)^2dt = T/2$. The other integral can similarly be calculated. Using SymPy, this is\n\n\n```python\nt,phi,T, u = symbols('t phi T u',positive =True)\n\nf01 = cos(2*pi*t/T+phi)*cos(2*pi*t/T+phi+2*pi*u/T )\n\nG = integrate(f01,(t,0,T),conds='none') # slow calculation\nsimplify(G)\n```\n\nfrom which it is seen that the normalised autocorrelation is also a cosine $\\displaystyle G(u) = \\cos(2\\pi \\frac{u}{T})$. If the initial cosine is written as $\\cos(\\omega t + \\varphi)$ then the period $T = 2\\pi/\\omega$.\n\nIf the trigonometric function is a complex exponential $\\displaystyle Ae^{-i(\\omega t+\\varphi)}$ rather than a sine or cosine then the complex conjugate of the function is taken in both of the autocorrelation integrals. The normalization could not be simpler $\\int_0^Tdt = T$. The correlation is also a very straightforward integral;\n\n$$\\displaystyle G(u)=\\frac{1}{T}\\int\\limits_0^T e^{-i\\omega t+\\varphi}e^{i\\omega (u+t)+\\varphi}dt =\\frac{1}{T}\\int\\limits_0^T e^{i\\omega u}dt=e^{i\\omega u}$$\n\nUsing the Euler relationship, $\\displaystyle e^{-i\\theta} = \\cos(\\theta) + i \\sin(\\theta)$, the real or imaginary parts of the function give the cosine or sine result respectively.\n\n**(ii)** If the function is not periodic, then the limits must be determined by the function being used. The normalized autocorrelation $A(u)$ of the function $f(t) = e^{-at}$, when $t \\ge 0$ and $f (t) = 0$ when $t \\lt 0$, will be calculated, and also its full width at half-maximum, fwhm. The integration limits can be changed from those in equation (42) because the function is zero for $t \\lt 0$ and the lower limit can be zero. The normalization, using equation (42), is\n\n$$\\displaystyle \\int_{-\\infty}^{\\infty} f(t)^2dt=\\int_0^\\infty e^{-2at}dt = \\frac{1}{2a}$$\n\nand the autocorrelation\n\n$$\\displaystyle \\int_{-\\infty}^{\\infty} f(t)f(u+t)dt=\\int_0^\\infty e^{-at}e^{-a(u+t)}dt =e^{-au}\\int_0^\\infty e^{-2at}dt=\\frac{e^{-au}}{2a}$$\n\nImportantly, the autocorrelation must be an even function because it is symmetrical thus it is $\\displaystyle A(u) = \\frac{e^{-a|u|}}{ 2a}$ therefore, the value of $u$ must always be positive. The normalised autocorrelation is $\\displaystyle A(u)=e^{-a|u|}$. The $|u|$ does not follow from the mathematics; it is imposed by our knowledge of symmetry of the function.\n\nAs a check, at $u = 0,\\, A(0) = 1$, which is correct and the function is even or symmetrical about its y-axis, or, $u = 0$. The _fwhm_ is calculated when $\\displaystyle A(u_h) = 0.5 = e^{-a|u_h|}$ or $\\displaystyle |u_h|=a^{-1}\\ln(2)$ and thus _fwhm_ is $\\displaystyle 2a^{-1}\\ln(2)$. This is twice as wide in this instance as the initial function.\n\n**(iii)** The duration of a short laser pulse is often measured as an autocorrelation with an optical correlator. If the intensity profile $I$ of the short laser pulse is a Gaussian centred at zero $\\displaystyle I = e^{-2(t/a)^2}$, it is possible to calculate the width of its normalized autocorrelation. If the calculated autocorrelation shape is compared with an experimentally measured one, an estimation of the laser pulse's duration can be made. The optical correlator to do this measurement is a Michelson interferometer; the path length in one arm is changed relative to the other so that one pulse is moved past the other in time. The pulses are combined in a frequency doubling crystal, and a signal is detected only when the pulses overlap. \n\nTo achieve this, the doubled frequency, which is in the ultraviolet part of the spectrum, is separated from the fundamental wavelength by a filter. The size of the signal vs the distance the mirror moves, which is proportional to time, is the autocorrelation see Fig. 32. \n\n\n\nFigure 32. Schematic of an optical autocorrelator used to measure the duration of pico- and femtosecond laser pulses.\n____\n\nThe pulse is centred at zero delay and (theoretically) extends from $-\\infty$ to $\\infty$, which are the integration limits of the autocorrelation, equation (42). The autocorrelation integral is\n\n$$\\displaystyle A(u)=\\int\\limits_{-\\infty}^{\\infty} e^{-t^2/a^2}e^{-(u+t)^2/a^2}dt = a\\sqrt{\\frac{\\pi}{2}} e^{-u^2/(2a^2)}$$\n\nand the calculation with SymPy is\n\n\n```python\nt, u, a =symbols('t u a',positive=True)\nf01= exp(-(t/a)**2)*exp(-((u+t)**2)/a**2)\nG= simplify(integrate(f01, (t,-oo,oo), conds='none')) # oo is infinity\nG.doit()\n```\n\nThe normalization integration can be looked up but need not be worked out because it is the value of autocorrelation when $u$ = 0. The normalization equation is therefore $\\displaystyle \\int e^{-2t^2/a^2}dt=a\\sqrt{\\pi /2}$.\n\nThe normalized autocorrelation $G(u)$ is also a Gaussian, with a value $\\displaystyle G(u)=e^{-u^2/(2a^2)}$.\n\nThe _fwhm_ of this function is calculated when $G(u)=1/2$ and is $a\\sqrt{2\\ln(2)}$ and that of the original pulse is $a\\sqrt{\\ln(2)}$ therefore, the autocorrelation is $\\sqrt{2} \\approx$ 1.414 times wider than the pulse. Knowing this factor provides a convenient way of measuring the duration of a short laser pulse assuming it has a Gaussian profile.\n\n**(iv)** The randomness or otherwise of the autocorrelation of the residuals obtained from fitting real data to a model (theory) is important when determining the 'goodness of fit'. The function is now a set of data points not an equation. The data in Fig. 33 shows the autocorrelation of a random sequence of values where the mean is 0 (left) and $1/2$ (right). When the mean is zero, only the first point has a value not essentially zero. When the mean is $1/2$, there is a correlation between each point, and this decreases as the separation between points increases. Since the mean is $1/2$ (or any value not zero), this means that each point is related to all the others, because, besides random fluctuations, they all have the same underlying value. Their correlation becomes less the further they are separated. \n\nThe normalized autocorrelation of any line $y$ = constant, is a sloping straight line starting at $1$ and ending at $0$. This is to be expected, because at zero displacement the line is overlapped with itself, whereas at the maximum displacement, only one term remains, see equation (36), and this value is small. In Fig. 33, the random noise has a large correlation at zero displacement because the whole trace must be perfectly correlated with itself; its value is 1 but only because the autocorrelation is normalized.\n\nIn calculating the autocorrelation of residuals from a set of fitted data, the mean value of the data is always subtracted first to prevent this sloping effect on the autocorrelation shown on the right of Fig. 9.33. Of course, if after doing this the autocorrelation is still sloping, then it clearly is not equally distributed about zero and the model used to describe the data may not be correct.\n\nThe autocorrelation calculation is shown below.\n\n\n```python\ndef do_autoc(f,w): # correlation call as (w,w) for autocorrelation ac(k)= sum_i=0^{n-k} f(i)w(k+i) /norm\n n = len(w)\n ac = [0.0 for i in range(n)]\n sf = sum([f[i]**2 for i in range(n)])\n sw = sum([w[i]**2 for i in range(n)])\n normfw = np.sqrt(sf*sw)\n for k in range(n-1):\n s = 0.0\n for i in range(n-k):\n s = s + f[i]*w[k+i]\n ac[k] = s\n \n return ac/normfw\n#-------------\n\nfig1= plt.figure(figsize=(8.0,4.0))\nax0 = fig1.add_subplot(1,2,1)\nax1 = fig1.add_subplot(1,2,2)\n\nn = 250\ns = [ np.random.rand() for i in range(n)]\nt0= [i for i in range(n)]\n\nss = sum(s)/n # get average \ns0 = [s[i] - ss for i in range(n)] # subtract average\n\nax0.plot(t0, do_autoc(s0,s0),color='blue')\nax0.axhline(0,color='black',linewidth=1)\nax0.set_xlabel('x')\nax0.set_title('autocorrelation, av = 0')\nax0.set_yticks([-0.5,0.0,0.5,1])\n\nax1.plot(t0, do_autoc(s,s),color='blue')\nax1.axhline(0,color='black',linewidth=1)\nax1.set_xlabel('x')\nax1.set_title('autocorrelation, av = 0.5')\nax1.set_yticks([-0.5,0.0,0.5,1])\nplt.tight_layout()\n\nplt.show()\n```\n\nFig. 33 Normalized autocorrelations of $250$ random numbers with an average of $0$ (left) and an average of $1/2$ (right). Only the right-hand half of the autocorrelation is calculated and plotted. The left-hand part is the exact mirror image.\n\n_____\n\n## 8.2 Autocorrelation of fluctuating and noisy signals\n\nThe autocorrelation of noise is now considered, and in the next section this will lead to understanding the shape of a spectroscopic transition and this is illustrated with NMR. Any experimental measurement is accompanied by noise. When measuring the properties of single atoms, molecules, or photons, considerable fluctuations in their measured values are expected and many events have to be averaged to obtain a precise result. The measured property might be energy, velocity, the number of photons in a given period measured by a photodiode, or the current in a transistor or diode when this is so small that discrete charge events are recorded. This latter noise is called _shot noise_. If you could hear shot noise, the effect would be rather similar to the sound of heavy rain falling on a car's roof. \n\nThere is thermal noise in all resistors in electrical circuits that causes fluctuations in the current. These fluctuations are caused by the thermal motion of the many electrons as they pass through the inhomogeneous material forming the body of the resistor. The frequency of the noise measured on an oscilloscope is determined by the frequency with which the circuitry responds and therefore depends on the capacitance, resistance, and inductance. This generally produces noise with a spread of frequencies of about equal amplitude, except for multiples of mains frequency and those of switched-mode power supplies, and is called _white noise_. At low frequencies, the amplitude of the noise increases in direct proportion to $1/f$ where $f$ is frequency and is therefore called '$1/f$' noise. The origin of $1/f$ noise is not fully understood.\n\nOn the macroscopic scale, random noise also accompanies experimental measurements. Measuring the amount of any of the many trace gases, such as CO$_2$, IO$_2$, and NOx, in the atmosphere using optical techniques is an inherently noisy process. This is due to the continuous and erratic motion of air packets along the line of sight during the measurement and from one measurement to another. The frequency of the noise is, however, mostly limited to the speed at which the air changes. \n\nIn the laboratory, all sorts of noise sources can affect an experiment; mostly these are due to voltage or current ripple in DC power supplies. In sensitive laser experiments, noise can be caused by dust particles in the air, vibrations of the building and from the air flow coming from air conditioning units. Atomic force microscopes have in the past needed to be suspended inside a sound proof box by elastic bungee ropes, to avoid adding noise to the measurements from the vibrations of the building and from nearby traffic. \n\nIn an attempt to reduce noise a Fourier transform and an autocorrelation of the signal will provide information about the frequencies present, and how quickly they change, or alternatively, how long the noise persists, and hence the possible source. The transform can also be used to remove noise as illustrated in Section 10.\n\nSuppose that the noise on a measurement is represented by some fluctuating signal $f(t)$, the frequency of which is determined by the nature of the experiment and by the measuring apparatus. This signal will be represented by a general Fourier series similar to that in Section 1.1 but where $T$ is the period over which a measurement is made and the summation starts from zero as this makes the resulting equations simpler,\n\n$$\\displaystyle f(t)=\\sum\\limits_{n=0}^\\infty a_n\\cos \\left(\\frac{2\\pi n t}{T}\\right)+\\sum\\limits_{n=0}^\\infty b_n\\sin\\left(\\frac{2\\pi n t}{T}\\right)$$\n\nFollowing Davidson (1962, chapter 14), the time average of $f$ and $f^2$ is the respective integral divided by the time interval $T$. The average $\\langle f \\rangle$ is zero because the noise is random, but the average of $f^2$ is not; the integral is\n\n$$\\displaystyle \\langle f^2 \\rangle =\\frac{1}{T}\\int\\limits_0^T\\left [\\sum\\limits_{n=0}^\\infty a_n\\cos \\left(\\frac{2\\pi n t}{T}\\right)+\\sum\\limits_{n=0}^\\infty b_n\\sin\\left(\\frac{2\\pi n t}{T}\\right) \\right]^2 dt$$\n\nwhich simplifies considerably because of the orthogonality of the cosine integrals such as $\\displaystyle \\int \\cos(2\\pi \\frac{nt}{T})\\sin(2\\pi \\frac{mt}{T})dt=0$, $n$ and $m$ being integers, and the result is very simple;\n\n$$\\displaystyle \\langle f^2\\rangle = \\frac{1}{2}\\sum_n(a_n^2+b_n^2) $$\n\nThis expression can also represent the average of many measurements if the coefficients $a$ and $b$ themselves represent average values. This means that the _ergodic hypothesis_ (or ergodic condition) applies, i.e. for a stationary system each part comprising the ensemble (of particles) will pass through all values accessible to it, given a sufficiently long time. Thus the time average is the same for all parts of the ensemble. This also means that the time average is the equivalent to the ensemble average. To explain further; the word 'stationary' means that there is no preferred origin for the measurement, thus any time period over which measurements are made is just as good as any other. The ensemble average is taken over all coordinates of a system at a fixed time. The time average considers just a part of the ensemble averaged over a sufficiently long time. If the ergodic hypothesis applies these averages are equal.\n\nThe variance (the square of the standard deviation) on the signal is $\\sigma^2=\\langle f^2\\rangle - \\langle f\\rangle^2 $ and in this case the standard deviation is $\\sqrt{\\langle f^2\\rangle}$ and is the determined only by the amplitudes $a$, $b$ of the noise. The energy in the noise is $a^2 + b^2$. \n\nThe autocorrelation of $f(x)$ is \n\n$$\\displaystyle A(u) =\\langle f(t)f(u+t)\\rangle =\\frac{1}{T}\\int_0^Tf(t)f(t+u)dt$$\n\nwhich looks quite complicated when the substitution for $f$ is made. However, using the formulas for $\\sin(A + B), \\cos(A + B)$ and the orthogonality rules, a remarkably simple result is produced:\n\n$$\\displaystyle A(u)=\\frac{1}{2}\\sum_n\\left(a_n^2+b_n^2\\right)\\cos\\left(\\frac{2\\pi nu}{T} \\right) \\tag{43}$$\n\nwhich is an oscillating signal that will repeat itself with a period $T$.\n\n## 8.3 Wiener–Khinchin relations\n\nThe autocorrelation (equation (43)) is related to the energy or power in a given signal. For example, with electromagnetic radiation the energy is the square of the amplitude $E$ of the electric field, the field is given by the constants $a$ and $b$ thus $a^2 + b^2$ represents the energy. This is also true of a sound wave in a fluid where the energy is proportional to the square of the oscillating pressure. There are other examples; the power dissipated in a resistor is proportional to the current squared and the kinetic energy of a molecule is proportional to the square of the velocity. Thus, in general if the signal is $f$, $\\langle f^2\\rangle$ represents the average energy or power. The period $T$ (equation (43)) is somewhat arbitrary and can reasonably take on any value; therefore, it is possible to define $n/T \\equiv \\nu_n$ as a frequency. The amount of power $P$ in a small frequency interval from $\\nu$ to $\\nu + \\nu + \\delta \\nu$ is therefore $\\displaystyle P(\\nu)d\\nu = \\frac{1}{2}\\left(a_\\nu^2 + b_\\nu^2\\right)$ and the autocorrelation can be written as an integral over frequencies rather than a summation over index $n$. This effectively means that there are so many terms in the sum that it can be changed into an integral without any significant error, and doing this produces the autocorrelation;\n\n$$\\displaystyle A(u)=\\int_{v=0}^\\infty P(\\nu)\\cos(2\\pi\\nu u)d\\nu \\tag{44}$$\n\nComparing this equation with a Fourier transform equation, the power spectrum is\n\n$$\\displaystyle P(\\nu) = 4\\int_{u=0}^\\infty A(u)\\cos(2\\pi\\nu u)d\\nu \\tag{45}$$\n\nand these two equations are known as the _Wiener - Khinchin_ relationships: the power spectrum $P(\\nu)$ and autocorrelation $A(u)$ form a Fourier transform pair. Very often the transform pair involve time and frequency, in which case the changes $u\\to t$ and $P(\\nu) \\to J(\\nu)$ are commonly made. In NMR and other spectroscopies $J(\\omega)$ is called the spectral density.\n\nThe power spectrum is proportional to what we would normally observe in a spectroscopic experiment, as the change in the signal vs frequency. The width of the signal is determined by the autocorrelation and this is determined by the noise. If the noise is due to a random process then it is often found that the autocorrelation decays exponentially as $\\displaystyle e^{-t/\\tau}$ with rate constant $k=1/\\tau$. In this case the power spectrum $J(\\nu)$ is\n\n$$\\displaystyle J(\\nu) =4\\int_{u=0}^\\infty e^{-u/\\tau}\\cos(2\\pi \\nu u)du = \\frac{4\\tau}{1+(2\\pi\\nu \\tau)^2} \\tag{46}$$\n\nand the integral is most easily evaluated by converting the cosine to its exponential form. \n\nThe nature of the random processes contributing to the power spectrum is now considered using NMR as an example. The nuclear spin angular momentum in a molecule remains in fixed precessing motion governed by the external magnetic field, but the molecules themselves also undergo random rotational diffusion due to thermal agitation when in solution. This random motion causes the nuclear spin to experience a fluctuating magnetic field in addition to the applied external field. Therefore, those nuclei undergoing NMR transitions experience this fluctuating field and its effect is to return the nuclear spin population to equilibrium with a lifetime called T1 (Sanders & Hunter 1987; Levitt 2001). The timescale of these fluctuations is of the order of tens of picoseconds because this is the timescale of molecular rotation. ( Translational diffusion is far slower ). The molecular rotation rate constant and hence frequency is similar to that of the NMR transition frequency (Larmor frequency) and therefore rotational diffusion can greatly influence the return to equilibrium of the nuclear spins and can dominate both the T1 and T2 decay processes. Loss of spin coherence is characterized by the lifetime T2. \n\nMolecular translational diffusion is far slower than rotation and so causes magnetic field fluctuations at a far lower frequency than the NMR transition and is therefore less important for T1 processes. Similarly, vibrational motion is too high to influence the NMR transition. Large molecules in a viscous solvent have a sluggish response and a small rotational diffusion coefficient, and long rotational relaxation times, and _vice versa_. However, while different solvents and molecules of different sizes will change the frequency of the random magnetic field fluctuations, the timescale remains comparable to that of the NMR transition. In proteins, while overall rotation can be slow, approximately tens of nanoseconds, faster local motion of residues called 'wobbling in a cone' motion still occurs. \n\nThe autocorrelation of rotational diffusion can be shown to be an exponentially decaying function with a lifetime $\\tau$ proportional to the reciprocal of the rotational diffusion coefficient. Fig. 34 shows the spectral density calculated for different rotational relaxation times. The coupling of the magnetic field fluctuations is most effective when $1/2\\pi\\tau$ is close to the Larmor frequency and therefore molecules of different sizes will be affected differently.\n\nWhen plotted on a linear scale the spectral density of a slowly decaying exponential autocorrelation, equation 46, is a narrow function centred at zero frequency, whereas the rapidly decaying autocorrelation has the same shape but is wide. Zero frequency here means the transition frequency, see fig 34. The line-width is a consequence of the time-energy or time-frequency uncertainty, causing a wide spectral line when processes are rapid and vice versa. When plotted on a linear - log scale the power spectrum is constant over a wide range of low frequencies, and this is called 'white noise'. It rapidly decreases, centred about the frequency $1/2\\pi\\tau$ as is shown in the figure. If the noise were completely random, the power spectrum would be constant at all frequencies.\n\nThe Weiner - Khinchin theorem also shows that the autocorrelation of the signal $f$ is the squared modulus of its Fourier transform $g(k)$. Apart from a constant of proportionality, this is\n\n$$\\displaystyle A(u) =\\int_{-\\infty}^\\infty f^*(t)f(u+t)dt = |g(t)|^2$$\n\nBecause the squared modulus of the Fourier transform is produced, the autocorrelation has lost all phase information so it is not possible to invert or reverse $g(k)$ to produce the original function $f$. Thus, in the NMR case, it is not possible to measure the spectral density, which is proportional the shape of the NMR transition, and then work backwards to obtain the function that produced this shape. All that can be done is to generate a model of the interactions, such as rotational diffusion, and, for example, by a non-linear, least-squares method fit this theoretical model to the data.\n\n\n\nFigure 34. Left: Power spectra (or spectral density) vs. frequency for a signal that has an exponential autocorrelation function, the decay lifetimes of the exponentials are from $1 \\to 100$ ps. The density of the fluctuation in the noise is almost constant at lower frequencies and this is called 'white noise'. \n", "meta": {"hexsha": "92c3d470b7af4ccf19fe2e7688ace3602a6304fd", "size": 122862, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter-9/fourier-D.ipynb", "max_stars_repo_name": "subblue/applied-maths-in-chem-book", "max_stars_repo_head_hexsha": "e3368645412fcc974e2b12d7cc584aa96e8eb2b4", "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": "chapter-9/fourier-D.ipynb", "max_issues_repo_name": "subblue/applied-maths-in-chem-book", "max_issues_repo_head_hexsha": "e3368645412fcc974e2b12d7cc584aa96e8eb2b4", "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": "chapter-9/fourier-D.ipynb", "max_forks_repo_name": "subblue/applied-maths-in-chem-book", "max_forks_repo_head_hexsha": "e3368645412fcc974e2b12d7cc584aa96e8eb2b4", "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": 186.7203647416, "max_line_length": 21356, "alphanum_fraction": 0.838705214, "converted": true, "num_tokens": 11758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.19930799790404563, "lm_q1q2_score": 0.09188433128490893}} {"text": "# Practical Session 1: Data exploration and regression algorithms\n\n*Notebook by Ekaterina Kochmar*\n\n## 0.1. Dataset\n\nThe California House Prices Dataset is originally obtained from the StatLib repository. This dataset contains the collected information on the variables (e.g., median income, number of households, precise geographical position) using all the block groups in California from the 1990 Census. A block group is the smallest geographical unit for which the US Census Bureau publishes sample data, and on average it includes $1425.5$ individuals living in a geographically compact area. The [original data](http://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html) contains $20640$ observations on $9$ variables, with the *median house value* being the dependent variable (or *target attribute*). The [modified dataset](https://www.kaggle.com/camnugent/california-housing-prices) from Aurelien Geron, *Hands-On Machine Learning with Scikit-Learn and TensorFlow* contains an additional categorical variable.\n\nFor more information on the original data, please refer to Pace, R. Kelley and Ronald Barry, *Sparse Spatial Autoregressions*, Statistics and Probability Letters, 33 (1997) 291-297. For the information on the modified dataset, please refer to Aurelien Geron, *Hands-On Machine Learning with Scikit-Learn and TensorFlow*, O′Reilly (2017), ISBN: 978-1491962299.\n\n## 0.2. Understanding your task\n\nYou are given a dataset that contains a range of attributes describing the houses in California. Your task is to predict the median price of a house based on its attributes. That is, you should train a machine learning (ML) algorithm on the available data, and the next time you get new information on some housing in California, you can use your trained algorithm to predict its price.\n\nThe questions to ask yourself before starting a new ML project:\n- Does the task suggest a supervised or an unsupervised approach?\n- Are you trying to predict a discrete or a continuous value?\n- Which ML algorithm is most suitable?\n\nTry to answer these questions before you start working on this task, using the following hints:\n- *Supervised* approaches rely on the availability of target label annotation in data; examples include regression and classification approaches. *Unsupervised* approaches don't use annotated data; clustering is a good example of such approach.\n- *Discrete* variables are associated with classes and imply classification approach. *Continuous* variables are associated with regression.\n\n## 0.3. Machine Learning check-list\n\nIn a typical ML project, you need to:\n\n- Get the dataset\n- Understand the data, the attributes and their correlations\n- Split the data into training and test set\n- Apply normalisation, scaling and other transformations to the attributes if needed\n- Build a machine learning model\n- Evaluate the model and investigate the errors\n- Tune your model to improve performance\n\nThis practical will show you how to implement the above steps.\n\n## 0.4. Prerequisites\n\nSome of you might have used Jupiter notebooks with the following libraries before in the [CL 1A Scientific Computing course](https://www.cl.cam.ac.uk/teaching/1920/SciComp/materials.html).\n\nTo run the notebooks on your machine, check if `Python 3` is installed. In addition, you will need the following libraries:\n\n- `Pandas` for easy data uploading and manipulation. Check installation instructions at https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html\n- `Matplotlib`: for visualisations. Check installation instructions at https://matplotlib.org/users/installing.html\n- `NumPy` and `SciPy`: for scietinfic programming. Check installation instruction at https://www.scipy.org/install.html\n- `Scikit-learn`: for machine learning algorithms. Check installation instructions at http://scikit-learn.org/stable/install.html\n\nAlternatively, a number of these libraries can be installed in one go through [Anaconda](https://www.anaconda.com/products/individual) distribution. \n\n## 0.5. Learning objectives\n\nIn this practical you will learn how to:\n\n- upload and explore a dataset\n- visualise and explore the correlations between the variables\n- structure a machine learning project\n- select the training and test data in a random and in a stratified way\n- handle missing values\n- handle categorical values\n- implement a custom data transformer\n- build a machine learning pipeline\n- implement a regression algorithm\n- evaluate a regression algorithm performance\n\nIn addition, you will learn about such common machine learning concepts as:\n- data scaling and normalisation\n- overfitting and underfitting\n- cross-validation\n- hyperparameter setting with grid search\n\n\n## Step 1: Uploading and inspecting the data\n\nFirst let's upload the dataset using `Pandas` and defining a function pointing to the location of the `housing.csv` file:\n\n\n```python\nimport pandas as pd\nimport os\n\ndef load_data(housing_path):\n csv_path = os.path.join(housing_path, \"housing.csv\")\n return pd.read_csv(csv_path)\n```\n\nNow, let's run `load_data` using the path where you stored your `housing.csv` file. This function will return a `Pandas` DataFrame object containing all the data. It is always a good idea to take a quick look into the uploaded dataset and make sure you understand the data you are working with. For example, you can check the top rows of the uploaded data and get the general information about the dataset using `Pandas` functionality as follows:\n\n\n```python\nhousing = load_data(\"housing/\")\nhousing.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_valueocean_proximity
0-122.2337.8841.0880.0129.0322.0126.08.3252452600.0NEAR BAY
1-122.2237.8621.07099.01106.02401.01138.08.3014358500.0NEAR BAY
2-122.2437.8552.01467.0190.0496.0177.07.2574352100.0NEAR BAY
3-122.2537.8552.01274.0235.0558.0219.05.6431341300.0NEAR BAY
4-122.2537.8552.01627.0280.0565.0259.03.8462342200.0NEAR BAY
\n
\n\n\n\nRemember that each row in this table represents a block group (housing district), and each column an attribute. How many attributes does the dataset contain? \n\nAnother way to get the summary information about the number of instances and attributes in the dataset is using `info` function. It also shows each attribute's type and number of non-null values:\n\n\n```python\nhousing.info()\n```\n\n \n RangeIndex: 20640 entries, 0 to 20639\n Data columns (total 10 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 20640 non-null float64\n 1 latitude 20640 non-null float64\n 2 housing_median_age 20640 non-null float64\n 3 total_rooms 20640 non-null float64\n 4 total_bedrooms 20433 non-null float64\n 5 population 20640 non-null float64\n 6 households 20640 non-null float64\n 7 median_income 20640 non-null float64\n 8 median_house_value 20640 non-null float64\n 9 ocean_proximity 20640 non-null object \n dtypes: float64(9), object(1)\n memory usage: 1.6+ MB\n\n\nBefore proceeding further, think about the following: \n- How is the data represented? \n- What do the attribute types suggest? \n- Are there any missing values in the dataset? If so, should you do anything about them? \n\nYou must have worked with numerical values before, and the data types like `float64` should look familiar. However, *ocean\\_proximity* attribute has values of a different type. You can inspect the values of a particular attribute in the DataFrame using the following code:\n\n\n```python\nhousing[\"ocean_proximity\"].value_counts()\n```\n\n\n\n\n <1H OCEAN 9136\n INLAND 6551\n NEAR OCEAN 2658\n NEAR BAY 2290\n ISLAND 5\n Name: ocean_proximity, dtype: int64\n\n\n\nThe above suggests that the values are categorical: there are $5$ categories that define ocean proximity. ML algorithms prefer to work with numerical data, besides all the other attributes are represented using numbers. Keep that in mind, as this suggests that you will need to cast the categorical data as numerical.\n\nFor now, let's have a general overview of the attributes and distribution of their values (note *ocean_proximity* is excluded from this summary):\n\n\n```python\nhousing.describe()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \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
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_value
count20640.00000020640.00000020640.00000020640.00000020433.00000020640.00000020640.00000020640.00000020640.000000
mean-119.56970435.63186128.6394862635.763081537.8705531425.476744499.5396803.870671206855.816909
std2.0035322.13595212.5855582181.615252421.3850701132.462122382.3297531.899822115395.615874
min-124.35000032.5400001.0000002.0000001.0000003.0000001.0000000.49990014999.000000
25%-121.80000033.93000018.0000001447.750000296.000000787.000000280.0000002.563400119600.000000
50%-118.49000034.26000029.0000002127.000000435.0000001166.000000409.0000003.534800179700.000000
75%-118.01000037.71000037.0000003148.000000647.0000001725.000000605.0000004.743250264725.000000
max-114.31000041.95000052.00000039320.0000006445.00000035682.0000006082.00000015.000100500001.000000
\n
\n\n\n\nTo make sure you understand the structure of the dataset, try answering the following questions: \n- How can you interpret the values in the table above?\n- What do the percentiles (e.g., $25\\%$ or $50\\%$) tell you about the distribution of values in this dataset (you can select one particular attribute to explain)? \n- How are the missing values handled?\n\nRemember that you can always refer to [`Pandas`](https://pandas.pydata.org/pandas-docs/stable/reference/index.html) documentation.\n\nAnother good way to get an overview of the values distribution is to plot histograms. This time, you'll need to use `matplotlib`:\n\n\n```python\n%matplotlib inline \n#so that the plot will be displayed in the notebook\nimport matplotlib.pyplot as plt\n\nhousing.hist(bins=50, figsize=(20,15))\nplt.show()\n```\n\nTwo observations about this graphs are worth making:\n- the *median_income*, *housing_median_age* and the *median_house_value* have been capped by the team that collected the data: that is, the values for the *median_income* are scaled by dividing the income by \\\\$10000 and capped so that they range between $[0.4999, 15.0001]$ with the incomes lower than $0.4999$ and higher than $15.0001$ binned together; similarly, the *housing_median_age* values have been scaled and binned to range between $[1, 52]$ years and the *median_house_value* – to range between $[14999, 500001]$. Data manipulations like these are not unusual in data science but it's good to be aware of how the data is represented;\n- several other attributes are \"tail heavy\" – they have a long distribution tail with many decreasingly rare values to the right of the mean. In practice that means that you might consider using the logarithms of these values rather than the absolute values.\n\n## Step 2: Splitting the data into training and test sets\n\nIn this practical, you are working with a dataset that has been collected and thoroughly labelled in the past. Each instance has a predefined set of values and the correct price label assigned to it. After training the ML model on this dataset you hope to be able to predict the prices for new houses, not contained in this dataset, based on their characteristics such as geographical position, median income, number of rooms and so on. How can you check in advance whether your model is good in making such predictions?\n\nThe answer is: you set part of your dataset, called *test set*, aside and use it to evaluate the performance of your model only. You train and tune your model using the rest of the dataset – *training set* – and evaluate the performance of the model trained this way on the test set. Since the model doesn't see the test set during training, this perfomance should give you a reasonable estimate of how well it would perform on new data. Traditionally, you split the data into $80\\%$ training and $20\\%$ test set, making sure that the test instances are selected randomly so that you don't end up with some biased selection leading to over-optimistic or over-pessimistic results on your test set.\n\nFor example, you can select your test set as the code below shows. To ensure random selection of the test items, use `np.random.permutation`. However, if you want to ensure that you have a stable test set, and the same test instances get selected from the dataset in a random fashion in different runs of the program, select a random seed, e.g. using `np.random.seed(42)`.\n\n\n```python\nimport numpy as np\nnp.random.seed(42)\n\ndef split_train_test(data, test_ratio): \n shuffled_indices = np.random.permutation(len(data))\n test_set_size = int(len(data) * test_ratio)\n test_indices = shuffled_indices[:test_set_size]\n train_indices = shuffled_indices[test_set_size:]\n return data.iloc[train_indices], data.iloc[test_indices]\n\ntrain_set, test_set = split_train_test(housing, 0.2)\nprint(len(train_set), \"training instances +\", len(test_set), \"test instances\")\n```\n\n 16512 training instances + 4128 test instances\n\n\nNote that `scikit-learn` provides a similar functionality to the code above with its `train_test_split` function. Morevoer, you can pass it several datasets with the same number of rows each, and it will split them into training and test sets on the same indices (you might find it useful if you need to pass in a separate DataFrame with labels):\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\nprint(len(train_set), \"training instances +\", len(test_set), \"test instances\")\n```\n\n 16512 training instances + 4128 test instances\n\n\nSo far, you have been selecting your test set using random sampling methods. If your data is representative of the task at hand, this should help ensure that the results of the model testing are informative. However, if your dataset is not very large and the data is skewed on some of the attributes or on the target label (as is often the case with the real-world data), random sampling might introduce a sampling bias. *Stratified sampling* is a technique that helps make sure that the distributions of the instance attributes or labels in the training and the test sets are similar, meaning that the proportion of instances drawn from each *stratum* in the dataset is similar in the training and test data.\n\nSampling bias may express itself both in the distribution of labels and in the distribution of the attribute values. For instance, take a look at the *median_income* attribute value distribution. Suppose for now (and you might find a confirmation to that later in the practical) that this attribute is predictive of the house price, however its values are unevenly distributed across the range of $[0.4999, 15.0001]$ with a very long tail. If random sampling doesn't select enough instances for each *stratum* (each range of incomes) the estimate of the under-represented strata's importance will be biased. \n\nFirst, to limit the number of income categories (strata), particularly at the long tail, let's apply further binning to the income values: e.g., you can divide the income by $1.5$, round up the values using `ceil` to have discrete categories (bins), and merge all the categories greater than $5$ into category $5$. The latter can be achieved using `Pandas`' `where` functionality, keeping the original values when they are smaller than $5$ and converting them to $5$ otherwise:\n\n\n```python\nhousing[\"income_cat\"] = np.ceil(housing[\"median_income\"] / 1.5)\nhousing[\"income_cat\"].where(housing[\"income_cat\"] < 5, 5.0, inplace = True)\n\nhousing[\"income_cat\"].hist()\nplt.show()\n```\n\nNow you have a much smaller number of categories of income, with the instances more evenly distributed, so you can hope to get enough data to represent the tail. Next, let's split the dataset into training and test sets making sure both contain similar proportion of instances from each income category. You can do that using `scikit-learn`'s `StratifiedShuffleSplit` specifying the condition on which the data should be stratified (in this case, income category):\n\n\n```python\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\nfor train_index, test_index in split.split(housing, housing[\"income_cat\"]):\n strat_train_set = housing.loc[train_index]\n strat_test_set = housing.loc[test_index]\n```\n\nLet's compare the distribution of the income values in the randomly selected train and test sets and the stratified train and test sets against the full dataset. To better understand the effect of random sampling versus stratified sampling, let's also estimate the error that would be introduced in the data by such splits:\n\n\n```python\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\n\ndef income_cat_proportions(data):\n return data[\"income_cat\"].value_counts() / len(data)\n\ncompare_props = pd.DataFrame({\n \"Overall\": income_cat_proportions(housing),\n \"Stratified tr\": income_cat_proportions(strat_train_set),\n \"Random tr\": income_cat_proportions(train_set),\n \"Stratified ts\": income_cat_proportions(strat_test_set),\n \"Random ts\": income_cat_proportions(test_set),\n})\ncompare_props[\"Rand. tr %error\"] = 100 * compare_props[\"Random tr\"] / compare_props[\"Overall\"] - 100\ncompare_props[\"Rand. ts %error\"] = 100 * compare_props[\"Random ts\"] / compare_props[\"Overall\"] - 100\ncompare_props[\"Strat. tr %error\"] = 100 * compare_props[\"Stratified tr\"] / compare_props[\"Overall\"] - 100\ncompare_props[\"Strat. ts %error\"] = 100 * compare_props[\"Stratified ts\"] / compare_props[\"Overall\"] - 100\n\ncompare_props.sort_index()\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 \n \n \n \n \n \n \n \n \n \n \n
OverallStratified trRandom trStratified tsRandom tsRand. tr %errorRand. ts %errorStrat. tr %errorStrat. ts %error
1.00.0398260.0398500.0397290.0397290.040213-0.2433090.9732360.060827-0.243309
2.00.3188470.3188590.3174660.3187980.324370-0.4330651.7322600.003799-0.015195
3.00.3505810.3505940.3485950.3505330.358527-0.5666112.2664460.003455-0.013820
4.00.1763080.1762960.1785370.1763570.1673931.264084-5.056334-0.0068700.027480
5.00.1144380.1144020.1156730.1145830.1094961.079594-4.318374-0.0317530.127011
\n
\n\n\n\nAs you can see, the distributions in the stratified training and test sets are much closer to the original distribution of categories as well as being much closer to each other. \n\nNote, that to help you split the data, you had to introduce a new category – *income_cat* – which contains the same information as the original attribute *median_income* binned in a different way:\n\n\n```python\nstrat_train_set.info()\n```\n\n \n Int64Index: 16512 entries, 17606 to 15775\n Data columns (total 11 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 16512 non-null float64\n 1 latitude 16512 non-null float64\n 2 housing_median_age 16512 non-null float64\n 3 total_rooms 16512 non-null float64\n 4 total_bedrooms 16354 non-null float64\n 5 population 16512 non-null float64\n 6 households 16512 non-null float64\n 7 median_income 16512 non-null float64\n 8 median_house_value 16512 non-null float64\n 9 ocean_proximity 16512 non-null object \n 10 income_cat 16512 non-null float64\n dtypes: float64(10), object(1)\n memory usage: 1.5+ MB\n\n\nBefore proceeding further let's remove the *income_cat* attribute so the data is back to its original state. Here is how you can do that:\n\n\n```python\nfor set_ in (strat_train_set, strat_test_set):\n set_.drop(\"income_cat\", axis=1, inplace=True)\n\nstrat_train_set.info()\n```\n\n \n Int64Index: 16512 entries, 17606 to 15775\n Data columns (total 10 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 16512 non-null float64\n 1 latitude 16512 non-null float64\n 2 housing_median_age 16512 non-null float64\n 3 total_rooms 16512 non-null float64\n 4 total_bedrooms 16354 non-null float64\n 5 population 16512 non-null float64\n 6 households 16512 non-null float64\n 7 median_income 16512 non-null float64\n 8 median_house_value 16512 non-null float64\n 9 ocean_proximity 16512 non-null object \n dtypes: float64(9), object(1)\n memory usage: 1.4+ MB\n\n\n## Step 3: Exploring the attributes\n\nThe next step is to look more closely into the attributes and gain insights into the data. In particular, you should try to answer the following questions: \n- Which attributes look most informative? \n- How do they correlate with each other and the target label?\n- Is any further normalisation or scaling needed?\n\nThe most informative ways in which you can answer the questions above are by *visualising* the data and by *collecting additional statistics* on the attributes and their relations to each other.\n\nFirst, remember that from now on you're only looking into and gaining insights from the training data. You will use the test data at the evaluation step only, thus ensuring no data leakage between the training and test sets occurs and the results on the test set are a fair evaluation of your algorithm's performance. Let's make a copy of the training set that you can experiment with without a danger of overwriting or changing the original data: \n\n\n```python\nhousing = strat_train_set.copy()\n```\n\n### Visualisations\n\nThe first two attributes describe the geographical position of the houses. Let's apply further visualisations and look into the geographical area that is covered: for that, use a scatter plot plotting longitude against latitude coordinates. To make the scatter plot more informative, use `alpha` option to highlight high density points:\n\n\n```python\nhousing.plot(kind='scatter', x='longitude', y='latitude', alpha=0.2)\n```\n\nYou can experiment with `alpha` values to get a better understanding, but it should be obvious from these plots that the areas in the south and along the coast of California are more densely populated (roughly corresponding to the Bay Area, Los Angeles, San Diego, and the Central Valley). \n\nNow, what does geographical position suggest about the housing prices? In the following code, the size of the circles represents the size of the population, and the color represents the price, ranging from blue for low prices to red for high prices (this color scheme is specified by the preselected `cmap` type):\n\n\n```python\nhousing.plot(kind='scatter', x='longitude', y='latitude', alpha=0.5,\n s=housing[\"population\"]/100, label=\"population\", figsize=(10,7), \n c=housing[\"median_house_value\"], cmap=plt.get_cmap(\"jet\"), colorbar=\"True\",\n )\nplt.legend()\n```\n\nThis plot suggests that the housing prices depend on the proximity to the ocean and on the population size. What does this suggest about the informativeness of the attributes for your ML task?\n\n### Correlations\n\nLet's also look into how the attributes correlate with each other:\n\n\n```python\ncorr_matrix = housing.corr()\ncorr_matrix\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 \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
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_value
longitude1.000000-0.924478-0.1058480.0488710.0765980.1080300.063070-0.019583-0.047432
latitude-0.9244781.0000000.005766-0.039184-0.072419-0.115222-0.077647-0.075205-0.142724
housing_median_age-0.1058480.0057661.000000-0.364509-0.325047-0.298710-0.306428-0.1113600.114110
total_rooms0.048871-0.039184-0.3645091.0000000.9293790.8551090.9183920.2000870.135097
total_bedrooms0.076598-0.072419-0.3250470.9293791.0000000.8763200.980170-0.0097400.047689
population0.108030-0.115222-0.2987100.8551090.8763201.0000000.9046370.002380-0.026920
households0.063070-0.077647-0.3064280.9183920.9801700.9046371.0000000.0107810.064506
median_income-0.019583-0.075205-0.1113600.200087-0.0097400.0023800.0107811.0000000.687160
median_house_value-0.047432-0.1427240.1141100.1350970.047689-0.0269200.0645060.6871601.000000
\n
\n\n\n\nSince you are trying to predict the house value, the last column in this table is the most informative. Let's make the output clearer:\n\n\n```python\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n```\n\n\n\n\n median_house_value 1.000000\n median_income 0.687160\n total_rooms 0.135097\n housing_median_age 0.114110\n households 0.064506\n total_bedrooms 0.047689\n population -0.026920\n longitude -0.047432\n latitude -0.142724\n Name: median_house_value, dtype: float64\n\n\n\nThis makes it clear that the *median_income* is most strongly positively correlated with the price. There is small positive correlation of the price with *total_rooms* and *housing_median_age*, and small negative correlation with *latitude*, which suggests that the prices go up with the increase in income, number of rooms and house age, and go down when you go north. `Pandas`' `scatter_matrix` function allows you to visualise the correlation of attributes with each other (note that since the correlation of an attribute with itself will result in a straight line, `Pandas` uses a histogram instead – that's what you see along the diagonal):\n\n\n```python\nfrom pandas.plotting import scatter_matrix\n# If the above returns an error, use the following:\n#from pandas.tools.plotting import scatter_matrix\n\nattributes = [\"median_house_value\", \"median_income\", \"total_rooms\", \"housing_median_age\", \"latitude\"]\nscatter_matrix(housing[attributes], figsize=(12,8))\n```\n\nThese plots confirm that the income attribute is the most promising one for predicting house prices, so let's zoom in on this attribute:\n\n\n```python\nhousing.plot(kind=\"scatter\", x=\"median_income\", y=\"median_house_value\", alpha=0.3)\n```\n\nThere are a couple of observations to be made about this plot:\n- The correlation is indeed quite strong: the values follow the upward trend and are not too dispersed otherwise;\n- You can clearly see a line around $500000$ which covers a full range of income values and is due to the fact that the house prices above that value were capped in the original dataset. However, the plot suggests that there are also some other less obvious groups of values, most visible around $350000$ and $450000$, that also cover a range of different income values. Since your ML algorithm will learn to reproduce such data quirks, you might consider looking into these matters further and removing these districts from your dataset (after all, in any real-world application, one can expect a certain amount of noise in the data and clearing the data is one of the steps in any practical application). \n\nThe next thing to notice is that a number of attributes from the original dataset, including *total_rooms*, \t*total_bedrooms* and *population*, do not actually describe each house in particular but rather represent the cumulative counts for *all households* in the block group. At the same time, the task at hand requires you to predict the house price for *each individual household*. In addition, an attribute that measures the proportion of bedrooms against the total number of rooms might be informative. Therefore, the following transformed attributes might be more useful for the prediction:\n\n\n```python\nhousing[\"rooms_per_household\"] = housing[\"total_rooms\"] / housing[\"households\"]\nhousing[\"bedrooms_per_household\"] = housing[\"total_bedrooms\"] / housing[\"households\"]\nhousing[\"bedrooms_per_rooms\"] = housing[\"total_bedrooms\"] / housing[\"total_rooms\"]\nhousing[\"population_per_household\"] = housing[\"population\"] / housing[\"households\"]\n```\n\nA good way to check whether these transformations have any effect on the task is to check attributes correlations again:\n\n\n```python\ncorr_matrix = housing.corr()\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n```\n\n\n\n\n median_house_value 1.000000\n median_income 0.687160\n rooms_per_household 0.146285\n total_rooms 0.135097\n housing_median_age 0.114110\n households 0.064506\n total_bedrooms 0.047689\n population_per_household -0.021985\n population -0.026920\n bedrooms_per_household -0.043343\n longitude -0.047432\n latitude -0.142724\n bedrooms_per_rooms -0.259984\n Name: median_house_value, dtype: float64\n\n\n\nYou can see that the number of rooms per household is more strongly correlated with the house price – the more rooms the more expensive the house, while the proportion of bedrooms is more strongly correlated with the price than either the number of rooms or bedrooms in the household – since the correlation is negative, the lower the bedroom-to-room ratio, the more expensive the property.\n\n## Step 4: Data preparation and transformations for machine learning algorithms\n\nNow you are almost ready to implement a regression algorithm for the task at hand. However, there are a couple of other things to address, in particular:\n- handle missing values if there are any;\n- convert all attribute values (e.g. categorical, textual) into numerical format;\n- scale / normalise the feature values if necessary.\n\nFirst, let's separate the labels you're trying to predict (*median_house_value*) from the attributes in the dataset that you will use as *features*. The following code will keep a copy of the labels and the rest of the attributes separate (note that `drop()` will create a copy of the data and will not affect `strat_train_set` itself): \n\n\n```python\nhousing = strat_train_set.drop(\"median_house_value\", axis=1)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n```\n\nYou can add the transformed features that you found useful before with the additional function as shown below. Then you can run `add_features(housing)` to add the features:\n\n\n```python\ndef add_features(data):\n # add the transformed features that you found useful before\n data[\"rooms_per_household\"] = data[\"total_rooms\"] / data[\"households\"]\n data[\"bedrooms_per_household\"] = data[\"total_bedrooms\"] / data[\"households\"]\n data[\"bedrooms_per_rooms\"] = data[\"total_bedrooms\"] / data[\"total_rooms\"]\n data[\"population_per_household\"] = data[\"population\"] / data[\"households\"]\n \n# add_features(housing)\n```\n\nYou will learn shortly about how to implement your own *data transformers* and will be able to re-implement addition of these features as a data transfomer.\n\n### Handling missing values\n\nIn Step 1 above, when you took a quick look into the dataset, you might have noticed that all attributes but one have $20640$ values in the dataset; *total_bedrooms* has $20433$, so some values are missing. ML algorithms cannot deal with missing values, so you'll need to decide how to replace these values. There are three possible solutions:\n\n1. remove the corresponding housing blocks from the dataset (i.e., remove the rows in the dataset)\n2. remove the whole attribute (i.e., remove the column)\n3. set the missing values to some predefined value (e.g., zero value, the mean, the median, the most frequent value of the attribute, etc.)\n\nThe following `Pandas` functionality will help you implement each of these options:\n\n\n```python\n## option 1:\n# housing.dropna(subset=[\"total_bedrooms\"])\n## option 2:\n# housing.drop(\"total_bedrooms\", axis=1)\n# option 3:\nmedian = housing[\"total_bedrooms\"].median()\nhousing[\"total_bedrooms\"].fillna(median, inplace=True)\n```\n\nAlthough, all three options are possible, keep in mind that in the first two cases you are throwing away either some valuable attributes (e.g., as you've seen earlier, *bedrooms_per_rooms* correlates well with the label you're trying to predict) or a number of valuable training examples. Option 3, therefore, looks more promising. Note, that for that you estimate a mean or median based on the training set only (as, in general, your ML algorithm has access to the training data only during the training phase), and then store the mean / median values to replace the missing values in the test set (or any new dataset, to that effect). In addition, you might want to calculate and store the mean / median values for all attributes as in a real-life application you can never be sure if any of the attributes will have missing values in the future.\n\nHere is how you can calculate and store median values using `sklearn` (note that you'll need to exclude `ocean_proximity` attribute from this calculation since it has non-numerical values):\n\n\n```python\n# for earlier versions of sklearn use:\n#from sklearn.preprocessing import Imputer \n#imputer = Imputer(strategy=\"median\")\n\nfrom sklearn.impute import SimpleImputer\n\nimputer = SimpleImputer(strategy=\"median\")\nhousing_num = housing.drop(\"ocean_proximity\", axis=1)\nimputer.fit(housing_num)\n```\n\n\n\n\n SimpleImputer(strategy='median')\n\n\n\nYou can check the median values stored in the `imputer` as follows:\n\n\n```python\nimputer.statistics_\n```\n\n\n\n\n array([-118.51 , 34.26 , 29. , 2119.5 , 433. , 1164. ,\n 408. , 3.5409])\n\n\n\nand also make sure that they exactly coincide with the median values for all numerical attributes:\n\n\n```python\nhousing_num.median().values\n```\n\n\n\n\n array([-118.51 , 34.26 , 29. , 2119.5 , 433. , 1164. ,\n 408. , 3.5409])\n\n\n\nFinally, let's replace the missing values in the training data:\n\n\n```python\nX = imputer.transform(housing_num)\nhousing_tr = pd.DataFrame(X, columns=housing_num.columns)\nhousing_tr.info()\n```\n\n \n RangeIndex: 16512 entries, 0 to 16511\n Data columns (total 8 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 16512 non-null float64\n 1 latitude 16512 non-null float64\n 2 housing_median_age 16512 non-null float64\n 3 total_rooms 16512 non-null float64\n 4 total_bedrooms 16512 non-null float64\n 5 population 16512 non-null float64\n 6 households 16512 non-null float64\n 7 median_income 16512 non-null float64\n dtypes: float64(8)\n memory usage: 1.0 MB\n\n\n### Handling textual and categorical attributes\n\nAnother aspect of the dataset that should be handled is the textual / categorical values of the *ocean_proximity* attribute. ML algorithms prefer working with numerical data, so let's use `sklearn`'s functionality and cast the categorical values as numerical values as follows:\n\n\n```python\nfrom sklearn.preprocessing import LabelEncoder\n\nencoder = LabelEncoder()\nhousing_cat_encoded = encoder.fit_transform(housing[\"ocean_proximity\"])\nhousing_cat_encoded\n```\n\n\n\n\n array([0, 0, 4, ..., 1, 0, 3])\n\n\n\nThe code above mapped the categories to numerical values. You can check what the numerical values correspond to in the original data using:\n\n\n```python\nencoder.classes_\n```\n\n\n\n\n array(['<1H OCEAN', 'INLAND', 'ISLAND', 'NEAR BAY', 'NEAR OCEAN'],\n dtype=object)\n\n\n\nOne problem with the encoding above is that the ML algorithm will automatically assume that the numerical values that are close to each other encode similar concepts, which for this data is not quite true: for example, value $0$ corresponding to *$<$1H OCEAN* category is actually most similar to values $3$ and $4$ (*NEAR BAY* and *NEAR OCEAN*) and not to value $1$ (*INLAND*).\n\nAn alternative to this encoding is called *one-hot encoding* and it runs as follows: for each category, it creates a separate binary attribute which is set to $1$ (hot) when the category coincides with the attribute, and $0$ (cold) otherwise. So, for instance, *$<$1H OCEAN* will be encoded as a one-hot vector $[1, 0, 0, 0, 0]$ and *NEAR OCEAN* will be encoded as $[0, 0, 0, 0, 1]$. The following `sklearn`'s functionality allows to convert categorical values into one-hot vectors:\n\n\n```python\nfrom sklearn.preprocessing import OneHotEncoder\n\nencoder = OneHotEncoder()\n# fit_transform expects a 2D array, but housing_cat_encoded is a 1D array.\n# Reshape it using NumPy's reshape functionality where -1 simply means \"unspecified\" dimension \nhousing_cat_1hot = encoder.fit_transform(housing_cat_encoded.reshape(-1,1))\nhousing_cat_1hot\n```\n\n\n\n\n <16512x5 sparse matrix of type ''\n \twith 16512 stored elements in Compressed Sparse Row format>\n\n\n\nNote that the data format above says that the output is a sparse matrix. This means that the data structure only stores the location of the non-zero elements, rather than the full set of vectors which are mostly full of zeros. You can check the [documentation on sparse matrices](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html) if you'd like to learn more. If you'd like to see how the encoding looks like you can also convert it back into a dense NumPy array using:\n\n\n```python\nhousing_cat_1hot.toarray()\n```\n\n\n\n\n array([[1., 0., 0., 0., 0.],\n [1., 0., 0., 0., 0.],\n [0., 0., 0., 0., 1.],\n ...,\n [0., 1., 0., 0., 0.],\n [1., 0., 0., 0., 0.],\n [0., 0., 0., 1., 0.]])\n\n\n\nThe steps above, including casting text categories to numerical categories and then converting them into 1-hot vectors, can be performed using `sklearn`'s `LabelBinarizer`:\n\n\n```python\nfrom sklearn.preprocessing import LabelBinarizer\n\nencoder = LabelBinarizer()\nhousing_cat_1hot = encoder.fit_transform(housing[\"ocean_proximity\"])\nhousing_cat_1hot\n```\n\n\n\n\n array([[1, 0, 0, 0, 0],\n [1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1],\n ...,\n [0, 1, 0, 0, 0],\n [1, 0, 0, 0, 0],\n [0, 0, 0, 1, 0]])\n\n\n\nThe above produces dense array as an output, so if you'd like to have a sparse matrix instead you can specify it in the `LabelBinarizer` constructor:\n\n\n```python\nencoder = LabelBinarizer(sparse_output=True)\nhousing_cat_1hot = encoder.fit_transform(housing[\"ocean_proximity\"])\nhousing_cat_1hot\n```\n\n\n\n\n <16512x5 sparse matrix of type ''\n \twith 16512 stored elements in Compressed Sparse Row format>\n\n\n\n### Data transformers\n\nA useful functionality of `sklearn` is [data transformers](http://scikit-learn.org/stable/data_transforms.html): you will see them used in preprocessing very often. For example, you have just used one to impute the missing values. In addition, you can implement your own custom data transformers. In general, a transformer class needs to implement three methods:\n- a constructor method;\n- a `fit` method that learns parameters (e.g. mean and standard deviation for a normalization transformer) or returns `self`; and\n- a `transform` method that applies the learned transformation to the new data.\n\nWhenever you see `fit_transform` method, it means that the method uses an optimised combination of `fit` and `transform`. Here is how you can implement a data transformer that will convert categorical values into 1-hot vectors:\n\n\n```python\nfrom sklearn.base import TransformerMixin # TransformerMixin allows you to use fit_transform method\n\nclass CustomLabelBinarizer(TransformerMixin):\n def __init__(self, *args, **kwargs):\n self.encoder = LabelBinarizer(*args, **kwargs)\n def fit(self, X, y=0):\n self.encoder.fit(X)\n return self\n def transform(self, X, y=0):\n return self.encoder.transform(X)\n```\n\nSimilarly, here is how you can wrap up adding new transformed features like bedroom-to-room ratio with a data transformer:\n\n\n```python\nfrom sklearn.base import BaseEstimator, TransformerMixin \n# BaseEstimator allows you to drop *args and **kwargs from you constructor\n# and, in addition, allows you to use methods set_params() and get_params()\n\nrooms_id, bedrooms_id, population_id, household_id = 3, 4, 5, 6\n\nclass CombinedAttributesAdder(BaseEstimator, TransformerMixin):\n def __init__(self, add_bedrooms_per_rooms = True): # note no *args and **kwargs used this time\n self.add_bedrooms_per_rooms = add_bedrooms_per_rooms\n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n rooms_per_household = X[:, rooms_id] / X[:, household_id]\n bedrooms_per_household = X[:, bedrooms_id] / X[:, household_id]\n population_per_household = X[:, population_id] / X[:, household_id]\n if self.add_bedrooms_per_rooms:\n bedrooms_per_rooms = X[:, bedrooms_id] / X[:, rooms_id]\n return np.c_[X, rooms_per_household, bedrooms_per_household, \n population_per_household, bedrooms_per_rooms]\n else:\n return np.c_[X, rooms_per_household, bedrooms_per_household, \n population_per_household]\n \nattr_adder = CombinedAttributesAdder()\nhousing_extra_attribs = attr_adder.transform(housing.values)\nhousing_extra_attribs\n```\n\n\n\n\n array([[-121.89, 37.29, 38.0, ..., 1.0353982300884956, 2.094395280235988,\n 0.22385204081632654],\n [-121.93, 37.05, 14.0, ..., 0.9557522123893806,\n 2.7079646017699117, 0.15905743740795286],\n [-117.2, 32.77, 31.0, ..., 1.0194805194805194, 2.0259740259740258,\n 0.24129098360655737],\n ...,\n [-116.4, 34.09, 9.0, ..., 1.1398692810457516, 2.742483660130719,\n 0.1796086508753862],\n [-118.01, 33.82, 31.0, ..., 1.0674157303370786, 3.808988764044944,\n 0.19387755102040816],\n [-122.45, 37.77, 52.0, ..., 1.0672926447574336,\n 1.9859154929577465, 0.22035541195476574]], dtype=object)\n\n\n\nIf you'd like to explore the new attributes, you can convert the `housing_extra_attribs` into a `Pandas` DataFrame and apply the functionality as before:\n\n\n```python\nhousing_extra_attribs = pd.DataFrame(housing_extra_attribs, columns=list(housing.columns)+\n [\"rooms_per_household\", \"bedrooms_per_household\", \n \"population_per_household\", \"bedrooms_per_rooms\"])\nhousing_extra_attribs.head()\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 \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
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomeocean_proximityrooms_per_householdbedrooms_per_householdpopulation_per_householdbedrooms_per_rooms
0-121.8937.293815683517103392.7042<1H OCEAN4.625371.03542.09440.223852
1-121.9337.05146791083061136.4214<1H OCEAN6.008850.9557522.707960.159057
2-117.232.773119524719364622.8621NEAR OCEAN4.225111.019482.025970.241291
3-119.6136.3125184737114603531.8839INLAND5.232291.050994.135980.200866
4-118.5934.231765921525445914633.0347<1H OCEAN4.505811.042383.047850.231341
\n
\n\n\n\n\n```python\nhousing_extra_attribs.info()\n```\n\n \n RangeIndex: 16512 entries, 0 to 16511\n Data columns (total 13 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 longitude 16512 non-null object\n 1 latitude 16512 non-null object\n 2 housing_median_age 16512 non-null object\n 3 total_rooms 16512 non-null object\n 4 total_bedrooms 16512 non-null object\n 5 population 16512 non-null object\n 6 households 16512 non-null object\n 7 median_income 16512 non-null object\n 8 ocean_proximity 16512 non-null object\n 9 rooms_per_household 16512 non-null object\n 10 bedrooms_per_household 16512 non-null object\n 11 population_per_household 16512 non-null object\n 12 bedrooms_per_rooms 16512 non-null object\n dtypes: object(13)\n memory usage: 1.6+ MB\n\n\n### Feature scaling\n\nFinally, ML algorithms do not typically perform well when the feature values cover significantly different ranges of values. For example, in the dataset at hand, the income ranges from $0.4999$ to $15.0001$, while population ranges from $3$ to $35682$. Taken at the same scale, these values are not directly comparable. The data transformation that should be applied to these values is called *feature scaling*.\n\nOne of the most common ways to scale the data is to apply *min-max scaling* (also often referred to as *normalisaton*). Min-max scaling puts all values on the scale of $[0, 1]$ making the ranges directly comparable. For that, you need to subtract the min from the actual value and divide by the difference between the maximum and minimum values, i.e.:\n\n\\begin{equation}\nf_{scaled} = \\frac{f - F_{min}}{F_{max} - F_{min}}\n\\end{equation}\n\nwhere $f \\in F$ is the actual feature value of a feature type $F$, and $F_{min}$ and $F_{max}$ are the minumum and maximum values for the feature of type $F$.\n\nAnother common approach is *standardisation*, which subtracts the mean value (so the standardised values have a zero mean) and divides by the variance (so the standardised values have unit variance). Standardisation does not impose a specific range on the values and is more robust to the outliers: i.e., a noisy input or an incorrect income value of $100$ (when the rest of the values lie within the range of $[0.4999, 15.0001]$) will introduce a significant skew in the data after min-max scaling. At the same time, standardisation does not bind values to the same range of $[0, 1]$, which might be problematic for some algorithms.\n\n`Scikit-learn` has an implementation for the `MinMaxScaler`, `StandardScaler`, as well as [other scaling approaches](http://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler), i.e.:\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\n\nscaler = StandardScaler()\nhousing_tr_scaled = scaler.fit_transform(housing_tr)\n```\n\n### Putting all the data transformations together\n\nAnother useful functionality of `sklearn` is pipelines. These allow you to stack several separate transformations together. For example, you can apply the numerical transformations such as missing values handling and data scaling as follows:\n\n\n```python\nfrom sklearn.pipeline import Pipeline\n\nnum_pipeline = Pipeline([\n #('imputer', Imputer(strategy=\"median\")),\n ('imputer', SimpleImputer(strategy=\"median\")),\n ('std_scaler', StandardScaler()),\n])\n\nhousing_num_tr = num_pipeline.fit_transform(housing_num)\nhousing_num_tr.shape\n```\n\n\n\n\n (16512, 8)\n\n\n\nPipelines are useful because they help combining several steps together, so that the output of one data transformer (e.g., `Imputer`) is passed on as an input to the next one (e.g., `StandardScaler`) and so you don't need to worry about the intermediate steps. Besides, it makes the code look more concise and readable. However:\n- the code above doesn't handle categorical values;\n- we started with `Pandas` DataFrames because they are useful for data uploading and inspection, but the `Pipeline` expects `NumPy` arrays as input, and at the moment, `sklearn`'s `Pipeline` cannot handle `Pandas` DataFrames.\n\nIn fact, there is a way around the two issues above. Let's implement another custom data transformer that will allow you to select specific attributes from a `Pandas` DataFrame:\n\n\n```python\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n# Create a class to select numerical or categorical columns \n# since Scikit-Learn doesn't handle DataFrames yet\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attribute_names):\n self.attribute_names = attribute_names\n def fit(self, X, y=None):\n return self\n def transform(self, X):\n return X[self.attribute_names].values\n```\n\nThe transformer above allows you to select a predefined set of attributes from a DataFrame, dropping the rest and converting the selected ones into a `NumPy` array. This is quite useful because now you can select the numerical attributes and apply one set of transformations to them, and then select categorical attributes and apply another set of transformation to them, i.e.:\n\n\n```python\nnum_attribs = list(housing_num)\ncat_attribs = [\"ocean_proximity\"]\n\nnum_pipeline = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n #('imputer', Imputer(strategy=\"median\")),\n ('imputer', SimpleImputer(strategy=\"median\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', StandardScaler()),\n ])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', CustomLabelBinarizer()),\n ])\n```\n\nFinally, to merge the output of the two separate data transformers back together, you can use `sklearn`'s `FeatureUnion` functionality: it runs the two pipelines' `fit` methods and the two `transform` methods in parallel, and then concatenates the output. I.e.:\n\n\n```python\nfrom sklearn.pipeline import FeatureUnion\n\nfull_pipeline = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\n\nhousing = strat_train_set.drop(\"median_house_value\", axis=1)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\nhousing_prepared = full_pipeline.fit_transform(housing)\nprint(housing_prepared.shape)\nhousing_prepared\n```\n\n (16512, 17)\n\n\n\n\n\n array([[-1.15604281, 0.77194962, 0.74333089, ..., 0. ,\n 0. , 0. ],\n [-1.17602483, 0.6596948 , -1.1653172 , ..., 0. ,\n 0. , 0. ],\n [ 1.18684903, -1.34218285, 0.18664186, ..., 0. ,\n 0. , 1. ],\n ...,\n [ 1.58648943, -0.72478134, -1.56295222, ..., 0. ,\n 0. , 0. ],\n [ 0.78221312, -0.85106801, 0.18664186, ..., 0. ,\n 0. , 0. ],\n [-1.43579109, 0.99645926, 1.85670895, ..., 0. ,\n 1. , 0. ]])\n\n\n\n## Step 5: Implementation, evaluation and fine-tuning of a regression model\n\nNow that you've explored and prepared the data, you can implement a regression model to predict the house prices on the test set. \n\n### Training and evaluating the model\n\nLet's train a [Linear Regression](http://scikit-learn.org/stable/modules/linear_model.html) model first. During training, a Linear Regression model tries to find the optimal set of weights $w=(w_{1}, w_{2}, ..., w_{n})$ for the features (attributes) $X=(x_{1}, x_{2}, ..., x_{n})$ by minimising the residual sum of squares between the responses predicted by such linear approximation $Xw$ and the observed responses $y$ in the dataset, i.e. trying to solve:\n\n\\begin{equation}\nmin_{w} ||Xw - y||_{2}^{2}\n\\end{equation}\n\n\n```python\nfrom sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(housing_prepared, housing_labels)\n```\n\n\n\n\n LinearRegression()\n\n\n\nFirst, let's try the model on some instances from the training set itself:\n\n\n```python\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\n# note the use of transform, as you'd like to apply already learned (fitted) transformations to the data\nsome_data_prepared = full_pipeline.transform(some_data)\n\nprint(\"Predictions:\", list(lin_reg.predict(some_data_prepared)))\nprint(\"Actual labels:\", list(some_labels))\n```\n\n Predictions: [209255.56837821114, 316024.2524890248, 209614.66475986046, 58638.55109778934, 186723.33486566014]\n Actual labels: [286600.0, 340600.0, 196900.0, 46300.0, 254500.0]\n\n\nThe above shows that the model is able to predict some price values, however they don't seem to be very accurate. How can you measure the performance of your model in a more comprehensive way?\n\nTypically, the output of the regression model is measured in terms of the error in prediction. There are two error measures that are commonly used. *Root Mean Square Error (RMSE)* measures the average deviation of the model's prediction from the actual label, but note that it gives a higher weight for large errors:\n\n\\begin{equation}\nRMSE(X, h) = \\sqrt{\\frac{1}{m} \\sum_{i=1}^{m} (h(x^{(i)}) - y^{(i)})^{2}}\n\\end{equation}\n\nwhere $m$ is the number of instances, $h$ is the model (hypothesis), $X$ is the matrix containing all feature values, $x^{(i)}$ is the feature vector describing instance $i$, and $y^{(i)}$ is the actual label for instance $i$.\n\nBecause *RMSE* is highly influenced by the outliers (i.e., large errors), in some situations *Mean Absolute Error (MAE)* is preferred. You may note that its estimation is somewhat similar to the estimation of *RMSE*:\n\n\\begin{equation}\nMAE(X, h) = \\frac{1}{m} \\sum_{i=1}^{m} |h(x^{(i)}) - y^{(i)}|\n\\end{equation}\n\nLet's measure the performance of the linear regression model using these error estimations:\n\n\n```python\nfrom sklearn.metrics import mean_squared_error\n\nhousing_predictions = lin_reg.predict(housing_prepared)\nlin_mse = mean_squared_error(housing_labels, housing_predictions)\nlin_rmse = np.sqrt(lin_mse)\nlin_rmse\n```\n\n\n\n\n 68226.59728659761\n\n\n\nGiven that the majority of the districts' housing values lie somewhere between $[\\$100000, \\$300000]$ an estimation error of over \\\\$68000 is very high. This shows that the regression model *underfits* the training data: it doesn't capture the patterns in the training data well enough because it lacks the descriptive power either due to the features not providing enough information to make a good prediction or due to the model itself being not complex enough. The ways to fix this include:\n- using more features and/or more informative features, for example applying log to some of the existing features to address the long tail distributions;\n- using more complex models;\n- reducing the constraints on the model.\n\nThe model that you used above is not constrained (or, *regularised* – more on this in later lectures), so you should try using more powerful models or work on the feature set.\n\nFor example, *polynomial regression* models the relationship between the $X$ and $y$ as an $n$-th degree polynomial. Polynomial regression extends simple linear regression by constructing polynomial features from the existing ones. For simplicity, assume that your data has only $2$ features rather than $8$, i.e. $X=[x_{1}, x_{2}]$. The linear regression model above tries to learn the coefficients (weights) $w=[w_{0}, w_{1}, w_{3}]$ for the linear prediction (a plane) $\\hat{y} = w_{0} + w_{1}x_{1} + w_{2}x_{2}$ that minimises the residual sum of squares between the prediction and actual label as you've seen above. \n\nIf you want to fit a paraboloid to the data instead of a plane, you can combine the features in second-order polynomials, so that the model looks like this: \n\n\\begin{equation}\n\\hat{y} = w_{0} + w_{1}x_{1} + w_{2}x_{2} + w_{3}x_{1}x_{2} + w_{4}x_{1}^2 + w_{5}x_{2}^2\n\\end{equation}\n\nThis time, the model tries to learn an optimal set of weights $w=[w_{0}, ..., w_{5}]$ (note that $w_{0}$ is called an intercept).\n\nNote that polynomial regression still employs a linear model. For instance, you can define a new variable $z = [x_1, x_2, x_1x_2, x_1^2, x_2^2]$ and rewrite the polynomial above as:\n\n\\begin{equation}\n\\hat{y} = w_{0} + w_{1}z_{0} + w_{2}z_{1} + w_{3}z_{2} + w_{4}z_{3} + w_{5}z_{4}\n\\end{equation}\n\nFor that reason, the polynomial regression in `sklearn` is addressed at the `preprocessing` steps – that is, first the second-order polynomials are estimated on the features, and then the same `LinearRegression` model as above is applied. For instance, use a second- and third-order polynomials and compare the results (feel free to use higher order polynomials, though keep in mind that as the complexity of the model increases, so does the processing time, the number of weights to be learned, and the chance that the model *overfits* to the training data). For more information, refer to `sklearn` [documentation](http://scikit-learn.org/stable/auto_examples/linear_model/plot_polynomial_interpolation.html):\n\n\n```python\nfrom sklearn.preprocessing import PolynomialFeatures\n\nmodel = Pipeline([('poly', PolynomialFeatures(degree=3)),\n ('linear', LinearRegression())])\n\nmodel = model.fit(housing_prepared, housing_labels)\nhousing_predictions = model.predict(housing_prepared)\nlin_mse = mean_squared_error(housing_labels, housing_predictions)\nlin_rmse = np.sqrt(lin_mse)\nlin_rmse\n```\n\n\n\n\n 51339.09311598264\n\n\n\nHow does the performance of the polynomial regression model compare to the first-order linear regression? You see that the performance improves as the complexity of the feature space increases. However, note that the more complex the model becomes, the more accurately it learns to replicate the training data, and the less likely it will generalise to the new pattern, i.e. in the test data. This phenomenon of learning to replicate the patterns from the training data too closely is called *overfitting*, and it is an opposite of *underfitting* when the model does not learn enough about the pattern from the training data due to its simplicity.\n\nJust to give you a flavor of the problem, here is an example of a complex model from the `sklearn` suite called `DecisionTreeRegressor` (Decision Trees are outside of the scope of this course, so don't worry if this looks unfamiliar to you. `sklearn` has implementation for a wide range of ML algorithms, so do check the [documentation](http://scikit-learn.org/stable/auto_examples/tree/plot_tree_regression.html) if you want to learn more). Note that the `DecisionTreeRegressor` learns to predict the values in the training data perfectly well (resulting in the error of $0$!) which usually means that it won't work well on the new data – e.g., check this later on the test data:\n\n\n```python\nfrom sklearn.tree import DecisionTreeRegressor\n\ntree_reg = DecisionTreeRegressor()\ntree_reg = tree_reg.fit(housing_prepared, housing_labels)\nhousing_predictions = tree_reg.predict(housing_prepared)\ntree_mse = mean_squared_error(housing_labels, housing_predictions)\ntree_mse = np.sqrt(tree_mse)\ntree_mse\n```\n\n\n\n\n 0.0\n\n\n\n### Learning to better evaluate you model using cross-validation\n\nObviously, one of the problems with overfitting above is caused by the fact that you're training and testing on the same (training) set (remember, that you should do all model tuning and optimisation on the training data, and only then apply the best model to the test data). So how can you measure the level of overfitting *before* you apply this model to the test data?\n\nThere are two possible solutions. You can either reapply `train_test_split` function from Step 2 to set aside part of the training set as a *development* (or *validation*) set, and then train the model on the smaller training set and tune it on the development set, before applying your best model to the test set. Or you can use *cross-validation*.\n\nWith *K-fold cross-validation* strategy, the training data gets randomly split into $k$ distinct subsets (*splits*). Then the model gets trained $10$ times, in each run being tested on a different fold and trained on the other $9$ folds. That way, the algorithm is evaluated on each data point in the training set, but during training is not exposed to the data points that it gets tested on later. The result is an array of $10$ evaluation scores, which can be averaged for better understanding and model comparison, i.e.:\n\n\n```python\nfrom sklearn.model_selection import cross_val_score\n \ndef analyse_cv(model): \n scores = cross_val_score(model, housing_prepared, housing_labels,\n scoring = \"neg_mean_squared_error\", cv=10)\n\n # cross-validation expects utility function (greater is better)\n # rather than cost function (lower is better), so the scores returned\n # are negative as they are the opposite of MSE\n sqrt_scores = np.sqrt(-scores) \n print(\"Scores:\", sqrt_scores)\n print(\"Mean:\", sqrt_scores.mean())\n print(\"Standard deviation:\", sqrt_scores.std())\n \nanalyse_cv(tree_reg)\n```\n\n Scores: [71302.97621239 68039.17701236 72733.72316834 71776.24020398\n 70702.05438268 74411.24933951 71645.9789824 70345.21765236\n 77351.99235982 70137.6290673 ]\n Mean: 71844.62383811326\n Standard deviation: 2428.901622738753\n\n\nThis shows that the `DecisionTreeRegression` model does not actually perform well when tested on a set different from the one it was trained on. What about the other models? E.g.:\n\n\n```python\nanalyse_cv(lin_reg)\n```\n\n Scores: [66400.11538513 66561.82084573 67510.6874652 74900.77582974\n 67509.87374136 70884.73634886 64791.38470292 68141.40160344\n 70934.13138413 67393.71765602]\n Mean: 68502.86449625254\n Standard deviation: 2789.502396552837\n\n\nLet's try one more model – [`RandomForestRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) that implements many Decision Trees (similar to above) on random subsets of the features. This type of models are called *ensemble learning* models and they are very powerful because they benefit from combining the decisions of multiple algorithms:\n\n\n```python\nfrom sklearn.ensemble import RandomForestRegressor\n\nforest_reg = RandomForestRegressor()\nanalyse_cv(forest_reg)\n```\n\n Scores: [50064.14969512 47706.34684052 50239.42228771 52645.72403144\n 49822.38774802 53567.01564887 49201.06035738 47859.43987529\n 53254.23210646 50436.53102518]\n Mean: 50479.630961598814\n Standard deviation: 1969.2058038348039\n\n\n### Fine-tuning the model\n\nSome learning algorithms have *hyperparameters* – the parameters of the algorithms that should be set up prior to training and don't get changed during training. Such hyperparameters are usually specified for the `sklearn` algorithms in brackets, so you can always check the list of parameters specified in the documentation. For example, whether the [`LinearRegression`](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model should calculate the intercept or not should be set prior to training and does not depend on the training itself, and so does the number of helper algorithms (decision trees) that should be combined in a [`RandomForestRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) for the final prediction. `RandomForestRegressor` has $16$ parameters, so if you want to find the *best* setting of the hyperparametes for `RandomForestRegressor`, it will take you a long time to try out all possible combinations.\n\nThe code below shows you how the best hyperparameter setting can be automatically found for an `sklearn` ML algorithm using a `GridSearch` functionality. Let's use the example of `RandomForestRegressor` and focus on specific hyperparameters: the number of helper algorithms (decision trees in the forest, or `n_estimators`) and the number of features the regressor considers in order to find the most informative subsets of instances to each of the helper algorithms (`max_features`):\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\n\n# specify the range of hyperparameter values for the grid search to try out \nparam_grid = {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]}\n\nforest_reg = RandomForestRegressor()\ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5,\n scoring=\"neg_mean_squared_error\")\ngrid_search.fit(housing_prepared, housing_labels)\n\ngrid_search.best_params_\n```\n\n\n\n\n {'max_features': 6, 'n_estimators': 30}\n\n\n\nYou can also monitor the intermediate results as shown below. Note also that if the best results are achieved with the maximum value for each of the parameters specified for exploration, you might want to keep experimenting with even higher values to see if the results improve any further:\n\n\n```python\ncv_results = grid_search.cv_results_\nfor mean_score, params in zip(cv_results[\"mean_test_score\"], cv_results[\"params\"]):\n print(np.sqrt(-mean_score), params)\n```\n\n 65442.56255758722 {'max_features': 2, 'n_estimators': 3}\n 56419.15564006979 {'max_features': 2, 'n_estimators': 10}\n 53740.7564750999 {'max_features': 2, 'n_estimators': 30}\n 60534.30928224138 {'max_features': 4, 'n_estimators': 3}\n 53328.88679847037 {'max_features': 4, 'n_estimators': 10}\n 50942.234922637035 {'max_features': 4, 'n_estimators': 30}\n 58855.46860401188 {'max_features': 6, 'n_estimators': 3}\n 52567.16946461185 {'max_features': 6, 'n_estimators': 10}\n 50345.67100807773 {'max_features': 6, 'n_estimators': 30}\n 58967.3949333711 {'max_features': 8, 'n_estimators': 3}\n 52212.05654437531 {'max_features': 8, 'n_estimators': 10}\n 50345.45130515203 {'max_features': 8, 'n_estimators': 30}\n\n\nOne more insight you can gain from the best estimator is the importance of each feature (expressed in the weight the best estimator learned to assign to each of the features). Here is how you can do that:\n\n\n```python\nfeature_importances = grid_search.best_estimator_.feature_importances_\nfeature_importances\n```\n\n\n\n\n array([7.03704835e-02, 6.35046538e-02, 4.16614744e-02, 1.61778280e-02,\n 1.35451741e-02, 1.43944952e-02, 1.30420492e-02, 3.47772051e-01,\n 6.10278343e-02, 2.08328874e-02, 1.05853691e-01, 5.39136792e-02,\n 7.20488240e-03, 1.64644734e-01, 3.46425049e-05, 3.23336373e-03,\n 2.78607657e-03])\n\n\n\nIf you also want to display the feature names, you can do that as follows:\n\n\n```python\nextra_attribs = ['rooms_per_household', 'bedrooms_per_household', 'population_per_household', 'bedrooms_per_rooms']\ncat_one_hot_attribs = ['<1H OCEAN', 'INLAND', 'ISLAND', 'NEAR BAY', 'NEAR OCEAN']\nattributes = num_attribs + extra_attribs + cat_one_hot_attribs\nsorted(zip(feature_importances, attributes), reverse=True)\n```\n\n\n\n\n [(0.347772051379105, 'median_income'),\n (0.16464473359058016, 'INLAND'),\n (0.10585369057933745, 'population_per_household'),\n (0.07037048351061218, 'longitude'),\n (0.06350465384430061, 'latitude'),\n (0.061027834274864405, 'rooms_per_household'),\n (0.05391367920754573, 'bedrooms_per_rooms'),\n (0.04166147439601101, 'housing_median_age'),\n (0.02083288739395782, 'bedrooms_per_household'),\n (0.016177828017537574, 'total_rooms'),\n (0.014394495230388975, 'population'),\n (0.013545174129594096, 'total_bedrooms'),\n (0.01304204924214857, 'households'),\n (0.0072048823952477635, '<1H OCEAN'),\n (0.0032333637318216315, 'NEAR BAY'),\n (0.0027860765720088385, 'NEAR OCEAN'),\n (3.464250493825699e-05, 'ISLAND')]\n\n\n\nHow do these compare with the insights you gained earlier (e.g., during data exploration in Step 1, or during attribute exporation in Step 3)?\n\n\n### At last, evaluating your best model on the test set!\n\nFinally, let's take the best model you built and tuned on the training set and apply in to the test set:\n\n\n```python\nfinal_model = grid_search.best_estimator_\n\nX_test = strat_test_set.drop(\"median_house_value\", axis=1)\ny_test = strat_test_set[\"median_house_value\"].copy()\n\nX_test_prepared = full_pipeline.transform(X_test)\nfinal_predictions = final_model.predict(X_test_prepared)\n\nfinal_mse = mean_squared_error(y_test, final_predictions)\nfinal_rmse = np.sqrt(final_mse)\n\nfinal_rmse\n```\n\n\n\n\n 48120.666286373504\n\n\n\n# Assignments\n\n**For the tick session**:\n\n## 1. \nFamiliarise yourself with the code in this practical. During the tick session, be prepared to discuss the different steps and answer questions (as well as ask questions yourself).\n\n## 2.\nExperiment with the different steps in the ML pipeline:\n- try dropping less informative features from the feature set and test whether it improves performance\n\n\n```python\ndef analyse_cv_new(model, housing_prepared, housing_labels): \n scores = cross_val_score(model, housing_prepared, housing_labels,\n scoring = \"neg_mean_squared_error\", cv=10)\n\n # cross-validation expects utility function (greater is better)\n # rather than cost function (lower is better), so the scores returned\n # are negative as they are the opposite of MSE\n sqrt_scores = np.sqrt(-scores) \n print(\"Scores:\", sqrt_scores)\n print(\"Mean:\", sqrt_scores.mean())\n print(\"Standard deviation:\", sqrt_scores.std())\n\nanalyse_cv_new(lin_reg, housing_prepared, housing_labels)\n```\n\n Scores: [66400.11538513 66561.82084573 67510.6874652 74900.77582974\n 67509.87374136 70884.73634886 64791.38470292 68141.40160344\n 70934.13138413 67393.71765602]\n Mean: 68502.86449625254\n Standard deviation: 2789.502396552837\n\n\n\n```python\ntotal_bedrooms_id, population_id, households_id = 4, 5, 6\nhousing_prepared_new = np.delete(housing_prepared, [total_bedrooms_id, population_id, households_id], axis=1)\nanalyse_cv_new(lin_reg, housing_prepared_new, housing_labels)\n```\n\n Scores: [68341.00047502 70016.22953188 71567.93792938 72810.29800432\n 71143.49586681 73744.20325876 67859.34345896 71423.46352447\n 73943.76494902 70905.890316 ]\n Mean: 71175.56273146225\n Standard deviation: 1939.0329703057362\n\n\n- use other options in preprocessing: e.g., different imputer strategies, min-max rather than standardisation for scaling, feature scaling vs. no feature scaling, and compare the results\n\n\n```python\nnum_pipeline_new = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n ('imputer', SimpleImputer(strategy=\"mean\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', StandardScaler()),\n ])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', CustomLabelBinarizer()),\n ])\n\nfull_pipeline_new = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline_new),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\nhousing_prepared_new = full_pipeline_new.fit_transform(housing)\nanalyse_cv_new(lin_reg, housing_prepared_new, housing_labels)\n```\n\n Scores: [66516.75393928 66631.06952871 67615.86467157 74913.20313627\n 67534.23635142 70940.21464109 65046.37854943 68166.47297387\n 71029.59283166 67433.19883791]\n Mean: 68582.69854612317\n Standard deviation: 2751.9381938658416\n\n\n\n```python\nnum_pipeline_new = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n ('imputer', SimpleImputer(strategy=\"mean\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', MinMaxScaler()),\n ])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', CustomLabelBinarizer()),\n ])\n\nfull_pipeline_new = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline_new),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\nhousing_prepared_new = full_pipeline_new.fit_transform(housing)\nanalyse_cv_new(lin_reg, housing_prepared_new, housing_labels)\n```\n\n Scores: [66516.75393928 66631.06952871 67615.86467157 74913.20313627\n 67534.23635142 70940.21464109 65046.37854943 68166.47297387\n 71029.59283166 67433.19883791]\n Mean: 68582.69854612318\n Standard deviation: 2751.9381938658476\n\n\n\n```python\nnum_pipeline_new = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n ('imputer', SimpleImputer(strategy=\"mean\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', CustomLabelBinarizer()),\n ])\n\nfull_pipeline_new = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline_new),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\nhousing_prepared_new = full_pipeline_new.fit_transform(housing)\nanalyse_cv_new(lin_reg, housing_prepared_new, housing_labels)\n```\n\n Scores: [66516.75393928 66631.06952871 67615.86467157 74913.20313627\n 67534.23635142 70940.21464109 65046.37854943 68166.47297387\n 71029.59283166 67433.19883791]\n Mean: 68582.69854612331\n Standard deviation: 2751.938193866012\n\n\n\n```python\nnum_pipeline_new = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n ('imputer', SimpleImputer(strategy=\"most_frequent\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', StandardScaler()),\n ])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', CustomLabelBinarizer()),\n ])\n\nfull_pipeline_new = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline_new),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\nhousing_prepared_new = full_pipeline_new.fit_transform(housing)\nanalyse_cv_new(lin_reg, housing_prepared_new, housing_labels)\n```\n\n Scores: [66264.25432041 66519.31819408 67785.23415589 74900.96620437\n 67476.65729311 70830.92177914 64388.85775551 68130.08856578\n 70811.60742081 67368.98562333]\n Mean: 68447.68913124381\n Standard deviation: 2837.5874876297885\n\n\n- evaluate the performance of the simple linear regression model on the test set. What is the `final_rmse` for this model?\n\n\n```python\n# final_model = grid_search.best_estimator_\nfinal_rmse\n```\n\n\n\n\n 48120.666286373504\n\n\n\n\n```python\nX_test = strat_test_set.drop(\"median_house_value\", axis=1)\ny_test = strat_test_set[\"median_house_value\"].copy()\n\nX_test_prepared = full_pipeline.transform(X_test)\nlin_reg_predictions = lin_reg.predict(X_test_prepared)\n\nlin_reg_mse = mean_squared_error(y_test, lin_reg_predictions)\nlin_reg_rmse = np.sqrt(lin_reg_mse)\n\nlin_reg_rmse\n```\n\n\n\n\n 66947.71053632068\n\n\n\n- estimate different feature importance weights with the simple linear regression model (if unsure how to extract the feature weights, check [documentation](http://scikit-learn.org/stable/modules/linear_model.html)). How do these compare to the (1) feature importance weights with the best estimator, and (2) feature correlation scores with the target value from Step 3?\n\n\n```python\nlin_reg_feature_importances = lin_reg.coef_\nsorted(zip(lin_reg_feature_importances, attributes), key=lambda importance: abs(importance[0]), reverse=True)\n```\n\n\n\n\n [(111141.19494268733, 'ISLAND'),\n (73190.50276486577, 'median_income'),\n (-57129.13357507744, 'latitude'),\n (-56098.57475829553, 'longitude'),\n (-54728.951389406924, 'INLAND'),\n (-46450.15548364255, 'population'),\n (45746.7921736657, 'households'),\n (31271.586491276645, 'rooms_per_household'),\n (-24833.115865396365, 'bedrooms_per_household'),\n (-22903.26946272087, 'NEAR BAY'),\n (22817.9599524631, 'bedrooms_per_rooms'),\n (-18442.4266798994, '<1H OCEAN'),\n (-15066.547410660214, 'NEAR OCEAN'),\n (14043.79310322378, 'housing_median_age'),\n (6873.222029285127, 'total_bedrooms'),\n (1088.019155080726, 'population_per_household'),\n (-1037.0634223499717, 'total_rooms')]\n\n\n\n\n```python\n# feature_importances = grid_search.best_estimator_.feature_importances_\nsorted(zip(feature_importances, attributes), reverse=True) \n```\n\n\n\n\n [(0.347772051379105, 'median_income'),\n (0.16464473359058016, 'INLAND'),\n (0.10585369057933745, 'population_per_household'),\n (0.07037048351061218, 'longitude'),\n (0.06350465384430061, 'latitude'),\n (0.061027834274864405, 'rooms_per_household'),\n (0.05391367920754573, 'bedrooms_per_rooms'),\n (0.04166147439601101, 'housing_median_age'),\n (0.02083288739395782, 'bedrooms_per_household'),\n (0.016177828017537574, 'total_rooms'),\n (0.014394495230388975, 'population'),\n (0.013545174129594096, 'total_bedrooms'),\n (0.01304204924214857, 'households'),\n (0.0072048823952477635, '<1H OCEAN'),\n (0.0032333637318216315, 'NEAR BAY'),\n (0.0027860765720088385, 'NEAR OCEAN'),\n (3.464250493825699e-05, 'ISLAND')]\n\n\n\n\n```python\n# corr_matrix = housing.corr()\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n```\n\n\n\n\n median_house_value 1.000000\n median_income 0.687160\n rooms_per_household 0.146285\n total_rooms 0.135097\n housing_median_age 0.114110\n households 0.064506\n total_bedrooms 0.047689\n population_per_household -0.021985\n population -0.026920\n bedrooms_per_household -0.043343\n longitude -0.047432\n latitude -0.142724\n bedrooms_per_rooms -0.259984\n Name: median_house_value, dtype: float64\n\n\n\n- [`RandomizedSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html), as opposed to the `GridSearchCV` used in the practical, does not try out each parameter values combination. Instead it only tries a fixed number of parameter settings sampled from the specified distributions. As a result, it allows you to try out a wider range of parameter values in a less expensive way than `GridSearchCV`. Apply `RandomizedSearchCV` and compare the best estimator results.\n\n\n```python\nfrom sklearn.model_selection import RandomizedSearchCV\n\nparam = {'n_estimators': range(1, 50), 'max_features': range(1, 10)}\n\nrandom_search= RandomizedSearchCV(forest_reg, param, n_iter=10, cv=5, scoring=\"neg_mean_squared_error\")\nrandom_search.fit(housing_prepared, housing_labels)\n\nrandom_search.best_params_\n```\n\n\n\n\n {'n_estimators': 42, 'max_features': 7}\n\n\n\n\n```python\n# grid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring=\"neg_mean_squared_error\")\ngrid_search.best_params_\n```\n\n\n\n\n {'max_features': 6, 'n_estimators': 30}\n\n\n\nFinally, if you want to have more practice with regression tasks, you can **work on the following optional task**:\n\n## 3. (Optional)\n\nUse the bike sharing dataset (`./bike_sharing/bike_hour.csv`, check `./bike_sharing/Readme.txt` for the description), apply the ML steps and gain insights from the data. What data transformations should be applied? Which attributes are most predictive? What additional attributes can be introduced? Which regression model performs best?\n\n\n```python\n\n```\n", "meta": {"hexsha": "ee643ff331d3592f7757f518a78c2e9ceefb36ab", "size": 790049, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Practical 1 - Linear Regression/DSPNP_notebook1.ipynb", "max_stars_repo_name": "VictorZXY/datasci-pnp-practicals", "max_stars_repo_head_hexsha": "0913c887a17c25e4995067eaf29bb8f278f270d3", "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": "Practical 1 - Linear Regression/DSPNP_notebook1.ipynb", "max_issues_repo_name": "VictorZXY/datasci-pnp-practicals", "max_issues_repo_head_hexsha": "0913c887a17c25e4995067eaf29bb8f278f270d3", "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": "Practical 1 - Linear Regression/DSPNP_notebook1.ipynb", "max_forks_repo_name": "VictorZXY/datasci-pnp-practicals", "max_forks_repo_head_hexsha": "0913c887a17c25e4995067eaf29bb8f278f270d3", "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": 230.6712408759, "max_line_length": 333912, "alphanum_fraction": 0.9001985953, "converted": true, "num_tokens": 23532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.19193279569159502, "lm_q1q2_score": 0.09147126479837617}} {"text": "##### Copyright 2021 The TF-Agents Authors.\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# RL 和深度 Q 网络简介\n\n\n \n \n \n \n
在 TensorFlow.org 上查看\n 在 Google Colab 运行\n 在 Github 上查看源代码\n 下载笔记本
\n\n## 简介\n\n强化学习 (RL) 是一种通用框架,其中代理可以学习在所处的环境中执行操作来使奖励最大化。两个主要组件是环境(代表要解决的问题)和代理(代表学习算法)。\n\n代理与环境持续相互作用。在每个时间步骤,代理都会根据其*策略* $\\pi(a_t|s_t)$(其中 $s_t$ 是来自环境的当前观测值)对环境执行操作并获得奖励 $r_{t+1}$ 和来自环境的下一个观测值 $s_{t+1}$。目标是改进策略,使奖励总和(回报)最大化。\n\n注:区分环境的 `state` 和 `observation` 非常重要,这是代理可以看到的环境 `state` 部分,例如在扑克游戏中,环境状态由属于所有玩家的纸牌和公共牌组成,但是代理只能观测到自己的纸牌和部分公共牌。在大多数文献中,这些术语可互换使用,观测值也表示为 $s$。\n\n\n\n这是一个非常通用的框架,可以对游戏、机器人等各种顺序决策问题进行建模\n\n\n## Cartpole 环境\n\nCartpole 环境是最著名的经典强化学习问题之一(RL 的 *\"Hello, World!\"*)。一根长杆连接到一个小车上,小车可以沿着无摩擦的轨道移动。长杆开始时是直立的,目标是通过控制小车来防止其倒下。\n\n- 来自环境 $s_t$ 的观测值是一个 4D 向量,表示小车的位置和速度以及长杆的角度和角速度。\n- 代理可以通过执行以下两个操作 $a_t$ 之一来控制系统:向右 (+1) 或向左 (-1) 推小车。\n- 对于长杆保持直立的每个时间步骤,都会提供 $r_{t+1} = 1$ 奖励。如果满足以下任一条件,则片段结束:\n - 长杆超过某个角度限制\n - 小车移出世界边缘\n - 经过 200 个时间步骤。\n\n代理的目标是学习策略 $\\pi(a_t|s_t)$,以使片段 $\\sum_{t=0}^{T} \\gamma^t r_t$ 中的奖励总和最大化。在这里,$\\gamma$ 是以 $[0, 1]$ 表示的折扣因子,该因子相对于即时奖励对未来的奖励打折扣。此参数有助于我们专注于策略,使其更关心快速获得奖励。\n\n\n## DQN 代理\n\n[DQN(深度 Q 网络)算法](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf)由 DeepMind 在 2015 年开发。通过将强化学习和深度神经网络进行大规模组合,它能够通关各种 Atari 游戏(有些甚至达到了超出人类能力的水平)。此算法通过使用深度神经网络和一种称为*经验回放*的技术来增强经典的 RL 算法(称为 Q-Learning)开发而成。\n\n### Q-Learning\n\nQ-Learning 基于 Q 函数的概念。策略 $\\pi$, $Q^{\\pi}(s, a)$ 的 Q 函数(又称状态-操作值函数)用于衡量通过首先采取操作 $a$、随后采取策略 $\\pi$,从状态 $s$ 获得的预期回报或折扣奖励总和。我们将最优 Q 函数 $Q^*(s, a)$ 定义为从观测值 $s$ 开始,先采取操作 $a$,随后采取最优策略所能获得的最大回报。最优 Q 函数遵循以下*贝尔曼*最优性方程:\n\n$\\begin{equation}Q^\\ast(s, a) = \\mathbb{E}[ r + \\gamma \\max_{a'} Q^\\ast(s', a') ]\\end{equation}$\n\n这意味着,从状态 $s$ 和操作 $a$ 获得的最大回报等于即时奖励 $r$ 与通过遵循最优策略,随后直到片段结束所获得的回报(折扣因子为 $\\gamma$)的总和(即,来自下一个状态 $s'$ 的最高奖励)。期望是在即时奖励 $r$ 的分布以及可能的下一个状态 $s'$ 的基础上计算的。\n\nQ-Learning 背后的基本思想是使用贝尔曼最优性方程作为迭代更新 $Q_{i+1}(s, a) \\leftarrow \\mathbb{E}\\left[ r + \\gamma \\max_{a'} Q_{i}(s', a')\\right]$,可以表明它会收敛到最优 $Q$ 函数,即 $Q_i \\rightarrow Q^*$ 作为 $i \\rightarrow \\infty$(请参阅 [DQN 论文](https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf))。\n\n### 深度 Q-Learning\n\n对于大多数问题,将 $Q$ 函数表示为包含 $s$ 和 $a$ 每种组合的值的表是不切实际的。相反,我们训练一个函数逼近器(例如,带参数 $\\theta$ 的神经网络)来估算 Q 值,即 $Q(s, a; \\theta) \\approx Q^*(s, a)$。这可以通过在每个步骤 $i$ 使以下损失最小化来实现:\n\n$\\begin{equation}L_i(\\theta_i) = \\mathbb{E}*{s, a, r, s'\\sim \\rho(.)} \\left[ (y_i - Q(s, a; \\theta_i))^2 \\right]\\end{equation}$,其中 $y_i = r + \\gamma \\max*{a'} Q(s', a'; \\theta_{i-1})$\n\n此处,$y_i$ 称为 TD(时间差分)目标,而 $y_i - Q$ 称为 TD 误差。$\\rho$ 表示行为分布,即从环境中收集的转换 ${s, a, r, s'}$ 的分布。\n\n注意,先前迭代 $\\theta_{i-1}$ 中的参数是固定的,不会更新。实际上,我们使用前几次迭代而不是最后一次迭代的网络参数快照。此副本称为*目标网络*。\n\nQ-Learning 是一种*离策略*算法,可在学习贪心策略 $a = \\max_{a} Q(s, a; \\theta)$ 的同时使用不同的行为策略在环境/收集数据过程中执行操作。此行为策略通常是一种 $\\epsilon$ 贪心策略,可选择概率为 $1-\\epsilon$ 的贪心操作和概率为 $\\epsilon$ 的随机操作,以确保良好覆盖状态-操作空间。\n\n### 经验回放\n\n为了避免计算 DQN 损失的全期望,我们可以使用随机梯度下降算法将其最小化。如果仅使用最后一个转换 ${s, a, r, s'}$ 来计算损失,那么这会简化为标准 Q-Learning。\n\nAtari DQN 工作引入了一种称为“经验回放”的技术,可使网络更新更加稳定。在数据收集的每个时间步骤,转换都会添加到称为*回放缓冲区*的循环缓冲区中。然后,在训练过程中,我们不是仅仅使用最新的转换来计算损失及其梯度,而是使用从回放缓冲区中采样的转换的 mini-batch 来计算它们。这样做有两个优点:通过在许多更新中重用每个转换来提高数据效率,以及在批次中使用不相关的转换来提高稳定性。\n\n\n## TF-Agents 中基于 Cartpole 的 DQN\n\nTF-Agents 提供了训练 DQN 代理所需的全部组件,例如代理本身、环境、策略、网络、回放缓冲区、数据收集循环和指标。这些组件以 Python 函数或 TensorFlow 计算图运算的形式实现,我们还提供用于在它们之间进行转换的包装器。此外,TF-Agents 还支持 TensorFlow 2.0 模式,这样我们便能在命令式模式下使用 TF。\n\n接下来,请查看[使用 TF-Agents 在 Cartpole 环境中训练 DQN 代理的教程](https://github.com/tensorflow/agents/blob/master/docs/tutorials/1_dqn_tutorial.ipynb)。\n\n", "meta": {"hexsha": "40bf4fe906140ab7b559b3c22f8af5268f15664d", "size": 7208, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "site/zh-cn/agents/tutorials/0_intro_rl.ipynb", "max_stars_repo_name": "RedContritio/docs-l10n", "max_stars_repo_head_hexsha": "f69a7c0d2157703a26cef95bac34b39ac0250373", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T22:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:32:18.000Z", "max_issues_repo_path": "site/zh-cn/agents/tutorials/0_intro_rl.ipynb", "max_issues_repo_name": "Juanita-cortez447/docs-l10n", "max_issues_repo_head_hexsha": "edaba1f2b5e329857860db1e937cb1333b6e3f31", "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": "site/zh-cn/agents/tutorials/0_intro_rl.ipynb", "max_forks_repo_name": "Juanita-cortez447/docs-l10n", "max_forks_repo_head_hexsha": "edaba1f2b5e329857860db1e937cb1333b6e3f31", "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": 45.3333333333, "max_line_length": 275, "alphanum_fraction": 0.5688124306, "converted": true, "num_tokens": 2875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.19193279338050545, "lm_q1q2_score": 0.0914712636969579}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n#####Version 0.1\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n第1章\n======\n***\n\nベイズ推論の考え方\n------\n\n\n> あなたは優秀なプログラマーだ.しかし,だれしも書いたコードにバグはある.実装するのが非常に難しいアルゴリズムのコードをなんとか書いた後,そのコードが正しいかどうかを簡単な例題でテストしようと考えた.OK,テストにパスした.次にもっと難しい問題でコードをテストした.今度もパスした.そして,なんと*もっともっと難しい問題*でも,パスした! だからあなたは,このコードにはバグはないかもしれないと思い始めてしまった...\n\n\nもしこのように考えたことがあるのなら,おめでとう! あなたはベイズ的に考る人の仲間入りだ.ベイズ推論とは,\n新しい証拠が得られるたびに自分の考えを改めるというものである.\nベイズ的に考える人は,ある結果が必ず起こるとは考えない.たぶん起こるだろうと考えるのである.\n上の例のように,普通は,プログラムに100%まったくバグがないとは考えない.\nないと言い切るには,実際にはありえないような場合も含めて,すべての場合についてチェックしなければならないだろう.\nそれよりも,たくさんの問題にたいしてテストして,それら全てにパスしたら,\nプログラムにバグは「たぶんないだろう」と思うのである.しかし「まったくない」とは言い切れない.\nベイズ推論も同じである.情報が得られたら信念を更新する.すべての可能な場合をチェックしなければ,絶対に,とは言わないのである.\n\n\n\n### 考え方のベイズ的な考え方\n\n\nベイス推論が伝統的な統計的推論と異なるのは,\n「不確実」なものは不確実なままにするという点である.\n不確実なままということに,最初はダメな方法だと思うかもしれない.\n統計とはランダムな現象から確実さを引き出すものではなかったのか?\nこれを理解するには,ベイズ的に考えることが必要になる.\n\n\n\nベイズ的な考え方,つまりベイズ主義(Bayesian)では,\n確率を「ある出来事がどのくらい信頼できるか」を表す指標と解釈する.\nつまり,ある事象が生じるということを,\nどのくらい確かだと思っているのか表すものと考える.\nすぐあとで見るように,実際にこれが確率を解釈する自然な方法である.\n\n\nこの解釈をもっと分かりやすくするために,\n確率のもう一つの解釈を考えてみよう.\nそれは「頻度主義」(*Frequentist*)というものであり,\nもっと*古典的*な統計学である.\n頻度主義では,確率を「長期間における事象の頻度」とみなす\n(だから「頻度主義」という名前で呼ばれている).\nたとえば,*飛行機事故の確率*を頻度主義で考えれば,\n「長期間における飛行機事故の頻度」になる.\nこの考え方は,多くの場合,事象の確率として意味がある.\nしかし長期間にわたって事象が発生しないような場合には,\n理解することが難しくなる.\n例えば大統領選挙の結果の確率を計算しようとしても,\nある特定の選挙は1回きりしか行われないのだ!\n頻度主義でこの問題を避けるには,\n他のすべての選挙も考慮して,\nこれらの発生する頻度で確率を定義することになる.\n\n\n\n一方のベイズ主義では,もっと直感的に考える.\nベイズ主義では,確率を,\nある事象が発生する信念(*belief*)\nもしくは確信(confidence)の度合いとみなす.\n確率とは,思っていることを要約したものであるだけなのである.\nある人が,ある事象の信念を0だと思っている場合,\nその事象が発生するとは考えていないことになる.\n反対に,ある事象の信念を1だと思っている場合,\nその事象が必ず発生すると考えていることになる.\n信念を0から1の実数値で表せば,それを使って\n他の結果に重みを付けることができる.\nこの定義を使えば,飛行機事故の確率の例を\nうまく表現することができる.\n飛行機事故の頻度が得られた時に,他の情報が何もなければ,\nある人の信念はその頻度に一致するべきである.\n同様に,確率が信念であるという定義を使えば,\n大統領選挙の結果の確率(信念)というものを考えてもよいだろう.\nつまり,ある候補者Aが当選することをどのくらい確信しているのか,\nを表しているのである.\n\n\n\n上のパラグラフでは,一般的な信念(確率)ではなく,\n「ある人」の信念(確率)というものを説明していたことに注意して欲しい.\nこれが面白いのは,人によって信念が違うということを定義が許していることになる点である.\nこれは日常では見かける.この世界について持っている情報は人それぞれ違うので,\nある人の信念は別の人の信念とは違うのである.\n信念が違っているということは,「誰かが間違っている」ということではない.\n以下の例で,各個人が持っている信念と確率との関係を考えてみてみよう.\n\n\n\n- 私がコインを投げて,表が出るか裏が出るか,わたしとあなたが賭けているとしよう.イカサマのコインでなければ,表が出る確率は1/2である.これはわたしもあなたも同意している.ここで,私だけがコインの結果を除いてみたとする.そうすると,私にとっては表か裏の確率のどちらかが1.0になる(コインの結果による).では「コインが表である」について,あなたの信念はどうだろう? 私がコインの結果を知っても,コインの結果は変わらない.私とあなたの信念は,同じではなくなってしまった.\n- あなたのプログラムにはバグがあるかもしれないし,ないかもしれない.あなたも私も,どちらが正しいのか分からないが,バグがあるのかないのかについての信念は持っている.\n- 病院において,ある患者がx,y,zという症状を自覚している.それらの症状を発生する病気はたくさんあるが,どれか一つの病気が原因である.ある医師はその原因がある病気だろうという思っているが,別の医師はすこし違った原因を思っているかもしれない.\n\n\n\n人間にとっては,確率を信念のように扱うということは自然なやり方である.この世の中で生きていくために,いつもこのようなやり方をしているし,真実というものが完全ではないという例もたくさん見ている.それでも信念から何か情報がえられないかと考えてもいる.もし頻度主義のように考えるとするなら,かなり訓練しなければならないだろう.\n\n\n\n従来の確率論の記法に従って,\nある事象$A$が生じるという信念を$P(A)$と表し,\n事前確率(*prior probability*)と呼ぶことにする.\n\n\n\n偉大な経済学者であり思想家であるジョン・メイナード・ケインズ曰く,\n「事実が変わったならば,わたしは考えを改める.あなたはどうしますか?」\nこれは証拠が得られた後に信念を更新す,ベイズ主義的なやり方である.\nもし,その証拠が最初に思っていた信念と相反することであったとしても,\n証拠を無視することはできない.\nこの更新された信念を$P(A |X )$と表し,\n証拠$X$が与えられた時の$A$の確率である,と解釈する.\n事前確率に対応して,この更新された信念を事後確率(*posterior probability*)と呼ぶ.\n例えば上記の例では,証拠$X$が得られた後の事後確率(事後信念と言ってもよい)は次のようになる.\n\n\n\n1\\. $P(A): \\;\\;$ コインの表が出る確率は50パーセントである.$P(A | X):\\;\\;$ コインの結果をみて表が出ていたとする.この情報を$X$とする.明らかに,表の事後確率は1.0で,裏の事後確率は0.0である.\n\n2\\. $P(A): \\;\\;$ この複雑で巨大なプログラムにはたぶんバグがある.$P(A | X): \\;\\;$ プログラムはすべてのテスト$X$にパスした.たぶんバグがあるかもしれないが,その可能性は非常に小さいだろう.\n\n3\\. $P(A):\\;\\;$ ある患者が病気にかかっている.$P(A | X):\\;\\;$ 血液検査の結果,$X$という証拠が得られたので,いくつかの病気の可能性は排除してもよいだろう.\n\n\n\nこれらの例から明らかなように,新しい証拠$X$が得られたとしても,\n事前の信念を完全に否定することはなく,新しい証拠を事前確率の重みとして使っている\n(つまり,ある信念にはより大きい重み,つまり確信度を与えるのである).\n\n\n事前にある事象がどのくらい生じるのかということを考えても,それは非常に不確実である.\nしたがって,どんな結果を予想したとしても,間違っている可能性が高い.\nデータや証拠や情報が得られれば,信念を更新して,\n間違っている可能性がもっと少ない予測をすることができるようになる.\nコインの裏表を予測すること例では,正しい予測ができるようになる.\n\n\n\n### 実用的なベイズ推論\n\n\n頻度主義とベイス主義がプログラミング言語の関数だったら,統計的な問題を入力すると,ユーザーに返される結果は同じではないだろう.\n頻度主義の推論関数の戻り値は,推定値を表す数値である(標本平均などの要約統計量であることが多い).\n一方でベイズ主義の推論関数は,「確率」を返す.\n\n\n例えばデバッグの例題であれば,頻度主義関数の引数に\n「このプログラムはテスト$X$のすべてをパスしたんだ.このプログラムにはバグがないかな?」を渡すと,\n戻り値は「バグはありません」だろう.\nしかしベイズ主義関数に\n「プログラムを書くといつもバグがあるんだ.\nこのプログラムはテスト$X$のすべてをパスしたんだ.このプログラムにはバグがないかな?」という引数を渡すと,\n「バグはありません」と「バグがあります」の答えのそれぞれに確率が返される.\n\n\n\n> バグがない確率は0.8,バグがある確率は0.2です.\n\n\nこの戻り値は頻度主義関数の戻り値とはまったく違うものである.\nベイズ主義関数は引数に「プログラムを書くといつもバグがあるんだ」という情報を追加していることに気がついてほしい.\nこれが**事前情報**(prior)である.\nこの事前情報パラメータを引数に与えることで,今の状況についての信念をベイズ主義関数に伝えている.\nこれを与えるかどうかはユーザーの自由だが,与えない場合には別の結果が得られることになる.\nその例は後で見ることにしよう.\n\n\n#### 証拠を取り入れる\n\n\n証拠をたくさん手に入れることができれば,事前の信念は,その多数の証拠にかき消されてしまう.\nこれは想像できるだろう.\n例えば,あなたが「今日,太陽が爆発するんじゃないか」という事前信念を持っていたとすれば,日に日にその信念は揺らいでいき,\nそして,どんな推論でもいいから自分の間違いを正してくれ,少なくともこの信念をもっとマシなものにしてくれ,\nと思うようになる(かもしれない).\nそしてベイズ推論は,その信念を正してくれる.\n\n\n$N$を手に入る証拠の数とする.もし無限個の証拠が手に入れば,つまり$N \\rightarrow \\infty$ならば,\nベイズ推論の結果は頻度主義の結果と(多くの場合)一致する.\nしたがって$N$が大きくなれば,統計的推論は客観的なものになる.\n反対に$N$が小さければ,推論は*不安定*なものになる.\n頻度主義の推定値は分散も信頼区間も大きくなる.\nそんな時にはベイズ推論の出番である.\n事前分布を引数にとり,結果に(推定値ではなく)確率を出力する.\nこれは,$N$の小さいデータセットに対する統計的推論の不安定さを反映した,不確実さを表すものになっている.\n\n\n\n$N$が非常に大きい場合は,頻度主義とベイズ主義は似たような推論結果を出してくるので,二つの区別はつかなくなるだろう.\nそのため,少ない計算で済む頻度主義を用いたくなるかもしれない.\nもしそんな状況にあるのであれば,そうする前に以下の\n[Andrew Gelman (2005)][1]の文章を読んでほしい.\n\n\n\n> サンプル数が大きい場合,というものは存在しない.もし$N$が小さすぎて十分に正確な推定値を得ることができないのであれば,データをもっと増やす(もしくはもっと多くの仮定を使う)必要がある.しかし,もし$N$が「十分に大きい」のであれば,データを分割してもっと多くの情報を得ることができるだろう(例えば世論調査の場合には,全国区での良い推定値が得られたら,次は男女別,地域別,年齢別の推定値を得ることもできるだろう).$N$が十分であることはない.もし「十分」だとしたら,あなたはもうすでにもっと多くのデータを必要とする次の問題に取り組んでいるのだ.\n\n\n\n\n### じゃあ頻度主義は間違っているの?\n\n\n\n**間違ってはいない.**\n\n\n頻度主義の方法は今でも多くの分野で有用であり,最先端で使われれいる.\n最小二乗回帰やlasso回帰,EMアルゴリズムなどのツールはどれも優れていて処理も速い.\nベイズ主義の手法は,それらの手法を補うものである.\nそれらの手法が適用できない問題を解いたり,\nもっと柔軟なモデル化で隠れた構造を解き明かしたりするのである.\n\n\n### 「ビッグデータ」について\n\n\n逆説的に聞こえるかもしれないが,ビッグデータで予測したり解析したりする問題には,\n実際には比較的単純なアルゴリズムが使われている[2][4].\nビッグデータを用いた予測の難しさは,アルゴリズムにあるのではない.\nビッグデータを保存し読み出すストレージや\nビッグデータに対して実行する時の計算量が大変なのである.\n(上述のGelmanの文章を読んで「自分は本当にビッグデータを持っているのだろうか?」と考えてみてほしい)\n\n\n解析するのがもっと難しい問題は,「ミディアムなデータ」の場合であり,\n特に問題となるのは「スモールデータ」の場合である.\nGelmanの文章を借りるなら,ビッグデータの問題が「十分にビッグ」で実際には解けないのであれば,\n「それほど十分にビッグではない」データを扱えばよいのである.\n\n\n\n### ここでのベイズ推論の枠組み\n\n\n\n計算するべき信念は,ベイズ的に考えた確率と解釈することができる.\nここで,ある事象$A$について「事前」信念を持っているとしよう\n(例えば,テストを実行する前に,プログラムにバグがありそうかどうかについての信念).\n\n\n\n次は,得られた証拠を使おう.バグありプログラムの例を使えば,\nプログラムはテスト$X$にパスしたので,その情報を取り入れて信念を更新したい.\nこの更新された新しい信念を「事後」信念と呼ぶことにする.\n以下の式を使えば,信念を更新することができる.\nこの式は,発見者のトーマス・ベイズにちなんで,ベイズの定理と呼ばれている.\n\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{は比例を表す} )\n\\end{align}\n\n\n\nこの公式はベイズ推論だけのものではない.ベイズ推論以外でも使われている数学的事実である.\nベイズ推論では,単にこの式を使って\n初期の事前確率$P(A)$と更新後の事後確率$P(A | X)$を結びつけているだけである.\n\n\n\n\n##### 例題:だれもが一度はやる「コイン投げ」の問題\n\n\n統計学のテキストであれば,コイン投げの問題を扱っていない本はない.\nちょっと変わったやり方でこの問題を扱ってみよう.\nあなたは,コインの表が出る確率がよくわからないとする(本当は50%).\n何らかの比率(ここでは$p$とする)で表裏がでるということについては信じているが,\nその$p$がどのくらいなのかについては,まったく情報を持っていない.\n\n\nではコイン投げを初めて,表$H$が出たのか裏$T$が出たのかを記録することにする.\nここでちょっと考えてみよう.\nデータが増えるにつれて,推論結果はどのように変わっていくのだろうか?\nもっと正確に言えば,データが少ない時とデータが多い時とで,事後確率はどのように違うのだろうか?\n\n\n以下のコードは,\n(コイン投げの)データが増えるたびに更新される事後確率の系列をプロットするものである.\n\n\n\n\n\n```\n\"\"\"\n本書ではmatplotlibのグラフのスタイルを変更するために,matplotlibrcファイルをカスタマイズしている.\n本書を実行して,本書のスタイルを使いたいのであれば,以下の2つの方法がある.\n 1. 本書の style/ ディレクトリにあるrcフィアルで,自分の環境のmatplotlibrcを書き換える.\n http://matplotlib.org/users/customizing.htmlを参照.\n 2. スタイルはbmh_matplotlibrc.jsonファイルにもある.これを使って以下のコードを実行すれば,\n 本書にだけスタイルを適用することができる.\n import json\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\"\"\"\n\n# 以下のコードは読み飛ばして構わない.ここではあまり重要ではないし,\n# まだ説明していない進んだ内容も含んでいる.その下のグラフを見て!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n \n# 分かっている人へ:ここでは二項分布の共役事前分布を使っている.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials) / 2, 2, k + 1)\n # u\"$p$, 表が出る確率\"\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials) - 1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads)) # u\"%d回投げて, \\n 表は%d回\"\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\", # u\"ベイズ推論による事後確率の更新\"\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\n事後確率は曲線で表されている.\n不確実さは,この曲線の広がり具合に比例している.\n上のグラフを見れば分かるように,\nデータが増えるたびに事後確率の曲線は右へ左へと動き回る.\n最終的に,データがたくさん手に入れば(たくさんコインを投げたら),\n事後確率曲線は,真の確率である$p=0.5$に次第に集まってくる.\n\n\nなお,曲線のピークの位置は0.5ではないし,そうである理由もない.$p$の値については何も知らない,という前提だったのだから.\n実際のとこr,コイン投げの結果が極端な,たとえば8回投げて表が1回しかなかったような場合には,\n事後確率曲線のピークは0.5から非常に離れているだろう\n(事前情報がないのだから,8回投げて表が1回しか出ないコインにイカサマはないと,どのくらい確信できるだろう?).\nもっとデータが増えれば,確率はもっと$p=0.5$に近くなるだろう.\n\n\n次の例で,数学がベイズ推論でどのように使われるのか見てみよう.\n\n\n##### 例題:バグか,仕様か?\n\n\n「プログラムにはバグがない」という事象を$A$とする.\n「このプログラムがすべてのデバッグテストにパスする」という事象を$X$とする.\nとりあえず,バグがないという事前確率$P(A)$を変数$p$にしておこう.\nつまり$P(A) = p$とする.\n\n\n今から考えるのはこの$P(A|X)$だ.\nつまり,「デバッグテスト$X$をパスした時に,バグがない」確率である.\n上の公式を使うために,いくつか計算しなければならない.\n\n\nでは$P(X | A)$とは何だろう? これは,「バグがない時にすべてのテスト$X$をパスする」確率である.明らかに,これは1である.バグがなければ,どんなテストにもパスするからだ.\n\n\nそれよりも厄介なのは$P(X)$である.事象$X$が起きる可能性は2つある.\n実はバグがある(これを$\\sim A$や$\\lnot A$と書いて*not $A$*と読む)にも関わらず事象$X$が起こっているのか,それともバグがないから事象$X$が起きているのか,である.\nすると,$P(X)$は以下のように解釈できる.\n\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nすでに$P(X|A)$は計算してある.しかし$P(X | \\sim A)$をどうするかは,主観的である.\nプログラムはテストをパスしたが,それでもバグがあるのだ.\nしかしバグがある確率は小さくなっている.\nこれは実行したテストの数や,テストがどれだけ精巧なのかにも依存する.\nここでは控えめに考えて,$P(X|\\sim A) = 0.5$としよう.すると以下のようになる.\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nこれが事後確率である.これを事前確率パラメータ$p \\in [0,1]$の関数としてみたら,\nどんな形をしているだろう?\n\n\n\n```\nfigsize(12.5, 4) # グラフの縦横サイズを12.5:4にする\np = np.linspace(0, 1, 50) # 0から1までを50点に分割\nplt.plot(p, 2 * p / (1 + p), color=\"#348ABD\", lw=3) # 事後確率をプロット.色は青系,線幅は3\n# plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"]) # コメントを外して試してみよう\nplt.scatter(0.2, 2 * (0.2) / 1.2, s=140, c=\"#348ABD\") # p=0.2のところに点を描画.色は青系,サイズは140\nplt.xlim(0, 1) # x軸の範囲を(0,1)に設定\nplt.ylim(0, 1) # y軸の範囲を(0,1)に設定\nplt.xlabel(\"Prior, $P(A) = p$\") # x軸ラベル u\"事前確率$P(A) = p$\"\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\") # y軸ラベル u\"$P(A) = p$の時の事後確率$P(A|X)$\"\nplt.title(\"Are there bugs in my code?\") # グラフのタイトル u\"プログラムにバグがあるか?\"\n```\n\n事前確率$p$が小さい時は,テスト$X$にパスしたという証拠が非常に効いている.\nここで事前確率の値を一つ決めてみよう.\n私は優秀なプログラマーなので(自分ではそう思っている),0.20でも現実的だろう.\nつまり,20%の確率でバグのないプログラムを書くことができる,というわけだ.\nもっとも現実的には,この事前確率は\nプログラムがどれだけ複雑で大規模なのかにもよるのだが,\nとりあえず0.20としておこう.\nすると,プログラムにはバグがないという更新された信念は0.33となる.\n\n\nここで事前確率は確率である,ということを思い出しておこう.\n$p$はバグがない事前確率で,$1-p$はバグがある事前確率である\n\n\n同様に,事後確率も確率である.\n$P(A | X)$は「すべてのテストをパスしてバグがない」確率,\n$1-P(A|X)$は「すべてのテストをパスしてバグがある」確率である.\nこの事後確率はどんな値だろうか?\n以下のグラフは,事前確率と事後確率を計算したものである.\n\n\n\n```\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1. / 3, 2. / 3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\", # u\"事前確率\"\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\", # u\"事後確率\"\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"]) # u\"バグがない\", u\"バグがある\nplt.title(\"Prior and Posterior probability of bugs present\") # u\"バグがある事前確率と事後確率\"\nplt.ylabel(\"Probability\") # u\"確率\"\nplt.legend(loc=\"upper left\"); # 凡例の位置は左上\n```\n\n証拠となる事象$X$が得られた後では,バグがないという確率が大きくなっている.\nテストの数を増やせば,バグがない(確率1)ということを確信できるだろう.\n\n\nこれはベイズ推論とベイズ則の非常に単純な例である.\n残念ながら,もう少し複雑なベイズ推論を実行するための数学は,\n非常に調整された例題でなければ,もっともっと難しくなってしまう.\nあとで見るように,この手の数学的な解析は実際には必要ない.\nいろいろなモデル化のためのツールを知るほうが先である.\n次の節は「確率分布」を扱う.もしよく知っているなら,\n読み飛ばして(もしくは斜め読みして)もよい.\nよく知らなければ,非常に重要なのでよく理解してほしい.\n\n\n\n_______\n\n## 確率分布\n\n\n\n**確率分布とは何かを簡単におさらいしよう.**\n$Z$を確率変数とする.\n$Z$が取る値それぞれに確率を与えるのが確率分布である.\nグラフで描けば,確率分布は曲線で書くことができて,\nその曲線の高さに比例して確率が大きくなる.\nすでにこの章の最初の図で,確率分布の曲線の例を説明している.\n\n\n確率変数には以下のように3種類ある.\n\n\n- **$Z$が離散の場合**:離散確率変数は,与えられた値のリストの中のどれか一つの値を取る.人口,映画の評価,得票数などは離散確率変数の例である.離散確率変数は,以下の連続の場合と対比すると分かりやすい.\n- **$Z$が連続の場合**:連続確率変数は任意精度の値を取る.例えば温度,速度,時間,色などは連続確率変数でモデル化される.これらの値は,いくらでも精度よく指定することができるからだ.\n- **$Z$が混合型の場合**:混合型の確率変数は,離散と連続のどちらの値も取る.上の2つのタイプの組み合わせである.\n\n\n\n\n###離散の場合\n\n\nもし$Z$が離散なら,確率分布は*確率質量関数*と呼ばれる.\nこれは$Z$が値$k$を取る確率を$P(Z=k)$で表す.\n確率質量関数は確率変数$Z$を完全に決定する.つまり\n確率質量関数が分かれば$Z$がどのように振る舞うのかが分かるのである.\nこの先よく登場する有名な確率質量関数がいくつかあるが,\n必要に応じて紹介する.一番最初に紹介する有用な確率質量関数は,ポワソン分布である.\n$Z$の確率質量関数が以下の式の時,$Z$はポワソン分布に従うと言う.\n\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$は分布のパラメータで,分布の形状を決める.\nポワソン分布の場合,$\\lambda$は任意の正の実数である.\n$\\lambda$を大きくすると大きな値の確率が高くなり,\n$\\lambda$を小さくすると小さな値の確率が高くなる.\nそのため,$\\lambda$はポワソン分布の「強度」と考えてもよい.\n\n\n任意の正の実数である$\\lambda$とは異なり,上の式での$k$の値は正の整数,つまり0, 1, 2, ... でなければならない.これは重要な事である.人数をモデル化しようとするなら,4.25人とか5.612人というのは意味が無いのだから.\n\n\nもし確率変数$Z$がポワソン分布に従うなら,それを以下のように書く.\n\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nポワソン分布の便利な性質の一つは,期待値が分布パラメータに等しいということである.\n\n\n$$E[ \\;Z\\; | \\; \\lambda \\;] = \\lambda $$\n\n\nこの先この性質を利用するので覚えておいてほしい.\n以下のグラフは,いくつかの$\\lambda$の値について確率質量関数をプロットしたものである.\nこのグラフで注意してほしいことは2つ.1つ目は$\\lambda$を大きくすれば,\n大きな値の確率が高くなること.2つ目は,グラフの横軸は15で終わっているが,\n分布はそうではない.すべての正の整数に対して確率が割り当てられている.\n\n\n\n```\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\") # u\"$k$の確率\"\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\") # u\"いくつかの$\\lambda$に対するポワソン分布の確率質量関数\"\n```\n\n###連続の場合\n\n\n連続確率変数は,確率質量関数ではなく確率密度分布関数で表される.\nこれは単なる名前の問題のように見えるかもしれないが,\n密度関数と質量関数はまったく違うものなのである.\n連続確率変数の例は,以下の式で表される指数分布である.\n\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1. / l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0, 1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n###But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```\nimport pymc as pm\n\nalpha = 1.0 / count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nwith pm.Model() as model:\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\nwith model:\n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```\nprint \"Random output:\", tau.random(), tau.random(), tau.random()\n```\n\n\n```\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. \n\n\n```\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```\n# Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n\n```\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```\nfigsize(12.5, 10)\n# histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data) - 20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n###Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```\n# type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```\n# type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```\n# type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n", "meta": {"hexsha": "a09cdf407514ceb34a5d8e8c945596cf14d66816", "size": 341367, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_stars_repo_name": "tttamaki/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "8a9fa5070c84021a29e3cad9fd5769f84cce0542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-05-24T17:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T11:33:11.000Z", "max_issues_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_issues_repo_name": "tttamaki/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "8a9fa5070c84021a29e3cad9fd5769f84cce0542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_forks_repo_name": "tttamaki/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "8a9fa5070c84021a29e3cad9fd5769f84cce0542", "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": 238.8852344297, "max_line_length": 95083, "alphanum_fraction": 0.8602618296, "converted": true, "num_tokens": 21357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.2909808662149068, "lm_q1q2_score": 0.0913826996169797}} {"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n \n\n \n\n\n\n[Python for Probability, Statistics, and Machine Learning](https://www.springer.com/fr/book/9783319307152)\n\n\n```python\nfrom __future__ import division\n%pylab inline\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\nWe considered Maximum Likelihood Estimation (MLE) and Maximum A-Posteriori\n(MAP) estimation and in each case we started out with a probability density\nfunction of 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 survive the\nweakening of either or both of these assumptions. More concretely, suppose you\nhave a model that works great except for a few outliers. The temptation is to\njust ignore the outliers and proceed. Robust estimation methods provide a\ndisciplined way to handle outliers without cherry-picking data that works for\nyour favored model.\n\n### The Notion of Location\n\nThe first notion we need is *location*, which is a generalization of the idea\nof *central value*. Typically, we just use an estimate of the mean for this,\nbut we will see later why this could be a bad idea. The general idea of\nlocation satisfies the following requirements Let $X$ be a random variable with\ndistribution $F$, and let $\\theta(X)$ be some descriptive measure of $F$. Then\n$\\theta(X)$ is said to be a measure of *location* if for any constants *a* and\n*b*, we have the following:\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 located.\n\nFor example, the sample mean estimator is $ \\hat{\\mu}=\\frac{1}{n}\\sum X_i $. The first\nrequirement is obviously satisfied as $ \\hat{\\mu}=\\frac{1}{n}\\sum (X_i+b) = b +\n\\frac{1}{n}\\sum X_i =b+\\hat{\\mu}$. Let us consider the second requirement:$\n\\hat{\\mu}=\\frac{1}{n}\\sum -X_i = -\\hat{\\mu}$. Finally, the last requirement is\nsatisfied with $ \\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 in the\n*location* parameter, what can we do with it? Previously, we assumed that our samples\nwere all identically distributed. The key idea is that the samples might be\nactually coming from a *single* distribution that is contaminated 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 data 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 are contaminating $G(X)$. This means that whatever estimators we construct\nhave to be derived from a more generalized family of distributions instead of\nfrom a single distribution, as the maximum-likelihood method assumes. This is\nwhat makes 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 generalized maximum likelihood estimators. Recall that for\nmaximum likelihood, we 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 except for the fact that we don't assume a specific $f_0$ as the\ndistribution of the $\\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 $\\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$ gives\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 reasons we will assume that\n$\\psi$ is increasing. So far, it looks like we just pushed some definitions\naround, but the key idea is we want to consider general $\\rho$ functions that\nmay not be maximum likelihood estimators for *any* distribution. 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 $\\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 = \\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 $\\hat{\\mu}$ is to the optimum. In other words, this provides a sense of\nhow much outlier contamination costs in terms of samples. For example, if for\ntwo estimates with asymptotic variances $v_1$ and $v_2$, we have $v_1=3v_2$,\nthen first estimate requires three times as many observations to obtain the\nsame variance 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 $\\psi=x$ and also $\\psi'=1$. Thus, we have $v=\\mathbb{V}(x)$.\nAlternatively, using the sample median as the estimator for the location, we\nhave $v=1/(4 f(\\mu_0)^2)$. Thus, if we have $F=\\mathcal{N}(0,1)$, for the\nsample median, we obtain $v={2\\pi}/{4} \\approx 1.571$. This means that the\nsample median takes approximately 1.6 times as many samples to obtain the same\nvariance for the location as the sample mean. The sample median is \nfar more immune to the effects of outliers than the sample mean, so this \ngives a sense of how much this robustness costs in samples.\n\n** M-Estimates as Weighted Means.** One way to think about M-estimates is a\nweighted means. Operationally, this\nmeans that we want weight functions that can circumscribe the\ninfluence of the individual data points, but, when taken as a whole,\nstill provide good estimated parameters. Most of the time, we have $\\psi(0)=0$ and $\\psi'(0)$ exists so\nthat $\\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 ref{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} \\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 $w_i$ contains $\\hat{\\mu}$, which is what we are trying to solve\nfor. The question that remains is how to pick the $\\psi$ functions. This is\nstill an open question, but the Huber functions are a well-studied choice.\n\n### Huber Functions\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 k \\\\\\\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| \\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\nref{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 choosing $k=0$ leads to the sample median, but that is not so\nstraightforward to solve for. Nonetheless, Huber functions provide a way\nto move between two extremes of estimators for location (namely, \nthe mean vs. the median) with a tunable parameter $k$. \nThe $W$ function corresponding to Huber's $\\psi$ is the following:\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$ with some sample points. The idea is that the computed\nlocation, $\\hat{\\mu}$ is computed from Equation ref{eq:Wmuhat} to lie somewhere\nin the middle of the weight function so that those terms (i.e., *insiders*)\nhave their values fully reflected in the location estimate. The black circles\nare the *outliers* that have their values attenuated by the weight function so\nthat only a fraction of their presence is represented in the location estimate.\n\n\n\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\n

Histogram 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\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n\n\n''')\n```\n\n\n\n\n\n\n\n\n\n\n\n# Benchmark Problem 5: Stokes Flow\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''{% include jupyter_benchmark_table.html num=\"[5]\" revision=0 %}''')\n```\n\n\n\n\n{% include jupyter_benchmark_table.html num=\"[5]\" revision=0 %}\n\n\n\nSee the Overleaf document entitled [\"Phase Field Benchmark Problems for Dendritic Growth and Linear Elasticity\"][overleaf] for more details about the benchmark problems. Furthermore, read [the extended essay][benchmarks] for a discussion about the need for benchmark problems.\n\n[benchmarks]: ../ \n[overleaf]: https://www.overleaf.com/read/nqjkdwyybvdz\n\n# Overview\n\nFlow of a liquid can be incorporated into phase field models, so we present this benchmark problem for incompressible fluid flow through a channel (the flow of many liquids can be modeled as incompressible). The flow of a fluid can generally be modeled via the Navier-Stokes equations. When length scales are small, fluid velocities are low, and/or viscosity is large, such that the Reynolds number $Re<<1$, inertial forces are small compared with viscous forces, resulting in a simplification of Navier-Stokes flow to Stokes flow. \n\n# Model Formulation\n\n## Governing Equations\n\nIn this problem, two variables are used: the fluid velocity, $\\textbf{u}$, which is a vector field, and the fluid pressure, $p$, which is a scalar field. The Stokes momentum equation is given as\n\n\\begin{equation}\n-\\mu \\nabla^{2} \\textbf{u} + \\nabla p - \\rho \\textbf{g} = 0,\n\\end{equation}\n\nwhere $\\rho$ is the density, assumed constant in this problem, $\\mu$ is the dynamic viscosity, and $\\textbf{g}$ is the acceleration due to gravity. To fully describe fluid flow, the momentum balance equation is supplemented with the continuity equation for mass flow,\n\n\\begin{equation}\n\\frac{d\\rho}{dt}+\\nabla\\cdot\\left(\\rho{\\mathbf u}\\right)=0;\n\\end{equation}\n\nthis simplifies to \n\\begin{equation}\n\\nabla \\cdot \\textbf{u} = 0\n\\end{equation}\n\nfor incompressible flow. Use $\\rho=100$, $\\mu=1$, and $\\textbf{g}=(0,-0.001)$.\n\n## Domain\n\nIn this problem, we consider flow in a 2D channel (a) without and (b) with an obstruction. The computational domain for case (b) is shown below with inlet boundary condition indicated by arrows for the Stokes flow benchmark problem with an obstruction (case (b)). The domain and boundary conditions, etc., for case (a) are the same as that in case (b), but without the obstruction. \n\n### Figure 1: Domain for variation (b)\n\n\n\n\n## Boundary Conditions\n\nAll solid surfaces, including the boundary for the obstruction, have no-slip boundary conditions, that is, $u_x=u_y=0$. The inlet velocity, on the left boundary, follows a parabolic profile described by \n\n\\begin{equation}\nu_x(0,y) = -0.001(y-3)^2+0.009.\n\\end{equation}\n\nThe outlet velocity (on the right boundary) is left to the solver to determine, as is the pressure over the entire domain. However, we specify that the pressure at point (30, 6) is zero. Finally, the obstruction is described by an ellipse centered at (7, 2.5). The semi-major axis (in the *y*-direction) is $a=1.5$, and the semi-minor axis (in the *x*-direction) is $b=1$. \n\n## Submission Guidelines\n\nBoth variation (a) and (b) should be run to steady state.\nPlease submit the steady state pressure and the steady state velocity fields for both variation (a) and (b) along the $x=7$ and $y=5$ cut planes.\n\nThis will require two CSV or JSON files for each variation. Please,\n\n - link to your first CSV or JSON file, labeled x_cut_plane in the upload form; the columns or keys should be named y, velocity_x, velocity_y and pressure\n \n - link to your second CSV or JSON file, labeled y_cut_plane in the upload form; the columns or keys should be named x, velocity_x, velocity_y and pressure\n\nFurther data to upload can include images of the pressure and velocity fields at steady state. These are not required, but will help others view your work.\n\n\n", "meta": {"hexsha": "7992965f251b6ddb036a6400a31d2208088badc1", "size": 8721, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "benchmarks/benchmark5-hackathon.ipynb", "max_stars_repo_name": "wd15/chimad-phase-field", "max_stars_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "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": "benchmarks/benchmark5-hackathon.ipynb", "max_issues_repo_name": "wd15/chimad-phase-field", "max_issues_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-02-06T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-12T17:39:56.000Z", "max_forks_repo_path": "benchmarks/benchmark5-hackathon.ipynb", "max_forks_repo_name": "wd15/chimad-phase-field", "max_forks_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "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": 33.286259542, "max_line_length": 539, "alphanum_fraction": 0.5744754042, "converted": true, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.22000710486009023, "lm_q1q2_score": 0.09128069387354013}} {"text": "# Funciones de utilidad y aversión al riesgo\n\n\n\nEn el módulo anterior aprendimos \n- qué es un portafolio, cómo medir su rendimiento esperado y su volatilidad; \n- un portafolio de activos riesgosos tiene menos riesgo que la suma ponderada de los riesgos individuales,\n- y que esto se logra mediante el concepto de diversificación;\n- la diversificación elimina el riesgo idiosincrático, que es el que afecta a cada compañía en particular,\n- sin embargo, el riesgo de mercado no se puede eliminar porque afecta a todos por igual.\n- Finalmente, aprendimos conceptos importantes como frontera de mínima varianza, portafolios eficientes y el portafolio de mínima varianza, que son claves en el problema de selección óptima de portafolios.\n\nMuy bien, sin embargo, para plantear el problema de selección óptima de portafolios necesitamos definir la función que vamos a optimizar: función de utilidad.\n\n**Objetivos:**\n- ¿Cómo tomamos decisiones según los economistas?\n- ¿Cómo toman decisiones los inversionistas?\n- ¿Qué son las funciones de utilidad?\n\n*Referencia:*\n- Notas del curso \"Portfolio Selection and Risk Management\", Rice University, disponible en Coursera.\n___\n\n## 1. Introducción\n\nLa teoría económica comienza con una suposición muy importante: \n- **cada individuo actúa para obtener el mayor beneficio posible con los recursos disponibles**.\n- En otras palabras, **maximizan su propia utilidad**\n\n¿Qué es utilidad?\n- Es un concepto relacionado con la felicidad, pero más amplio.\n- Por ejemplo, yo obtengo utilidad de lavar mis dientes o comer sano. Ninguna de las dos me brindan felicidad, pero lo primero mantendrá mis dientes sanos y en el largo plazo, lo segundo probablemente contribuirá a una buena vejez.\n\nLos economistas no se preocupan en realidad por lo que nos da utilidad, sino simplemente que cada uno de nosotros tiene sus propias preferencias.\n- Por ejemplo, a mi me gusta el café, el fútbol, los perros, la academia, viajar, entre otros.\n- Ustedes tienen sus propias preferencias también.\n\nLa vida es compleja y con demasiada incertidumbre. Debemos tomar decisiones a cada momento, y estas decisiones involucran ciertos \"trade-off\".\n- Por ejemplo, normalmente tenemos una compensación entre utilidad hoy contra utilidad en el futuro.\n- Debemos balancear nuestro consumo hoy contra nuestro consumo luego.\n- Por ejemplo, ustedes gastan cerca de cuatro horas a la semana viniendo a clases de portafolios, porque esperan que esto contribuya a mejorar su nivel de vida en el futuro.\n\nDe manera que los economistas dicen que cada individuo se comporta como el siguiente optimizador:\n\n\\begin{align}\n\\max & \\quad\\text{Utilidad}\\\\\n\\text{s. a.} & \\quad\\text{Recursos disponibles}\n\\end{align}\n\n¿Qué tiene que ver todo esto con el curso?\n- En este módulo desarrollaremos herramientas para describir las preferencias de los inversionistas cuando se encuentran con decisiones de riesgo y rendimiento.\n- Veremos como podemos medir la actitud frente al riesgo, ¿cuánto te gusta o disgusta el riesgo?\n- Finalmente, veremos como podemos formular el problema de maximizar la utilidad de un inversionista para tomar la decisión de inversión óptima.\n___\n\n## 2. Funciones de utilidad.\n\n¿Cómo tomamos decisiones?\nPor ejemplo:\n- Ustedes tienen que decidir si venir a clase o quedarse en su casa viendo Netflix, o ir al gimnasio.\n- Tienen que decidir entre irse de fiesta cada fin, o ahorrar para salir de vacaciones.\n\nEn el caso de un portafolio, la decisión que se debe tomar es **¿cuáto riesgo estás dispuesto a tomar por qué cantidad de rendimiento?**\n\n**¿Cómo evaluarías el \"trade-off\" entre tener cetes contra una estrategia muy riesgosa con un posible altísimo rendimiento?**\n\nDe manera que veremos como tomamos decisiones cuando tenemos distintas posibilidades. Específicamente, hablaremos acerca de las **preferencias**, como los economistas usan dichas preferencias para explicar las decisiones y los \"trade-offs\" en dichas decisiones.\n\nUsamos las **preferencias** para describir las decisiones que tomamos. Las preferencias nos dicen cómo un individuo evalúa los \"trade-offs\" entre distintas elecciones.\n\nPor definición, las preferencias son únicas para cada individuo. En el problema de selección de portafolios:\n- las preferencias que dictan cuánto riesgo estás dispuesto a asumir por cuánto rendimiento, son específicas para cada uno de ustedes.\n- Sus respuestas a esa pregunta pueden ser muy distintas, porque tenemos distintas preferencias.\n\nAhora, nosotros no podemos *cuantificar* dichas preferencias.\n- Por esto usamos el concepto de utilidad, para medir qué tan satisfecho está un individuo con sus elecciones.\n- Así que podemos pensar en la utilidad como un indicador numérico que describe las preferencias,\n- o un índice que nos ayuda a clasificar diferentes decisiones.\n- En términos simples, **la utilidad nos ayuda a transmitir a números la noción de cómo te sientes**;\n- mientras más utilidad, mejor te sientes.\n\n**Función de utilidad**: manera sistemática de asignar una medida o indicador numérico para clasificar diferentes escogencias.\n\nEl número que da una función de utilidad no tiene significado alguno. Simplemente es una manera de clasificar diferentes decisiones.\n\n**Ejemplo.**\n\nPodemos escribir la utilidad de un inversionista como función de la riqueza,\n\n$$U(W).$$\n\n- $U(W)$ nos da una medida de qué tan satisfechos estamos con el nivel de riqueza que tenemos. \n- $U(W)$ no es la riqueza como tal, sino que la función de utilidad traduce la cantidad de riqueza en un índice numérico subjetivo.\n\n¿Cómo luciría gráficamente una función de utilidad de riqueza $U(W)$?\n\n Ver en el tablero \n- ¿Qué caracteristicas debe tener?\n- ¿Cómo es su primera derivada?\n- ¿Cómo es su segunda derivada?\n- Tiempos buenos: riqueza alta (¿cómo es la primera derivada acá?)\n- Tiempos malos: poca riqueza (¿cómo es la primera derivada acá?)\n\n## 3. Aversión al riesgo\n\nUna dimensión importante en la toma de decisiones en finanzas y economía es la **incertidumbre**. Probablemente no hay ninguna decisión en economía que no involucre riesgo.\n\n- A la mayoría de las personas no les gusta mucho el riesgo.\n- De hecho, estudios del comportamiento humano de cara al riesgo, sugieren fuertemente que los seres humanos somos aversos al riesgo.\n- Por ejemplo, la mayoría de hogares poseen seguros para sus activos.\n- Así, cuando planteamos el problema de selección óptima de portafolios, suponemos que el inversionista es averso al riesgo.\n\n¿Qué significa esto en términos de preferencias? ¿Cómo lo medimos?\n \n- Como seres humanos, todos tenemos diferentes genes y preferencias, y esto aplica también a la actitud frente al riesgo.\n- Por tanto, la aversión al riesgo es clave en cómo describimos las preferencias de un inversinista.\n- Individuos con un alto grado de aversión al riesgo valorarán la seguridad a un alto precio, mientras otros no tanto.\n- De manera que alguien con alta aversión al riesgo, no querrá enfrentarse a una situación con resultado incierto y querrá pagar una gran prima de seguro para eliminar dicho riesgo.\n- O equivalentemente, una persona con alta aversión al riesgo requerirá una compensación alta si se decide a asumir ese riesgo.\n\nEl **grado de aversión al riesgo** mide qué tanto un inversionista prefiere un resultado seguro a un resultado incierto.\n\nLo opuesto a aversión al riesgo es **tolerancia al riesgo**.\n \n Ver en el tablero gráficamente, cómo se explica la aversión al riesgo desde las funciones de utilidad. \n\n**Conclusión:** la concavidad en la función de utilidad dicta qué tan averso al riesgo es el individuo.\n\n### ¿Cómo medimos el grado de aversión al riesgo de un individuo?\n\n¿Saben cuál es su coeficiente de aversión al riesgo? Podemos estimarlo.\n\nSuponga que se puede participar en la siguiente lotería:\n- usted puede ganar $\\$1000$ con $50\\%$ de probabilidad, o\n- puede ganar $\\$500$ con $50\\%$ de probabilidad.\n\nEs decir, de entrada usted tendrá $\\$500$ seguros pero también tiene la posibilidad de ganar $\\$1000$.\n\n¿Cuánto estarías dispuesto a pagar por esta oportunidad?\n\nBien, podemos relacionar tu respuesta con tu coeficiente de aversión al riesgo.\n\n| Coeficiente de aversión al riesgo | Cantidad que pagarías |\n| --------------------------------- | --------------------- |\n| 0 | 750 |\n| 0.5 | 729 |\n| 1 | 707 |\n| 2 | 667 |\n| 3 | 632 |\n| 4 | 606 |\n| 5 | 586 |\n| 10 | 540 |\n| 15 | 525 |\n| 20 | 519 |\n| 50 | 507 |\n\nLa mayoría de la gente está dispuesta a pagar entre $\\$540$ (10) y $\\$707$ (1). Es muy raro encontrar coeficientes de aversión al riesgo menores a 1. Esto está soportado por una gran cantidad de encuestas.\n\n- En el mundo financiero, los consultores financieros utilizan cuestionarios para medir el coeficiente de aversión al riesgo.\n\n**Ejemplo.** Describir en términos de aversión al riesgo las siguientes funciones de utilidad que dibujaré en el tablero.\n___\n\n# Anuncios\n\n## 1. Quiz la siguiente clase.\n\n## 2. Tarea 5 entrega 2 para hoy, lunes 22 de Junio.\n\n\n\n
\nCreated with Jupyter by Esteban Jiménez Rodríguez.\n
\n", "meta": {"hexsha": "4610afeff1a17ce1ffebdfb0e78e5c4dcf7a911c", "size": 13487, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Modulo3/Clase10_FuncionesUtilidad.ipynb", "max_stars_repo_name": "memoglez3/porinvv2020", "max_stars_repo_head_hexsha": "14068e8c149cd624f5e58c32186f6065fbd5e13d", "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": "Modulo3/Clase10_FuncionesUtilidad.ipynb", "max_issues_repo_name": "memoglez3/porinvv2020", "max_issues_repo_head_hexsha": "14068e8c149cd624f5e58c32186f6065fbd5e13d", "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": "Modulo3/Clase10_FuncionesUtilidad.ipynb", "max_forks_repo_name": "memoglez3/porinvv2020", "max_forks_repo_head_hexsha": "14068e8c149cd624f5e58c32186f6065fbd5e13d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9522292994, "max_line_length": 272, "alphanum_fraction": 0.6175576481, "converted": true, "num_tokens": 2481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.09058694271188626}} {"text": "# KVLCC2 Ikeda estimators\n\n# Purpose\nThe are a lot of different ways to implement Ikeda's method. This notebook is creating a lot of different estimators and saving this to pkl files.\n\n# Methodology\nBuild the estimators and save them\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nimport sys\nsys.path.append(\"../../\")\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nimport copy\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport src.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nimport shipflowmotionshelpers.shipflowmotionshelpers as helpers\nimport src.visualization.visualize as visualize\nimport scipy\nfrom copy import deepcopy\nimport joblib\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 463 ('figure.dpi : 100 ## figure dots per inch')\n\n\n\n```python\nimport joblib\nfrom src.helpers import get_ikeda, calculate_ikeda, get_estimator_variation, get_data_variation , get_variation, hatify\nfrom rolldecayestimators import fit_on_amplitudes\nfrom copy import deepcopy\nimport rolldecayestimators.ikeda as ikeda_classes\nimport rolldecayestimators.ikeda_speed\nimport scipy\nimport rolldecayestimators.ikeda_speed\nimport src.helpers\nfrom pyscores2.runScores2 import Calculation\nfrom pyscores2.indata import Indata\nfrom pyscores2.output import OutputFile\nimport src.visualization.visualize as visualize\nfrom reports import mdl_results\nfrom notebook_helpers import load_time_series_fnpf\n\nimport reports.examples.FNPF\n```\n\n## Load data from FNPF:\n\n\n```python\ndf_parameters = pd.read_csv('../../data/processed/roll decay KVLCC2/fnpf_parameters.csv', index_col=0)\ndf_parameters.head()\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 \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 \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 \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 \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 \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 \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 \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
BIXYIXZIYYIYZIZZKXXKXYKYYKZZLPPSVXCGYCGZCGaccxactob1cb1crb1lb1qb2cb2crb2lb2qb3cb3crb3lb3qb4cb4crb4lb4qb5cb5crb5lb5qb6cb6crb6lb6qbdensbodyclevclevelcurvdensdensidofadofactordopadopaddingdopodopowerdowndownsdownstdtfilefile_path_tsfnformfreegraviheaveheelhullinterk1ndk2ndk3ndk4ndk5ndk6ndkxxkyylevelevellppmmaxtimaxtimemeshnamenpxpnpypnstepnthrpitchpowepowerreflereflenrnrollrud1rud2rud3rud4rud5rud6rudtsideslimstrestrengthsurgeswaytatftfnhitfnhightfnlotfnlowtitltitletrimupstupstrvm_swlinwlmeyawymaxyminzcgconvencountersid
kvlcc2_rolldecay_0kn0.8530.00.026.0550.026.0550.3417.5561.1771.1774.7065.9810.9932.5190.00.2740.0501.00.01.00.00.00.01.00.00.00.01.00.00.00.01.00.000000.000000.01.00.00.00.01.00.00.00.60.36.06.00.000021000.01000.050.050.02.02.02.02.01.00-5.01.000.02..C:\\Dev\\Prediction-of-roll-damping-using-fully-...1.472020e-070.230.39.806650.00.00.0020.000000e+000.10.10.00.00.00.10.3411851.17656.06.04.706993.42180.0180.00.000000e+00TRAN40.040.030.032.00.02.02.04.7064.7063.957280e+0010.00.00.00.00.00.00.00.01.0030.00.500.500.00.00.30590.30594.04.00.50.5KVLCC2KVLCC20.01.005.00.0000010.0000010.0000010.05.0-5.00.2735NaNNaN21338.0
kvlcc2_rolldecay_15-5kn_const_large20.8530.00.026.0550.026.0550.3417.5561.1771.1774.7065.9810.9932.5190.00.2740.0251.00.01.00.00.00.01.00.00.00.01.00.00.00.01.00.000000.000000.01.00.00.00.01.00.00.00.60.36.06.00.000021000.01000.01.01.02.02.01.01.00.70-5.00.700.02..C:\\Dev\\Prediction-of-roll-damping-using-fully-...1.423410e-010.230.39.806650.00.00.0020.000000e+000.10.10.00.00.00.10.3411851.17656.06.04.706993.42200.0200.00.000000e+00TRAN40.040.030.032.00.02.02.04.7064.7063.826600e+0610.00.00.00.00.00.00.00.00.7030.00.050.050.00.00.30590.30594.04.00.50.5KVLCC2KVLCC20.00.705.00.9669760.0000010.0000010.05.0-5.00.2735NaNNaN21340.0
kvlcc2_rolldecay_15-5kn_ikeda_dev0.8530.00.026.0550.026.0550.3417.5561.1771.1774.7065.9810.9932.5190.00.2740.0501.00.01.00.00.00.01.00.00.00.01.00.00.00.01.06.072172.743710.01.00.00.00.01.00.00.00.60.36.06.00.000041000.01000.00.00.02.02.01.01.00.25-2.00.25NaN..C:\\Dev\\Prediction-of-roll-damping-using-fully-...1.423410e-010.200.39.806650.00.00.0021.000000e-070.10.10.00.00.00.10.3411851.17656.06.04.706993.42600.0600.01.000000e-07TRAN24.024.030.06.00.02.02.04.7064.7063.826600e+0610.00.00.00.00.00.00.00.00.2530.01.001.000.00.00.30590.30594.04.00.50.5KVLCC2KVLCC20.00.252.00.9669760.0000010.0000010.02.0-2.00.27350.00010.021340.0
\n
\n\n\n\n## Load MDL results\n\n\n```python\ndf_rolldecays = mdl_results.df_rolldecays\n```\n\n## Bilge radius\n\n\n```python\nscale_factor = df_rolldecays.iloc[0].scale_factor\nlpp = df_rolldecays.iloc[0].lpp/scale_factor\n\nRs_data = [\n [lpp*scale_factor,40], \n [290,15.21],\n [225,2.4],\n [129,2.4],\n [45,8.48],\n [0,40], \n ] # Measured on full scale geometry\n\n\ndf_Rs = pd.DataFrame(data=Rs_data, columns=['x','R_b'])\ndf_Rs['R_b']/=scale_factor\ndf_Rs['x']/=scale_factor\ndf_Rs['station'] = df_Rs['x']/lpp*20\ndf_Rs.sort_values(by='station', inplace=True)\n\nstations = np.arange(0,21,1)\ndf_Rs_interp = pd.DataFrame(index=stations)\n\ndf_Rs_interp['R_b'] = np.interp(stations,df_Rs['station'].values,df_Rs['R_b'].values)\n```\n\n\n```python\ndf_areas = pd.read_csv('../../data/interim/kvlcc_areas.csv', sep=';', index_col=0)\ndf_areas.head()\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
areaxtbr_b
no
013.826612-5.4950002.0011.6385776.636080
1123.85130610.15993218.2527.89352242.367175
2428.21140928.05128420.8041.82428445.369454
3683.70916543.70621620.8050.28251441.080696
4917.89506661.59756820.8056.15923234.146143
\n
\n\n\n\n\n```python\ndf_areas_model = df_areas.copy()\ndf_areas_model['area']/=(scale_factor**2)\ndf_areas_model['x']/=(scale_factor)\ndf_areas_model['t']/=(scale_factor)\ndf_areas_model['b']/=(scale_factor)\ndf_areas_model['r_b']/=(scale_factor)\n\n\n```\n\n\n```python\nfig,ax=plt.subplots()\ndf_Rs_interp.plot(y='R_b', label='manually',ax=ax)\ndf_areas_model.plot(y='r_b', label='points',ax=ax)\nax.legend()\n```\n\n\n```python\nc_r_tree = joblib.load('../../models/C_r_tree.pkl')\n\ndef predict_C_r(sigma, a_1, a_3):\n \n X = np.array([sigma,a_1,a_3]).T\n \n return c_r_tree.predict(X)\n \n```\n\n\n```python\nrun_paths={\n 21338 : {\n 'scores_indata_path':'../../models/KVLCC2_speed.IN',\n 'scores_outdata_path':'../../data/interim/KVLCC2_speed.out',\n 'roll_decay_model':'../../models/KVLCC2_21338.pkl',\n 'motions_file_paths': ['kvlcc2_rolldecay_0kn'],\n 'combined_motions_ikeda': ['kvlcc2_rolldecay_0kn'], ## hybrid model with motions and Ikeda\n \n },\n 21340 : {\n 'scores_indata_path':'../../models/KVLCC2_speed.IN',\n 'scores_outdata_path':'../../data/interim/KVLCC2_speed.out',\n 'roll_decay_model':'../../models/KVLCC2_21340.pkl',\n #'motions_file_paths': ['kvlcc2_rolldecay_15-5kn'],\n #'combined_motions_ikeda': ['kvlcc2_rolldecay_15-5kn'], ## hybrid model with motions and Ikeda\n 'motions_file_paths': ['kvlcc2_rolldecay_15-5kn_const_large2'],\n 'combined_motions_ikeda': ['kvlcc2_rolldecay_15-5kn_const_large2'], ## hybrid model with motions and Ikeda\n \n }\n}\n```\n\n## Build Ikeda estimators:\n\n\n```python\nruns = OrderedDict()\n\nfor run_id, run in run_paths.items():\n \n mdl_meta_data = df_rolldecays.loc[run_id]\n runs[run_id] = new_run = {\n 'ikedas':OrderedDict(),\n }\n ikedas = new_run['ikedas']\n \n ## Common data:\n scale_factor = mdl_meta_data.scale_factor\n indata_file_path=run['scores_indata_path']\n output_file_path=run['scores_outdata_path']\n motions_file_path=run['motions_file_paths'][0] # Assuming same parameters\n parameters = df_parameters.loc[motions_file_path]\n \n ## Load ScoresII results\n indata = Indata()\n indata.open(indataPath=indata_file_path)\n output_file = OutputFile(filePath=output_file_path)\n \n V = mdl_meta_data.ship_speed*1.852/3.6/np.sqrt(scale_factor)\n \n if not mdl_meta_data.BKL:\n BKL=0\n else:\n BKL=mdl_meta_data.BKL/scale_factor\n \n if not mdl_meta_data.BKB:\n BKB = 0\n else:\n BKB=mdl_meta_data.BKB/scale_factor\n \n \n kg=mdl_meta_data.kg/scale_factor\n \n \n ## Various Ikeda models:\n \n # Regular ikeda (ikeda bilge radius approx.)\n name = 'ikeda'\n ikedas[name] = {}\n ikedas[name]['estimator'] = ikeda_classes.Ikeda.load_scoresII(V=V, w=None, fi_a=None, indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg)\n \n # ikeda (bilge radius from CAD)\n name = 'ikeda_r'\n ikedas[name] = {}\n R_b = df_Rs_interp['R_b'].values\n ikedas[name]['estimator'] = ikeda_classes.IkedaR.load_scoresII(V=V, w=None, fi_a=None, indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg, R_b=R_b)\n \n # ikeda (bilge radius from CAD)\n name = 'ikeda_s'\n ikedas[name] = {}\n #R_b = df_Rs_interp['R_b'].values\n R_b = df_areas_model['r_b'].values\n \n ikedas[name]['estimator'] = ikeda_classes.IkedaR.load_scoresII(V=V, w=None, fi_a=None, indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg, R_b=R_b)\n \n # Same as Ikeda class but with mandatory wetted surface.\n name = 'ikeda_s'\n ikedas[name] = {}\n S_f = parameters.S\n \n ikedas[name]['estimator'] = ikeda_classes.IkedaS.load_scoresII(V=V, w=None, fi_a=None, indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg, S_f=S_f)\n \n # Same as Ikeda class but with mandatory wetted surface and bilge radius from CAD.\n name = 'ikeda_r_s'\n ikedas[name] = {}\n S_f = parameters.S\n \n ikedas[name]['estimator'] = ikeda_classes.IkedaR.load_scoresII(V=V, w=None, fi_a=None,\n indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg, S_f=S_f, R_b=R_b)\n \n # Same as Ikeda eddy damping for barge.\n #name = 'ikeda_barge'\n #ikedas[name] = {}\n # \n #ikedas[name]['estimator'] = ikeda_classes.IkedaBarge.load_scoresII(V=V, w=None, fi_a=None, indata=indata, output_file=output_file, \n # scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg)\n \n \n # Same as Ikeda manual C_r.\n name = 'ikeda_C_r'\n ikedas[name] = {}\n \n #ikedas[name]['estimator'] = estimator = ikeda_classes.IkedaCr.load_scoresII(V=V, w=None, fi_a=None,\n # indata=indata, output_file=output_file, \n # scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg, S_f=S_f, R_b=R_b)\n # Note no S_f!\n ikedas[name]['estimator'] = estimator = ikeda_classes.IkedaCr.load_scoresII(V=V, w=None, fi_a=None,\n indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL, BKB=BKB, kg=kg, R_b=R_b)\n\n a, a_1, a_3, sigma_s, H = estimator.calculate_sectional_lewis_coefficients()\n estimator.C_r = predict_C_r(sigma=sigma_s, a_1=a_1, a_3=a_3)\n \n\n```\n\n c:\\python36-64\\lib\\re.py:212: FutureWarning: split() requires a non-empty pattern match.\n return _compile(pattern, flags).split(string, maxsplit)\n c:\\python36-64\\lib\\re.py:212: FutureWarning: split() requires a non-empty pattern match.\n return _compile(pattern, flags).split(string, maxsplit)\n\n\n## Saving Ikeda estimators:\n\n\n```python\nfor id,run in runs.items():\n for ikeda_name, ikeda in run['ikedas'].items():\n \n file_name = '%s_%s.pkl' % (id,ikeda_name)\n joblib.dump(ikeda['estimator'], '../../models/%s' % file_name)\n \n```\n\n## Load time series from FNPF\n\n\n```python\ntime_series = load_time_series_fnpf(names=df_parameters.index)\n```\n\n## Load FNPF models\n\n\n```python\nmotion_models, df_results_motions = reports.examples.FNPF.get_models_and_results()\n```\n\n c:\\dev\\prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-ikedas-method\\venv\\lib\\site-packages\\sklearn\\base.py:334: UserWarning: Trying to unpickle estimator Pipeline from version 0.24.1 when using version 0.23.2. This might lead to breaking code or invalid results. Use at your own risk.\n UserWarning)\n\n\n\n```python\nfor run_id, run in run_paths.items():\n \n mdl_meta_data = df_rolldecays.loc[run_id]\n \n new_run = runs[run_id]\n \n ## MDL:\n model_mdl = joblib.load(run['roll_decay_model'])\n estimator_mdl = model_mdl['estimator']\n estimator_mdl.calculate_amplitudes_and_damping()\n new_run['model_mdl']=model_mdl\n new_run['estimator_mdl']=estimator_mdl\n \n scale_factor = mdl_meta_data.scale_factor\n new_run['meta_data'] = meta_data={\n 'Volume':mdl_meta_data.Volume/(scale_factor**3),\n 'GM':mdl_meta_data.gm/scale_factor,\n 'rho':mdl_meta_data.rho,\n 'g':mdl_meta_data.g,\n 'beam':mdl_meta_data.beam/scale_factor,\n }\n \n new_run['results'] = estimator_mdl.result_for_database(meta_data=meta_data)\n results = new_run['results']\n \n # Prediction\n new_run['df_model'] = get_estimator_variation(estimator = estimator_mdl, results=results, meta_data=meta_data)\n \n # Model tests\n new_run['df'] = get_data_variation(estimator = estimator_mdl, results=results, meta_data=meta_data)\n phi_a = new_run['df']['phi_a']\n \n ## Motions\n new_run['motions'] = OrderedDict()\n for motions_file_path in run.get('motions_file_paths',[]):\n motion_file = new_run['motions'][motions_file_path] = {}\n \n motion_file['parameters'] = parameters = df_parameters.loc[motions_file_path]\n \n motion_file['X'] = X = time_series[motions_file_path]\n \n \n motion_file['model'] = model = motion_models[motions_file_path]\n #assert model.score() > 0.90\n \n motion_file['meta_data'] = meta_data ={\n 'Volume':parameters.V,\n 'GM':mdl_meta_data.gm/mdl_meta_data.scale_factor,\n 'rho':parameters.dens,\n 'g':parameters.gravi,\n 'beam':parameters.B,\n }\n \n results = model.result_for_database(meta_data=meta_data)\n if not 'B_3' in results:\n results['B_3'] = 0\n \n motion_file['results'] = results\n model.calculate_amplitudes_and_damping()\n \n # Prediction\n motion_file['df_model'] = get_estimator_variation(estimator = model, results = results, meta_data=meta_data)\n \n # Simulation\n motion_file['df'] = get_data_variation(estimator = model, results = results, meta_data=meta_data)\n \n \n ## Ikeda\n for ikeda_name, ikeda in new_run['ikedas'].items():\n \n omega0=new_run['results']['omega0']\n #phi_a=new_run['results']['phi_a']\n ikeda_estimator = ikeda['estimator']\n ikeda['df'] = results = ikeda_estimator.calculate(w=omega0, fi_a=phi_a)\n \n results['phi_a'] = phi_a\n results.set_index('phi_a', inplace=True)\n \n ## Convert to dimensional damping [Nm/s]\n ikeda['meta_data'] = meta_data = new_run['meta_data']\n result_ = src.helpers.unhat(df=results, Disp=meta_data['Volume'], beam=meta_data['beam'], g=meta_data['g'], rho=meta_data['rho'])\n ikeda['df'] = results = pd.concat((results,result_), axis=1)\n \n ## Feed the results into a quadratic model:\n output = fit_on_amplitudes.fit_quadratic(y=results['B_44'], phi_a=results.index, omega0=omega0, \n B_1_0=new_run['results']['B_1'], \n B_2_0=new_run['results']['B_2'], \n )\n \n parameters = {\n 'B_1A': output['B_1'] / new_run['results']['A_44'],\n 'B_2A': output['B_2'] / new_run['results']['A_44'],\n 'B_3A': 0,\n 'C_1A': estimator_mdl.parameters['C_1A'],\n 'C_3A': estimator_mdl.parameters['C_3A'],\n 'C_5A': estimator_mdl.parameters['C_5A'],\n }\n ikeda['model'] = EstimatorCubic.load(**parameters, X=estimator_mdl.X)\n \n \n ikeda['results'] = ikeda['model'].result_for_database(meta_data=meta_data)\n ikeda['df_model'] = get_estimator_variation(estimator = ikeda['model'], results = ikeda['results'], meta_data=new_run['meta_data'])\n \n ## Combined model:\n new_run['combined_models'] = combined_models = {}\n combined_motions_ikedas = run.get('combined_motions_ikeda',[])\n for combined_motions_ikeda in combined_motions_ikedas:\n \n combined_models[combined_motions_ikeda] = combined_model = {}\n \n combined_model['motions'] = model_motions = new_run['motions'][combined_motions_ikeda]\n combined_model['ikedas'] = OrderedDict()\n \n for ikeda_name, ikeda in new_run['ikedas'].items():\n \n combined_model['ikedas'][ikeda_name] = combined_model_ikeda = {}\n \n df = ikeda['df']\n df_motions = pd.DataFrame()\n df_motions['phi_a'] = df.index.copy()\n df_motions = get_variation(X_amplitudes=df_motions, results = model_motions['results'], meta_data=model_motions['meta_data'])\n df_motions.set_index('phi_a', inplace=True)\n \n columns_visc = ['B_L','B_F','B_E','B_BK']\n df_combined = df[columns_visc].copy()\n df_combined['B_W'] = df_motions['B_e']\n df_combined['B'] = df_combined.sum(axis=1)\n combined_model_ikeda['df'] = df_combined\n \n ## Feed the results into a cubic model:\n output = fit_on_amplitudes.fit_quadratic(y=df_combined['B'], phi_a=df_combined.index, omega0=omega0, \n B_1_0=new_run['results']['B_1'], \n B_2_0=new_run['results']['B_2'], \n )\n \n parameters = {\n 'B_1A': output['B_1'] / new_run['results']['A_44'],\n 'B_2A': output['B_2'] / new_run['results']['A_44'],\n 'B_3A': 0,\n 'C_1A': estimator_mdl.parameters['C_1A'],\n 'C_3A': estimator_mdl.parameters['C_3A'],\n 'C_5A': estimator_mdl.parameters['C_5A'],\n }\n combined_model_ikeda['model'] = EstimatorCubic.load(**parameters, X=estimator_mdl.X)\n combined_model_ikeda['results'] = combined_model_ikeda['model'].result_for_database(meta_data=meta_data)\n combined_model_ikeda['df_model'] = get_estimator_variation(estimator = combined_model_ikeda['model'], results = combined_model_ikeda['results'], meta_data=new_run['meta_data'])\n \n\n```\n\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:595: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n\n\n## Save Hybrid models\n\n\n```python\nfor id, run in runs.items():\n \n for key, combined_model in run['combined_models'].items():\n for ikeda_name, ikeda in combined_model['ikedas'].items():\n pipeline = Pipeline([('estimator',ikeda['model'])])\n file_name = '%i_%s_%s.pkl' % (id,key,ikeda_name) \n joblib.dump(pipeline, '../../models/%s' % file_name)\n```\n", "meta": {"hexsha": "a30f57316bc56da4082f07029b78a96f16917f54", "size": 80628, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reports/ISOPE_outline/00.7_KVLCC2_ikeda_estimators.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "reports/ISOPE_outline/00.7_KVLCC2_ikeda_estimators.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "reports/ISOPE_outline/00.7_KVLCC2_ikeda_estimators.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 53.1496374423, "max_line_length": 21540, "alphanum_fraction": 0.5798605943, "converted": true, "num_tokens": 11691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.18242552158390102, "lm_q1q2_score": 0.09050017559578734}} {"text": "# This Jupyter notebook illustrates how to read data in from an external file \n## [notebook provides a simple illustration, users can easily use these examples to modify and customize for their data storage scheme and/or preferred workflows] \n\n\n###Motion Blur Filtering: A Statistical Approach for Extracting Confinement Forces & Diffusivity from a Single Blurred Trajectory\n\n#####Author: Chris Calderon\n\nCopyright 2015 Ursa Analytics, Inc.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nYou may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n\n\n\n### Cell below loads the required modules and packages\n\n\n```python\n%matplotlib inline \n#command above avoids using the \"dreaded\" pylab flag when launching ipython (always put magic command above as first arg to ipynb file)\nimport matplotlib.font_manager as font_manager\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.optimize as spo\nimport findBerglundVersionOfMA1 #this module builds off of Berglund's 2010 PRE parameterization (atypical MA1 formulation)\nimport MotionBlurFilter\nimport Ursa_IPyNBpltWrapper\n\n```\n\n##Now that required modules packages are loaded, set parameters for simulating \"Blurred\" OU trajectories. Specific mixed continuous/discrete model:\n\n\\begin{align}\ndr_t = & ({v}-{\\kappa} r_t)dt + \\sqrt{2 D}dB_t \\\\\n\\psi_{t_i} = & \\frac{1}{t_E}\\int_{t_{i}-t_E}^{t_i} r_s ds + \\epsilon^{\\mathrm{loc}}_{t_i}\n\\end{align}\n\n###In above equations, parameter vector specifying model is: $\\theta = (\\kappa,D,\\sigma_{\\mathrm{loc}},v)$\n\n\n###Statistically exact discretization of above for uniform time spacing $\\delta$ (non-uniform $\\delta$ requires time dependent vectors and matrices below):\n\n\\begin{align}\nr_{t_{i+1}} = & A + F r_{t_{i}} + \\eta_{t_i} \\\\\n\\psi_{t_i} = & H_A + H_Fr_{t_{i-1}} + \\epsilon^{\\mathrm{loc}}_{t_i} + \\epsilon^{\\mathrm{mblur}}_{t_i} \\\\\n\\epsilon^{\\mathrm{loc}}_{t_i} + & \\epsilon^{\\mathrm{mblur}}_{t_i} \\sim \\mathcal{N}(0,R_i) \\\\\n\\eta_i \\sim & \\mathcal{N}(0,Q) \\\\\nt_{i-1} = & t_{i}-t_E \\\\\n C = & cov(\\epsilon^{\\mathrm{mblur}}_{t_i},\\eta_{t_{i-1}}) \\ne 0\n\\end{align}\n\n\n####Note: Kalman Filter (KF) and Motion Blur Filter (MBF) codes estimate $\\sqrt(2D)$ directly as \"thermal noise\" parameter\n\n### For situations where users would like to read data in from external source, many options exist. \n\n####In cell below, we show how to read in a text file and process the data assuming the text file contains two columns: One column with the 1D measurements and one with localization standard deviation vs. time estimates. Code chunk below sets up some default variables (tunable values indicated by comments below). Note that for multivariate signals, chunks below can readily be modified to process x/y or x/y/z measurements separately. Future work will address estimating 2D/3D models with the MBF (computational [not theoretical] issues exists in this case); however, the code currently provides diagnostic information to determine if unmodeled multivariate interaction effects are important (see main paper and Calderon, Weiss, Moerner, PRE 2014)\n\n### Plot examles from other notebooks can be used to explore output within this notbook or another. Next, a simple example of \"Batch\" processing is illustrated.\n\n\n```python\nfilenameBase='./ExampleData/MyTraj_' #assume all trajectory files have this prefix (adjust file location accordingly)\n\nN=20 #set the number of trajectories to read. \ndelta = 25./1000. #user must specify the time (in seconds) between observations. code provided assumes uniform continuous illumination and \n#NOTE: in this simple example, all trajectories assumed to be collected with exposure time delta input above\n\n\n\n#now loop over trajectories and store MLE results\nresBatch=[] #variable for storing MLE output\n\n#loop below just copies info from cell below (only difference is file to read is modified on each iteration of the loop)\nfor i in range(N):\n \n filei = filenameBase + str(i+1) + '.txt'\n print ''\n print '^'*100\n print 'Reading in file: ', filei\n #first load the sample data stored in text file. here we assume two columns of numerica data (col 1 are measurements)\n data = np.loadtxt(filei)\n (T,ncol)=data.shape\n #above we just used a simple default text file reader; however, any means of extracting the data and\n #casting it to a Tx2 array (or Tx1 if no localization accuracy info available) will work.\n\n\n\n ymeas = data[:,0]\n locStdGuess = data[:,1] #if no localization info avaible, just set this to zero or a reasonable estimate of localization error [in nm]\n\n Dguess = 0.1 #input a guess of the local diffusion coefficient of the trajecotry to seed the MLE searches (need not be accurate)\n velguess = np.mean(np.diff(ymeas))/delta #input a guess of the velocity of the trajecotry to seed the MLE searches (need not be accurate)\n\n MA=findBerglundVersionOfMA1.CostFuncMA1Diff(ymeas,delta) #construct an instance of the Berglund estimator\n res = spo.minimize(MA.evalCostFuncVel, (np.sqrt(Dguess),np.median(locStdGuess),velguess), method='nelder-mead')\n\n #output Berglund estimation result.\n print 'Berglund MLE',res.x[0]*np.sqrt(2),res.x[1],res.x[-1]\n print '-'*100\n\n #obtain crude estimate of mean reversion parameter. see Calderon, PRE (2013)\n kappa1 = np.log(np.sum(ymeas[1:]*ymeas[0:-1])/(np.sum(ymeas[0:-1]**2)-T*res.x[1]**2))/-delta\n\n #construct an instance of the MBF estimator\n BlurF = MotionBlurFilter.ModifiedKalmanFilter1DwithCrossCorr(ymeas,delta,StaticErrorEstSeq=locStdGuess)\n #use call below if no localization info avaible\n # BlurF = MotionBlurFilter.ModifiedKalmanFilter1DwithCrossCorr(ymeas,delta)\n\n parsIG=np.array([np.abs(kappa1),res.x[0]*np.sqrt(2),res.x[1],res.x[-1]]) #kick off MLE search with \"warm start\" based on simpler model\n #kick off nonlinear cost function optimization given data and initial guess\n resBlur = spo.minimize(BlurF.evalCostFunc,parsIG, method='nelder-mead')\n \n print 'parsIG for Motion Blur filter',parsIG\n print 'Motion Blur MLE result:',resBlur\n\n #finally evaluate diagnostic statistics at MLE just obtained\n loglike,xfilt,pit,Shist =BlurF.KFfilterOU1d(resBlur.x) \n\n print np.mean(pit),np.std(pit)\n print 'crude assessment of model: check above mean is near 0.5 and std is approximately',np.sqrt(1/12.)\n print 'statements above based on generalized residual U[0,1] shape' \n print 'other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.'\n \n #finally just store the MLE of the MBF in a list\n resBatch.append(resBlur.x)\n\n```\n\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_1.txt\n Berglund MLE 0.424450138266 0.0410840106778 -0.000253509776551\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 6.01896509e-01 4.24450138e-01 4.10840107e-02 -2.53509777e-04]\n Motion Blur MLE result: status: 0\n nfev: 196\n success: True\n fun: -1.1526156274680164\n x: array([ 9.88732097e-01, 4.30329177e-01, 1.69786977e-02,\n -1.88788339e-04])\n message: 'Optimization terminated successfully.'\n nit: 110\n 0.512506169502 0.289227348189\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_2.txt\n Berglund MLE 0.403080320506 0.0421133323903 0.0315952570332\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.79926789 0.40308032 0.04211333 0.03159526]\n Motion Blur MLE result: status: 0\n nfev: 299\n success: True\n fun: -1.1760118286776404\n x: array([ 1.44062784, 0.41103507, 0.01766368, -0.04607467])\n message: 'Optimization terminated successfully.'\n nit: 172\n 0.496990426074 0.29206459027\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_3.txt\n Berglund MLE 0.425243165442 0.0383252438668 0.0339861519423\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.27321687 0.42524317 0.03832524 0.03398615]\n Motion Blur MLE result: status: 0\n nfev: 312\n success: True\n fun: -1.1942812161329239\n x: array([ 1.37933008, 0.44563642, 0.01178971, 0.52399413])\n message: 'Optimization terminated successfully.'\n nit: 186\n 0.50078852219 0.291016376117\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_4.txt\n Berglund MLE 0.387088460983 0.0390914442611 0.00401072737933\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.29576551 0.38708846 0.03909144 0.00401073]\n Motion Blur MLE result: status: 0\n nfev: 429\n success: True\n fun: -1.2220005538177285\n x: array([ 1.20270778, 0.40031886, 0.01525121, 0.37603661])\n message: 'Optimization terminated successfully.'\n nit: 258\n 0.501678044756 0.287044032779\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_5.txt\n Berglund MLE 0.373653923964 0.0414090910471 -0.0271831915793\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.60942087 0.37365392 0.04140909 -0.02718319]\n Motion Blur MLE result: status: 0\n nfev: 315\n success: True\n fun: -1.1972364793651142\n x: array([ 1.42686492, 0.4006258 , 0.0179909 , -0.15973117])\n message: 'Optimization terminated successfully.'\n nit: 187\n 0.505548331825 0.28907161488\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_6.txt\n Berglund MLE 0.405658929477 0.0410255848183 -0.0527407580382\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.88813023 0.40565893 0.04102558 -0.05274076]\n Motion Blur MLE result: status: 0\n nfev: 278\n success: True\n fun: -1.1785934866396908\n x: array([ 2.206071 , 0.43743055, 0.01557288, -0.2198948 ])\n message: 'Optimization terminated successfully.'\n nit: 161\n 0.49752884216 0.290010436927\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_7.txt\n Berglund MLE 0.440296244194 0.037794781385 0.0555249133931\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.51073785 0.44029624 0.03779478 0.05552491]\n Motion Blur MLE result: status: 0\n nfev: 296\n success: True\n fun: -1.1646850756274711\n x: array([ 1.00900231, 0.45080595, 0.01384808, 0.0596462 ])\n message: 'Optimization terminated successfully.'\n nit: 171\n 0.500138244772 0.285738276794\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_8.txt\n Berglund MLE 0.388193789739 0.0433344124496 -0.0232538599371\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 1.23208956 0.38819379 0.04333441 -0.02325386]\n Motion Blur MLE result: status: 0\n nfev: 318\n success: True\n fun: -1.1901666108672013\n x: array([ 2.23788936, 0.40683237, 0.01763311, -0.06170199])\n message: 'Optimization terminated successfully.'\n nit: 185\n 0.500831978254 0.28767904269\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_9.txt\n Berglund MLE 0.428119184149 0.0368338621282 0.0631101005882\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.42504155 0.42811918 0.03683386 0.0631101 ]\n Motion Blur MLE result: status: 0\n nfev: 313\n success: True\n fun: -1.1921480409010281\n x: array([ 1.0874416 , 0.43535992, 0.0134389 , 0.19952 ])\n message: 'Optimization terminated successfully.'\n nit: 177\n 0.499882963813 0.286378046611\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_10.txt\n Berglund MLE 0.403241526019 0.0448782500646 0.0326597583831\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.36721914 0.40324153 0.04487825 0.03265976]\n Motion Blur MLE result: status: 0\n nfev: 295\n success: True\n fun: -1.1280944693617625\n x: array([ 0.88575554, 0.40813484, 0.02201115, 0.19055693])\n message: 'Optimization terminated successfully.'\n nit: 173\n 0.499027710082 0.290215367984\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_11.txt\n Berglund MLE 0.446022076218 0.0386925793552 0.0317446002903\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.75851698 0.44602208 0.03869258 0.0317446 ]\n Motion Blur MLE result: status: 0\n nfev: 364\n success: True\n fun: -1.1477995850212523\n x: array([ 1.34146215, 0.45217896, 0.01547886, 0.11062506])\n message: 'Optimization terminated successfully.'\n nit: 217\n 0.498350123323 0.28489583658\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_12.txt\n Berglund MLE 0.433878819812 0.0405257997338 0.0194618189645\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.57081066 0.43387882 0.0405258 0.01946182]\n Motion Blur MLE result: status: 0\n nfev: 320\n success: True\n fun: -1.1258718069898108\n x: array([ 1.0535438 , 0.44151737, 0.01909119, 0.0921696 ])\n message: 'Optimization terminated successfully.'\n nit: 189\n 0.4993722138 0.286382226048\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_13.txt\n Berglund MLE 0.442289936266 0.0413708496844 0.0900189405225\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.53984449 0.44228994 0.04137085 0.09001894]\n Motion Blur MLE result: status: 0\n nfev: 281\n success: True\n fun: -1.1194332404998935\n x: array([ 1.44682073, 0.44948337, 0.01867071, 0.17022423])\n message: 'Optimization terminated successfully.'\n nit: 167\n 0.498968531464 0.286556318588\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_14.txt\n Berglund MLE 0.434387236759 0.0392930335766 0.0256938157463\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.57814585 0.43438724 0.03929303 0.02569382]\n Motion Blur MLE result: status: 0\n nfev: 287\n success: True\n fun: -1.1622391321135688\n x: array([ 0.99021595, 0.44116143, 0.01484123, -0.01121947])\n message: 'Optimization terminated successfully.'\n nit: 167\n 0.503103615691 0.292303358037\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_15.txt\n Berglund MLE 0.411721173737 0.0381990349157 0.0153091535058\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.60076698 0.41172117 0.03819903 0.01530915]\n Motion Blur MLE result: status: 0\n nfev: 310\n success: True\n fun: -1.1694922158999403\n x: array([ 1.11385547, 0.42298358, 0.01809222, 0.09968667])\n message: 'Optimization terminated successfully.'\n nit: 191\n 0.493928160614 0.283653076911\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_16.txt\n Berglund MLE 0.449853292681 0.0346580553668 -0.014228133955\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.88913235 0.44985329 0.03465806 -0.01422813]\n Motion Blur MLE result: status: 0\n nfev: 189\n success: True\n fun: -1.1617781756413692\n x: array([ 1.49678266, 0.46607595, 0.01368101, -0.01265549])\n message: 'Optimization terminated successfully.'\n nit: 104\n 0.502248368185 0.285265534615\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_17.txt\n Berglund MLE 0.405791875716 0.0429526801662 0.0281841646573\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.79922712 0.40579188 0.04295268 0.02818416]\n Motion Blur MLE result: status: 0\n nfev: 311\n success: True\n fun: -1.1566192303985554\n x: array([ 1.80755174, 0.41859545, 0.01897457, -0.21484235])\n message: 'Optimization terminated successfully.'\n nit: 182\n 0.498866022839 0.288461118604\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_18.txt\n Berglund MLE 0.480290453713 0.033150036359 -0.0363831128213\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.44079153 0.48029045 0.03315004 -0.03638311]\n Motion Blur MLE result: status: 0\n nfev: 286\n success: True\n fun: -1.1667980253486265\n x: array([ 0.90486109, 0.4872516 , 0.00819091, 0.11628986])\n message: 'Optimization terminated successfully.'\n nit: 170\n 0.498456742145 0.288303457635\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_19.txt\n Berglund MLE 0.401125045744 0.0394428992004 -0.00560612519608\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 0.75923837 0.40112505 0.0394429 -0.00560613]\n Motion Blur MLE result: status: 0\n nfev: 358\n success: True\n fun: -1.182656245292518\n x: array([ 1.41280844, 0.41718142, 0.01732866, -0.11048628])\n message: 'Optimization terminated successfully.'\n nit: 218\n 0.499503636338 0.288565336397\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n \n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Reading in file: ./ExampleData/MyTraj_20.txt\n Berglund MLE 0.4678828153 0.0341188814665 0.000390470606951\n ----------------------------------------------------------------------------------------------------\n parsIG for Motion Blur filter [ 4.71922369e-01 4.67882815e-01 3.41188815e-02 3.90470607e-04]\n Motion Blur MLE result: status: 0\n nfev: 419\n success: True\n fun: -1.1464820600970622\n x: array([ 1.01456235, 0.46829891, 0.01419429, 0.20915194])\n message: 'Optimization terminated successfully.'\n nit: 245\n 0.502468629673 0.293260000307\n crude assessment of model: check above mean is near 0.5 and std is approximately 0.288675134595\n statements above based on generalized residual U[0,1] shape\n other hypothesis tests outlined which can use PIT sequence above outlined/referenced in paper.\n\n\n\n```python\n#Summarize the results of the above N simulations \n#\n\nresSUM=np.array(resBatch)\nprint 'Blur medians',np.median(resSUM[:,0]),np.median(resSUM[:,1]),np.median(resSUM[:,2]),np.median(resSUM[:,3])\nprint 'means',np.mean(resSUM[:,0]),np.mean(resSUM[:,1]),np.mean(resSUM[:,2]),np.mean(resSUM[:,3])\nprint 'std',np.std(resSUM[:,0]),np.std(resSUM[:,1]),np.std(resSUM[:,2]),np.std(resSUM[:,3])\n\nprint '^'*100 ,'\\n\\n'\n```\n\n Blur medians 1.27208496571 0.436395237852 0.0162757902936 0.0759079000468\n means 1.32234434672 0.434561850166 0.0160360992158 0.0655553122287\n std 0.380912845778 0.0234327797792 0.00299196795637 0.182354637945\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ \n \n \n\n", "meta": {"hexsha": "dc08bbfa73e58107dc2047442569df1d5cf9c008", "size": 31740, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/Example2_ReadInFileIllustration.ipynb", "max_stars_repo_name": "calderoc/MotionBlurFilter", "max_stars_repo_head_hexsha": "86786c2a7956421b93690ac9beeb9f3366fbdf7e", "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": "src/Example2_ReadInFileIllustration.ipynb", "max_issues_repo_name": "calderoc/MotionBlurFilter", "max_issues_repo_head_hexsha": "86786c2a7956421b93690ac9beeb9f3366fbdf7e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-28T10:08:00.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-28T10:08:00.000Z", "max_forks_repo_path": "src/Example2_ReadInFileIllustration.ipynb", "max_forks_repo_name": "calderoc/MotionBlurFilter", "max_forks_repo_head_hexsha": "86786c2a7956421b93690ac9beeb9f3366fbdf7e", "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": 55.7820738137, "max_line_length": 761, "alphanum_fraction": 0.5403276623, "converted": true, "num_tokens": 7687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.09050017339069463}} {"text": "```python\n%%capture\n## compile PyRoss for this notebook\nimport os\nowd = os.getcwd()\nos.chdir('../../')\n%run setup.py install\nos.chdir(owd)\n```\n\n\n```python\n%matplotlib inline\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport pyross\nimport time \nimport seaborn as sns\nimport pandas as pd\nfrom matplotlib.pyplot import cm\n```\n\nIn this notebook we consider a control protocol consisting of an initial lockdown, which is then partly released. For our numerical study we generate synthetic data using the stochastic SIIR model.\n\nWhile we use the UK age structure and contact matrix, we used here simulated data.\n\n**Summary:**\n\n1. We load the age structure and contact matrix for Denmark. The contact matrix is generally given as\n\\begin{equation}\n C = C_{H} + C_{W} + C_{S} + C_{O},\n\\end{equation}\nwhere the four terms denote the number of contacts at home, work, school, and all other remaining contacts.\n2. We define the other model parameters of the SIIR model **(these are not fitted to any real data)**.\n3. We define a \"lockdown-protocol\":\n Withing a certain time range, a lockdown is imposed (shcool closure). The contact matrix is reduced to \n \\begin{equation}\n C = C_{H} \n \\end{equation} \n\nWe want to see an impact if the school reopen, when do we see a change in the number of people infected ? Which age group is the most infected ?\n\n\n## Get the contact Matrices for UK\n\n\n```python\nM=16 # number of age groups\n\n# load age structure data\nmy_data = np.genfromtxt('../../data/age_structures/UK.csv', delimiter=',', skip_header=1)\naM, aF = my_data[:, 1], my_data[:, 2]\n\n# set age groups\nNi=aM+aF; Ni=Ni[0:M]; N=np.sum(Ni)\n```\n\n\n```python\ndf1= pd.DataFrame({'Female':aF, 'Age':['0-4','5-9','10-14','15-19','20-24','25-29','30-34','35-39','40-44','45-49','50-54','55-59','60-64','65-69','70-74','75-79','80-84','85-89','90-94','95-99','100+'], 'Sex':['F']*21})\ndf2 = pd.DataFrame({'Male':aM, 'Age':['0-4','5-9','10-14','15-19','20-24','25-29','30-34','35-39','40-44','45-49','50-54','55-59','60-64','65-69','70-74','75-79','80-84','85-89','90-94','95-99','100+'], 'Sex':['M']*21})\ndf3 = pd.concat([df1, df2], join='inner')\ndf3['number'] = np.concatenate((aF,aM))\n```\n\nC is the sum of contributions from contacts at home, workplace, schools and all other public spheres. Using superscripts $H$, $W$, $S$ and $O$ for each of these, we write the contact matrix as\n$$\nC_{ij} = C^H_{ij} + C^W_{ij} + C^S_{ij} + C^O_{ij}\n$$\n\nWe read in these contact matrices from the data sets provided in the paper *Projecting social contact matrices in 152 countries using contact surveys and demographic data* by Prem et al, sum them to obtain the total contact matrix. We also read in the age distribution of UK obtained from the *Population pyramid* website.\n\n\n```python\n# Get individual contact matrices\nCH, CW, CS, CO = pyross.contactMatrix.UK()\n\n# By default, home, work, school, and others contribute to the contact matrix\nC = CH + CW + CS + CO\n\n# Illustrate the individual contact matrices:\nfig,aCF = plt.subplots(2,2);\naCF[0][0].pcolor(CH, cmap=plt.cm.get_cmap('GnBu', 10));\naCF[0][1].pcolor(CW, cmap=plt.cm.get_cmap('GnBu', 10));\naCF[1][0].pcolor(CS, cmap=plt.cm.get_cmap('GnBu', 10));\naCF[1][1].pcolor(CO, cmap=plt.cm.get_cmap('GnBu', 10));\n```\n\n## Covid19 data \n\n\n```python\n# Get the latest data from Johns Hopkins University\n!git clone https://github.com/CSSEGISandData/COVID-19\n```\n\n fatal: destination path 'COVID-19' already exists and is not an empty directory.\r\n\n\n\n```python\ncases = pd.read_csv('COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\ncases.head()\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 \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 \n \n \n \n \n \n \n \n \n
Province/StateCountry/RegionLatLong1/22/201/23/201/24/201/25/201/26/201/27/20...5/24/205/25/205/26/205/27/205/28/205/29/205/30/205/31/206/1/206/2/20
0NaNAfghanistan33.000065.0000000000...10582111731183112456130361365914525152051575016509
1NaNAlbania41.153320.1683000000...998100410291050107610991122113711431164
2NaNAlgeria28.03391.6596000000...8306850386978857899791349267939495139626
3NaNAndorra42.50631.5218000000...762763763763763764764764765844
4NaNAngola-11.202717.8739000000...69707071748184868686
\n

5 rows × 137 columns

\n
\n\n\n\n\n```python\ndeaths = pd.read_csv('COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')\ndeaths.shape\n```\n\n\n\n\n (266, 137)\n\n\n\n\n```python\ncases[cases['Country/Region']=='United Kingdom']\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 \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 \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 \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 \n \n \n \n \n
Province/StateCountry/RegionLatLong1/22/201/23/201/24/201/25/201/26/201/27/20...5/24/205/25/205/26/205/27/205/28/205/29/205/30/205/31/206/1/206/2/20
217BermudaUnited Kingdom32.3078-64.7505000000...133133139139140140140140141141
218Cayman IslandsUnited Kingdom19.3133-81.2546000000...129134137140140141141141150151
219Channel IslandsUnited Kingdom49.3723-2.3644000000...558559559560560560560560560560
220GibraltarUnited Kingdom36.1408-5.3536000000...154154154157158161169170170172
221Isle of ManUnited Kingdom54.2361-4.5481000000...336336336336336336336336336336
222MontserratUnited Kingdom16.7425-62.1874000000...11111111111111111111
223NaNUnited Kingdom55.3781-3.4360000000...259559261184265227267240269127271222272826274762276332277985
248AnguillaUnited Kingdom18.2206-63.0686000000...3333333333
249British Virgin IslandsUnited Kingdom18.4207-64.6400000000...8888888888
250Turks and Caicos IslandsUnited Kingdom21.6940-71.7979000000...12121212121212121212
257Falkland Islands (Malvinas)United Kingdom-51.7963-59.5236000000...13131313131313131313
\n

11 rows × 137 columns

\n
\n\n\n\n\n```python\ncols = cases.columns.tolist() \ncase = cases.loc[223,][4:]\ndeath = deaths.loc[223,][4:]\n```\n\n\n```python\nplt.figure(figsize=(20,10))\nsns.set(font_scale=3) # crazy big\nplt.legend(fontsize='x-large', title_fontsize='1000')\nsns.set_style(style='white')\nplt.legend(fontsize='x-large', title_fontsize='10000')\nsns.scatterplot(np.arange(len(death)),death, label='death');\nsns.scatterplot(x=np.arange(len(case)), y=case, label='case');\nplt.ylabel('')\nplt.title('')\nplt.xticks(np.arange(0, 115,15), ('1/22', '2/6', '2/21', '3/16', '3/31', '4/15','4/30', '04/05'));\nplt.savefig('UKcovid19.png', format='png', dpi=200)\n```\n\n## Deterministic SIR model for UK\n\nUsing this code : https://github.com/rajeshrinet/pyross/blob/master/examples/deterministic/ex03-age-structured-SIR-for-India.ipynb\n\nAssume that the population has been partitioned into $i=1,\\ldots, M$ age groups and that we have available the $M\\times M$ contact matrix $C_{ij}$. We assume all initial cases are symptomatic, and remain so.\n\nSee SIR model : pyross/deterministic.pyx\n\n\n```python\n# Generate class with contact matrix for SIR model with UK contact structure\ngenerator = pyross.contactMatrix.SIR(CH, CW, CS, CO)\n```\n\nThe infection parameter $\\beta$ is unknown, so we fit it to the case data till 25th March. \n\n\n```python\n## Parameters of the model (random)\n\nbeta = 0.01546692 # infection rate assumed intrinsic to the pathogen\ngIa = 1./7 # recovery rate of asymptomatic infectives (7 days)\ngIs = 1./7 # recovery rate of symptomatic infectives \nalpha = 0. # fraction of asymptomatic infectives\nfsa = 1 # the self-isolation parameter \n \n \n# initial conditions \nIs_0 = np.zeros((M)); Is_0[0:15]=200\nIa_0 = np.zeros((M)) # no asymptomatic infectives\nR_0 = np.zeros((M))\nS_0 = Ni - (Ia_0 + Is_0 + R_0)\n```\n\n\n```python\n# matrix for linearised dynamics\nL0 = np.zeros((M, M))\nL = np.zeros((2*M, 2*M))\n\nfor i in range(M):\n for j in range(M):\n L0[i,j]=C[i,j]*Ni[i]/Ni[j]\n\nL[0:M, 0:M] = alpha*beta/gIs*L0\nL[0:M, M:2*M] = fsa*alpha*beta/gIs*L0\nL[M:2*M, 0:M] = ((1-alpha)*beta/gIs)*L0\nL[M:2*M, M:2*M] = fsa*((1-alpha)*beta/gIs)*L0\n\n\nr0 = np.max(np.linalg.eigvals(L))\nprint(\"The basic reproductive ratio for these parameters is\", r0)\n```\n\n The basic reproductive ratio for these parameters is (1.264513426078052+0j)\n\n\n\n```python\n# instantiate model\nparameters = {'alpha':alpha,'beta':beta, 'gIa':gIa,'gIs':gIs,'fsa':fsa}\nmodel = pyross.deterministic.SIR(parameters, M, Ni)\n```\n\n\n```python\n# the contact structure is independent of time \ndef contactMatrix(t):\n return C\n```\n\n\n```python\n# time_points to solve the ode (using odeint) Ti = 0 by default \nTf=350; Nf=3500; #Tf is the final day np.linspace(Ti, Tf, Nf) \n```\n\n\n```python\n# run model\ndata=model.simulate(S_0, Ia_0, Is_0, contactMatrix, Tf, Nf)\n```\n\n\n```python\ndata['X'].shape # 48 because 16 groups * 4 equations \n```\n\n\n\n\n (3500, 48)\n\n\n\n\n```python\nt = data['t']; IC = np.zeros((Nf))\nfor i in range(M):\n IC += data['X'][:,2*M+i]\n```\n\n\n```python\nindex_max = np.argmax(IC)\n```\n\n\n```python\nfig = plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k')\nplt.rcParams.update({'font.size': 12})\nplt.plot(t, IC, '-', lw=4, color='#A60628', label='forecast', alpha=0.8)\nplt.axvline(x=index_max/10, ymin=0, ymax=175000, color='#A60628')\nday, cases = np.array(np.arange(1,Tf)), np.array(case[0:Tf])\nplt.plot(cases, 'o-', lw=4, color='#348ABD', ms=5, label='data', alpha=0.5)\nplt.legend(fontsize=15, loc='upper left'); plt.grid() \nplt.autoscale(enable=True, axis='x', tight=True)\nplt.ylabel('Infected individuals');\nplt.title('No measure');\nplt.savefig('FullmatrixC.png', format='png', dpi=200)\n```\n\n\n```python\nSC = np.zeros((Nf))\nfor i in range(M):\n SC += data.get('X')[:,0*M+i]\n IC += data.get('X')[:,2*M+i]\n\nfig = plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k')\nplt.rcParams.update({'font.size': 22})\n\nplt.plot(t, SC*10**(-6), '-', lw=4, color='#348ABD', label='susceptible', alpha=0.8,)\nplt.fill_between(t, 0, SC*10**(-6), color=\"#348ABD\", alpha=0.3)\n\nplt.plot(t, IC*10**(-6), '-', lw=4, color='#A60628', label='infected', alpha=0.8)\nplt.fill_between(t, 0, IC*10**(-6), color=\"#A60628\", alpha=0.3)\n\n\nplt.plot(cases*10**(-6), 'ro-', lw=4, color='dimgrey', ms=16, label='data', alpha=0.5)\n\nplt.legend(fontsize=26); plt.grid() \nplt.autoscale(enable=True, axis='x', tight=True)\nplt.ylabel('Individuals (millions)')\nplt.xticks(np.arange(0, Tf, 90), ('22/01', '30/04' ));\nplt.savefig('C-SIRNomesure.png', format='png', dpi=200)\n```\n\n\n```python\n# matrix for linearised dynamics\nL0 = np.zeros((M, M))\nL = np.zeros((2*M, 2*M))\nxind=[np.argsort(IC)[-1]]\n\nrr = np.zeros((Tf))\n\nfor tt in range(Tf):\n Si = np.array((data['X'][tt*10,0:M])).flatten()\n for i in range(M):\n for j in range(M):\n L0[i,j]=C[i,j]*Si[i]/Ni[j]\n L[0:M, 0:M] = alpha*beta/gIs*L0\n L[0:M, M:2*M] = fsa*alpha*beta/gIs*L0\n L[M:2*M, 0:M] = ((1-alpha)*beta/gIs)*L0\n L[M:2*M, M:2*M] = fsa*((1-alpha)*beta/gIs)*L0\n\n rr[tt] = np.real(np.max(np.linalg.eigvals(L)))\n \n \nfig = plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k')\nplt.rcParams.update({'font.size': 22})\n\nplt.plot(t[::10], rr, 'o', lw=4, color='#A60628', label='suscetible', alpha=0.8,)\nplt.fill_between(t, 0, t*0+1, color=\"dimgrey\", alpha=0.2); plt.ylabel('Basic reproductive ratio')\nplt.ylim(np.min(rr)-.1, np.max(rr)+.1)\nplt.xticks(np.arange(0, Tf, 90), ('22/01', '30/04' ));\nplt.savefig('C-R0Nomesure.png', format='png', dpi=200)\n```\n\n\n```python\nfig = plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k')\nplt.rcParams.update({'font.size': 22})\n\nplt.bar(np.arange(16),data.get('X')[0,0:M]*10**(-6), label='susceptible (initial)', alpha=0.8)\nplt.bar(np.arange(16),data.get('X')[-1,0:M]*10**(-6), label='susceptible (final)', alpha=0.8)\n\nplt.xticks(np.arange(-0.4, 16.45, 3.95), ('0', '20', '40', '60', '80'));\nplt.xlim(-0.45, 15.45); plt.ylabel('Individuals (millions)'); plt.xlabel('Age')\nplt.legend(fontsize=22); plt.axis('tight')\nplt.autoscale(enable=True, axis='x', tight=True)\n\nplt.savefig('C-indsusNomesure.png', format='png', dpi=200)\n```\n\n### Mortality \n\nWe extract the number of susceptibles remaining in each age group, and the difference with the initial number of susceptibles is the total number that are infected. We multiply this with mortality data from China to obtain mortality estimates.\n\n\n\n\n```python\nMM = np.array((0,0,.0,1,1,1,1,1,1,3.5,3.5,3.5,3.5,6,6,14.2)) \n```\n\n\n```python\nfig = plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k')\nplt.rcParams.update({'font.size': 22})\n\nm1 = .01*MM*(data.get('X')[0,0:M]-data['X'][-1,0:M])\nplt.bar(np.arange(16),m1*10**(-6), label='susceptible (final)', alpha=0.8)\n\nplt.axis('tight'); plt.xticks(np.arange(-0.4, 16.45, 3.95), ('0', '20', '40', '60', '80'));\nplt.xlim(-0.45, 15.45); plt.ylabel('Mortality (millions)'); plt.xlabel('Age')\n\nplt.autoscale(enable=True, axis='x', tight=True)\n\nplt.savefig('C-mortalityNomesure.png', format='png', dpi=200)\n\n```\n\n## Non Pharmaceutical intervention\n\n# School closure\n\nFriday, March 20 in UK\n\n\n### Change the day to open again schools\n\n\n```python\ndayclosure = 58\ndayopen1 = dayclosure+60\ndayopen2 = dayclosure+80\ndayopen3 = dayclosure+200\n\n```\n\n\n```python\nmodel = pyross.deterministic.SIR(parameters, M, Ni)\n```\n\n\n```python\n# the contact matrix is time-dependent\ndef contactMatrix1(t):\n if there.''')\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\n# Examples: \n# Factored form: 1/(x**2*(x**2 + 1))\n# Expanded form: 1/(x**4+x**2)\n\nimport sympy as sym\nfrom IPython.display import Latex, display, Markdown, Javascript, clear_output\nfrom ipywidgets import widgets, Layout # Interactivity module\n```\n\n## Decomposizione in fratti semplici\n\nQuando si utilizza la trasformata di Laplace per l'analisi dei sistemi, la trasformata di Laplace del segnale di uscita si ottiene come prodotto della funzione di trasferimento del sistema per la trasformata di Laplace del segnale di ingresso. Il risultato di questa moltiplicazione solitamente è abbastanza complesso da interpretare. Per eseguire la trasformata inversa di Laplace, si esegue prima la decomposizione in fratti semplici. Questo esempio dimostra questa procedura.\n\n---\n\n### Come usare questo notebook?\nAlterna tra l'opzione *Input da funzione* o *Input da coefficienti polinomiali*.\n\n1. *Input da funzione*:\n * Esempio: per inserire la funzione $\\frac{1}{x^2(x^2 + 1)}$ (formato fattorizzato) digitare 1/(x\\*\\*2\\*(x\\*\\*2 + 1)); per inserire la stessa funzione nella forma espansa ($\\frac{1}{x^4+x^2}$) digitare 1/(x\\*\\*4+x\\*\\*2).\n\n2. *Input da coefficienti polinomiali*:\n * Usa i cursori per selezionare l'ordine del numeratore e del denominatore della funzione razionale di interesse.\n * Inserisci i coefficienti sia del numeratore che del denominatore nelle caselle di testo dedicate e fai clic su *Conferma*.\n\n\n```python\n## System selector buttons\nstyle = {'description_width': 'initial'}\ntypeSelect = widgets.ToggleButtons(\n options=[('Input da funzione', 0), ('Input da coefficienti polinomiali', 1),],\n description='Select: ',style={'button_width':'230px'})\n\nbtnReset=widgets.Button(description=\"Reset\")\n\n# function\ntextbox=widgets.Text(description=('Inserisci la funzione:'),style=style)\nbtnConfirmFunc=widgets.Button(description=\"Conferma\") # ex btnConfirm\n\n# poly\nbtnConfirmPoly=widgets.Button(description=\"Conferma\") # ex btn\n\ndisplay(typeSelect)\n\ndef on_button_clickedReset(ev):\n display(Javascript(\"Jupyter.notebook.execute_cells_below()\"))\n\ndef on_button_clickedFunc(ev):\n eq = sym.sympify(textbox.value)\n\n if eq==sym.factor(eq):\n display(Markdown('La funzione $%s$ è scritta in forma fattorizzata. ' %sym.latex(eq) + 'La sua forma espansa è $%s$.' %sym.latex(sym.expand(eq))))\n \n else:\n display(Markdown('La funzione $%s$ è scritta in forma espansa. ' %sym.latex(eq) + 'La sua forma fattorizzata è $%s$.' %sym.latex(sym.factor(eq))))\n \n display(Markdown('Il risultato della decomposizione in fratti semplici è: $%s$' %sym.latex(sym.apart(eq)) + '.'))\n display(btnReset)\n \ndef transfer_function(num,denom):\n num = np.array(num, dtype=np.float64)\n denom = np.array(denom, dtype=np.float64)\n len_dif = len(denom) - len(num)\n if len_dif<0:\n temp = np.zeros(abs(len_dif))\n denom = np.concatenate((temp, denom))\n transferf = np.vstack((num, denom))\n elif len_dif>0:\n temp = np.zeros(len_dif)\n num = np.concatenate((temp, num))\n transferf = np.vstack((num, denom))\n return transferf\n\ndef f(orderNum, orderDenom):\n global text1, text2\n text1=[None]*(int(orderNum)+1)\n text2=[None]*(int(orderDenom)+1)\n display(Markdown('2. Inserisci i coefficienti del numeratore.'))\n for i in range(orderNum+1):\n text1[i]=widgets.Text(description=(r'a%i'%(orderNum-i)))\n display(text1[i])\n display(Markdown('3. Inserisci i coefficienti del denominatore.')) \n for j in range(orderDenom+1):\n text2[j]=widgets.Text(description=(r'b%i'%(orderDenom-j)))\n display(text2[j])\n global orderNum1, orderDenom1\n orderNum1=orderNum\n orderDenom1=orderDenom\n\ndef on_button_clickedPoly(btn):\n clear_output()\n global num,denom\n enacbaNum=\"\"\n enacbaDenom=\"\"\n num=[None]*(int(orderNum1)+1)\n denom=[None]*(int(orderDenom1)+1)\n for i in range(int(orderNum1)+1):\n if text1[i].value=='' or text1[i].value=='Please insert a coefficient':\n text1[i].value='Please insert a coefficient'\n else:\n try:\n num[i]=int(text1[i].value)\n except ValueError:\n if text1[i].value!='' or text1[i].value!='Please insert a coefficient':\n num[i]=sym.var(text1[i].value)\n \n for i in range (len(num)-1,-1,-1):\n if i==0:\n enacbaNum=enacbaNum+str(num[len(num)-i-1])\n elif i==1:\n enacbaNum=enacbaNum+\"+\"+str(num[len(num)-i-1])+\"*x+\"\n elif i==int(len(num)-1):\n enacbaNum=enacbaNum+str(num[0])+\"*x**\"+str(len(num)-1)\n else:\n enacbaNum=enacbaNum+\"+\"+str(num[len(num)-i-1])+\"*x**\"+str(i) \n \n for j in range(int(orderDenom1)+1):\n if text2[j].value=='' or text2[j].value=='Please insert a coefficient':\n text2[j].value='Please insert a coefficient'\n else:\n try:\n denom[j]=int(text2[j].value)\n except ValueError:\n if text2[j].value!='' or text2[j].value!='Please insert a coefficient':\n denom[j]=sym.var(text2[j].value)\n \n for i in range (len(denom)-1,-1,-1):\n if i==0:\n enacbaDenom=enacbaDenom+\"+\"+str(denom[len(denom)-i-1])\n elif i==1:\n enacbaDenom=enacbaDenom+\"+\"+str(denom[len(denom)-i-1])+\"*x\"\n elif i==int(len(denom)-1):\n enacbaDenom=enacbaDenom+str(denom[0])+\"*x**\"+str(len(denom)-1)\n else:\n enacbaDenom=enacbaDenom+\"+\"+str(denom[len(denom)-i-1])+\"*x**\"+str(i)\n \n funcSym=sym.sympify('('+enacbaNum+')/('+enacbaDenom+')')\n\n DenomSym=sym.sympify(enacbaDenom)\n NumSym=sym.sympify(enacbaNum)\n DenomSymFact=sym.factor(DenomSym);\n funcFactSym=NumSym/DenomSymFact;\n \n if DenomSym==sym.expand(enacbaDenom):\n if DenomSym==DenomSymFact:\n display(Markdown('La funzione di interesse è: $%s$. Il numeratore non può essere fattorizzato.' %sym.latex(funcSym)))\n else:\n display(Markdown('La funzione di interesse è: $%s$. Il numeratore non può essere fattorizzato. La funzione con il denominatore fattorizzato è: $%s$.' %(sym.latex(funcSym), sym.latex(funcFactSym))))\n\n if sym.apart(funcSym)==funcSym:\n display(Markdown('La decomposizione in fratti semplici non può essere eseguita.'))\n else:\n display(Markdown('Il risultato della decomposizione in fratti semplici è: $%s$' %sym.latex(sym.apart(funcSym)) + '.'))\n \n btnReset.on_click(on_button_clickedReset)\n display(btnReset)\n \ndef partial_frac(index):\n\n if index==0:\n x = sym.Symbol('x') \n display(widgets.HBox((textbox, btnConfirmFunc)))\n btnConfirmFunc.on_click(on_button_clickedFunc)\n btnReset.on_click(on_button_clickedReset)\n \n elif index==1:\n display(Markdown('1. Definisci l\\'ordine del numeratore (orderNum) e del denominatore (orderDenom).'))\n widgets.interact(f, orderNum=widgets.IntSlider(min=0,max=10,step=1,value=0),\n orderDenom=widgets.IntSlider(min=0,max=10,step=1,value=0));\n btnConfirmPoly.on_click(on_button_clickedPoly)\n display(btnConfirmPoly) \n\ninput_data=widgets.interactive_output(partial_frac,{'index':typeSelect})\ndisplay(input_data)\n```\n\n\n ToggleButtons(description='Select: ', options=(('Input da funzione', 0), ('Input da coefficienti polinomiali',…\n\n\n\n Output()\n\n", "meta": {"hexsha": "453e79b91cb996434c12dcdccfa43563d3d4d30c", "size": 12122, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/02/TD-09-Decomposizione-in-fratti-semplici.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_it/examples/02/.ipynb_checkpoints/TD-09-Decomposizione-in-fratti-semplici-checkpoint.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_it/examples/02/.ipynb_checkpoints/TD-09-Decomposizione-in-fratti-semplici-checkpoint.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": 37.88125, "max_line_length": 487, "alphanum_fraction": 0.5364626299, "converted": true, "num_tokens": 2279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510525748676846, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.08966719171222819}} {"text": "\n\n# **CS224W - Colab 3**\n\nIn Colab 2 we constructed GNN models by using PyTorch Geometric's built in GCN layer, `GCNConv`. In this Colab we will go a step deeper and implement the **GraphSAGE** ([Hamilton et al. (2017)](https://arxiv.org/abs/1706.02216)) layer directly. Then we will run our models on the CORA dataset, which is a standard citation network benchmark dataset.\n\n**Note**: Make sure to **sequentially run all the cells in each section** so that the intermediate variables / packages will carry over to the next cell\n\nHave fun and good luck on Colab 3 :)\n\n# Device\nWe recommend using a GPU for this Colab.\n\nPlease click `Runtime` and then `Change runtime type`. Then set the `hardware accelerator` to **GPU**.\n\n## Installation\n\n\n```python\n# Install torch geometric\nimport os\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n !pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\n !pip install torch-sparse -f https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\n !pip install torch-geometric\n !pip install -q git+https://github.com/snap-stanford/deepsnap.git\n```\n\n Looking in links: https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\n Collecting torch-scatter\n Downloading https://data.pyg.org/whl/torch-1.9.0%2Bcu111/torch_scatter-2.0.8-cp37-cp37m-linux_x86_64.whl (10.4 MB)\n \u001b[K |████████████████████████████████| 10.4 MB 12.5 MB/s \n \u001b[?25hInstalling collected packages: torch-scatter\n Successfully installed torch-scatter-2.0.8\n Looking in links: https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\n Collecting torch-sparse\n Downloading https://data.pyg.org/whl/torch-1.9.0%2Bcu111/torch_sparse-0.6.12-cp37-cp37m-linux_x86_64.whl (3.7 MB)\n \u001b[K |████████████████████████████████| 3.7 MB 12.2 MB/s \n \u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-sparse) (1.4.1)\n Requirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from scipy->torch-sparse) (1.19.5)\n Installing collected packages: torch-sparse\n Successfully installed torch-sparse-0.6.12\n Collecting torch-geometric\n Downloading torch_geometric-2.0.1.tar.gz (308 kB)\n \u001b[K |████████████████████████████████| 308 kB 14.4 MB/s \n \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.19.5)\n Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (4.62.3)\n Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.4.1)\n Requirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.6.3)\n Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (0.22.2.post1)\n Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.23.0)\n Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.1.5)\n Collecting rdflib\n Downloading rdflib-6.0.2-py3-none-any.whl (407 kB)\n \u001b[K |████████████████████████████████| 407 kB 63.7 MB/s \n \u001b[?25hRequirement already satisfied: googledrivedownloader in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (0.4)\n Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.11.3)\n Requirement already satisfied: pyparsing in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.4.7)\n Collecting yacs\n Downloading yacs-0.1.8-py3-none-any.whl (14 kB)\n Requirement already satisfied: PyYAML in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (3.13)\n Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->torch-geometric) (2.0.1)\n Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2018.9)\n Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2.8.2)\n Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->torch-geometric) (1.15.0)\n Collecting isodate\n Downloading isodate-0.6.0-py2.py3-none-any.whl (45 kB)\n \u001b[K |████████████████████████████████| 45 kB 3.5 MB/s \n \u001b[?25hRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from rdflib->torch-geometric) (57.4.0)\n Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2.10)\n Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (3.0.4)\n Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (1.24.3)\n Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2021.5.30)\n Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->torch-geometric) (1.0.1)\n Building wheels for collected packages: torch-geometric\n Building wheel for torch-geometric (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for torch-geometric: filename=torch_geometric-2.0.1-py3-none-any.whl size=513822 sha256=0508097be7556c0ef204e9968e6883b06a3417e5d4502507cd4808897763bf9b\n Stored in directory: /root/.cache/pip/wheels/78/3d/42/20589db73c66b5109fb93a0c5743edfd6ab5ca820a52afacfc\n Successfully built torch-geometric\n Installing collected packages: isodate, yacs, rdflib, torch-geometric\n Successfully installed isodate-0.6.0 rdflib-6.0.2 torch-geometric-2.0.1 yacs-0.1.8\n Building wheel for deepsnap (setup.py) ... \u001b[?25l\u001b[?25hdone\n\n\n\n```python\nimport torch_geometric\ntorch_geometric.__version__\n```\n\n\n\n\n '2.0.1'\n\n\n\n# 1) GNN Layers\n\n## Implementing Layer Modules\n\nIn Colab 2, we implemented a GCN model for node and graph classification tasks. However, for that notebook we took advantage of PyG's built in GCN module. For Colab 3, we provide a build upon a general Graph Neural Network Stack, into which we will be able to plugin our own module implementations: GraphSAGE and GAT.\n\nWe will then use our layer implemenations to complete node classification on the CORA dataset, a standard citation network benchmark. In this dataset, nodes correspond to documents and edges correspond to undirected citations. Each node or document in the graph is assigned a class label and features based on the documents binarized bag-of-words representation. Specifically, the Cora graph has 2708 nodes, 5429 edges, 7 prediction classes, and 1433 features per node. \n\n## GNN Stack Module\n\nBelow is the implementation of a general GNN stack, where we can plugin any GNN layer, such as **GraphSage**, **GAT**, etc. This module is provided for you. Your implementations of the **GraphSage** and **GAT** (Colab 4) layers will function as components in the GNNStack Module.\n\n\n```python\nimport torch\nimport torch_scatter\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch_geometric.nn as pyg_nn\nimport torch_geometric.utils as pyg_utils\n\nfrom torch import Tensor\nfrom typing import Union, Tuple, Optional\nfrom torch_geometric.typing import (OptPairTensor, Adj, Size, NoneType,\n OptTensor)\n\nfrom torch.nn import Parameter, Linear\nfrom torch_sparse import SparseTensor, set_diag\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.utils import remove_self_loops, add_self_loops, softmax\n\nclass GNNStack(torch.nn.Module):\n def __init__(self, input_dim, hidden_dim, output_dim, args, emb=False):\n super(GNNStack, self).__init__()\n conv_model = self.build_conv_model(args.model_type)\n self.convs = nn.ModuleList()\n self.convs.append(conv_model(input_dim, hidden_dim))\n assert (args.num_layers >= 1), 'Number of layers is not >=1'\n for l in range(args.num_layers-1):\n self.convs.append(conv_model(args.heads * hidden_dim, hidden_dim))\n\n # post-message-passing\n self.post_mp = nn.Sequential(\n nn.Linear(args.heads * hidden_dim, hidden_dim), nn.Dropout(args.dropout), \n nn.Linear(hidden_dim, output_dim))\n\n self.dropout = args.dropout\n self.num_layers = args.num_layers\n\n self.emb = emb\n\n def build_conv_model(self, model_type):\n if model_type == 'GraphSage':\n return GraphSage\n elif model_type == 'GAT':\n # When applying GAT with num heads > 1, you need to modify the \n # input and output dimension of the conv layers (self.convs),\n # to ensure that the input dim of the next layer is num heads\n # multiplied by the output dim of the previous layer.\n # HINT: In case you want to play with multiheads, you need to change the for-loop that builds up self.convs to be\n # self.convs.append(conv_model(hidden_dim * num_heads, hidden_dim)), \n # and also the first nn.Linear(hidden_dim * num_heads, hidden_dim) in post-message-passing.\n return GAT\n\n def forward(self, data):\n x, edge_index, batch = data.x, data.edge_index, data.batch\n \n for i in range(self.num_layers):\n x = self.convs[i](x, edge_index)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout,training=self.training)\n\n x = self.post_mp(x)\n\n if self.emb == True:\n return x\n\n return F.log_softmax(x, dim=1)\n\n def loss(self, pred, label):\n return F.nll_loss(pred, label)\n```\n\n## Creating Our Own Message Passing Layer\n\nNow let's start implementing our own message passing layers! Working through this part will help us become acutely familiar with the behind the scenes work of implementing Pytorch Message Passing Layers, allowing us to build our own GNN models. To do so, we will work with and implement 3 critcal functions needed to define a PyG Message Passing Layer: `forward`, `message`, and `aggregate`.\n\nBefore diving head first into the coding details, let us quickly review the key components of the message passing process. To do so, we will focus on a single round of messsage passing with respect to a single central node $x$. Before message passing, $x$ is associated with a feature vector $x^{l-1}$, and the goal of message passing is to update this feature vector as $x^l$. To do so, we implement the following steps: 1) each neighboring node $v$ passes its current message $v^{l-1}$ across the edge $(x, v)$ - 2) for the node $x$, we aggregate all of the messages of the neighboring nodes (for example through a sum or mean) - and 3) we transform the aggregated information by for example applying linear and non-linear transformations. Altogether, the message passing process is applied such that every node $u$ in our graph updates its embedding by acting as the central node $x$ in step 1-3 described above. \n\nNow, we extending this process to that of a single message passing layer, the job of a message passing layer is to update the current feature representation or embedding of each node in a graph by propagating and transforming information within the graph. Overall, the general paradigm of a message passing layers is: 1) pre-processing -> 2) **message passing** / propagation -> 3) post-processing. \n\nThe `forward` fuction that we will implement for our message passing layer captures this execution logic. Namely, the `forward` function handles the pre and post-processing of node features / embeddings, as well as initiates message passing by calling the `propagate` function. \n\n\nThe `propagate` function encapsulates the message passing process! It does so by calling three important functions: 1) `message`, 2) `aggregate`, and 3) `update`. Our implementation will vary slightly from this, as we will not explicitly implement `update`, but instead place the logic for updating node embeddings after message passing and within the `forward` function. To be more specific, after information is propagated (message passing), we can further transform the node embeddings outputed by `propagate`. Therefore, the output of `forward` is exactly the node embeddings after one GNN layer.\n\nLastly, before starting to implement our own layer, let us dig a bit deeper into each of the functions described above:\n\n1. \n\n```\ndef propagate(edge_index, x=(x_i, x_j), extra=(extra_i, extra_j), size=size):\n```\nCalling `propagate` initiates the message passing process. Looking at the function parameters, we highlight a couple of key parameters. \n\n - `edge_index` is passed to the forward function and captures the edge structure of the graph.\n - `x=(x_i, x_j)` represents the node features that will be used in message passing. In order to explain why we pass the tuple `(x_i, x_j)`, we first look at how our edges are represented. For every edge $(i, j) \\in \\mathcal{E}$, we can differentiate $i$ as the source or central node ($x_{central}$) and j as the neighboring node ($x_{neighbor}$). \n \n Taking the example of message passing above, for a central node $u$ we will aggregate and transform all of the messages associated with the nodes $v$ s.t. $(u, v) \\in \\mathcal{E}$ (i.e. $v \\in \\mathcal{N}_{u}$). Thus we see, the subscripts `_i` and `_j` allow us to specifcally differenciate features associated with central nodes (i.e. nodes recieving message information) and neighboring nodes (i.e. nodes passing messages). \n\n This is definitely a somewhat confusing concept; however, one key thing to remember / wrap your head around is that depending on the perspective, a node $x$ acts as a central node or a neighboring node. In fact, in undirected graphs we store both edge directions (i.e. $(i, j)$ and $(j, i)$). From the central node perspective, `x_i`, x is collecting neighboring information to update its embedding. From a neighboring node perspective, `x_j`, x is passing its message information along the edge connecting it to a different central node.\n\n - `extra=(extra_i, extra_j)` represents additional information that we can associate with each node beyond its current feature embedding. In fact, we can include as many additional parameters of the form `param=(param_i, param_j)` as we would like. Again, we highlight that indexing with `_i` and `_j` allows us to differentiate central and neighboring nodes. \n\n The output of the `propagate` function is a matrix of node embeddings after the message passing process and has shape $[N, d]$.\n\n2. \n```\ndef message(x_j, ...):\n```\nThe `message` function is called by propagate and constructs the messages from\nneighboring nodes $j$ to central nodes $i$ for each edge $(i, j)$ in *edge_index*. This function can take any argument that was initially passed to `propagate`. Furthermore, we can again differentiate central nodes and neighboring nodes by appending `_i` or `_j` to the variable name, .e.g. `x_i` and `x_j`. Looking more specifically at the variables, we have:\n\n - `x_j` represents a matrix of feature embeddings for all neighboring nodes passing their messages along their respective edge (i.e. all nodes $j$ for edges $(i, j) \\in \\mathcal{E}$). Thus, its shape is $[|\\mathcal{E}|, d]$!\n - In implementing GAT we will see how to access additional variables passed to propagate\n\n Critically, we see that the output of the `message` function is a matrix of neighboring node embeddings ready to be aggregated, having shape $[|\\mathcal{E}|, d]$.\n\n3. \n```\ndef aggregate(self, inputs, index, dim_size = None):\n```\nLastly, the `aggregate` function is used to aggregate the messages from neighboring nodes. Looking at the parameters we highlight:\n\n - `inputs` represents a matrix of the messages passed from neighboring nodes (i.e. the output of the `message` function).\n - `index` has the same shape as `inputs` and tells us the central node that corresponding to each of the rows / messages $j$ in the `inputs` matrix. Thus, `index` tells us which rows / messages to aggregate for each central node.\n\n The output of `aggregate` is of shape $[N, d]$.\n\n\nFor additional resources refer to the PyG documentation for implementing custom message passing layers: https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html\n\n## GraphSage Implementation\n\nFor our first GNN layer, we will implement the well known GraphSage ([Hamilton et al. (2017)](https://arxiv.org/abs/1706.02216)) layer! \n\nFor a given *central* node $v$ with current embedding $h_v^{l-1}$, the message passing update rule to tranform $h_v^{l-1} \\rightarrow h_v^l$ is as follows: \n\n\\begin{equation}\nh_v^{(l)} = W_l\\cdot h_v^{(l-1)} + W_r \\cdot AGG(\\{h_u^{(l-1)}, \\forall u \\in N(v) \\})\n\\end{equation}\n\nwhere $W_1$ and $W_2$ are learanble weight matrices and the nodes $u$ are *neighboring* nodes. Additionally, we use mean aggregation for simplicity:\n\n\\begin{equation}\nAGG(\\{h_u^{(l-1)}, \\forall u \\in N(v) \\}) = \\frac{1}{|N(v)|} \\sum_{u\\in N(v)} h_u^{(l-1)}\n\\end{equation}\n\nOne thing to note is that we're adding a **skip connection** to our GraphSage implementation through the term $W_l\\cdot h_v^{(l-1)}$. \n\nBefore implementing this update rule, we encourage you to think about how different parts of the formulas above correspond with the functions outlined earlier: 1) `forward`, 2) `message`, and 3) `aggregate`. As a hint, we are given what the aggregation function is (i.e. mean aggregation)! Now the question remains, what are the messages passed by each neighbor nodes and when do we call the `propagate` function? \n\nNote: in this case the message function or messages are actually quite simple. Additionally, remember that the `propagate` function encapsulates the operations of / the outputs of the combined `message` and `aggregate` functions.\n\n\nLastly, $\\ell$-2 normalization of the node embeddings is applied after each iteration.\n\n\nFor the following questions, DON'T refer to any existing implementations online.\n\n\n```python\nclass GraphSage(MessagePassing):\n \n def __init__(self, in_channels, out_channels, normalize = True,\n bias = False, **kwargs): \n super(GraphSage, self).__init__(**kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.normalize = normalize\n\n self.lin_l = None\n self.lin_r = None\n\n ############################################################################\n # TODO: Your code here! \n # Define the layers needed for the message and update functions below.\n # self.lin_l is the linear transformation that you apply to embedding \n # for central node.\n # self.lin_r is the linear transformation that you apply to aggregated \n # message from neighbors.\n # Don't forget the bias!\n # Our implementation is ~2 lines, but don't worry if you deviate from this.\n\n ############################################################################\n\n self.reset_parameters()\n\n def reset_parameters(self):\n self.lin_l.reset_parameters()\n self.lin_r.reset_parameters()\n\n def forward(self, x, edge_index, size = None):\n \"\"\"\"\"\"\n\n out = None\n\n ############################################################################\n # TODO: Your code here! \n # Implement message passing, as well as any post-processing (our update rule).\n # 1. Call the propagate function to conduct the message passing.\n # 1.1 See the description of propagate above or the following link for more information: \n # https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html\n # 1.2 We will only use the representation for neighbor nodes (x_j), so by default\n # we pass the same representation for central and neighbor nodes as x=(x, x). \n # 2. Update our node embedding with skip connection from the previous layer.\n # 3. If normalize is set, do L-2 normalization (defined in \n # torch.nn.functional)\n #\n # Our implementation is ~5 lines, but don't worry if you deviate from this.\n\n ############################################################################\n\n return out\n\n def message(self, x_j):\n\n out = None\n\n ############################################################################\n # TODO: Your code here! \n # Implement your message function here.\n # Hint: Look at the formulation of the mean aggregation function, focusing on \n # what message each neighboring node passes.\n #\n # Our implementation is ~1 lines, but don't worry if you deviate from this.\n\n ############################################################################\n\n return out\n\n def aggregate(self, inputs, index, dim_size = None):\n\n out = None\n\n # The axis along which to index number of nodes.\n node_dim = self.node_dim\n\n ############################################################################\n # TODO: Your code here! \n # Implement your aggregate function here.\n # See here as how to use torch_scatter.scatter: \n # https://pytorch-scatter.readthedocs.io/en/latest/functions/scatter.html#torch_scatter.scatter\n #\n # Our implementation is ~1 lines, but don't worry if you deviate from this.\n\n\n ############################################################################\n\n return out\n\n```\n\n## Building Optimizers\n\nThis function has been implemented for you. **For grading purposes please use the default Adam optimizer**, but feel free to play with other types of optimizers on your own.\n\n\n```python\nimport torch.optim as optim\n\ndef build_optimizer(args, params):\n weight_decay = args.weight_decay\n filter_fn = filter(lambda p : p.requires_grad, params)\n if args.opt == 'adam':\n optimizer = optim.Adam(filter_fn, lr=args.lr, weight_decay=weight_decay)\n elif args.opt == 'sgd':\n optimizer = optim.SGD(filter_fn, lr=args.lr, momentum=0.95, weight_decay=weight_decay)\n elif args.opt == 'rmsprop':\n optimizer = optim.RMSprop(filter_fn, lr=args.lr, weight_decay=weight_decay)\n elif args.opt == 'adagrad':\n optimizer = optim.Adagrad(filter_fn, lr=args.lr, weight_decay=weight_decay)\n if args.opt_scheduler == 'none':\n return None, optimizer\n elif args.opt_scheduler == 'step':\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.opt_decay_step, gamma=args.opt_decay_rate)\n elif args.opt_scheduler == 'cos':\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.opt_restart)\n return scheduler, optimizer\n```\n\n## Training and Testing\n\nHere we provide you with the functions to train and test. **Please do not modify this part for grading purposes.**\n\n\n```python\nimport time\n\nimport networkx as nx\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom tqdm import trange\nimport pandas as pd\nimport copy\n\nfrom torch_geometric.datasets import TUDataset\nfrom torch_geometric.datasets import Planetoid\nfrom torch_geometric.data import DataLoader\n\nimport torch_geometric.nn as pyg_nn\n\nimport matplotlib.pyplot as plt\n\n\ndef train(dataset, args):\n \n print(\"Node task. test set size:\", np.sum(dataset[0]['test_mask'].numpy()))\n print()\n test_loader = loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False)\n\n # build model\n model = GNNStack(dataset.num_node_features, args.hidden_dim, dataset.num_classes, \n args)\n scheduler, opt = build_optimizer(args, model.parameters())\n\n # train\n losses = []\n test_accs = []\n best_acc = 0\n best_model = None\n for epoch in trange(args.epochs, desc=\"Training\", unit=\"Epochs\"):\n total_loss = 0\n model.train()\n for batch in loader:\n opt.zero_grad()\n pred = model(batch)\n label = batch.y\n pred = pred[batch.train_mask]\n label = label[batch.train_mask]\n loss = model.loss(pred, label)\n loss.backward()\n opt.step()\n total_loss += loss.item() * batch.num_graphs\n total_loss /= len(loader.dataset)\n losses.append(total_loss)\n\n if epoch % 10 == 0:\n test_acc = test(test_loader, model)\n test_accs.append(test_acc)\n if test_acc > best_acc:\n best_acc = test_acc\n best_model = copy.deepcopy(model)\n else:\n test_accs.append(test_accs[-1])\n \n return test_accs, losses, best_model, best_acc, test_loader\n\ndef test(loader, test_model, is_validation=False, save_model_preds=False, model_type=None):\n test_model.eval()\n\n correct = 0\n # Note that Cora is only one graph!\n for data in loader:\n with torch.no_grad():\n # max(dim=1) returns values, indices tuple; only need indices\n pred = test_model(data).max(dim=1)[1]\n label = data.y\n\n mask = data.val_mask if is_validation else data.test_mask\n # node classification: only evaluate on nodes in test set\n pred = pred[mask]\n label = label[mask]\n\n if save_model_preds:\n print (\"Saving Model Predictions for Model Type\", model_type)\n\n data = {}\n data['pred'] = pred.view(-1).cpu().detach().numpy()\n data['label'] = label.view(-1).cpu().detach().numpy()\n\n df = pd.DataFrame(data=data)\n # Save locally as csv\n df.to_csv('CORA-Node-' + model_type + '.csv', sep=',', index=False)\n \n correct += pred.eq(label).sum().item()\n\n total = 0\n for data in loader.dataset:\n total += torch.sum(data.val_mask if is_validation else data.test_mask).item()\n\n return correct / total\n \nclass objectview(object):\n def __init__(self, d):\n self.__dict__ = d\n\n```\n\n## Let's Start the Training!\n\nWe will be working on the CORA dataset on node-level classification.\n\nThis part is implemented for you. **For grading purposes, please do not modify the default parameters.** However, feel free to play with different configurations just for fun!\n\n**Submit your best accuracy and loss on Gradescope.**\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n for args in [\n {'model_type': 'GraphSage', 'dataset': 'cora', 'num_layers': 2, 'heads': 1, 'batch_size': 32, 'hidden_dim': 32, 'dropout': 0.5, 'epochs': 500, 'opt': 'adam', 'opt_scheduler': 'none', 'opt_restart': 0, 'weight_decay': 5e-3, 'lr': 0.01},\n ]:\n args = objectview(args)\n for model in ['GraphSage']:\n args.model_type = model\n\n # Match the dimension.\n if model == 'GAT':\n args.heads = 2\n else:\n args.heads = 1\n\n if args.dataset == 'cora':\n dataset = Planetoid(root='/tmp/cora', name='Cora')\n else:\n raise NotImplementedError(\"Unknown dataset\") \n test_accs, losses, best_model, best_acc, test_loader = train(dataset, args) \n\n print(\"Maximum test set accuracy: {0}\".format(max(test_accs)))\n print(\"Minimum loss: {0}\".format(min(losses)))\n\n # Run test for our best model to save the predictions!\n test(test_loader, best_model, is_validation=False, save_model_preds=True, model_type=model)\n print()\n\n plt.title(dataset.name)\n plt.plot(losses, label=\"training loss\" + \" - \" + args.model_type)\n plt.plot(test_accs, label=\"test accuracy\" + \" - \" + args.model_type)\n plt.legend()\n plt.show()\n\n```\n\n## Question 1.1: What is the maximum accuracy obtained on the test set for GraphSage? (10 points)\n\nRunning the cell above will show the results of your best model and save your best model's predictions to a file named *CORA-Node-GraphSage.csv*. \n\nAs we have seen before you can view this file by clicking on the *Folder* icon on the left side pannel. When you sumbit your assignment, you will have to download this file and attatch it to your submission.\n", "meta": {"hexsha": "c975c31262453c0802581c0e1d75c714c0505a97", "size": 84035, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "CS224W_Colab3.ipynb", "max_stars_repo_name": "jaeinkr/MLOps-Basics", "max_stars_repo_head_hexsha": "200d356b637fac8a1f609d37a4e7946a6e328dae", "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": "CS224W_Colab3.ipynb", "max_issues_repo_name": "jaeinkr/MLOps-Basics", "max_issues_repo_head_hexsha": "200d356b637fac8a1f609d37a4e7946a6e328dae", "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": "CS224W_Colab3.ipynb", "max_forks_repo_name": "jaeinkr/MLOps-Basics", "max_forks_repo_head_hexsha": "200d356b637fac8a1f609d37a4e7946a6e328dae", "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": 102.3568818514, "max_line_length": 41706, "alphanum_fraction": 0.7539239603, "converted": true, "num_tokens": 7047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1801066728881779, "lm_q1q2_score": 0.0893498090663624}} {"text": "```\n# this mounts your Google Drive to the Colab VM.\nfrom google.colab import drive\ndrive.mount('/content/drive', force_remount=True)\n\n# enter the foldername in your Drive where you have saved the unzipped\n# assignment folder, e.g. 'cs231n/assignments/assignment3/'\nFOLDERNAME = \"CS231n/assignment2\"\nassert FOLDERNAME is not None, \"[!] Enter the foldername.\"\n\n# now that we've mounted your Drive, this ensures that\n# the Python interpreter of the Colab VM can load\n# python files from within it.\nimport sys\nsys.path.append('/content/drive/My Drive/{}'.format(FOLDERNAME))\n\n# this downloads the CIFAR-10 dataset to your Drive\n# if it doesn't already exist.\n%cd drive/My\\ Drive/$FOLDERNAME/cs231n/datasets/\n!bash get_datasets.sh\n%cd /content\n```\n\n Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly&response_type=code\n \n Enter your authorization code:\n ··········\n Mounted at /content/drive\n /content/drive/My Drive/CS231n/assignment2/cs231n/datasets\n /content\n\n\n# Batch Normalization\nOne way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. \nOne idea along these lines is batch normalization which was proposed by [1] in 2015.\n\nThe idea is relatively straightforward. Machine learning methods tend to work better when their input data consists of uncorrelated features with zero mean and unit variance. When training a neural network, we can preprocess the data before feeding it to the network to explicitly decorrelate its features; this will ensure that the first layer of the network sees data that follows a nice distribution. However, even if we preprocess the input data, the activations at deeper layers of the network will likely no longer be decorrelated and will no longer have zero mean or unit variance since they are output from earlier layers in the network. Even worse, during the training process the distribution of features at each layer of the network will shift as the weights of each layer are updated.\n\nThe authors of [1] hypothesize that the shifting distribution of features inside deep neural networks may make training deep networks more difficult. To overcome this problem, [1] proposes to insert batch normalization layers into the network. At training time, a batch normalization layer uses a minibatch of data to estimate the mean and standard deviation of each feature. These estimated means and standard deviations are then used to center and normalize the features of the minibatch. A running average of these means and standard deviations is kept during training, and at test time these running averages are used to center and normalize features.\n\nIt is possible that this normalization strategy could reduce the representational power of the network, since it may sometimes be optimal for certain layers to have features that are not zero-mean or unit variance. To this end, the batch normalization layer includes learnable shift and scale parameters for each feature dimension.\n\n[1] [Sergey Ioffe and Christian Szegedy, \"Batch Normalization: Accelerating Deep Network Training by Reducing\nInternal Covariate Shift\", ICML 2015.](https://arxiv.org/abs/1502.03167)\n\n\n```\n# As usual, a bit of setup\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.fc_net import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array\nfrom cs231n.solver import Solver\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# for auto-reloading external modules\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2\n\ndef rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\ndef print_mean_std(x,axis=0):\n print(' means: ', x.mean(axis=axis))\n print(' stds: ', x.std(axis=axis))\n print() \n```\n\n =========== You can safely ignore the message below if you are NOT working on ConvolutionalNetworks.ipynb ===========\n \tYou will need to compile a Cython extension for a portion of this assignment.\n \tThe instructions to do this will be given in a section of the notebook below.\n \tThere will be an option for Colab users and another for Jupyter (local) users.\n\n\n\n```\n# Load the (preprocessed) CIFAR10 data.\ndata = get_CIFAR10_data()\nfor k, v in data.items():\n print('%s: ' % k, v.shape)\n```\n\n X_train: (49000, 3, 32, 32)\n y_train: (49000,)\n X_val: (1000, 3, 32, 32)\n y_val: (1000,)\n X_test: (1000, 3, 32, 32)\n y_test: (1000,)\n\n\n## Batch normalization: forward\nIn the file `cs231n/layers.py`, implement the batch normalization forward pass in the function `batchnorm_forward`. Once you have done so, run the following to test your implementation.\n\nReferencing the paper linked to above in [1] may be helpful!\n\n\n```\n# Check the training-time forward pass by checking means and variances\n# of features both before and after batch normalization \n\n# Simulate the forward pass for a two-layer network\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before batch normalization:')\nprint_mean_std(a,axis=0)\n\ngamma = np.ones((D3,))\nbeta = np.zeros((D3,))\n# Means should be close to zero and stds close to one\nprint('After batch normalization (gamma=1, beta=0)')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n\ngamma = np.asarray([1.0, 2.0, 3.0])\nbeta = np.asarray([11.0, 12.0, 13.0])\n# Now means should be close to beta and stds close to gamma\nprint('After batch normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n```\n\n Before batch normalization:\n means: [ -2.3814598 -13.18038246 1.91780462]\n stds: [27.18502186 34.21455511 37.68611762]\n \n After batch normalization (gamma=1, beta=0)\n means: [5.99520433e-17 6.93889390e-17 8.32667268e-19]\n stds: [0.99999999 1. 1. ]\n \n After batch normalization (gamma= [1. 2. 3.] , beta= [11. 12. 13.] )\n means: [11. 12. 13.]\n stds: [0.99999999 1.99999999 2.99999999]\n \n\n\n\n```\n# Check the test-time forward pass by running the training-time\n# forward pass many times to warm up the running averages, and then\n# checking the means and variances of activations after a test-time\n# forward pass.\n\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\n\nbn_param = {'mode': 'train'}\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n\nfor t in range(50):\n X = np.random.randn(N, D1)\n a = np.maximum(0, X.dot(W1)).dot(W2)\n batchnorm_forward(a, gamma, beta, bn_param)\n\nbn_param['mode'] = 'test'\nX = np.random.randn(N, D1)\na = np.maximum(0, X.dot(W1)).dot(W2)\na_norm, _ = batchnorm_forward(a, gamma, beta, bn_param)\n\n# Means should be close to zero and stds close to one, but will be\n# noisier than training-time forward passes.\nprint('After batch normalization (test-time):')\nprint_mean_std(a_norm,axis=0)\n```\n\n After batch normalization (test-time):\n means: [-0.03927354 -0.04349152 -0.10452688]\n stds: [1.01531428 1.01238373 0.97819988]\n \n\n\n## Batch normalization: backward\nNow implement the backward pass for batch normalization in the function `batchnorm_backward`.\n\nTo derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing branches; make sure to sum gradients across these branches in the backward pass.\n\nOnce you have finished, run the following to numerically check your backward pass.\n\n\n```\n# Gradient check batchnorm backward pass\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nfx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]\nfg = lambda a: batchnorm_forward(x, a, beta, bn_param)[0]\nfb = lambda b: batchnorm_forward(x, gamma, b, bn_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = batchnorm_forward(x, gamma, beta, bn_param)\ndx, dgamma, dbeta = batchnorm_backward(dout, cache)\n#You should expect to see relative errors between 1e-13 and 1e-8\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.6674604875341426e-09\n dgamma error: 7.417225040694815e-13\n dbeta error: 2.379446949959628e-12\n\n\n## Batch normalization: alternative backward\nIn class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For example, you can derive a very simple formula for the sigmoid function's backward pass by simplifying gradients on paper.\n\nSurprisingly, it turns out that you can do a similar simplification for the batch normalization backward pass too! \n\nIn the forward pass, given a set of inputs $X=\\begin{bmatrix}x_1\\\\x_2\\\\...\\\\x_N\\end{bmatrix}$, \n\nwe first calculate the mean $\\mu$ and variance $v$.\nWith $\\mu$ and $v$ calculated, we can calculate the standard deviation $\\sigma$ and normalized data $Y$.\nThe equations and graph illustration below describe the computation ($y_i$ is the i-th element of the vector $Y$).\n\n\\begin{align}\n& \\mu=\\frac{1}{N}\\sum_{k=1}^N x_k & v=\\frac{1}{N}\\sum_{k=1}^N (x_k-\\mu)^2 \\\\\n& \\sigma=\\sqrt{v+\\epsilon} & y_i=\\frac{x_i-\\mu}{\\sigma}\n\\end{align}\n\n\n\nThe meat of our problem during backpropagation is to compute $\\frac{\\partial L}{\\partial X}$, given the upstream gradient we receive, $\\frac{\\partial L}{\\partial Y}.$ To do this, recall the chain rule in calculus gives us $\\frac{\\partial L}{\\partial X} = \\frac{\\partial L}{\\partial Y} \\cdot \\frac{\\partial Y}{\\partial X}$.\n\nThe unknown/hart part is $\\frac{\\partial Y}{\\partial X}$. We can find this by first deriving step-by-step our local gradients at \n$\\frac{\\partial v}{\\partial X}$, $\\frac{\\partial \\mu}{\\partial X}$,\n$\\frac{\\partial \\sigma}{\\partial v}$, \n$\\frac{\\partial Y}{\\partial \\sigma}$, and $\\frac{\\partial Y}{\\partial \\mu}$,\nand then use the chain rule to compose these gradients (which appear in the form of vectors!) appropriately to compute $\\frac{\\partial Y}{\\partial X}$.\n\nIf it's challenging to directly reason about the gradients over $X$ and $Y$ which require matrix multiplication, try reasoning about the gradients in terms of individual elements $x_i$ and $y_i$ first: in that case, you will need to come up with the derivations for $\\frac{\\partial L}{\\partial x_i}$, by relying on the Chain Rule to first calculate the intermediate $\\frac{\\partial \\mu}{\\partial x_i}, \\frac{\\partial v}{\\partial x_i}, \\frac{\\partial \\sigma}{\\partial x_i},$ then assemble these pieces to calculate $\\frac{\\partial y_i}{\\partial x_i}$. \n\nYou should make sure each of the intermediary gradient derivations are all as simplified as possible, for ease of implementation. \n\nAfter doing so, implement the simplified batch normalization backward pass in the function `batchnorm_backward_alt` and compare the two implementations by running the following. Your two implementations should compute nearly identical results, but the alternative implementation should be a bit faster.\n\n\n```\nnp.random.seed(231)\nN, D = 100, 500\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nout, cache = batchnorm_forward(x, gamma, beta, bn_param)\n\nt1 = time.time()\ndx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache)\nt2 = time.time()\ndx2, dgamma2, dbeta2 = batchnorm_backward_alt(dout, cache)\nt3 = time.time()\n\nprint('dx difference: ', rel_error(dx1, dx2))\nprint('dgamma difference: ', rel_error(dgamma1, dgamma2))\nprint('dbeta difference: ', rel_error(dbeta1, dbeta2))\nprint('speedup: %.2fx' % ((t2 - t1) / (t3 - t2)))\n```\n\n dx difference: 1.8400087424475466e-12\n dgamma difference: 0.0\n dbeta difference: 0.0\n speedup: 1.73x\n\n\n## Fully Connected Nets with Batch Normalization\nNow that you have a working implementation for batch normalization, go back to your `FullyConnectedNet` in the file `cs231n/classifiers/fc_net.py`. Modify your implementation to add batch normalization.\n\nConcretely, when the `normalization` flag is set to `\"batchnorm\"` in the constructor, you should insert a batch normalization layer before each ReLU nonlinearity. The outputs from the last layer of the network should not be normalized. Once you are done, run the following to gradient-check your implementation.\n\nHINT: You might find it useful to define an additional helper layer similar to those in the file `cs231n/layer_utils.py`. If you decide to do so, do it in the file `cs231n/classifiers/fc_net.py`.\n\n\n```\nnp.random.seed(231)\nN, D, H1, H2, C = 2, 15, 20, 30, 10\nX = np.random.randn(N, D)\ny = np.random.randint(C, size=(N,))\n\n# You should expect losses between 1e-4~1e-10 for W, \n# losses between 1e-08~1e-10 for b,\n# and losses between 1e-08~1e-09 for beta and gammas.\nfor reg in [0, 3.14]:\n print('Running check with reg = ', reg)\n model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,\n reg=reg, weight_scale=5e-2, dtype=np.float64,\n normalization='batchnorm')\n\n loss, grads = model.loss(X, y)\n print('Initial loss: ', loss)\n\n for name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)\n print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))\n if reg == 0: print()\n```\n\n Running check with reg = 0\n Initial loss: 2.2611955101340957\n W1 relative error: 1.10e-04\n W2 relative error: 3.11e-06\n W3 relative error: 4.05e-10\n b1 relative error: 4.44e-08\n b2 relative error: 2.22e-08\n b3 relative error: 1.01e-10\n beta1 relative error: 7.33e-09\n beta2 relative error: 1.89e-09\n gamma1 relative error: 6.96e-09\n gamma2 relative error: 2.41e-09\n \n Running check with reg = 3.14\n Initial loss: 6.996533220108303\n W1 relative error: 1.98e-06\n W2 relative error: 2.29e-06\n W3 relative error: 2.79e-08\n b1 relative error: 5.55e-09\n b2 relative error: 2.22e-08\n b3 relative error: 2.10e-10\n beta1 relative error: 6.65e-09\n beta2 relative error: 3.39e-09\n gamma1 relative error: 6.27e-09\n gamma2 relative error: 5.28e-09\n\n\n# Batchnorm for deep networks\nRun the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization.\n\n\n```\nnp.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [100, 100, 100, 100, 100]\n\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nweight_scale = 2e-2\nbn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\nmodel = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\nprint('Solver with batch norm:')\nbn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=200)\nbn_solver.train()\n\nprint('\\nSolver without batch norm:')\nsolver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=20)\nsolver.train()\n```\n\n Solver with batch norm:\n (Iteration 1 / 200) loss: 2.340974\n (Epoch 0 / 10) train acc: 0.107000; val_acc: 0.115000\n (Epoch 1 / 10) train acc: 0.313000; val_acc: 0.266000\n (Epoch 2 / 10) train acc: 0.396000; val_acc: 0.280000\n (Epoch 3 / 10) train acc: 0.485000; val_acc: 0.316000\n (Epoch 4 / 10) train acc: 0.524000; val_acc: 0.318000\n (Epoch 5 / 10) train acc: 0.595000; val_acc: 0.341000\n (Epoch 6 / 10) train acc: 0.640000; val_acc: 0.321000\n (Epoch 7 / 10) train acc: 0.689000; val_acc: 0.341000\n (Epoch 8 / 10) train acc: 0.669000; val_acc: 0.299000\n (Epoch 9 / 10) train acc: 0.791000; val_acc: 0.340000\n (Epoch 10 / 10) train acc: 0.779000; val_acc: 0.305000\n \n Solver without batch norm:\n (Iteration 1 / 200) loss: 2.302332\n (Epoch 0 / 10) train acc: 0.129000; val_acc: 0.131000\n (Epoch 1 / 10) train acc: 0.283000; val_acc: 0.250000\n (Iteration 21 / 200) loss: 2.041970\n (Epoch 2 / 10) train acc: 0.316000; val_acc: 0.277000\n (Iteration 41 / 200) loss: 1.900473\n (Epoch 3 / 10) train acc: 0.373000; val_acc: 0.282000\n (Iteration 61 / 200) loss: 1.713156\n (Epoch 4 / 10) train acc: 0.390000; val_acc: 0.310000\n (Iteration 81 / 200) loss: 1.662209\n (Epoch 5 / 10) train acc: 0.434000; val_acc: 0.300000\n (Iteration 101 / 200) loss: 1.696062\n (Epoch 6 / 10) train acc: 0.536000; val_acc: 0.346000\n (Iteration 121 / 200) loss: 1.550785\n (Epoch 7 / 10) train acc: 0.530000; val_acc: 0.310000\n (Iteration 141 / 200) loss: 1.436308\n (Epoch 8 / 10) train acc: 0.622000; val_acc: 0.342000\n (Iteration 161 / 200) loss: 1.000868\n (Epoch 9 / 10) train acc: 0.654000; val_acc: 0.328000\n (Iteration 181 / 200) loss: 0.925456\n (Epoch 10 / 10) train acc: 0.726000; val_acc: 0.335000\n\n\nRun the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster.\n\n\n```\ndef plot_training_history(title, label, baseline, bn_solvers, plot_fn, bl_marker='.', bn_marker='.', labels=None):\n \"\"\"utility function for plotting training history\"\"\"\n plt.title(title)\n plt.xlabel(label)\n bn_plots = [plot_fn(bn_solver) for bn_solver in bn_solvers]\n bl_plot = plot_fn(baseline)\n num_bn = len(bn_plots)\n for i in range(num_bn):\n label='with_norm'\n if labels is not None:\n label += str(labels[i])\n plt.plot(bn_plots[i], bn_marker, label=label)\n label='baseline'\n if labels is not None:\n label += str(labels[0])\n plt.plot(bl_plot, bl_marker, label=label)\n plt.legend(loc='lower center', ncol=num_bn+1) \n\n \nplt.subplot(3, 1, 1)\nplot_training_history('Training loss','Iteration', solver, [bn_solver], \\\n lambda x: x.loss_history, bl_marker='o', bn_marker='o')\nplt.subplot(3, 1, 2)\nplot_training_history('Training accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.train_acc_history, bl_marker='-o', bn_marker='-o')\nplt.subplot(3, 1, 3)\nplot_training_history('Validation accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.val_acc_history, bl_marker='-o', bn_marker='-o')\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n# Batch normalization and initialization\nWe will now run a small experiment to study the interaction of batch normalization and weight initialization.\n\nThe first cell will train 8-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training accuracy, validation set accuracy, and training loss as a function of the weight initialization scale.\n\n\n```\nnp.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [50, 50, 50, 50, 50, 50, 50]\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nbn_solvers_ws = {}\nsolvers_ws = {}\nweight_scales = np.logspace(-4, 0, num=20)\nfor i, weight_scale in enumerate(weight_scales):\n print('Running weight scale %d / %d' % (i + 1, len(weight_scales)))\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\n bn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n bn_solver.train()\n bn_solvers_ws[weight_scale] = bn_solver\n\n solver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n solver.train()\n solvers_ws[weight_scale] = solver\n```\n\n Running weight scale 1 / 20\n Running weight scale 2 / 20\n Running weight scale 3 / 20\n Running weight scale 4 / 20\n Running weight scale 5 / 20\n Running weight scale 6 / 20\n Running weight scale 7 / 20\n Running weight scale 8 / 20\n Running weight scale 9 / 20\n Running weight scale 10 / 20\n Running weight scale 11 / 20\n Running weight scale 12 / 20\n Running weight scale 13 / 20\n Running weight scale 14 / 20\n Running weight scale 15 / 20\n Running weight scale 16 / 20\n Running weight scale 17 / 20\n Running weight scale 18 / 20\n Running weight scale 19 / 20\n Running weight scale 20 / 20\n\n\n\n```\n# Plot results of weight scale experiment\nbest_train_accs, bn_best_train_accs = [], []\nbest_val_accs, bn_best_val_accs = [], []\nfinal_train_loss, bn_final_train_loss = [], []\n\nfor ws in weight_scales:\n best_train_accs.append(max(solvers_ws[ws].train_acc_history))\n bn_best_train_accs.append(max(bn_solvers_ws[ws].train_acc_history))\n \n best_val_accs.append(max(solvers_ws[ws].val_acc_history))\n bn_best_val_accs.append(max(bn_solvers_ws[ws].val_acc_history))\n \n final_train_loss.append(np.mean(solvers_ws[ws].loss_history[-100:]))\n bn_final_train_loss.append(np.mean(bn_solvers_ws[ws].loss_history[-100:]))\n \nplt.subplot(3, 1, 1)\nplt.title('Best val accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best val accuracy')\nplt.semilogx(weight_scales, best_val_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm')\nplt.legend(ncol=2, loc='lower right')\n\nplt.subplot(3, 1, 2)\nplt.title('Best train accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best training accuracy')\nplt.semilogx(weight_scales, best_train_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm')\nplt.legend()\n\nplt.subplot(3, 1, 3)\nplt.title('Final training loss vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Final training loss')\nplt.semilogx(weight_scales, final_train_loss, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_final_train_loss, '-o', label='batchnorm')\nplt.legend()\nplt.gca().set_ylim(1.0, 3.5)\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n## Inline Question 1:\nDescribe the results of this experiment. How does the scale of weight initialization affect models with/without batch normalization differently, and why?\n\n## Answer:\n[FILL THIS IN]\n\n\n# Batch normalization and batch size\nWe will now run a small experiment to study the interaction of batch normalization and batch size.\n\nThe first cell will train 6-layer networks both with and without batch normalization using different batch sizes. The second layer will plot training accuracy and validation set accuracy over time.\n\n\n```\ndef run_batchsize_experiments(normalization_mode):\n np.random.seed(231)\n # Try training a very deep net with batchnorm\n hidden_dims = [100, 100, 100, 100, 100]\n num_train = 1000\n small_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n }\n n_epochs=10\n weight_scale = 2e-2\n batch_sizes = [5,10,50]\n lr = 10**(-3.5)\n solver_bsize = batch_sizes[0]\n\n print('No normalization: batch size = ',solver_bsize)\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n solver = Solver(model, small_data,\n num_epochs=n_epochs, batch_size=solver_bsize,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n solver.train()\n \n bn_solvers = []\n for i in range(len(batch_sizes)):\n b_size=batch_sizes[i]\n print('Normalization: batch size = ',b_size)\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=normalization_mode)\n bn_solver = Solver(bn_model, small_data,\n num_epochs=n_epochs, batch_size=b_size,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n bn_solver.train()\n bn_solvers.append(bn_solver)\n \n return bn_solvers, solver, batch_sizes\n\nbatch_sizes = [5,10,50]\nbn_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('batchnorm')\n```\n\n No normalization: batch size = 5\n Normalization: batch size = 5\n Normalization: batch size = 10\n Normalization: batch size = 50\n\n\n\n```\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 2:\nDescribe the results of this experiment. What does this imply about the relationship between batch normalization and batch size? Why is this relationship observed?\n\n## Answer:\n[FILL THIS IN]\n\n\n# Layer Normalization\nBatch normalization has proved to be effective in making networks easier to train, but the dependency on batch size makes it less useful in complex networks which have a cap on the input batch size due to hardware limitations. \n\nSeveral alternatives to batch normalization have been proposed to mitigate this problem; one such technique is Layer Normalization [2]. Instead of normalizing over the batch, we normalize over the features. In other words, when using Layer Normalization, each feature vector corresponding to a single datapoint is normalized based on the sum of all terms within that feature vector.\n\n[2] [Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. \"Layer Normalization.\" stat 1050 (2016): 21.](https://arxiv.org/pdf/1607.06450.pdf)\n\n## Inline Question 3:\nWhich of these data preprocessing steps is analogous to batch normalization, and which is analogous to layer normalization?\n\n1. Scaling each image in the dataset, so that the RGB channels for each row of pixels within an image sums up to 1.\n2. Scaling each image in the dataset, so that the RGB channels for all pixels within an image sums up to 1. \n3. Subtracting the mean image of the dataset from each image in the dataset.\n4. Setting all RGB values to either 0 or 1 depending on a given threshold.\n\n## Answer:\n[FILL THIS IN]\n\n\n# Layer Normalization: Implementation\n\nNow you'll implement layer normalization. This step should be relatively straightforward, as conceptually the implementation is almost identical to that of batch normalization. One significant difference though is that for layer normalization, we do not keep track of the moving moments, and the testing phase is identical to the training phase, where the mean and variance are directly calculated per datapoint.\n\nHere's what you need to do:\n\n* In `cs231n/layers.py`, implement the forward pass for layer normalization in the function `layernorm_forward`. \n\nRun the cell below to check your results.\n* In `cs231n/layers.py`, implement the backward pass for layer normalization in the function `layernorm_backward`. \n\nRun the second cell below to check your results.\n* Modify `cs231n/classifiers/fc_net.py` to add layer normalization to the `FullyConnectedNet`. When the `normalization` flag is set to `\"layernorm\"` in the constructor, you should insert a layer normalization layer before each ReLU nonlinearity. \n\nRun the third cell below to run the batch size experiment on layer normalization.\n\n\n```\n# Check the training-time forward pass by checking means and variances\n# of features both before and after layer normalization \n\n# Simulate the forward pass for a two-layer network\nnp.random.seed(231)\nN, D1, D2, D3 =4, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before layer normalization:')\nprint_mean_std(a,axis=1)\n\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n# Means should be close to zero and stds close to one\nprint('After layer normalization (gamma=1, beta=0)')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n\ngamma = np.asarray([3.0,3.0,3.0])\nbeta = np.asarray([5.0,5.0,5.0])\n# Now means should be close to beta and stds close to gamma\nprint('After layer normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n```\n\n Before layer normalization:\n means: [-59.06673243 -47.60782686 -43.31137368 -26.40991744]\n stds: [10.07429373 28.39478981 35.28360729 4.01831507]\n \n After layer normalization (gamma=1, beta=0)\n means: [-0.58416774 0.03223092 -0.29106935 0.84300618]\n stds: [0.42903404 1.0673565 1.17954475 0.38429471]\n \n After layer normalization (gamma= [3. 3. 3.] , beta= [5. 5. 5.] )\n means: [3.24749679 5.09669275 4.12679194 7.52901853]\n stds: [1.28710213 3.2020695 3.53863425 1.15288413]\n \n\n\n\n```\n# Gradient check batchnorm backward pass\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nln_param = {}\nfx = lambda x: layernorm_forward(x, gamma, beta, ln_param)[0]\nfg = lambda a: layernorm_forward(x, a, beta, ln_param)[0]\nfb = lambda b: layernorm_forward(x, gamma, b, ln_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = layernorm_forward(x, gamma, beta, ln_param)\ndx, dgamma, dbeta = layernorm_backward(dout, cache)\n\n#You should expect to see relative errors between 1e-12 and 1e-8\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.6674604875341426e-09\n dgamma error: 7.417225040694815e-13\n dbeta error: 2.379446949959628e-12\n\n\n# Layer Normalization and batch size\n\nWe will now run the previous batch size experiment with layer normalization instead of batch normalization. Compared to the previous experiment, you should see a markedly smaller influence of batch size on the training history!\n\n\n```\nln_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('layernorm')\n\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 4:\nWhen is layer normalization likely to not work well, and why?\n\n1. Using it in a very deep network\n2. Having a very small dimension of features\n3. Having a high regularization term\n\n\n## Answer:\n[FILL THIS IN]\n\n", "meta": {"hexsha": "da6ca3eb4b69d38ea648d799cbca134c15adcbc5", "size": 358159, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignment2/BatchNormalization.ipynb", "max_stars_repo_name": "moustafa-7/CS231n", "max_stars_repo_head_hexsha": "d06494d940f07c814b9225cc8feb9350d06ba14b", "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": "assignment2/BatchNormalization.ipynb", "max_issues_repo_name": "moustafa-7/CS231n", "max_issues_repo_head_hexsha": "d06494d940f07c814b9225cc8feb9350d06ba14b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-02-02T22:57:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:42:58.000Z", "max_forks_repo_path": "assignment2/BatchNormalization.ipynb", "max_forks_repo_name": "moustafa-7/CS231n", "max_forks_repo_head_hexsha": "d06494d940f07c814b9225cc8feb9350d06ba14b", "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": 358159.0, "max_line_length": 358159, "alphanum_fraction": 0.9233413093, "converted": true, "num_tokens": 9306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423538592116924, "lm_q2_score": 0.27512971193602087, "lm_q1q2_score": 0.08920678832795585}} {"text": "```python\nfrom IPython.core.display import HTML\ncss_file = '../style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Introduction to matrices\n\n## Preamble\n\nBefore we start our journey into linear algebra, we take a quick look at creating matrices using the `sympy` package. As always, we start off by initializing LaTex printing using the `init_printing()` function.\n\n\n```python\nfrom sympy import init_printing\ninit_printing()\n```\n\n## Representing matrices\n\nMatrices are represented as $m$ rows of values, spread over $n$ columns, to make up an $m \\times n$ array or grid. The `sympy` package contains the `Matrix()` function to create these objects.\n\n\n```python\nfrom sympy import Matrix\n```\n\nExpression (1) depicts a $4 \\times 3$ matrix of integer values. We can recreate this using the `Matrix()` function. This is a matrix. A matrix has a dimension, which lists, in order, the number of rows and the number of columns. The matrix in (1) has dimension $3 \\times 3$.\n\n$$\\begin{bmatrix} 1 && 2 && 3 \\\\ 4 && 5 && 6 \\\\ 7 && 8 && 9 \\\\ 10 && 11 && 12 \\end{bmatrix} \\tag{1}$$\n\nThe values are entered as a list of list, with each sublist containing a row of values.\n\n\n```python\nmatrix_1 = Matrix([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [10, 11, 12]])\nmatrix_1\n```\n\nBy using the `type()` function we can inspect the object type of which `matrix_1` is an instance.\n\n\n```python\ntype(matrix_1)\n```\n\n\n\n\n sympy.matrices.dense.MutableDenseMatrix\n\n\n\nWe note that it is a `MutableDenseMatrix`. Mutable refers to the fact that we can change the values in the matrix and dense refers to the fact that there are not an abundance of zeros in the data.\n\n## Shape\n\nThe `.shape()` method calculates the number of rows and columns of a matrix.\n\n\n```python\nmatrix_1.shape\n```\n\n## Accessing values in rows and columns\n\nThe `.row()` and `.col()` methods give us access to the values in a matrix. Remember that Python indexing starts at $0$, such that the first row (in the mathematical representation) is the zeroth row in `python`.\n\n\n```python\nmatrix_1.row(0) # The first row\n```\n\n\n```python\nmatrix_1.col(0) # The first column\n```\n\nThe `-1` value gives us access to the last row or column.\n\n\n```python\nmatrix_1.row(-1)\n```\n\nEvery element in a matrix is indexed, with a row and column number. In (2), we see a $3 \\times 4$ matrix with the index of every element. Note we place both values together, without a comma separating them.\n\n$$\\begin{pmatrix} a_{11} && a_{12} && a_{13} && a_{14} \\\\ a_{21} && a_{22} && a_{23} && a_{24} \\\\ a_{31} && a_{32} && a_{33} && a_{34} \\end{pmatrix} \\tag{2}$$\n\nSo, if we wish to find the element in the first row and the first column in our `matrix_1` variable (which holds a `sympy` matrix object), we will use `0,0` and not `1,1`. The _indexing_ (using the _address_ of each element) is done by using square brackets.\n\n\n```python\n# Repriting matrix_1\nmatrix_1\n```\n\n\n```python\nmatrix_1[0,0]\n```\n\nLet's look at the element in the second row and third column, which is $6$.\n\n\n```python\nmatrix_1[1,2]\n```\n\nWe can also span a few rows and column. Below, we index the first two rows. This is done by using the colon, `:`, symbol. The last number (after the colon is excluded, such that `0:2` refers to the zeroth and first row indices.\n\n\n```python\nmatrix_1[0:2,0:4]\n```\n\nWe can also specify the actual rows or columns, by placing them in square brackets (creating a list). Below, we also use the colon symbol on is won. This denotes the selection of all values. So, we have the first and third rows (mathematically) or the zeroth and second `python` row index, and all the columns.\n\n\n```python\nmatrix_1[[0,2],:]\n```\n\n## Deleting and inserting rows\n\nRow and column can be inserted into or deleted from a matrix using the `.row_insert()`, `.col_insert()`, `.row_del()`, and `.col_del()` methods. \n\nLet's have a look at where these inserted and deletions take place.\n\n\n```python\nmatrix_1.row_insert(1, Matrix([[10, 20, 30]])) # Using row 1\n```\n\nWe note that the row was inserted as row 1.\n\nIf we call the matrix again, we note that the changes were not permanent.\n\n\n```python\nmatrix_1\n```\n\nWe have to overwrite the computer variable to make the changes permanent or alternatively create a new computer variable. (This is contrary to the current documentation.)\n\n\n```python\nmatrix_2 = matrix_1.row_insert(1, Matrix([[10, 20, 30]]))\n```\n\n\n```python\nmatrix_2\n```\n\n\n```python\nmatrix_3 = matrix_1.row_del(1) # Permanently deleting the second row\nmatrix_3 # A bug in the code currently returns a NoneType object\n```\n\n## Useful matrix constructors\n\nThere are a few special matrices that can be constructed using `sympy` functions. The zero matrix of size $n \\times n$ can be created with the `zeros()` function and the $n \\times n$ identity matrix (more on this later) can be created with the `eye()` function.\n\n\n```python\nfrom sympy import zeros, eye\n```\n\n\n```python\nzeros(5) # A 5x5 matrix of all zeros\nzeros(5)\n```\n\n\n```python\neye(4) # A 4x4 identity matrix\n```\n\nThe `diag()` function creates a diagonal matrix (which is square) with specified values along the main axis (top-left to bottom-right) and zeros everywhere else.\n\n\n```python\nfrom sympy import diag\n```\n\n\n```python\ndiag(1, 2, 3, 4, 5)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5eaccf8118cd64ebc9c05a237a2eac45b3612dd1", "size": 53753, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/3. Computational Sciences and Mathematics/Linear Algebra/0.0 Start Here/0.3 Introduction_to_matrices.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": "Python/3. Computational Sciences and Mathematics/Linear Algebra/0.0 Start Here/0.3 Introduction_to_matrices.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": "Python/3. Computational Sciences and Mathematics/Linear Algebra/0.0 Start Here/0.3 Introduction_to_matrices.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": 61.2919042189, "max_line_length": 4072, "alphanum_fraction": 0.7707290756, "converted": true, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.17781086729958678, "lm_q1q2_score": 0.08890543364979339}} {"text": "```python\n%matplotlib inline\n```\n\n\nWord Embeddings: Encoding Lexical Semantics\n===========================================\n\nWord embeddings are dense vectors of real numbers, one per word in your\nvocabulary. In NLP, it is almost always the case that your features are\nwords! But how should you represent a word in a computer? You could\nstore its ascii character representation, but that only tells you what\nthe word *is*, it doesn't say much about what it *means* (you might be\nable to derive its part of speech from its affixes, or properties from\nits capitalization, but not much). Even more, in what sense could you\ncombine these representations? We often want dense outputs from our\nneural networks, where the inputs are $|V|$ dimensional, where\n$V$ is our vocabulary, but often the outputs are only a few\ndimensional (if we are only predicting a handful of labels, for\ninstance). How do we get from a massive dimensional space to a smaller\ndimensional space?\n\nHow about instead of ascii representations, we use a one-hot encoding?\nThat is, we represent the word $w$ by\n\n\\begin{align}\\overbrace{\\left[ 0, 0, \\dots, 1, \\dots, 0, 0 \\right]}^\\text{|V| elements}\\end{align}\n\nwhere the 1 is in a location unique to $w$. Any other word will\nhave a 1 in some other location, and a 0 everywhere else.\n\nThere is an enormous drawback to this representation, besides just how\nhuge it is. It basically treats all words as independent entities with\nno relation to each other. What we really want is some notion of\n*similarity* between words. Why? Let's see an example.\n\nSuppose we are building a language model. Suppose we have seen the\nsentences\n\n* The mathematician ran to the store.\n* The physicist ran to the store.\n* The mathematician solved the open problem.\n\nin our training data. Now suppose we get a new sentence never before\nseen in our training data:\n\n* The physicist solved the open problem.\n\nOur language model might do OK on this sentence, but wouldn't it be much\nbetter if we could use the following two facts:\n\n* We have seen mathematician and physicist in the same role in a sentence. Somehow they\n have a semantic relation.\n* We have seen mathematician in the same role in this new unseen sentence\n as we are now seeing physicist.\n\nand then infer that physicist is actually a good fit in the new unseen\nsentence? This is what we mean by a notion of similarity: we mean\n*semantic similarity*, not simply having similar orthographic\nrepresentations. It is a technique to combat the sparsity of linguistic\ndata, by connecting the dots between what we have seen and what we\nhaven't. This example of course relies on a fundamental linguistic\nassumption: that words appearing in similar contexts are related to each\nother semantically. This is called the `distributional\nhypothesis `__.\n\n\nGetting Dense Word Embeddings\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nHow can we solve this problem? That is, how could we actually encode\nsemantic similarity in words? Maybe we think up some semantic\nattributes. For example, we see that both mathematicians and physicists\ncan run, so maybe we give these words a high score for the \"is able to\nrun\" semantic attribute. Think of some other attributes, and imagine\nwhat you might score some common words on those attributes.\n\nIf each attribute is a dimension, then we might give each word a vector,\nlike this:\n\n\\begin{align}q_\\text{mathematician} = \\left[ \\overbrace{2.3}^\\text{can run},\n \\overbrace{9.4}^\\text{likes coffee}, \\overbrace{-5.5}^\\text{majored in Physics}, \\dots \\right]\\end{align}\n\n\\begin{align}q_\\text{physicist} = \\left[ \\overbrace{2.5}^\\text{can run},\n \\overbrace{9.1}^\\text{likes coffee}, \\overbrace{6.4}^\\text{majored in Physics}, \\dots \\right]\\end{align}\n\nThen we can get a measure of similarity between these words by doing:\n\n\\begin{align}\\text{Similarity}(\\text{physicist}, \\text{mathematician}) = q_\\text{physicist} \\cdot q_\\text{mathematician}\\end{align}\n\nAlthough it is more common to normalize by the lengths:\n\n\\begin{align}\\text{Similarity}(\\text{physicist}, \\text{mathematician}) = \\frac{q_\\text{physicist} \\cdot q_\\text{mathematician}}\n {\\| q_\\text{physicist} \\| \\| q_\\text{mathematician} \\|} = \\cos (\\phi)\\end{align}\n\nWhere $\\phi$ is the angle between the two vectors. That way,\nextremely similar words (words whose embeddings point in the same\ndirection) will have similarity 1. Extremely dissimilar words should\nhave similarity -1.\n\n\nYou can think of the sparse one-hot vectors from the beginning of this\nsection as a special case of these new vectors we have defined, where\neach word basically has similarity 0, and we gave each word some unique\nsemantic attribute. These new vectors are *dense*, which is to say their\nentries are (typically) non-zero.\n\nBut these new vectors are a big pain: you could think of thousands of\ndifferent semantic attributes that might be relevant to determining\nsimilarity, and how on earth would you set the values of the different\nattributes? Central to the idea of deep learning is that the neural\nnetwork learns representations of the features, rather than requiring\nthe programmer to design them herself. So why not just let the word\nembeddings be parameters in our model, and then be updated during\ntraining? This is exactly what we will do. We will have some *latent\nsemantic attributes* that the network can, in principle, learn. Note\nthat the word embeddings will probably not be interpretable. That is,\nalthough with our hand-crafted vectors above we can see that\nmathematicians and physicists are similar in that they both like coffee,\nif we allow a neural network to learn the embeddings and see that both\nmathematicians and physicists have a large value in the second\ndimension, it is not clear what that means. They are similar in some\nlatent semantic dimension, but this probably has no interpretation to\nus.\n\n\nIn summary, **word embeddings are a representation of the *semantics* of\na word, efficiently encoding semantic information that might be relevant\nto the task at hand**. You can embed other things too: part of speech\ntags, parse trees, anything! The idea of feature embeddings is central\nto the field.\n\n\nWord Embeddings in Pytorch\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBefore we get to a worked example and an exercise, a few quick notes\nabout how to use embeddings in Pytorch and in deep learning programming\nin general. Similar to how we defined a unique index for each word when\nmaking one-hot vectors, we also need to define an index for each word\nwhen using embeddings. These will be keys into a lookup table. That is,\nembeddings are stored as a $|V| \\times D$ matrix, where $D$\nis the dimensionality of the embeddings, such that the word assigned\nindex $i$ has its embedding stored in the $i$'th row of the\nmatrix. In all of my code, the mapping from words to indices is a\ndictionary named word\\_to\\_ix.\n\nThe module that allows you to use embeddings is torch.nn.Embedding,\nwhich takes two arguments: the vocabulary size, and the dimensionality\nof the embeddings.\n\nTo index into this table, you must use torch.LongTensor (since the\nindices are integers, not floats).\n\n\n\n\n\n```python\n# Author: Robert Guthrie\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntorch.manual_seed(1)\n```\n\n\n```python\nword_to_ix = {\"hello\": 0, \"world\": 1}\nembeds = nn.Embedding(2, 5) # 2 words in vocab, 5 dimensional embeddings\nlookup_tensor = torch.tensor([word_to_ix[\"hello\"]], dtype=torch.long)\nhello_embed = embeds(lookup_tensor)\nprint(hello_embed)\n```\n\nAn Example: N-Gram Language Modeling\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nRecall that in an n-gram language model, given a sequence of words\n$w$, we want to compute\n\n\\begin{align}P(w_i | w_{i-1}, w_{i-2}, \\dots, w_{i-n+1} )\\end{align}\n\nWhere $w_i$ is the ith word of the sequence.\n\nIn this example, we will compute the loss function on some training\nexamples and update the parameters with backpropagation.\n\n\n\n\n\n```python\nCONTEXT_SIZE = 2\nEMBEDDING_DIM = 10\n# We will use Shakespeare Sonnet 2\ntest_sentence = \"\"\"When forty winters shall besiege thy brow,\nAnd dig deep trenches in thy beauty's field,\nThy youth's proud livery so gazed on now,\nWill be a totter'd weed of small worth held:\nThen being asked, where all thy beauty lies,\nWhere all the treasure of thy lusty days;\nTo say, within thine own deep sunken eyes,\nWere an all-eating shame, and thriftless praise.\nHow much more praise deserv'd thy beauty's use,\nIf thou couldst answer 'This fair child of mine\nShall sum my count, and make my old excuse,'\nProving his beauty by succession thine!\nThis were to be new made when thou art old,\nAnd see thy blood warm when thou feel'st it cold.\"\"\".split()\n# we should tokenize the input, but we will ignore that for now\n# build a list of tuples. Each tuple is ([ word_i-2, word_i-1 ], target word)\ntrigrams = [([test_sentence[i], test_sentence[i + 1]], test_sentence[i + 2])\n for i in range(len(test_sentence) - 2)]\n# print the first 3, just so you can see what they look like\nprint(trigrams[:3])\n\nvocab = set(test_sentence)\nword_to_ix = {word: i for i, word in enumerate(vocab)}\n\n\nclass NGramLanguageModeler(nn.Module):\n\n def __init__(self, vocab_size, embedding_dim, context_size):\n super(NGramLanguageModeler, self).__init__()\n self.embeddings = nn.Embedding(vocab_size, embedding_dim)\n self.linear1 = nn.Linear(context_size * embedding_dim, 128)\n self.linear2 = nn.Linear(128, vocab_size)\n\n def forward(self, inputs):\n embeds = self.embeddings(inputs).view((1, -1))\n out = F.relu(self.linear1(embeds))\n out = self.linear2(out)\n log_probs = F.log_softmax(out, dim=1)\n return log_probs\n\n\nlosses = []\nloss_function = nn.NLLLoss()\nmodel = NGramLanguageModeler(len(vocab), EMBEDDING_DIM, CONTEXT_SIZE)\noptimizer = optim.SGD(model.parameters(), lr=0.001)\n\nfor epoch in range(10):\n total_loss = 0\n for context, target in trigrams:\n\n # Step 1. Prepare the inputs to be passed to the model (i.e, turn the words\n # into integer indices and wrap them in tensors)\n context_idxs = torch.tensor([word_to_ix[w] for w in context], dtype=torch.long)\n\n # Step 2. Recall that torch *accumulates* gradients. Before passing in a\n # new instance, you need to zero out the gradients from the old\n # instance\n model.zero_grad()\n\n # Step 3. Run the forward pass, getting log probabilities over next\n # words\n log_probs = model(context_idxs)\n\n # Step 4. Compute your loss function. (Again, Torch wants the target\n # word wrapped in a tensor)\n loss = loss_function(log_probs, torch.tensor([word_to_ix[target]], dtype=torch.long))\n\n # Step 5. Do the backward pass and update the gradient\n loss.backward()\n optimizer.step()\n\n # Get the Python number from a 1-element Tensor by calling tensor.item()\n total_loss += loss.item()\n losses.append(total_loss)\nprint(losses) # The loss decreased every iteration over the training data!\n```\n\nExercise: Computing Word Embeddings: Continuous Bag-of-Words\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe Continuous Bag-of-Words model (CBOW) is frequently used in NLP deep\nlearning. It is a model that tries to predict words given the context of\na few words before and a few words after the target word. This is\ndistinct from language modeling, since CBOW is not sequential and does\nnot have to be probabilistic. Typcially, CBOW is used to quickly train\nword embeddings, and these embeddings are used to initialize the\nembeddings of some more complicated model. Usually, this is referred to\nas *pretraining embeddings*. It almost always helps performance a couple\nof percent.\n\nThe CBOW model is as follows. Given a target word $w_i$ and an\n$N$ context window on each side, $w_{i-1}, \\dots, w_{i-N}$\nand $w_{i+1}, \\dots, w_{i+N}$, referring to all context words\ncollectively as $C$, CBOW tries to minimize\n\n\\begin{align}-\\log p(w_i | C) = -\\log \\text{Softmax}(A(\\sum_{w \\in C} q_w) + b)\\end{align}\n\nwhere $q_w$ is the embedding for word $w$.\n\nImplement this model in Pytorch by filling in the class below. Some\ntips:\n\n* Think about which parameters you need to define.\n* Make sure you know what shape each operation expects. Use .view() if you need to\n reshape.\n\n\n\n\n\n```python\nCONTEXT_SIZE = 2 # 2 words to the left, 2 to the right\nraw_text = \"\"\"We are about to study the idea of a computational process.\nComputational processes are abstract beings that inhabit computers.\nAs they evolve, processes manipulate other abstract things called data.\nThe evolution of a process is directed by a pattern of rules\ncalled a program. People create programs to direct processes. In effect,\nwe conjure the spirits of the computer with our spells.\"\"\".split()\n\n# By deriving a set from `raw_text`, we deduplicate the array\nvocab = set(raw_text)\nvocab_size = len(vocab)\n\nword_to_ix = {word: i for i, word in enumerate(vocab)}\ndata = []\nfor i in range(2, len(raw_text) - 2):\n context = [raw_text[i - 2], raw_text[i - 1],\n raw_text[i + 1], raw_text[i + 2]]\n target = raw_text[i]\n data.append((context, target))\nprint(data[:5])\n\n\nclass CBOW(nn.Module):\n\n def __init__(self):\n pass\n\n def forward(self, inputs):\n pass\n\n# create your model and train. here are some functions to help you make\n# the data ready for use by your module\n\n\ndef make_context_vector(context, word_to_ix):\n idxs = [word_to_ix[w] for w in context]\n return torch.tensor(idxs, dtype=torch.long)\n\n\nmake_context_vector(data[0][0], word_to_ix) # example\n```\n", "meta": {"hexsha": "10fae07aaca6519ef8a6807256b777a518f9b56a", "size": 15718, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_downloads/3161e5aef42e3f09c479534ca90f74ea/word_embeddings_tutorial.ipynb", "max_stars_repo_name": "leejh1230/PyTorch-tutorials-kr", "max_stars_repo_head_hexsha": "ebbf44b863ff96c597631e28fc194eafa590c9eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-05T05:16:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-05T05:16:44.000Z", "max_issues_repo_path": "docs/_downloads/3161e5aef42e3f09c479534ca90f74ea/word_embeddings_tutorial.ipynb", "max_issues_repo_name": "leejh1230/PyTorch-tutorials-kr", "max_issues_repo_head_hexsha": "ebbf44b863ff96c597631e28fc194eafa590c9eb", "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": "docs/_downloads/3161e5aef42e3f09c479534ca90f74ea/word_embeddings_tutorial.ipynb", "max_forks_repo_name": "leejh1230/PyTorch-tutorials-kr", "max_forks_repo_head_hexsha": "ebbf44b863ff96c597631e28fc194eafa590c9eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 155.6237623762, "max_line_length": 7338, "alphanum_fraction": 0.7009161471, "converted": true, "num_tokens": 3360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.08836328736605667}} {"text": "```\n# this mounts your Google Drive to the Colab VM.\nfrom google.colab import drive\ndrive.mount('/content/drive', force_remount=True)\n\n# enter the foldername in your Drive where you have saved the unzipped\n# assignment folder, e.g. 'cs231n/assignments/assignment3/'\nFOLDERNAME = 'colab/cs231n/assignments/assignment2/'\nassert FOLDERNAME is not None, \"[!] Enter the foldername.\"\n\n# now that we've mounted your Drive, this ensures that\n# the Python interpreter of the Colab VM can load\n# python files from within it.\nimport sys\nsys.path.append('/content/drive/My Drive/{}'.format(FOLDERNAME))\n\n# this downloads the CIFAR-10 dataset to your Drive\n# if it doesn't already exist.\n%cd drive/My\\ Drive/$FOLDERNAME/cs231n/datasets/\n!bash get_datasets.sh\n%cd /content\n```\n\n Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n \n Enter your authorization code:\n ··········\n Mounted at /content/drive\n /content/drive/My Drive/colab/cs231n/assignments/assignment2/cs231n/datasets\n /content\n\n\n# Batch Normalization\nOne way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. \nOne idea along these lines is batch normalization which was proposed by [1] in 2015.\n\nThe idea is relatively straightforward. Machine learning methods tend to work better when their input data consists of uncorrelated features with zero mean and unit variance. When training a neural network, we can preprocess the data before feeding it to the network to explicitly decorrelate its features; this will ensure that the first layer of the network sees data that follows a nice distribution. However, even if we preprocess the input data, the activations at deeper layers of the network will likely no longer be decorrelated and will no longer have zero mean or unit variance since they are output from earlier layers in the network. Even worse, during the training process the distribution of features at each layer of the network will shift as the weights of each layer are updated.\n\nThe authors of [1] hypothesize that the shifting distribution of features inside deep neural networks may make training deep networks more difficult. To overcome this problem, [1] proposes to insert batch normalization layers into the network. At training time, a batch normalization layer uses a minibatch of data to estimate the mean and standard deviation of each feature. These estimated means and standard deviations are then used to center and normalize the features of the minibatch. A running average of these means and standard deviations is kept during training, and at test time these running averages are used to center and normalize features.\n\nIt is possible that this normalization strategy could reduce the representational power of the network, since it may sometimes be optimal for certain layers to have features that are not zero-mean or unit variance. To this end, the batch normalization layer includes learnable shift and scale parameters for each feature dimension.\n\n[1] [Sergey Ioffe and Christian Szegedy, \"Batch Normalization: Accelerating Deep Network Training by Reducing\nInternal Covariate Shift\", ICML 2015.](https://arxiv.org/abs/1502.03167)\n\n\n```\n# As usual, a bit of setup\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.fc_net import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array\nfrom cs231n.solver import Solver\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# for auto-reloading external modules\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2\n\ndef rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\ndef print_mean_std(x,axis=0):\n print(' means: ', x.mean(axis=axis))\n print(' stds: ', x.std(axis=axis))\n print() \n```\n\n\n```\n# Load the (preprocessed) CIFAR10 data.\ndata = get_CIFAR10_data()\nfor k, v in data.items():\n print('%s: ' % k, v.shape)\n```\n\n X_train: (49000, 3, 32, 32)\n y_train: (49000,)\n X_val: (1000, 3, 32, 32)\n y_val: (1000,)\n X_test: (1000, 3, 32, 32)\n y_test: (1000,)\n\n\n## Batch normalization: forward\nIn the file `cs231n/layers.py`, implement the batch normalization forward pass in the function `batchnorm_forward`. Once you have done so, run the following to test your implementation.\n\nReferencing the paper linked to above in [1] may be helpful!\n\n\n```\n# Check the training-time forward pass by checking means and variances\n# of features both before and after batch normalization \n\n# Simulate the forward pass for a two-layer network\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before batch normalization:')\nprint_mean_std(a,axis=0)\n\ngamma = np.ones((D3,))\nbeta = np.zeros((D3,))\n# Means should be close to zero and stds close to one\nprint('After batch normalization (gamma=1, beta=0)')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n\ngamma = np.asarray([1.0, 2.0, 3.0])\nbeta = np.asarray([11.0, 12.0, 13.0])\n# Now means should be close to beta and stds close to gamma\nprint('After batch normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n```\n\n Before batch normalization:\n means: [ -2.3814598 -13.18038246 1.91780462]\n stds: [27.18502186 34.21455511 37.68611762]\n \n After batch normalization (gamma=1, beta=0)\n means: [5.32907052e-17 7.04991621e-17 1.85962357e-17]\n stds: [0.99999999 1. 1. ]\n \n After batch normalization (gamma= [1. 2. 3.] , beta= [11. 12. 13.] )\n means: [11. 12. 13.]\n stds: [0.99999999 1.99999999 2.99999999]\n \n\n\n\n```\n# Check the test-time forward pass by running the training-time\n# forward pass many times to warm up the running averages, and then\n# checking the means and variances of activations after a test-time\n# forward pass.\n\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\n\nbn_param = {'mode': 'train'}\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n\nfor t in range(50):\n X = np.random.randn(N, D1)\n a = np.maximum(0, X.dot(W1)).dot(W2)\n batchnorm_forward(a, gamma, beta, bn_param)\n\nbn_param['mode'] = 'test'\nX = np.random.randn(N, D1)\na = np.maximum(0, X.dot(W1)).dot(W2)\na_norm, _ = batchnorm_forward(a, gamma, beta, bn_param)\n\n# Means should be close to zero and stds close to one, but will be\n# noisier than training-time forward passes.\nprint('After batch normalization (test-time):')\nprint_mean_std(a_norm,axis=0)\n```\n\n After batch normalization (test-time):\n means: [-0.03927354 -0.04349152 -0.10452688]\n stds: [1.01531427 1.01238373 0.97819987]\n \n\n\n## Batch normalization: backward\nNow implement the backward pass for batch normalization in the function `batchnorm_backward`.\n\nTo derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing branches; make sure to sum gradients across these branches in the backward pass.\n\nOnce you have finished, run the following to numerically check your backward pass.\n\n\n```\n# Gradient check batchnorm backward pass\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nfx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]\nfg = lambda a: batchnorm_forward(x, a, beta, bn_param)[0]\nfb = lambda b: batchnorm_forward(x, gamma, b, bn_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = batchnorm_forward(x, gamma, beta, bn_param)\ndx, dgamma, dbeta = batchnorm_backward(dout, cache)\n#You should expect to see relative errors between 1e-13 and 1e-8\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.7029258328157158e-09\n dgamma error: 7.420414216247087e-13\n dbeta error: 2.8795057655839487e-12\n\n\n## Batch normalization: alternative backward\nIn class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For example, you can derive a very simple formula for the sigmoid function's backward pass by simplifying gradients on paper.\n\nSurprisingly, it turns out that you can do a similar simplification for the batch normalization backward pass too! \n\nIn the forward pass, given a set of inputs $X=\\begin{bmatrix}x_1\\\\x_2\\\\...\\\\x_N\\end{bmatrix}$, \n\nwe first calculate the mean $\\mu$ and variance $v$.\nWith $\\mu$ and $v$ calculated, we can calculate the standard deviation $\\sigma$ and normalized data $Y$.\nThe equations and graph illustration below describe the computation ($y_i$ is the i-th element of the vector $Y$).\n\n\\begin{align}\n& \\mu=\\frac{1}{N}\\sum_{k=1}^N x_k & v=\\frac{1}{N}\\sum_{k=1}^N (x_k-\\mu)^2 \\\\\n& \\sigma=\\sqrt{v+\\epsilon} & y_i=\\frac{x_i-\\mu}{\\sigma}\n\\end{align}\n\n\n\nThe meat of our problem during backpropagation is to compute $\\frac{\\partial L}{\\partial X}$, given the upstream gradient we receive, $\\frac{\\partial L}{\\partial Y}.$ To do this, recall the chain rule in calculus gives us $\\frac{\\partial L}{\\partial X} = \\frac{\\partial L}{\\partial Y} \\cdot \\frac{\\partial Y}{\\partial X}$.\n\nThe unknown/hart part is $\\frac{\\partial Y}{\\partial X}$. We can find this by first deriving step-by-step our local gradients at \n$\\frac{\\partial v}{\\partial X}$, $\\frac{\\partial \\mu}{\\partial X}$,\n$\\frac{\\partial \\sigma}{\\partial v}$, \n$\\frac{\\partial Y}{\\partial \\sigma}$, and $\\frac{\\partial Y}{\\partial \\mu}$,\nand then use the chain rule to compose these gradients (which appear in the form of vectors!) appropriately to compute $\\frac{\\partial Y}{\\partial X}$.\n\nIf it's challenging to directly reason about the gradients over $X$ and $Y$ which require matrix multiplication, try reasoning about the gradients in terms of individual elements $x_i$ and $y_i$ first: in that case, you will need to come up with the derivations for $\\frac{\\partial L}{\\partial x_i}$, by relying on the Chain Rule to first calculate the intermediate $\\frac{\\partial \\mu}{\\partial x_i}, \\frac{\\partial v}{\\partial x_i}, \\frac{\\partial \\sigma}{\\partial x_i},$ then assemble these pieces to calculate $\\frac{\\partial y_i}{\\partial x_i}$. \n\nYou should make sure each of the intermediary gradient derivations are all as simplified as possible, for ease of implementation. \n\nAfter doing so, implement the simplified batch normalization backward pass in the function `batchnorm_backward_alt` and compare the two implementations by running the following. Your two implementations should compute nearly identical results, but the alternative implementation should be a bit faster.\n\n\n```\nnp.random.seed(231)\nN, D = 100, 500\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nout, cache = batchnorm_forward(x, gamma, beta, bn_param)\n\nt1 = time.time()\ndx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache)\nt2 = time.time()\ndx2, dgamma2, dbeta2 = batchnorm_backward_alt(dout, cache)\nt3 = time.time()\n\nprint('dx difference: ', rel_error(dx1, dx2))\nprint('dgamma difference: ', rel_error(dgamma1, dgamma2))\nprint('dbeta difference: ', rel_error(dbeta1, dbeta2))\nprint('speedup: %.2fx' % ((t2 - t1) / (t3 - t2)))\n```\n\n dx difference: 6.284600172572596e-13\n dgamma difference: 0.0\n dbeta difference: 0.0\n speedup: 2.77x\n\n\n## Fully Connected Nets with Batch Normalization\nNow that you have a working implementation for batch normalization, go back to your `FullyConnectedNet` in the file `cs231n/classifiers/fc_net.py`. Modify your implementation to add batch normalization.\n\nConcretely, when the `normalization` flag is set to `\"batchnorm\"` in the constructor, you should insert a batch normalization layer before each ReLU nonlinearity. The outputs from the last layer of the network should not be normalized. Once you are done, run the following to gradient-check your implementation.\n\nHINT: You might find it useful to define an additional helper layer similar to those in the file `cs231n/layer_utils.py`. If you decide to do so, do it in the file `cs231n/classifiers/fc_net.py`.\n\n\n```\nnp.random.seed(231)\nN, D, H1, H2, C = 2, 15, 20, 30, 10\nX = np.random.randn(N, D)\ny = np.random.randint(C, size=(N,))\n\n# You should expect losses between 1e-4~1e-10 for W, \n# losses between 1e-08~1e-10 for b,\n# and losses between 1e-08~1e-09 for beta and gammas.\nfor reg in [0, 3.14]:\n print('Running check with reg = ', reg)\n model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,\n reg=reg, weight_scale=5e-2, dtype=np.float64,\n normalization='batchnorm')\n\n loss, grads = model.loss(X, y)\n print('Initial loss: ', loss)\n\n for name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)\n print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))\n if reg == 0: print()\n```\n\n Running check with reg = 0\n Initial loss: 2.2611955101340957\n W1 relative error: 1.10e-04\n W2 relative error: 2.85e-06\n W3 relative error: 4.05e-10\n b1 relative error: 2.22e-07\n b2 relative error: 2.22e-08\n b3 relative error: 1.01e-10\n beta1 relative error: 7.33e-09\n beta2 relative error: 1.89e-09\n gamma1 relative error: 6.96e-09\n gamma2 relative error: 1.96e-09\n \n Running check with reg = 3.14\n Initial loss: 6.996533220108303\n W1 relative error: 1.98e-06\n W2 relative error: 2.28e-06\n W3 relative error: 1.11e-08\n b1 relative error: 1.38e-08\n b2 relative error: 7.99e-07\n b3 relative error: 1.73e-10\n beta1 relative error: 6.65e-09\n beta2 relative error: 3.48e-09\n gamma1 relative error: 8.80e-09\n gamma2 relative error: 5.28e-09\n\n\n# Batchnorm for deep networks\nRun the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization.\n\n\n```\nnp.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [100, 100, 100, 100, 100]\n\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nweight_scale = 2e-2\nbn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\nmodel = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\nprint('Solver with batch norm:')\nbn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True,print_every=20)\nbn_solver.train()\n\nprint('\\nSolver without batch norm:')\nsolver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=20)\nsolver.train()\n```\n\n Solver with batch norm:\n (Iteration 1 / 200) loss: 2.340975\n (Epoch 0 / 10) train acc: 0.107000; val_acc: 0.115000\n (Epoch 1 / 10) train acc: 0.314000; val_acc: 0.266000\n (Iteration 21 / 200) loss: 2.039365\n (Epoch 2 / 10) train acc: 0.389000; val_acc: 0.279000\n (Iteration 41 / 200) loss: 2.036704\n (Epoch 3 / 10) train acc: 0.501000; val_acc: 0.322000\n (Iteration 61 / 200) loss: 1.776305\n (Epoch 4 / 10) train acc: 0.521000; val_acc: 0.311000\n (Iteration 81 / 200) loss: 1.285794\n (Epoch 5 / 10) train acc: 0.607000; val_acc: 0.310000\n (Iteration 101 / 200) loss: 1.277616\n (Epoch 6 / 10) train acc: 0.667000; val_acc: 0.344000\n (Iteration 121 / 200) loss: 1.074345\n (Epoch 7 / 10) train acc: 0.675000; val_acc: 0.320000\n (Iteration 141 / 200) loss: 1.133021\n (Epoch 8 / 10) train acc: 0.716000; val_acc: 0.310000\n (Iteration 161 / 200) loss: 0.798814\n (Epoch 9 / 10) train acc: 0.805000; val_acc: 0.323000\n (Iteration 181 / 200) loss: 0.996323\n (Epoch 10 / 10) train acc: 0.804000; val_acc: 0.300000\n \n Solver without batch norm:\n (Iteration 1 / 200) loss: 2.302332\n (Epoch 0 / 10) train acc: 0.129000; val_acc: 0.131000\n (Epoch 1 / 10) train acc: 0.283000; val_acc: 0.250000\n (Iteration 21 / 200) loss: 2.041970\n (Epoch 2 / 10) train acc: 0.316000; val_acc: 0.277000\n (Iteration 41 / 200) loss: 1.900473\n (Epoch 3 / 10) train acc: 0.373000; val_acc: 0.282000\n (Iteration 61 / 200) loss: 1.713156\n (Epoch 4 / 10) train acc: 0.390000; val_acc: 0.310000\n (Iteration 81 / 200) loss: 1.662209\n (Epoch 5 / 10) train acc: 0.434000; val_acc: 0.300000\n (Iteration 101 / 200) loss: 1.696062\n (Epoch 6 / 10) train acc: 0.536000; val_acc: 0.346000\n (Iteration 121 / 200) loss: 1.550785\n (Epoch 7 / 10) train acc: 0.530000; val_acc: 0.310000\n (Iteration 141 / 200) loss: 1.436308\n (Epoch 8 / 10) train acc: 0.622000; val_acc: 0.342000\n (Iteration 161 / 200) loss: 1.000868\n (Epoch 9 / 10) train acc: 0.654000; val_acc: 0.328000\n (Iteration 181 / 200) loss: 0.925455\n (Epoch 10 / 10) train acc: 0.726000; val_acc: 0.335000\n\n\nRun the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster.\n\n\n```\ndef plot_training_history(title, label, baseline, bn_solvers, plot_fn, bl_marker='.', bn_marker='.', labels=None):\n \"\"\"utility function for plotting training history\"\"\"\n plt.title(title)\n plt.xlabel(label)\n bn_plots = [plot_fn(bn_solver) for bn_solver in bn_solvers]\n bl_plot = plot_fn(baseline)\n num_bn = len(bn_plots)\n for i in range(num_bn):\n label='with_norm'\n if labels is not None:\n label += str(labels[i])\n plt.plot(bn_plots[i], bn_marker, label=label)\n label='baseline'\n if labels is not None:\n label += str(labels[0])\n plt.plot(bl_plot, bl_marker, label=label)\n plt.legend(loc='lower center', ncol=num_bn+1) \n\n \nplt.subplot(3, 1, 1)\nplot_training_history('Training loss','Iteration', solver, [bn_solver], \\\n lambda x: x.loss_history, bl_marker='o', bn_marker='o')\nplt.subplot(3, 1, 2)\nplot_training_history('Training accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.train_acc_history, bl_marker='-o', bn_marker='-o')\nplt.subplot(3, 1, 3)\nplot_training_history('Validation accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.val_acc_history, bl_marker='-o', bn_marker='-o')\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n# Batch normalization and initialization\nWe will now run a small experiment to study the interaction of batch normalization and weight initialization.\n\nThe first cell will train 8-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training accuracy, validation set accuracy, and training loss as a function of the weight initialization scale.\n\n\n```\nnp.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [50, 50, 50, 50, 50, 50, 50]\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nbn_solvers_ws = {}\nsolvers_ws = {}\nweight_scales = np.logspace(-4, 0, num=20)\nfor i, weight_scale in enumerate(weight_scales):\n print('Running weight scale %d / %d' % (i + 1, len(weight_scales)))\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\n bn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n bn_solver.train()\n bn_solvers_ws[weight_scale] = bn_solver\n\n solver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n solver.train()\n solvers_ws[weight_scale] = solver\n```\n\n Running weight scale 1 / 20\n Running weight scale 2 / 20\n Running weight scale 3 / 20\n Running weight scale 4 / 20\n Running weight scale 5 / 20\n Running weight scale 6 / 20\n Running weight scale 7 / 20\n Running weight scale 8 / 20\n Running weight scale 9 / 20\n Running weight scale 10 / 20\n Running weight scale 11 / 20\n Running weight scale 12 / 20\n Running weight scale 13 / 20\n Running weight scale 14 / 20\n Running weight scale 15 / 20\n Running weight scale 16 / 20\n Running weight scale 17 / 20\n Running weight scale 18 / 20\n Running weight scale 19 / 20\n Running weight scale 20 / 20\n\n\n\n```\n# Plot results of weight scale experiment\nbest_train_accs, bn_best_train_accs = [], []\nbest_val_accs, bn_best_val_accs = [], []\nfinal_train_loss, bn_final_train_loss = [], []\n\nfor ws in weight_scales:\n best_train_accs.append(max(solvers_ws[ws].train_acc_history))\n bn_best_train_accs.append(max(bn_solvers_ws[ws].train_acc_history))\n \n best_val_accs.append(max(solvers_ws[ws].val_acc_history))\n bn_best_val_accs.append(max(bn_solvers_ws[ws].val_acc_history))\n \n final_train_loss.append(np.mean(solvers_ws[ws].loss_history[-100:]))\n bn_final_train_loss.append(np.mean(bn_solvers_ws[ws].loss_history[-100:]))\n \nplt.subplot(3, 1, 1)\nplt.title('Best val accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best val accuracy')\nplt.semilogx(weight_scales, best_val_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm')\nplt.legend(ncol=2, loc='lower right')\n\nplt.subplot(3, 1, 2)\nplt.title('Best train accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best training accuracy')\nplt.semilogx(weight_scales, best_train_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm')\nplt.legend()\n\nplt.subplot(3, 1, 3)\nplt.title('Final training loss vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Final training loss')\nplt.semilogx(weight_scales, final_train_loss, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_final_train_loss, '-o', label='batchnorm')\nplt.legend()\nplt.gca().set_ylim(1.0, 3.5)\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n## Inline Question 1:\nDescribe the results of this experiment. How does the scale of weight initialization affect models with/without batch normalization differently, and why?\n\n## Answer:\nWeight scale is higher than certain point, then both have failed to learn. This is bacause some features are distorted through batchnorm layer when we sclae weight too much. \n\n\n# Batch normalization and batch size\nWe will now run a small experiment to study the interaction of batch normalization and batch size.\n\nThe first cell will train 6-layer networks both with and without batch normalization using different batch sizes. The second layer will plot training accuracy and validation set accuracy over time.\n\n\n```\ndef run_batchsize_experiments(normalization_mode):\n np.random.seed(231)\n # Try training a very deep net with batchnorm\n hidden_dims = [100, 100, 100, 100, 100]\n num_train = 1000\n small_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n }\n n_epochs=10\n weight_scale = 2e-2\n batch_sizes = [5,10,50]\n lr = 10**(-3.5)\n solver_bsize = batch_sizes[0]\n\n print('No normalization: batch size = ',solver_bsize)\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n solver = Solver(model, small_data,\n num_epochs=n_epochs, batch_size=solver_bsize,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n solver.train()\n \n bn_solvers = []\n for i in range(len(batch_sizes)):\n b_size=batch_sizes[i]\n print('Normalization: batch size = ',b_size)\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=normalization_mode)\n bn_solver = Solver(bn_model, small_data,\n num_epochs=n_epochs, batch_size=b_size,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n bn_solver.train()\n bn_solvers.append(bn_solver)\n \n return bn_solvers, solver, batch_sizes\n\nbatch_sizes = [5,10,50]\nbn_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('batchnorm')\n```\n\n No normalization: batch size = 5\n Normalization: batch size = 5\n Normalization: batch size = 10\n Normalization: batch size = 50\n\n\n\n```\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 2:\nDescribe the results of this experiment. What does this imply about the relationship between batch normalization and batch size? Why is this relationship observed?\n\n## Answer:\nIf the layer is not ehough batch size, then adding batch normalization affects negatively. But after increasing batch size, then the normalization begin to work. We can check that batch normalization can be used as a kind of regularization when we compare both baseline and norm with 5 in batch size.\n\n# Layer Normalization\nBatch normalization has proved to be effective in making networks easier to train, but the dependency on batch size makes it less useful in complex networks which have a cap on the input batch size due to hardware limitations. \n\nSeveral alternatives to batch normalization have been proposed to mitigate this problem; one such technique is Layer Normalization [2]. Instead of normalizing over the batch, we normalize over the features. In other words, when using Layer Normalization, each feature vector corresponding to a single datapoint is normalized based on the sum of all terms within that feature vector.\n\n[2] [Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. \"Layer Normalization.\" stat 1050 (2016): 21.](https://arxiv.org/pdf/1607.06450.pdf)\n\n## Inline Question 3:\nWhich of these data preprocessing steps is analogous to batch normalization, and which is analogous to layer normalization?\n\n1. Scaling each image in the dataset, so that the RGB channels for each row of pixels within an image sums up to 1.\n2. Scaling each image in the dataset, so that the RGB channels for all pixels within an image sums up to 1. \n3. Subtracting the mean image of the dataset from each image in the dataset.\n4. Setting all RGB values to either 0 or 1 depending on a given threshold.\n\n## Answer:\nanalogous to batch normalization: 3 \\\nanalogous to layer normalization: 2\n\n\n# Layer Normalization: Implementation\n\nNow you'll implement layer normalization. This step should be relatively straightforward, as conceptually the implementation is almost identical to that of batch normalization. One significant difference though is that for layer normalization, we do not keep track of the moving moments, and the testing phase is identical to the training phase, where the mean and variance are directly calculated per datapoint.\n\nHere's what you need to do:\n\n* In `cs231n/layers.py`, implement the forward pass for layer normalization in the function `layernorm_forward`. \n\nRun the cell below to check your results.\n* In `cs231n/layers.py`, implement the backward pass for layer normalization in the function `layernorm_backward`. \n\nRun the second cell below to check your results.\n* Modify `cs231n/classifiers/fc_net.py` to add layer normalization to the `FullyConnectedNet`. When the `normalization` flag is set to `\"layernorm\"` in the constructor, you should insert a layer normalization layer before each ReLU nonlinearity. \n\nRun the third cell below to run the batch size experiment on layer normalization.\n\n\n```\n# Check the training-time forward pass by checking means and variances\n# of features both before and after layer normalization \n\n# Simulate the forward pass for a two-layer network\nnp.random.seed(231)\nN, D1, D2, D3 =4, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before layer normalization:')\nprint_mean_std(a,axis=1)\n\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n# Means should be close to zero and stds close to one\nprint('After layer normalization (gamma=1, beta=0)')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n\ngamma = np.asarray([3.0,3.0,3.0])\nbeta = np.asarray([5.0,5.0,5.0])\n# Now means should be close to beta and stds close to gamma\nprint('After layer normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n```\n\n Before layer normalization:\n means: [-59.06673243 -47.60782686 -43.31137368 -26.40991744]\n stds: [10.07429373 28.39478981 35.28360729 4.01831507]\n \n After layer normalization (gamma=1, beta=0)\n means: [ 4.81096644e-16 -7.40148683e-17 2.22044605e-16 -5.92118946e-16]\n stds: [0.99999995 0.99999999 1. 0.99999969]\n \n After layer normalization (gamma= [3. 3. 3.] , beta= [5. 5. 5.] )\n means: [5. 5. 5. 5.]\n stds: [2.99999985 2.99999998 2.99999999 2.99999907]\n \n\n\n\n```\n# Gradient check layernorm backward pass\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nln_param = {}\nfx = lambda x: layernorm_forward(x, gamma, beta, ln_param)[0]\nfg = lambda a: layernorm_forward(x, a, beta, ln_param)[0]\nfb = lambda b: layernorm_forward(x, gamma, b, ln_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = layernorm_forward(x, gamma, beta, ln_param)\ndx, dgamma, dbeta = layernorm_backward(dout, cache)\n\n#You should expect to see relative errors between 1e-12 and 1e-8\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.4336158494902849e-09\n dgamma error: 4.519489546032799e-12\n dbeta error: 2.276445013433725e-12\n\n\n# Layer Normalization and batch size\n\nWe will now run the previous batch size experiment with layer normalization instead of batch normalization. Compared to the previous experiment, you should see a markedly smaller influence of batch size on the training history!\n\n\n```\nln_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('layernorm')\n\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 4:\nWhen is layer normalization likely to not work well, and why?\n\n1. Using it in a very deep network\n2. Having a very small dimension of features\n3. Having a high regularization term\n\n\n## Answer:\n[FILL THIS IN]\n\n", "meta": {"hexsha": "2f53e0931b43193e8430caf4084d0375e218e64e", "size": 443582, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "a2/BatchNormalization.ipynb", "max_stars_repo_name": "KIONLEE/cs231n", "max_stars_repo_head_hexsha": "0649469def9dd39fa80e2cfb95c077ec768dcd20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-22T02:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T11:46:53.000Z", "max_issues_repo_path": "a2/BatchNormalization.ipynb", "max_issues_repo_name": "KIONLEE/cs231n", "max_issues_repo_head_hexsha": "0649469def9dd39fa80e2cfb95c077ec768dcd20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-02-02T22:52:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:47:44.000Z", "max_forks_repo_path": "a2/BatchNormalization.ipynb", "max_forks_repo_name": "KIONLEE/cs231n", "max_forks_repo_head_hexsha": "0649469def9dd39fa80e2cfb95c077ec768dcd20", "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": 443582.0, "max_line_length": 443582, "alphanum_fraction": 0.9376485069, "converted": true, "num_tokens": 9481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.2720245392906821, "lm_q1q2_score": 0.08819998858210565}} {"text": "\n\n\n# PHY321: Introduction to Classical Mechanics and plans for Spring 2022\n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA and Department of Physics, University of Oslo, Norway \n**Scott Pratt**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA\n\nDate: **Jan 12, 2022**\n\nCopyright 1999-2022, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n## Aims and Overview of week 2: January 10-14\n\nThe first week starts on Monday January 10. This week is dedicated to a\nreview of learning material and reminder on programming aspects,\nuseful tools, where to find information and much more. \n\n* Introduction to the course and reminder on vectors, space, time and motion.\n\n* Python programming reminder, elements from [CMSE 201 INTRODUCTION TO COMPUTATIONAL MODELING](https://cmse.msu.edu/academics/undergraduate-program/undergraduate-courses/cmse-201-introduction-to-computational-modeling/) and how they are used in this course. Installing software (anaconda). . \n\n* Introduction to Git and GitHub. [Overview video on Git and GitHub](https://mediaspace.msu.edu/media/t/1_8mgx3cyf).\n\n**Recommended reading**: John R. Taylor, Classical Mechanics (Univ. Sci. Books 2005), , see also . Chapters 1.2 and 1.3 of Taylor.\n\n## Classical mechanics\n\nClassical mechanics is a topic which has been taught intensively over\nseveral centuries. It is, with its many variants and ways of\npresenting the educational material, normally the first **real** physics\ncourse many of us meet and it lays the foundation for further physics\nstudies. Many of the equations and ways of reasoning about the\nunderlying laws of motion and pertinent forces, shape our approaches and understanding\nof the scientific method and discourse, as well as the way we develop our insights\nand deeper understanding about physical systems.\n\n## From Continuous to Discretized Approaches\n\nThere is a wealth of\nwell-tested (from both a physics point of view and a pedagogical\nstandpoint) exercises and problems which can be solved\nanalytically. However, many of these problems represent idealized and\nless realistic situations. The large majority of these problems are\nsolved by paper and pencil and are traditionally aimed\nat what we normally refer to as continuous models from which we may find an analytical solution. As a consequence,\nwhen teaching mechanics, it implies that we can seldomly venture beyond an idealized case\nin order to develop our understandings and insights about the\nunderlying forces and laws of motion.\n\nWe aim at changing this here by introducing throughout the course what\nwe will call a **computational path**, where with computations we mean\nsolving scientific problems with all possible tools and means, from\nplain paper an pencil exercises, via symbolic calculations to writing\na code and running a program to solve a specific\nproblem. Mathematically this normally means that we move from a\ncontinuous problem to a discretized one. This appproach enables us to\nsolve a much broader class of problems.\nIn mechanics this means, since we often rephrase the physical problems in terms of differential equations, that we can in most settings reuse the same program with some minimal changes.\n\n## Space, Time, Motion, Reference Frames and Reminder on vectors and other mathematical quantities\n\nOur studies will start with the motion of different types of objects\nsuch as a falling ball, a runner, a bicycle etc etc. It means that an\nobject's position in space varies with time.\nIn order to study such systems we need to define\n\n* choice of origin\n\n* choice of the direction of the axes\n\n* choice of positive direction (left-handed or right-handed system of reference)\n\n* choice of units and dimensions\n\nThese choices lead to some important questions such as\n\n* is the physics of a system independent of the origin of the axes?\n\n* is the physics independent of the directions of the axes, that is are there privileged axes?\n\n* is the physics independent of the orientation of system?\n\n* is the physics independent of the scale of the length?\n\n## Dimension, units and labels\n\nThroughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass\none kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s$^2$ and for energy 1 Joule 1kgm$^2$s$^{-2}$.\n\nWe will use the following notations for various variables (vectors are always boldfaced in these lecture notes):\n* position $\\boldsymbol{r}$, in one dimention we will normally just use $x$,\n\n* mass $m$,\n\n* time $t$,\n\n* velocity $\\boldsymbol{v}$ or just $v$ in one dimension,\n\n* acceleration $\\boldsymbol{a}$ or just $a$ in one dimension,\n\n* momentum $\\boldsymbol{p}$ or just $p$ in one dimension,\n\n* kinetic energy $K$,\n\n* potential energy $V$ and\n\n* frequency $\\omega$.\n\nMore variables will be defined as we need them.\n\n## Dimensions and Units\n\nIt is also important to keep track of dimensionalities. Don't mix this\nup with a chosen unit for a given variable. We mark the dimensionality\nin these lectures as $[a]$, where $a$ is the quantity we are\ninterested in. Thus\n\n* $[\\boldsymbol{r}]=$ length\n\n* $[m]=$ mass\n\n* $[K]=$ energy\n\n* $[t]=$ time\n\n* $[\\boldsymbol{v}]=$ length over time\n\n* $[\\boldsymbol{a}]=$ length over time squared\n\n* $[\\boldsymbol{p}]=$ mass times length over time\n\n* $[\\omega]=$ 1/time\n\n## Scalars, Vectors and Matrices\n\nA scalar is something with a value that is independent of coordinate\nsystem. Examples are mass, or the relative time between events. A\nvector has magnitude and direction. Under rotation, the magnitude\nstays the same but the direction changes. Scalars have no spatial\nindex, whereas a three-dimensional vector has 3 indices, e.g. the\nposition $\\boldsymbol{r}$ has components $r_1,r_2,r_3$, which are often\nreferred to as $x,y,z$.\n\nThere are several categories of changes of coordinate system. The\nobserver can translate the origin, might move with a different\nvelocity, or might rotate her/his coordinate axes. For instance, a\nparticle's position vector changes when the origin is translated, but\nits velocity does not. When you study relativity you will find that\nquantities you thought of as scalars, such as time or an electric\npotential, are actually parts of four-dimensional vectors and that\nchanges of the velocity of the reference frame act in a similar way to\nrotations.\n\nIn addition to vectors and scalars, there are matrices, which have two\nindices. One also has objects with 3 or four indices. These are called\ntensors of rank $n$, where $n$ is the number of indices. A matrix is a\nrank-two tensor. The Levi-Civita symbol, $\\epsilon_{ijk}$ used for\ncross products of vectors, is a tensor of rank three.\n\n## Definitions of Vectors\n\nIn these lectures we will use boldfaced lower-case letters to label a\nvector. A vector $\\boldsymbol{a}$ in three dimensions is thus defined as\n\n$$\n\\boldsymbol{a} =(a_x,a_y, a_z),\n$$\n\nand using the unit vectors (see below) in a cartesian system we have\n\n$$\n\\boldsymbol{a} = a_x\\boldsymbol{e}_1+a_y\\boldsymbol{e}_2+a_z\\boldsymbol{e}_3,\n$$\n\nwhere the unit vectors have magnitude $\\vert\\boldsymbol{e}_i\\vert = 1$ with\n$i=1=x$, $i=2=y$ and $i=3=z$. Some authors use letters\n$\\boldsymbol{i}=\\boldsymbol{e}_1$, $\\boldsymbol{j}=\\boldsymbol{e}_2$ and $\\boldsymbol{k}=\\boldsymbol{e}_3$.\n\n## Other ways to define a Vector\n\nAlternatively, you may also encounter the above vector as\n\n$$\n\\boldsymbol{a} = a_1\\boldsymbol{e}_1+a_2\\boldsymbol{e}_2+a_3\\boldsymbol{e}_3.\n$$\n\nHere we have used that $a_1=a_x$, $a_2=a_y$ and $a_3=a_z$. Such a\nnotation is sometimes more convenient if we wish to represent vector\noperations in a mathematically more compact way, see below here. We may also find this useful if we want the different\ncomponents to represent other coordinate systems that the Cartesian one. A typical example would be going from a Cartesian representation to a spherical basis. We will encounter such cases many times in this course. \n\nWe use lower-case letters for vectors and upper-case letters for matrices. Vectors and matrices are always boldfaced.\n\n## Polar Coordinates\n\nAs an example, consider a two-dimensional Cartesian system with a vector $\\boldsymbol{r}=(x,y)$.\nOur vector is then written as\n\n$$\n\\boldsymbol{r} = x\\boldsymbol{e}_1+y\\boldsymbol{e}_2.\n$$\n\nTransforming to polar coordinates with the radius $\\rho\\in [0,\\infty)$\nand the angle $\\phi \\in [0,2\\pi]$ we have the familiar transformations\n\n$$\nx = \\rho \\cos{\\phi} \\hspace{0.5cm} y = \\rho \\sin{\\phi},\n$$\n\nand the inverse relations\n\n$$\n\\rho =\\sqrt{x^2+y^2} \\hspace{0.5cm} \\phi = \\mathrm{arctan}(\\frac{y}{x}).\n$$\n\nWe can rewrite the vector $\\boldsymbol{a}$ in terms of $\\rho$ and $\\phi$ as\n\n$$\n\\boldsymbol{a} = \\rho \\cos{\\phi}\\boldsymbol{e}_1+\\rho \\sin{\\phi}\\boldsymbol{e}_2,\n$$\n\nand we define the new unit vectors as $\\boldsymbol{e}'_1=\\cos{\\phi}\\boldsymbol{e}_1$ and $\\boldsymbol{e}'_2=\\sin{\\phi}\\boldsymbol{e}_2$, we have\n\n$$\n\\boldsymbol{a}' = \\rho\\boldsymbol{e}'_1+\\rho \\boldsymbol{e}'_2.\n$$\n\nBelow we will show that the norms of this vector in a Cartesian basis and a Polar basis are equal.\n\n## Unit Vectors\n\nAlso known as basis vectors, unit vectors point in the direction of\nthe coordinate axes, have unit norm, and are orthogonal to one\nanother. Sometimes this is referred to as an orthonormal basis,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{e}_i\\cdot\\boldsymbol{e}_j=\\delta_{ij}=\\begin{bmatrix}\n1 & 0 & 0\\\\\n0& 1 & 0\\\\\n0 & 0 & 1\n\\end{bmatrix}.\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nHere, $\\delta_{ij}$ is unity when $i=j$ and is zero otherwise. This is\ncalled the unit matrix, because you can multiply it with any other\nmatrix and not change the matrix. The **dot** denotes the dot product,\n$\\boldsymbol{a}\\cdot\\boldsymbol{b}=a_1b_1+a_2b_2+a_3b_3=|a||b|\\cos\\theta_{ab}$. Sometimes\nthe unit vectors are called $\\hat{x}$, $\\hat{y}$ and\n$\\hat{z}$.\n\n## Our definition of unit vectors\n\nVectors can be decomposed in terms of unit vectors,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{r}=r_1\\hat{e}_1+r_2\\hat{e}_2+r_3\\hat{e}_3.\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\nThe vector components $r_1$, $r_2$ and $r_3$ might be\ncalled $x$, $y$ and $z$ for a displacement. Another way to write this is to define the vector $\\boldsymbol{r}=(x,y,z)$.\n\nSimilarly, for the velocity we will use in this course the components $\\boldsymbol{v}=(v_x, v_y,v_z$. The accelaration is then given by $\\boldsymbol{a}=(a_x,a_y,a_z)$.\n\n## More definitions, repeated indices\n\nAs mentioned above, repeated indices infer sums.\nThis means that when you encounter an expression like the one on the left-hand side here, it stands actually for a sum (right-hand side)\n\n$$\nx_iy_i=\\sum_i x_iy_i=\\boldsymbol{x}\\cdot\\boldsymbol{y}.\n$$\n\nWe will in our lectures seldom use this notation and rather spell out the summations. This inferred summation over indices is normally called [Einstein summation convention](https://en.wikipedia.org/wiki/Einstein_notation).\n\n## Vector Operations, Scalar Product (or dot product)\n\nFor two vectors $\\boldsymbol{a}$ and $\\boldsymbol{b}$ we have\n\n$$\n\\begin{eqnarray*}\n\\boldsymbol{a}\\cdot\\boldsymbol{b}&=&\\sum_ia_ib_i=|a||b|\\cos\\theta_{ab},\\\\\n|a|&\\equiv& \\sqrt{\\boldsymbol{a}\\cdot\\boldsymbol{a}},\n\\end{eqnarray*}\n$$\n\nor with a norm-2 notation\n\n$$\n|a|\\equiv \\vert\\vert \\boldsymbol{a}\\vert\\vert_2=\\sqrt{\\sum_i a_i^2}.\n$$\n\nNot of all of you are familiar with linear algebra. Numerically we will always deal with arrays and the dot product vector is given by the product of the transposed vector multiplied with the other vector, that is we have\n\n$$\n\\boldsymbol{a}^T\\boldsymbol{b}=\\sum_i a_ib_i=|a||b|\\cos\\theta_{ab}.\n$$\n\nThe superscript $T$ represents the transposition operations.\n\n## Digression, Linear Algebra Notation for Vectors\n\nAs an example, consider a three-dimensional velocity defined by a vector $\\boldsymbol{v}=(v_x,v_y,v_z)$. For those of you familiar with linear algebra, we would write this quantity as\n\n$$\n\\boldsymbol{v}=\\begin{bmatrix} v_x\\\\ v_y \\\\ v_z \\end{bmatrix},\n$$\n\nand the transpose as\n\n$$\n\\boldsymbol{v}^T=\\begin{bmatrix} v_x & v_y &v_z \\end{bmatrix}.\n$$\n\nThe norm is\n\n$$\n\\boldsymbol{v}^T\\boldsymbol{v}=v_x^2+v_y^2+v_z^2,\n$$\n\nas it should.\n\nSince we will use Python as a programming language throughout this course, the above vector, using the package **numpy** (see discussions below), can be written as\n\n\n```python\nimport numpy as np\n# Define the values of vx, vy and vz\nvx = 0.0\nvy = 1.0\nvz = 0.0\nv = np.array([vx, vy, vz])\nprint(v)\n# The print the transpose of v\nprint(v.T)\n```\n\nTry to figure out how to calculate the norm with **numpy**.\nWe will come back to **numpy** in the examples below.\n\n## Norm of a transformed Vector\n\nAs an example, consider our transformation of a two-dimensional Cartesian vector $\\boldsymbol{r}$ to polar coordinates.\nWe had\n\n$$\n\\boldsymbol{r} = x\\boldsymbol{e}_1+y\\boldsymbol{e}_2.\n$$\n\nTransforming to polar coordinates with the radius $\\rho\\in [0,\\infty)$\nand the angle $\\phi \\in [0,2\\pi]$ we have\n\n$$\nx = \\rho \\cos{\\phi} \\hspace{0.5cm} y = \\rho \\sin{\\phi}.\n$$\n\nWe can write this\n\n$$\n\\boldsymbol{r} = \\begin{bmatrix} x \\\\ y \\end{bmatrix}= \\begin{bmatrix} \\rho \\cos{\\phi} \\\\ \\rho \\sin{\\phi} \\end{bmatrix}.\n$$\n\nThe norm in Cartesian coordinates is $\\boldsymbol{r}\\cdot\\boldsymbol{r}=x^2+y^2$ and\nusing Polar coordinates we have\n$\\rho^2(\\cos{\\phi})^2+\\rho^2(\\cos{\\phi})^2=\\rho^2$, which shows that\nthe norm is conserved since we have $\\rho = \\sqrt{x^2+y^2}$. A\ntransformation to a new basis should not change the norm.\n\n## Vector Product (or cross product) of vectors $\\boldsymbol{a}$ and $\\boldsymbol{b}$\n\n$$\n\\begin{eqnarray*}\n\\boldsymbol{c}&=&\\boldsymbol{a}\\times\\boldsymbol{b},\\\\\nc_i&=&\\epsilon_{ijk}a_jb_k.\n\\end{eqnarray*}\n$$\n\nHere $\\epsilon$ is the third-rank anti-symmetric tensor, also known as\nthe Levi-Civita symbol. It is $\\pm 1$ only if all three indices are\ndifferent, and is zero otherwise. The choice of $\\pm 1$ depends on\nwhether the indices are an even or odd permutation of the original\nsymbols. The permutation $xyz$ or $123$ is considered to be $+1$. Its elements are\n\n$$\n\\begin{eqnarray}\n\\epsilon_{ijk}&=&-\\epsilon_{ikj}=-\\epsilon_{jik}=-\\epsilon_{kji}\\\\\n\\nonumber\n\\epsilon_{123}&=&\\epsilon_{231}=\\epsilon_{312}=1,\\\\\n\\nonumber\n\\epsilon_{213}&=&\\epsilon_{132}=\\epsilon_{321}=-1,\\\\\n\\nonumber\n\\epsilon_{iij}&=&\\epsilon_{iji}=\\epsilon_{jii}=0.\n\\end{eqnarray}\n$$\n\n## More on cross-products\n\nYou may have met cross-products when studying magnetic\nfields. Because the matrix is anti-symmetric, switching the $x$ and\n$y$ axes (or any two axes) flips the sign. If the coordinate system is\nright-handed, meaning the $xyz$ axes satisfy\n$\\hat{x}\\times\\hat{y}=\\hat{z}$, where you can point along the $x$ axis\nwith your extended right index finger, the $y$ axis with your\ncontracted middle finger and the $z$ axis with your extended\nthumb. Switching to a left-handed system flips the sign of the vector\n$\\boldsymbol{c}=\\boldsymbol{a}\\times\\boldsymbol{b}$.\n\nNote that\n$\\boldsymbol{a}\\times\\boldsymbol{b}=-\\boldsymbol{b}\\times\\boldsymbol{a}$. The vector $\\boldsymbol{c}$ is\nperpendicular to both $\\boldsymbol{a}$ and $\\boldsymbol{b}$ and the magnitude of\n$\\boldsymbol{c}$ is given by\n\n$$\n|c|=|a||b|\\sin{\\theta_{ab}}.\n$$\n\n## Pseudo-vectors\n\nVectors obtained by the cross product of two real vectors are called\npseudo-vectors because the assignment of their direction can be\narbitrarily flipped by defining the Levi-Civita symbol to be based on\nleft-handed rules. Examples are the magnetic field and angular\nmomentum. If the direction of a real vector prefers the right-handed\nover the left-handed direction, that constitutes a violation of\nparity. For instance, one can polarize the spins (angular momentum) of\nnuclei with a magnetic field so that the spins preferentially point\nalong the direction of the magnetic field. This does not violate\nparity because both are pseudo-vectors. Now assume these polarized\nnuclei decay and that electrons are one of the products. If these\nelectrons prefer to exit the decay parallel vs. antiparallel to the\npolarizing magnetic field, this constitutes parity violation because\nthe direction of the outgoing electron momenta are a real vector. This\nis precisely what is observed in weak decays.\n\n## Differentiation of a vector with respect to a scalar\n\nFor example, the\nacceleration $\\boldsymbol{a}$ is given by the change in velocity per unit time, $\\boldsymbol{a}=d\\boldsymbol{v}/dt$\nwith components\n\n$$\na_i = (d\\boldsymbol{v}/dt)_i=\\frac{dv_i}{dt}.\n$$\n\nHere $i=x,y,z$ or $i=1,2,3$ if we are in three dimensions.\n\n## Gradient operator $\\nabla$\n\nThis represents the derivatives $\\partial/\\partial\nx$, $\\partial/\\partial y$ and $\\partial/\\partial z$. An often used shorthand is $\\partial_x=\\partial/\\partial_x$.\n\nThe gradient of a scalar function of position and time\n$\\Phi(x,y,z)=\\Phi(\\boldsymbol{r},t)$ is given by\n\n$$\n\\boldsymbol{\\nabla}~\\Phi,\n$$\n\nwith components $i$\n\n$$\n(\\nabla\\Phi(x,y,z,t))_i=\\partial/\\partial r_i\\Phi(\\boldsymbol{r},t)=\\partial_i\\Phi(\\boldsymbol{r},t).\n$$\n\nNote that the gradient is a vector.\n\nTaking the dot product of the gradient with a vector, normally called the divergence,\nwe have\n\n$$\n\\mathrm{div} \\boldsymbol{a}, \\nabla\\cdot\\boldsymbol{a}=\\sum_i \\partial_i a_i.\n$$\n\nNote that the divergence is a scalar.\n\n## The curl\n\nThe **curl** of a vector is defined as\n$\\nabla\\times\\boldsymbol{a}$,\n\n$$\n{\\rm\\bf curl}~\\boldsymbol{a},\n$$\n\nwith components\n\n$$\n(\\boldsymbol{\\nabla}\\times\\boldsymbol{a})_i=\\epsilon_{ijk}\\partial_j a_k(\\boldsymbol{r},t).\n$$\n\n## The Laplacian\n\nThe Laplacian is referred to as $\\nabla^2$ and is defined as\n\n$$\n\\boldsymbol{\\nabla}^2=\\boldsymbol{\\nabla}\\cdot\\boldsymbol{\\nabla}=\\frac{\\partial^2}{\\partial x^2}+\\frac{\\partial^2}{\\partial y^2}+\\frac{\\partial^2}{\\partial z^2}.\n$$\n\nQuestion: is the Laplacian a scalar or a vector?\n\n## Some identities\n\nHere we simply state these, but you may wish to prove a few. They are useful for this class and will be essential when you study electromagnetism.\n\n$$\n\\begin{eqnarray}\n\\boldsymbol{a}\\cdot(\\boldsymbol{b}\\times\\boldsymbol{c})&=&\\boldsymbol{b}\\cdot(\\boldsymbol{c}\\times\\boldsymbol{a})=\\boldsymbol{c}\\cdot(\\boldsymbol{a}\\times\\boldsymbol{b})\\\\\n\\nonumber\n\\boldsymbol{a}\\times(\\boldsymbol{b}\\times\\boldsymbol{c})&=&(\\boldsymbol{a}\\cdot\\boldsymbol{c})\\boldsymbol{b}-(\\boldsymbol{a}\\cdot\\boldsymbol{b})\\boldsymbol{c}\\\\\n\\nonumber\n(\\boldsymbol{a}\\times\\boldsymbol{b})\\cdot(\\boldsymbol{c}\\times\\boldsymbol{d})&=&(\\boldsymbol{a}\\cdot\\boldsymbol{c})(\\boldsymbol{b}\\cdot\\boldsymbol{d})\n-(\\boldsymbol{a}\\cdot\\boldsymbol{d})(\\boldsymbol{b}\\cdot\\boldsymbol{c})\n\\end{eqnarray}\n$$\n\n## More useful relations\n\nUsing the fact that multiplication of reals is distributive we can show that\n\n$$\n\\boldsymbol{a}(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\boldsymbol{b}+\\boldsymbol{a}\\boldsymbol{c},\n$$\n\nSimilarly we can also show that (using product rule for differentiating reals)\n\n$$\n\\frac{d}{dt}(\\boldsymbol{a}\\boldsymbol{b})=\\boldsymbol{a}\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\frac{d\\boldsymbol{a}}{dt}.\n$$\n\nWe can repeat these operations for the cross products and show that they are distribuitive\n\n$$\n\\boldsymbol{a}\\times(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\times\\boldsymbol{b}+\\boldsymbol{a}\\times\\boldsymbol{c}.\n$$\n\nWe have also that\n\n$$\n\\frac{d}{dt}(\\boldsymbol{a}\\times\\boldsymbol{b})=\\boldsymbol{a}\\times\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\times\\frac{d\\boldsymbol{a}}{dt}.\n$$\n\n## Gauss's Theorem\n\nFor an integral over a volume $V$ confined by a surface $S$, Gauss's theorem gives\n\n$$\n\\int_V dv~\\nabla\\cdot\\boldsymbol{A}=\\int_Sd\\boldsymbol{S}\\cdot\\boldsymbol{A}.\n$$\n\nFor a closed path $C$ which carves out some area $S$,\n\n$$\n\\int_C d\\boldsymbol{\\ell}\\cdot\\boldsymbol{A}=\\int_Sd\\boldsymbol{s} \\cdot(\\nabla\\times\\boldsymbol{A})\n$$\n\n## and Stokes's Theorem\n\nStoke's law can be understood by considering a small rectangle,\n$-\\Delta x\n\n Relations Name matrix elements \n\n\n $A = A^{T}$ symmetric $a_{ij} = a_{ji}$ \n $A = \\left (A^{T} \\right )^{-1}$ real orthogonal $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$ \n $A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$ \n $A = A^{\\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$ \n $A = \\left (A^{\\dagger} \\right )^{-1}$ unitary $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$ \n\n\n\n## Some famous Matrices\n\n * Diagonal if $a_{ij}=0$ for $i\\ne j$\n\n * Upper triangular if $a_{ij}=0$ for $i > j$\n\n * Lower triangular if $a_{ij}=0$ for $i < j$\n\n * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n\n * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n\n * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n\n * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n\n * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n\n * Banded, block upper triangular, block lower triangular....\n\n## More Basic Matrix Features\n\n**Some Equivalent Statements.**\n\nFor an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n\n * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n\n * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n\n * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n\n * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n\n * $\\mathbf{A}$ is a product of elementary matrices.\n\n * $0$ is not eigenvalue of $\\mathbf{A}$.\n\n## Rotations\n\nHere, we use rotations as an example of matrices and their operations. One can consider a different orthonormal basis $\\hat{e}'_1$, $\\hat{e}'_2$ and $\\hat{e}'_3$. The same vector $\\boldsymbol{r}$ mentioned above can also be expressed in the new basis,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{r}=r'_1\\hat{e}'_1+r'_2\\hat{e}'_2+r'_3\\hat{e}'_3.\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\nEven though it is the same vector, the components have changed. Each\nnew unit vector $\\hat{e}'_i$ can be expressed as a linear sum of the\nprevious vectors,\n\n\n
\n\n$$\n\\begin{equation}\n\\hat{e}'_i=\\sum_j U_{ij}\\hat{e}_j,\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\nand the matrix $U$ can be found by taking the dot product of both sides with $\\hat{e}_k$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\nonumber\n\\hat{e}_k\\cdot\\hat{e}'_i&=&\\sum_jU_{ij}\\hat{e}_k\\cdot\\hat{e}_j\\\\\n\\label{eq:lambda_angles} \\tag{5}\n\\hat{e}_k\\cdot\\hat{e}'_i&=&\\sum_jU_{ij}\\delta_{jk}=U_{ik}.\n\\end{eqnarray}\n$$\n\n## More on the matrix $U$\n\nThus, the matrix lambda has components $U_{ij}$ that are equal to the\ncosine of the angle between new unit vector $\\hat{e}'_i$ and the old\nunit vector $\\hat{e}_j$.\n\n\n
\n\n$$\n\\begin{equation}\nU = \\begin{bmatrix}\n\\hat{e}'_1\\cdot\\hat{e}_1& \\hat{e}'_1\\cdot\\hat{e}_2& \\hat{e}'_1\\cdot\\hat{e}_3\\\\\n\\hat{e}'_2\\cdot\\hat{e}_1& \\hat{e}'_2\\cdot\\hat{e}_2& \\hat{e}'_2\\cdot\\hat{e}_3\\\\\n\\hat{e}'_3\\cdot\\hat{e}_1& \\hat{e}'_3\\cdot\\hat{e}_2& \\hat{e}'_3\\cdot\\hat{e}_3\n\\end{bmatrix},~~~~~U_{ij}=\\hat{e}'_i\\cdot\\hat{e}_j=\\cos\\theta_{ij}.\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$\n\n## Properties of the matrix $U$\n\nNote that the matrix is not symmetric, $U_{ij}\\ne U_{ji}$. One can also look at the inverse transformation, by switching the primed and unprimed coordinates,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:inverseU} \\tag{7}\n\\hat{e}_i&=&\\sum_jU^{-1}_{ij}\\hat{e}'_j,\\\\\n\\nonumber\nU^{-1}_{ij}&=&\\hat{e}_i\\cdot\\hat{e}'_j=U_{ji}.\n\\end{eqnarray}\n$$\n\nThe definition of transpose of a matrix, $M^{t}_{ij}=M_{ji}$, allows one to state this as\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:transposedef} \\tag{8}\nU^{-1}&=&U^{t}.\n\\end{eqnarray}\n$$\n\n## Tensors\n\nA tensor obeying Eq. ([8](#eq:transposedef)) defines what is known as\na unitary, or orthogonal, transformation.\n\nThe matrix $U$ can be used to transform any vector to the new basis. Consider a vector\n\n$$\n\\begin{eqnarray}\n\\boldsymbol{r}&=&r_1\\hat{e}_1+r_2\\hat{e}_2+r_3\\hat{e}_3\\\\\n\\nonumber\n&=&r'_1\\hat{e}'_1+r'_2\\hat{e}'_2+r'_3\\hat{e}'_3.\n\\end{eqnarray}\n$$\n\nThis is the same vector expressed as a sum over two different sets of\nbasis vectors. The coefficients $r_i$ and $r'_i$ represent components\nof the same vector. The relation between them can be found by taking\nthe dot product of each side with one of the unit vectors,\n$\\hat{e}_i$, which gives\n\n$$\n\\begin{eqnarray}\nr_i&=&\\sum_j \\hat{e}_i\\cdot\\hat{e}'_j~r'_j.\n\\end{eqnarray}\n$$\n\nUsing Eq. ([7](#eq:inverseU)) one can see that the transformation of $r$ can be also written in terms of $U$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:rotateR} \\tag{9}\nr_i&=&\\sum_jU^{-1}_{ij}~r'_j.\n\\end{eqnarray}\n$$\n\nThus, the matrix that transforms the coordinates of the unit vectors,\nEq. ([7](#eq:inverseU)) is the same one that transforms the\ncoordinates of a vector, Eq. ([9](#eq:rotateR)).\n\n## Rotation matrix\n\nAs a small exercise, find the rotation matrix $U$ for finding the\ncomponents in the primed coordinate system given from those in the\nunprimed system, given that the unit vectors in the new system are\nfound by rotating the coordinate system by and angle $\\phi$ about the\n$z$ axis.\n\nIn this case\n\n$$\n\\begin{eqnarray*}\n\\hat{e}'_1&=&\\cos\\phi \\hat{e}_1-\\sin\\phi\\hat{e}_2,\\\\\n\\hat{e}'_2&=&\\sin\\phi\\hat{e}_1+\\cos\\phi\\hat{e}_2,\\\\\n\\hat{e}'_3&=&\\hat{e}_3.\n\\end{eqnarray*}\n$$\n\nBy inspecting Eq. ([5](#eq:lambda_angles)), we get\n\n$$\nU=\\left(\\begin{array}{ccc}\n\\cos\\phi&-\\sin\\phi&0\\\\\n\\sin\\phi&\\cos\\phi&0\\\\\n0&0&1\\end{array}\\right).\n$$\n\n## Unitary Transformations\n\nUnder a unitary transformation $U$ (or basis transformation) scalars\nare unchanged, whereas vectors $\\boldsymbol{r}$ and matrices $M$ change as\n\n$$\n\\begin{eqnarray}\nr'_i&=&U_{ij}~ r_j, ~~({\\rm sum~inferred})\\\\\n\\nonumber\nM'_{ij}&=&U_{ik}M_{km}U^{-1}_{mj}.\n\\end{eqnarray}\n$$\n\nPhysical quantities with no spatial indices are scalars (or\npseudoscalars if they depend on right-handed vs. left-handed\ncoordinate systems), and are unchanged by unitary\ntransformations. This includes quantities like the trace of a matrix,\nthe matrix itself had indices but none remain after performing the\ntrace.\n\n$$\n\\begin{eqnarray}\n{\\rm Tr} M&\\equiv& M_{ii}.\n\\end{eqnarray}\n$$\n\nBecause there are no remaining indices, one expects it to be a scalar. Indeed one can see this,\n\n$$\n\\begin{eqnarray}\n{\\rm Tr} M'&=&U_{ij}M_{jm}U^{-1}_{mi}\\\\\n\\nonumber\n&=&M_{jm}U^{-1}_{mi}U_{ij}\\\\\n\\nonumber\n&=&M_{jm}\\delta_{mj}\\\\\n\\nonumber\n&=&M_{jj}={\\rm Tr} M.\n\\end{eqnarray}\n$$\n\nA similar example is the determinant of a matrix, which is also a scalar.\n\n## Numerical Elements\n\nNumerical algorithms call for approximate discrete models and much of\nthe development of methods for continuous models are nowadays being\nreplaced by methods for discrete models in science and industry,\nsimply because **much larger classes of problems can be addressed** with\ndiscrete models, often by simpler and more generic methodologies.\n\nAs we will see throughout this course, when properly scaling the equations at hand,\ndiscrete models open up for more advanced abstractions and the possibility to\nstudy real life systems, with the added bonus that we can explore and\ndeepen our basic understanding of various physical systems\n\nAnalytical solutions are as important as before. In addition, such\nsolutions provide us with invaluable benchmarks and tests for our\ndiscrete models. Such benchmarks, as we will see below, allow us \nto discuss possible sources of errors and their behaviors. And\nfinally, since most of our models are based on various algorithms from\nnumerical mathematics, we have a unique oppotunity to gain a deeper\nunderstanding of the mathematical approaches we are using.\n\nWith computing and data science as important elements in essentially\nall aspects of a modern society, we could then try to define Computing as\n**solving scientific problems using all possible tools, including\nsymbolic computing, computers and numerical algorithms, and analytical\npaper and pencil solutions**. \nComputing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.\n\n## Computations and the Scientific Method\n\nThe way we will teach this course reflects this definition of\ncomputing. The course contains both classical paper and pencil\nexercises as well as computational projects and exercises. The hope is\nthat this will allow you to explore the physics of systems governed by\nthe degrees of freedom of classical mechanics at a deeper level, and\nthat these insights about the scientific method will help you to\ndevelop a better understanding of how the underlying forces and\nequations of motion and how they impact a given system.\n\nFurthermore,\nby introducing various numerical methods via computational projects\nand exercises, we aim at developing your competences and skills about\nthese topics.\n\n## Computational Competences\n\nThese competences will enable you to\n\n* understand how algorithms are used to solve mathematical problems,\n\n* derive, verify, and implement algorithms,\n\n* understand what can go wrong with algorithms,\n\n* use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and\n\n* think algorithmically for the purposes of gaining deeper insights about scientific problems.\n\nAll these elements are central for maturing and gaining a better understanding of the modern scientific process *per se*.\n\nThe power of the scientific method lies in identifying a given problem\nas a special case of an abstract class of problems, identifying\ngeneral solution methods for this class of problems, and applying a\ngeneral method to the specific problem (applying means, in the case of\ncomputing, calculations by pen and paper, symbolic computing, or\nnumerical computing by ready-made and/or self-written software). This\ngeneric view on problems and methods is particularly important for\nunderstanding how to apply available, generic software to solve a\nparticular problem.\n\n*However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.*\n\n## A well-known example to illustrate many of the above concepts\n\nBefore we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the\nabovementioned topics using an example many of you may have seen before in for example CMSE201. \nA simple algorithm for integration is the Trapezoidal rule. \nIntegration of a function $f(x)$ by the Trapezoidal Rule is given by following algorithm for an interval $x \\in [a,b]$\n\n$$\n\\int_a^b(f(x) dx = \\frac{1}{2}\\left [f(a)+2f(a+h)+\\dots+2f(b-h)+f(b)\\right] +O(h^2),\n$$\n\nwhere $h$ is the so-called stepsize defined by the number of integration points $N$ as $h=(b-a)/(n)$.\nPython offers an extremely versatile programming environment, allowing for\nthe inclusion of analytical studies in a numerical program. Here we show an\nexample code with the **trapezoidal rule**. We use also **SymPy** to evaluate the exact value of the integral and compute the absolute error\nwith respect to the numerically evaluated one of the integral\n$\\int_0^1 dx x^2 = 1/3$.\nThe following code for the trapezoidal rule allows you to plot the relative error by comparing with the exact result. By increasing to $10^8$ points one arrives at a region where numerical errors start to accumulate.\n\n\n```python\n%matplotlib inline\n\nfrom math import log10\nimport numpy as np\nfrom sympy import Symbol, integrate\nimport matplotlib.pyplot as plt\n# function for the trapezoidal rule\ndef Trapez(a,b,f,n):\n h = (b-a)/float(n)\n s = 0\n x = a\n for i in range(1,n,1):\n x = x+h\n s = s+ f(x)\n s = 0.5*(f(a)+f(b)) +s\n return h*s\n# function to compute pi\ndef function(x):\n return x*x\n# define integration limits\na = 0.0; b = 1.0;\n# find result from sympy\n# define x as a symbol to be used by sympy\nx = Symbol('x')\nexact = integrate(function(x), (x, a, b))\n# set up the arrays for plotting the relative error\nn = np.zeros(9); y = np.zeros(9);\n# find the relative error as function of integration points\nfor i in range(1, 8, 1):\n npts = 10**i\n result = Trapez(a,b,function,npts)\n RelativeError = abs((exact-result)/exact)\n n[i] = log10(npts); y[i] = log10(RelativeError);\nplt.plot(n,y, 'ro')\nplt.xlabel('n')\nplt.ylabel('Relative error')\nplt.show()\n```\n\n## Analyzing the above example\n\nThis example shows the potential of combining numerical algorithms\nwith symbolic calculations, allowing us to\n\n* Validate and verify their algorithms. \n\n* Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.\n\n* Validation and verification are then included *naturally* and one can develop a better attitude to what is meant with an ethically sound scientific approach.\n\n* The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get **trained from day one to think error analysis**. \n\n* With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks.\n\n## Python practicalities, Software and needed installations\n\nWe will make extensive use of Python as programming language and its\nmyriad of available libraries. You will find\nJupyter notebooks invaluable in your work. \n\nIf you have Python installed (we strongly recommend Python3) and you feel\npretty familiar with installing different packages, we recommend that\nyou install the following Python packages via **pip** as \n\n1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n\nFor Python3, replace **pip** with **pip3**.\n\nFor OSX users we recommend, after having installed Xcode, to\ninstall **brew**. Brew allows for a seamless installation of additional\nsoftware via for example \n\n1. brew install python3\n\nFor Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\nyou can use **pip** as well and simply install Python as \n\n1. sudo apt-get install python3 (or python for pyhton2.7)\n\netc etc.\n\n## Python installers\n\nIf you don't want to perform these operations separately and venture\ninto the hassle of exploring how to set up dependencies and paths, we\nrecommend two widely used distrubutions which set up all relevant\ndependencies for Python, namely \n\n* [Anaconda](https://docs.anaconda.com/), \n\nwhich is an open source\ndistribution of the Python and R programming languages for large-scale\ndata processing, predictive analytics, and scientific computing, that\naims to simplify package management and deployment. Package versions\nare managed by the package management system **conda**. \n\n* [Enthought canopy](https://www.enthought.com/product/canopy/) \n\nis a Python\ndistribution for scientific and analytic computing distribution and\nanalysis environment, available for free and under a commercial\nlicense.\n\nFurthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \nno setup and runs entirely in the cloud. Try it out!\n\n## Useful Python libraries\nHere we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n\n* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n\n* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n\n* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n\n* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n\n* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n\n* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n\n* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n\n* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n\n* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n\n* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n\n* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n\nYour jupyter notebook can easily be\nconverted into a nicely rendered **PDF** file or a Latex file for\nfurther processing. For example, convert to latex as\n\n pycod jupyter nbconvert filename.ipynb --to latex \n\n\nAnd to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.\n\n## Numpy examples and Important Matrix and vector handling packages\n\nThere are several central software libraries for linear algebra and eigenvalue problems. Several of the more\npopular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\nsoftware package LAPACK, which follows two other popular packages\ndeveloped in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n\n * LINPACK: package for linear equations and least square problems.\n\n * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n\n * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n\n## Numpy and arrays\n\n[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as\n\n\n```python\nimport numpy as np\n```\n\nHere follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,\n\n\n```python\nn = 10\nx = np.random.normal(size=n)\nprint(x)\n```\n\nWe defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\nAnother alternative is to declare a vector as follows\n\n\n```python\nimport numpy as np\nx = np.array([1, 2, 3])\nprint(x)\n```\n\nHere we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\nstart numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4, 7, 8]))\nprint(x)\n```\n\nIn the last example we used Numpy's unary function $np.log$. This function is\nhighly tuned to compute array elements since the code is vectorized\nand does not require looping. We normaly recommend that you use the\nNumpy intrinsic functions instead of the corresponding **log** function\nfrom Python's **math** module. The looping is done explicitely by the\n**np.log** function. The alternative, and slower way to compute the\nlogarithms of a vector would be to write\n\n\n```python\nimport numpy as np\nfrom math import log\nx = np.array([4, 7, 8])\nfor i in range(0, len(x)):\n x[i] = log(x[i])\nprint(x)\n```\n\nWe note that our code is much longer already and we need to import the **log** function from the **math** module. \nThe attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4, 7, 8], dtype = np.float64))\nprint(x)\n```\n\nor simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x)\n```\n\nTo check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x.itemsize)\n```\n\n## Matrices in Python\n\nHaving defined vectors, we are now ready to try out matrices. We can\ndefine a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\nlowercase letters for vectors and uppercase letters for matrices)\n\n\n```python\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\nprint(A)\n```\n\nIf we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as\n\n\n```python\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[:,0])\n```\n\nWe can continue this was by printing out other columns or rows. The example here prints out the second column\n\n\n```python\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[1,:])\n```\n\nNumpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero\n\n\n```python\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to zero\nA = np.zeros( (n, n) )\nprint(A)\n```\n\nor initializing all elements to\n\n\n```python\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to one\nA = np.ones( (n, n) )\nprint(A)\n```\n\nor as unitarily distributed random numbers (see the material on random number generators in the statistics part)\n\n\n```python\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\nA = np.random.rand(n, n)\nprint(A)\n```\n\n## Meet the Pandas\n\n\n\n\n

Figure 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\n* \n\n* \n\n## Useful IDEs and text editors\n\nWhen dealing with homeworks, at some point you would need to use an\neditor, or an integrated development envinroment (IDE). As an IDE, we\nwould like to recommend **anaconda** since we end up using\njupyter-notebooks. **anaconda** runs on all known operating systems.\n\nIf you prefer editing **Python** codes, there are several excellent cross-platform editors.\nIf you are in a Windows environment, **word** is the classical text editor.\n\nThere is however a wealth of text editors and/ord IDEs that run on all operating\nsystems and functions well with Python. Some of the more popular ones are\n\n* [Atom](https://atom.io/)\n\n* [Sublime](https://www.sublimetext.com/)\n\n## Our first Physics encounter\n\nWe start studying the problem of a falling object and use this to introduce numerical aspects.\n\n## Falling baseball in one dimension\n\nWe anticipate the mathematical model to come and assume that we have a\nmodel for the motion of a falling baseball without air resistance.\nOur system (the baseball) is at an initial height $y_0$ (which we will\nspecify in the program below) at the initial time $t_0=0$. In our program example here we will plot the position in steps of $\\Delta t$ up to a final time $t_f$. \nThe mathematical formula for the position $y(t)$ as function of time $t$ is\n\n$$\ny(t) = y_0-\\frac{1}{2}gt^2,\n$$\n\nwhere $g=9.80665=0.980655\\times 10^1$m/s${}^2$ is a constant representing the standard acceleration due to gravity.\nWe have here adopted the conventional standard value. This does not take into account other effects, such as buoyancy or drag.\nFurthermore, we stop when the ball hits the ground, which takes place at\n\n$$\ny(t) = 0= y_0-\\frac{1}{2}gt^2,\n$$\n\nwhich gives us a final time $t_f=\\sqrt{2y_0/g}$. \n\nAs of now we simply assume that we know the formula for the falling object. Afterwards, we will derive it.\n\n## Our Python Encounter\n\nWe start with preparing folders for storing our calculations, figures and if needed, specific data files we use as input or output files.\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n#in case we have an input file we wish to read in\n#infile = open(data_path(\"MassEval2016.dat\"),'r')\n```\n\nYou could also define a function for making our plots. You\ncan obviously avoid this and simply set up various **matplotlib**\ncommands every time you need them. You may however find it convenient\nto collect all such commands in one function and simply call this\nfunction.\n\n\n```python\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndef MakePlot(x,y, styles, labels, axlabels):\n plt.figure(figsize=(10,6))\n for i in range(len(x)):\n plt.plot(x[i], y[i], styles[i], label = labels[i])\n plt.xlabel(axlabels[0])\n plt.ylabel(axlabels[1])\n plt.legend(loc=0)\n```\n\nThereafter we start setting up the code for the falling object.\n\n\n```python\n%matplotlib inline\nimport matplotlib.patches as mpatches\n\ng = 9.80655 #m/s^2\ny_0 = 10.0 # initial position in meters\nDeltaT = 0.1 # time step\n# final time when y = 0, t = sqrt(2*10/g)\ntfinal = np.sqrt(2.0*y_0/g)\n#set up arrays \nt = np.arange(0,tfinal,DeltaT)\ny =y_0 -g*.5*t**2\n# Then make a nice printout in table form using Pandas\nimport pandas as pd\nfrom IPython.display import display\ndata = {'t[s]': t,\n 'y[m]': y\n }\nRawData = pd.DataFrame(data)\ndisplay(RawData)\nplt.style.use('ggplot')\nplt.figure(figsize=(8,8))\nplt.scatter(t, y, color = 'b')\nblue_patch = mpatches.Patch(color = 'b', label = 'Height y as function of time t')\nplt.legend(handles=[blue_patch])\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"y[m]\")\nsave_fig(\"FallingBaseball\")\nplt.show()\n```\n\nHere we used **pandas** (see below) to systemize the output of the position as function of time.\n\n## Average quantities\nWe define now the average velocity as\n\n$$\n\\overline{v}(t) = \\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n$$\n\nIn the code we have set the time step $\\Delta t$ to a given value. We could define it in terms of the number of points $n$ as\n\n$$\n\\Delta t = \\frac{t_{\\mathrm{final}-}t_{\\mathrm{initial}}}{n}.\n$$\n\nSince we have discretized the variables, we introduce the counter $i$ and let $y(t)\\rightarrow y(t_i)=y_i$ and $t\\rightarrow t_i$\nwith $i=0,1,\\dots, n$. This gives us the following shorthand notations that we will use for the rest of this course. We define\n\n$$\ny_i = y(t_i),\\hspace{0.2cm} i=0,1,2,\\dots,n.\n$$\n\nThis applies to other variables which depend on say time. Examples are the velocities, accelerations, momenta etc.\nFurthermore we use the shorthand\n\n$$\ny_{i\\pm 1} = y(t_i\\pm \\Delta t),\\hspace{0.12cm} i=0,1,2,\\dots,n.\n$$\n\n## Compact equations\nWe can then rewrite in a more compact form the average velocity as\n\n$$\n\\overline{v}_i = \\frac{y_{i+1}-y_{i}}{\\Delta t}.\n$$\n\nThe velocity is defined as the change in position per unit time.\nIn the limit $\\Delta t \\rightarrow 0$ this defines the instantaneous velocity, which is nothing but the slope of the position at a time $t$.\nWe have thus\n\n$$\nv(t) = \\frac{dy}{dt}=\\lim_{\\Delta t \\rightarrow 0}\\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n$$\n\nSimilarly, we can define the average acceleration as the change in velocity per unit time as\n\n$$\n\\overline{a}_i = \\frac{v_{i+1}-v_{i}}{\\Delta t},\n$$\n\nresulting in the instantaneous acceleration\n\n$$\na(t) = \\frac{dv}{dt}=\\lim_{\\Delta t\\rightarrow 0}\\frac{v(t+\\Delta t)-v(t)}{\\Delta t}.\n$$\n\n**A note on notations**: When writing for example the velocity as $v(t)$ we are then referring to the continuous and instantaneous value. A subscript like\n$v_i$ refers always to the discretized values.\n\n## A differential equation\nWe can rewrite the instantaneous acceleration as\n\n$$\na(t) = \\frac{dv}{dt}=\\frac{d}{dt}\\frac{dy}{dt}=\\frac{d^2y}{dt^2}.\n$$\n\nThis forms the starting point for our definition of forces later. It is a famous second-order differential equation. If the acceleration is constant we can now recover the formula for the falling ball we started with.\nThe acceleration can depend on the position and the velocity. To be more formal we should then write the above differential equation as\n\n$$\n\\frac{d^2y}{dt^2}=a(t,y(t),\\frac{dy}{dt}).\n$$\n\nWith given initial conditions for $y(t_0)$ and $v(t_0)$ we can then\nintegrate the above equation and find the velocities and positions at\na given time $t$.\n\nIf we multiply with mass, we have one of the famous expressions for Newton's second law,\n\n$$\nF(y,v,t)=m\\frac{d^2y}{dt^2}=ma(t,y(t),\\frac{dy}{dt}),\n$$\n\nwhere $F$ is the force acting on an object with mass $m$. We see that it also has the right dimension, mass times length divided by time squared.\nWe will come back to this soon.\n\n## Integrating our equations\n\nFormally we can then, starting with the acceleration (suppose we have measured it, how could we do that?)\ncompute say the height of a building. To see this we perform the following integrations from an initial time $t_0$ to a given time $t$\n\n$$\n\\int_{t_0}^t dt' a(t') = \\int_{t_0}^t dt' \\frac{dv}{dt'} = v(t)-v(t_0),\n$$\n\nor as\n\n$$\nv(t)=v(t_0)+\\int_{t_0}^t dt' a(t').\n$$\n\nWhen we know the velocity as function of time, we can find the position as function of time starting from the defintion of velocity as the derivative with respect to time, that is we have\n\n$$\n\\int_{t_0}^t dt' v(t') = \\int_{t_0}^t dt' \\frac{dy}{dt'} = y(t)-y(t_0),\n$$\n\nor as\n\n$$\ny(t)=y(t_0)+\\int_{t_0}^t dt' v(t').\n$$\n\nThese equations define what is called the integration method for\nfinding the position and the velocity as functions of time. There is\nno loss of generality if we extend these equations to more than one\nspatial dimension.\n\n## Constant acceleration case, the velocity\nLet us compute the velocity using the constant value for the acceleration given by $-g$. We have\n\n$$\nv(t)=v(t_0)+\\int_{t_0}^t dt' a(t')=v(t_0)+\\int_{t_0}^t dt' (-g).\n$$\n\nUsing our initial time as $t_0=0$s and setting the initial velocity $v(t_0)=v_0=0$m/s we get when integrating\n\n$$\nv(t)=-gt.\n$$\n\nThe more general case is\n\n$$\nv(t)=v_0-g(t-t_0).\n$$\n\nWe can then integrate the velocity and obtain the final formula for the position as function of time through\n\n$$\ny(t)=y(t_0)+\\int_{t_0}^t dt' v(t')=y_0+\\int_{t_0}^t dt' v(t')=y_0+\\int_{t_0}^t dt' (-gt'),\n$$\n\nWith $y_0=10$m and $t_0=0$s, we obtain the equation we started with\n\n$$\ny(t)=10-\\frac{1}{2}gt^2.\n$$\n\n## Computing the averages\nAfter this mathematical background we are now ready to compute the mean velocity using our data.\n\n\n```python\n# Now we can compute the mean velocity using our data\n# We define first an array Vaverage\nn = np.size(t)\nVaverage = np.zeros(n)\nfor i in range(1,n-1):\n Vaverage[i] = (y[i+1]-y[i])/DeltaT\n# Now we can compute the mean accelearatio using our data\n# We define first an array Aaverage\nn = np.size(t)\nAaverage = np.zeros(n)\nAaverage[0] = -g\nfor i in range(1,n-1):\n Aaverage[i] = (Vaverage[i+1]-Vaverage[i])/DeltaT\ndata = {'t[s]': t,\n 'y[m]': y,\n 'v[m/s]': Vaverage,\n 'a[m/s^2]': Aaverage\n }\nNewData = pd.DataFrame(data)\ndisplay(NewData[0:n-2])\n```\n\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 \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
t[s]y[m]v[m/s]a[m/s^2]
00.010.0000000.000000-9.80655
10.19.950967-1.470982-9.80655
20.29.803869-2.451638-9.80655
30.39.558705-3.432292-9.80655
40.49.215476-4.412948-9.80655
50.58.774181-5.393602-9.80655
60.68.234821-6.374258-9.80655
70.77.597395-7.354913-9.80655
80.86.861904-8.335567-9.80655
90.96.028347-9.316222-9.80655
101.05.096725-10.296878-9.80655
111.14.067037-11.277533-9.80655
121.22.939284-12.258187-9.80655
\n
\n\n\nNote that we don't print the last values!\n\n## Including Air Resistance in our model\n\nIn our discussions till now of the falling baseball, we have ignored\nair resistance and simply assumed that our system is only influenced\nby the gravitational force. We will postpone the derivation of air\nresistance till later, after our discussion of Newton's laws and\nforces.\n\nFor our discussions here it suffices to state that the accelerations is now modified to\n\n$$\n\\boldsymbol{a}(t) = -g +D\\boldsymbol{v}(t)\\vert v(t)\\vert,\n$$\n\nwhere $\\vert v(t)\\vert$ is the absolute value of the velocity and $D$ is a constant which pertains to the specific object we are studying.\nSince we are dealing with motion in one dimension, we can simplify the above to\n\n$$\na(t) = -g +Dv^2(t).\n$$\n\nWe can rewrite this as a differential equation\n\n$$\na(t) = \\frac{dv}{dt}=\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n$$\n\nUsing the integral equations discussed above we can integrate twice\nand obtain first the velocity as function of time and thereafter the\nposition as function of time.\n\nFor this particular case, we can actually obtain an analytical\nsolution for the velocity and for the position. Here we will first\ncompute the solutions analytically, thereafter we will derive Euler's\nmethod for solving these differential equations numerically.\n\n## Analytical solutions\n\nFor simplicity let us just write $v(t)$ as $v$. We have\n\n$$\n\\frac{dv}{dt}= -g +Dv^2(t).\n$$\n\nWe can solve this using the technique of separation of variables. We\nisolate on the left all terms that involve $v$ and on the right all\nterms that involve time. We get then\n\n$$\n\\frac{dv}{g -Dv^2(t) }= -dt,\n$$\n\nWe scale now the equation to the left by introducing a constant\n$v_T=\\sqrt{g/D}$. This constant has dimension length/time. Can you\nshow this?\n\nNext we integrate the left-hand side (lhs) from $v_0=0$ m/s to $v$ and\nthe right-hand side (rhs) from $t_0=0$ to $t$ and obtain\n\n$$\n\\int_{0}^v\\frac{dv'}{g -D(v')^2(t) }= \\frac{v_T}{g}\\mathrm{arctanh}(\\frac{v}{v_T}) =-\\int_0^tdt' = -t.\n$$\n\nWe can reorganize these equations as\n\n$$\nv_T\\mathrm{arctanh}(\\frac{v}{v_T}) =-gt,\n$$\n\nwhich gives us $v$ as function of time\n\n$$\nv(t)=v_T\\tanh{-(\\frac{gt}{v_T})}.\n$$\n\n## Finding the final height\nWith the velocity we can then find the height $y(t)$ by integrating yet another time, that is\n\n$$\ny(t)=y(t_0)+\\int_{t_0}^t dt' v(t')=\\int_{0}^t dt'[v_T\\tanh{-(\\frac{gt'}{v_T})}].\n$$\n\nThis integral is trickier but we can look it up in a table over \nknown integrals and we get\n\n$$\ny(t)=y(t_0)-\\frac{v_T^2}{g}\\log{[\\cosh{(\\frac{gt}{v_T})}]}.\n$$\n\nAlternatively we could have used the symbolic Python package **Sympy** (example will be inserted later). \n\nIn most cases however, we need to revert to numerical solutions.\n\n## Our first attempt at solving differential equations\n\nHere we will try the simplest possible approach to solving the second-order differential \nequation\n\n$$\na(t) =\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n$$\n\nWe rewrite it as two coupled first-order equations (this is a standard approach)\n\n$$\n\\frac{dy}{dt} = v(t),\n$$\n\nwith initial condition $y(t_0)=y_0$ and\n\n$$\na(t) =\\frac{dv}{dt}= -g +Dv^2(t),\n$$\n\nwith initial condition $v(t_0)=v_0$.\n\nMany of the algorithms for solving differential equations start with simple Taylor equations.\nIf we now Taylor expand $y$ and $v$ around a value $t+\\Delta t$ we have\n\n$$\ny(t+\\Delta t) = y(t)+\\Delta t \\frac{dy}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2y}{dt^2}+O(\\Delta t^3),\n$$\n\nand\n\n$$\nv(t+\\Delta t) = v(t)+\\Delta t \\frac{dv}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2v}{dt^2}+O(\\Delta t^3).\n$$\n\nUsing the fact that $dy/dt = v$ and $dv/dt=a$ and keeping only terms up to $\\Delta t$ we have\n\n$$\ny(t+\\Delta t) = y(t)+\\Delta t v(t)+O(\\Delta t^2),\n$$\n\nand\n\n$$\nv(t+\\Delta t) = v(t)+\\Delta t a(t)+O(\\Delta t^2).\n$$\n\n## Discretizing our equations\n\nUsing our discretized versions of the equations with for example\n$y_{i}=y(t_i)$ and $y_{i\\pm 1}=y(t_i+\\Delta t)$, we can rewrite the\nabove equations as (and truncating at $\\Delta t$)\n\n$$\ny_{i+1} = y_i+\\Delta t v_i,\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\Delta t a_i.\n$$\n\nThese are the famous Euler equations (forward Euler).\n\nTo solve these equations numerically we start at a time $t_0$ and simply integrate up these equations to a final time $t_f$,\nThe step size $\\Delta t$ is an input parameter in our code.\nYou can define it directly in the code below as\n\n\n```python\nDeltaT = 0.1\n```\n\nWith a given final time **tfinal** we can then find the number of integration points via the **ceil** function included in the **math** package of Python\nas\n\n\n```python\n#define final time, assuming that initial time is zero\nfrom math import ceil\ntfinal = 0.5\nn = ceil(tfinal/DeltaT)\nprint(n)\n```\n\n 5\n\n\nThe **ceil** function returns the smallest integer not less than the input in say\n\n\n```python\nx = 21.15\nprint(ceil(x))\n```\n\n 22\n\n\nwhich in the case here is 22.\n\n\n```python\nx = 21.75\nprint(ceil(x))\n```\n\n 22\n\n\nwhich also yields 22. The **floor** function in the **math** package\nis used to return the closest integer value which is less than or equal to the specified expression or value.\nCompare the previous result to the usage of **floor**\n\n\n```python\nfrom math import floor\nx = 21.75\nprint(floor(x))\n```\n\n 21\n\n\nAlternatively, we can define ourselves the number of integration(mesh) points. In this case we could have\n\n\n```python\nn = 10\ntinitial = 0.0\ntfinal = 0.5\nDeltaT = (tfinal-tinitial)/(n)\nprint(DeltaT)\n```\n\n 0.05\n\n\nSince we will set up one-dimensional arrays that contain the values of\nvarious variables like time, position, velocity, acceleration etc, we\nneed to know the value of $n$, the number of data points (or\nintegration or mesh points). With $n$ we can initialize a given array\nby setting all elelements to zero, as done here\n\n\n```python\n# define array a\na = np.zeros(n)\nprint(a)\n```\n\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n\n\n## Code for implementing Euler's method\nIn the code here we implement this simple Eurler scheme choosing a value for $D=0.0245$ m/s.\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\ng = 9.80655 #m/s^2\nD = 0.00245 #m/s\nDeltaT = 0.1\n#set up arrays \ntfinal = 0.5\nn = ceil(tfinal/DeltaT)\n# define scaling constant vT\nvT = sqrt(g/D)\n# set up arrays for t, a, v, and y and we can compare our results with analytical ones\nt = np.zeros(n)\na = np.zeros(n)\nv = np.zeros(n)\ny = np.zeros(n)\nyanalytic = np.zeros(n)\n# Initial conditions\nv[0] = 0.0 #m/s\ny[0] = 10.0 #m\nyanalytic[0] = y[0]\n# Start integrating using Euler's method\nfor i in range(n-1):\n # expression for acceleration\n a[i] = -g + D*v[i]*v[i]\n # update velocity and position\n y[i+1] = y[i] + DeltaT*v[i]\n v[i+1] = v[i] + DeltaT*a[i]\n # update time to next time step and compute analytical answer\n t[i+1] = t[i] + DeltaT\n yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))\n if ( y[i+1] < 0.0):\n break\na[n-1] = -g + D*v[n-1]*v[n-1]\ndata = {'t[s]': t,\n 'y[m]': y-yanalytic,\n 'v[m/s]': v,\n 'a[m/s^2]': a\n }\nNewData = pd.DataFrame(data)\ndisplay(NewData)\n#finally we plot the data\nfig, axs = plt.subplots(3, 1)\naxs[0].plot(t, y, t, yanalytic)\naxs[0].set_xlim(0, tfinal)\naxs[0].set_ylabel('y and exact')\naxs[1].plot(t, v)\naxs[1].set_ylabel('v[m/s]')\naxs[2].plot(t, a)\naxs[2].set_xlabel('time[s]')\naxs[2].set_ylabel('a[m/s^2]')\nfig.tight_layout()\nsave_fig(\"EulerIntegration\")\nplt.show()\n```\n\nTry different values for $\\Delta t$ and study the difference between the exact solution and the numerical solution.\n\n## Simple extension, the Euler-Cromer method\n\nThe Euler-Cromer method is a simple variant of the standard Euler\nmethod. We use the newly updated velocity $v_{i+1}$ as an input to the\nnew position, that is, instead of\n\n$$\ny_{i+1} = y_i+\\Delta t v_i,\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\Delta t a_i,\n$$\n\nwe use now the newly calculate for $v_{i+1}$ as input to $y_{i+1}$, that is \nwe compute first\n\n$$\nv_{i+1} = v_i+\\Delta t a_i,\n$$\n\nand then\n\n$$\ny_{i+1} = y_i+\\Delta t v_{i+1},\n$$\n\nImplementing the Euler-Cromer method yields a simple change to the previous code. We only need to change the following line in the loop over time\nsteps\n\n\n```python\nfor i in range(n-1):\n # more codes in between here\n v[i+1] = v[i] + DeltaT*a[i]\n y[i+1] = y[i] + DeltaT*v[i+1]\n # more code\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "39e8bcefb89d61a57b648f4daf9e5720dcdbe6bf", "size": 174790, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/week2/ipynb/week2.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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/pub/week2/ipynb/week2.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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/week2/ipynb/week2.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": 38.8508557457, "max_line_length": 27680, "alphanum_fraction": 0.6425710853, "converted": true, "num_tokens": 21232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.08812357856061397}} {"text": "```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"./styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Shallow Water Equations\n\nAs a simple example of solving the Riemann problem for a nonlinear system we look at the *shallow water* equations. These are a simplification of the Navier-Stokes equations, reduced here to one spatial dimension $x$, which determine the height $h(x, t)$ of the water with respect to some reference location, and its velocity $u(x, t)$. In the simplest case (where the bed of the channel is flat, and the gravitational constant is renormalised to $1$) these can be written in the conservation law form\n$$\n \\partial_t \\begin{pmatrix} h \\\\ h u \\end{pmatrix} + \\partial_x \\begin{pmatrix} hu \\\\ h u^2 + \\tfrac{1}{2} h^2 \\end{pmatrix} = {\\bf 0}.\n$$\nThe *conserved variables* ${\\bf q} = (q_1, q_2)^T = (h, h u)^T$ are effectively the total mass and momentum of the fluid.\n\n## Quasilinear form\n\nAs seen in the [theory lesson](Lesson_Theory.ipynb), to construct the solution we need the eigenvalues and eigenvectors of the Jacobian matrix. We can construct them directly, by first noting that, in terms of the conserved variables, \n$$\n {\\bf f} = \\begin{pmatrix} f_1 \\\\ f_2 \\end{pmatrix} = \\begin{pmatrix} q_2 \\\\ \\frac{q_2^2}{q_1} + \\frac{q_1^2}{2} \\end{pmatrix}.\n$$\nTherefore the Jacobian is\n$$ \\frac{\\partial {\\bf f}}{\\partial {\\bf q}} = \\begin{pmatrix} 0 & 1 \\\\ -u^2 + h & 2 u \\end{pmatrix}.\n$$\nThe eigenvalues and eigenvectors follow immediately as\n$$\n\\begin{align}\n \\lambda_{1} & = u - \\sqrt{h}, & \\lambda_{2} & = u + \\sqrt{h}, \\\\\n {\\bf r}_{1} & = \\begin{pmatrix} 1 \\\\ u - \\sqrt{h} \\end{pmatrix}, & {\\bf r}_{2} & = \\begin{pmatrix} 1 \\\\ u + \\sqrt{h} \\end{pmatrix} .\n\\end{align}\n$$\nHere we have followed the standard convention $\\lambda_1 \\le \\lambda_2 \\le \\dots \\le \\lambda_N$.\n\nAn alternative approach that may be considerably easier to apply for more complex problems is to write down a different quasilinear form of the equation, which in this case is in terms of the *primitive variables* ${\\bf w} = (h, u)^T$,\n$$\n \\partial_t \\begin{pmatrix} h \\\\ u \\end{pmatrix} + \\begin{pmatrix} u & h \\\\ 1 & u \\end{pmatrix} \\partial_x \\begin{pmatrix} h \\\\ u \\end{pmatrix} = {\\bf 0}.\n$$\nThe general form here would be written \n$$\n \\partial_t {\\bf w} + B({\\bf w}) \\partial_x {\\bf w} = {\\bf 0}.\n$$\nIt is straightforward to check that \n$$\n B = \\left( \\frac{\\partial {\\bf q}}{\\partial {\\bf w}} \\right)^{-1} \\frac{\\partial {\\bf f}}{\\partial {\\bf w}} = \\left( \\frac{\\partial {\\bf q}}{\\partial {\\bf w}} \\right)^{-1} \\frac{\\partial {\\bf f}}{\\partial {\\bf q}} \\left( \\frac{\\partial {\\bf q}}{\\partial {\\bf w}} \\right).\n$$\nThus $B$ is *similar* to the Jacobian, so must have the same eigenvalues, which is straightforward to check. We also have that\n$$\n\\begin{align}\n B \\left\\{ \\left( \\frac{\\partial {\\bf q}}{\\partial {\\bf w}} \\right)^{-1} {\\bf r} \\right\\} = \\lambda \\left\\{ \\left( \\frac{\\partial {\\bf q}}{\\partial {\\bf w}} \\right)^{-1} {\\bf r} \\right\\},\n\\end{align}\n$$\nshowing that the eigenvectors of the Jacobian can be straightforwardly found from the eigenvectors of $B$, which for the shallow water case are\n$$\n\\begin{align}\n {\\bf \\hat{r}}_1 &= \\begin{pmatrix} -\\sqrt{h} \\\\ 1 \\end{pmatrix} & {\\bf \\hat{r}}_2 &= \\begin{pmatrix} \\sqrt{h} \\\\ 1 \\end{pmatrix}.\n\\end{align}\n$$\n\n## Rarefaction waves\n\nThe solution across a continuous rarefaction wave is given by the solution of the ordinary differential equation\n$$\n \\partial_{\\xi} {\\bf q} = \\frac{{\\bf r}}{{\\bf r} \\cdot \\partial_{{\\bf q}} \\lambda}\n$$\nwhere $\\lambda, {\\bf r}$ are the eigenvalues and eigenvectors of the Jacobian matrix. Note that we can change variables to get the (physically equivalent) relation differential equation\n$$\n \\partial_{\\xi} {\\bf w} = \\frac{{\\bf r}}{{\\bf r} \\cdot \\partial_{{\\bf w}} \\lambda}\n$$\nwhere now the eigenvectors are those of the appropriate matrix for the quasilinear form for ${\\bf w}$. Where ${\\bf w}$ are the primitive variables as above, the matrix is $B$ and the eigenvectors given by ${\\bf \\hat{r}}$ as above.\n\nFor the shallow water equations we will solve this equation for the primitive variables for the first wave only - symmetry gives the other wave straightforwardly. Starting from\n$$\n \\lambda_1 = u - \\sqrt{h}, \\qquad {\\bf \\hat{r}}_1 = \\begin{pmatrix} -\\sqrt{h} \\\\ 1 \\end{pmatrix}\n$$\nwe have\n$$\n \\partial_{{\\bf w}} \\lambda_1 = \\begin{pmatrix} -\\frac{1}{2 \\sqrt{h}} \\\\ 1 \\end{pmatrix}\n$$\nand hence\n$$\n {\\bf \\hat{r}}_1 \\cdot \\partial_{{\\bf w}} \\lambda_1 = \\frac{3}{2}\n$$\nfrom which we have\n$$\n \\partial_{\\xi} \\begin{pmatrix} h \\\\ u \\end{pmatrix} = \\frac{2}{3} \\begin{pmatrix} -\\sqrt{h} \\\\ 1 \\end{pmatrix}.\n$$\n\nThis is straightforwardly integrated to get\n$$\n \\begin{pmatrix} h \\\\ u \\end{pmatrix} = \\begin{pmatrix} \\left( c_1 - \\frac{\\xi}{3} \\right)^2 \\\\ \\frac{2}{3} \\xi + c_2 \\end{pmatrix}. \n$$\n\nTo fix the integration constants $c_{1,2}$ we need to say which state the solution is starting from. As we are looking at the left wave, we expect it to start from the left state ${\\bf w}_l = (h_l, u_l)^T$. The left state will connect to the rarefaction wave when the characteristic speeds match, i.e. when $\\xi = \\xi_l = \\lambda_1 = u_l - \\sqrt{h_l}$. Therefore we have\n$$\n \\begin{pmatrix} h_l \\\\ u_l \\end{pmatrix} = \\begin{pmatrix} \\left( c_1 - \\frac{\\xi_l}{3} \\right)^2 \\\\ \\frac{2}{3} \\xi_l + c_2 \\end{pmatrix},\n$$\nfrom which we determine\n$$\n c_1 = \\frac{1}{3} \\xi_l + \\sqrt{h_l}, \\qquad c_2 = u_l - \\frac{2}{3} \\xi_l.\n$$\n\nThis gives the final solution\n$$\n \\begin{pmatrix} h \\\\ u \\end{pmatrix} = \\begin{pmatrix} \\left( \\frac{\\xi_l - \\xi}{3} + \\sqrt{h_l} \\right)^2 \\\\ \\frac{2}{3} (\\xi - \\xi_l) + u_l \\end{pmatrix}. \n$$\n\n### Rarefaction examples\n\nLet us look at all points that can be connected to a certain state by a rarefaction. We do this in the *phase plane*, which is the $(h, u)$ plane. The \"known state\" will be given by a marker, and all states along the rarefaction curve given by the line, sometimes known as an integral curve.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\nhl = np.linspace(0.1, 10.1)\nul = np.linspace(-1.0, 1.0)\nHL, UL = np.meshgrid(hl, ul)\nXIL = UL - np.sqrt(HL)\nxi_min = np.min(XIL)\nxi_max = np.max(XIL)\nh_min = np.min(hl)\nh_max = np.max(hl)\nu_min = np.min(ul)\nu_max = np.max(ul)\nxi = np.linspace(xi_min, xi_max)\n```\n\n\n```python\ndef plot_sw_rarefaction(hl, ul):\n \"Plot the rarefaction curve through the state (hl, ul)\"\n \n xil = ul - np.sqrt(hl)\n h = ((xil - xi) / 3.0 + np.sqrt(hl))**2\n u = 2.0 * (xi - xil) / 3.0 + ul\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, u, 'k--', linewidth = 2)\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 fig.tight_layout()\n```\n\n\n```python\nfrom ipywidgets import interactive, FloatSlider\n\ninteractive(plot_sw_rarefaction, \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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\n

Failed to display Jupyter Widget of type interactive.

\n

\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\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 \n \n \n \n
$w_{opt}$$E[r_p]$$\\sigma_p$
$\\gamma$
12.9722750.3339780.569191
21.4861370.1719890.284595
30.9907580.1179930.189730
40.7430690.0909940.142298
50.5944550.0747960.113838
60.4953790.0639960.094865
70.4246110.0562830.081313
80.3715340.0504970.071149
90.3302530.0459980.063243
100.2972270.0423980.056919
\n
\n\n\n\n¿Cómo se interpreta $w^\\ast>1$?\n- Cuando $01$, tenemos $1-w^\\ast<0$. Lo anterior implica una posición corta en el activo libre de riesgo (suponiendo que se puede) y una posición larga (de más del 100%) en el mercado de activos: apalancamiento.\n\n# Anuncios parroquiales.\n\n## 1. Quiz la siguiente clase.\n## 2. [Calificaciones](https://docs.google.com/spreadsheets/d/18-SDXpkuN6LULO16_1VPHPksrP-QCEpj7OLxiaSpQ3U/edit?usp=sharing)\n\n\n\n
\nCreated with Jupyter by Esteban Jiménez Rodríguez.\n
\n", "meta": {"hexsha": "b3e81c0ac9d004a06bfe74a477cfd65b512eeac1", "size": 46801, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Modulo3/Clase13_OptimizacionMediaVarianza.ipynb", "max_stars_repo_name": "PiedrasAyala95/PorInv2018-2", "max_stars_repo_head_hexsha": "8f5eb1648989728f21d01720c85827d9478211ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-27T16:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-27T16:54:10.000Z", "max_issues_repo_path": "Modulo3/Clase13_OptimizacionMediaVarianza.ipynb", "max_issues_repo_name": "PiedrasAyala95/PorInv2018-2", "max_issues_repo_head_hexsha": "8f5eb1648989728f21d01720c85827d9478211ab", "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": "Modulo3/Clase13_OptimizacionMediaVarianza.ipynb", "max_forks_repo_name": "PiedrasAyala95/PorInv2018-2", "max_forks_repo_head_hexsha": "8f5eb1648989728f21d01720c85827d9478211ab", "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": 88.1374764595, "max_line_length": 29000, "alphanum_fraction": 0.8026751565, "converted": true, "num_tokens": 3491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.17781087383497526, "lm_q1q2_score": 0.08751640250372206}} {"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols\nfrom IPython.display import Image\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Projections onto subspaces\n\n## Geometry in the plane\n\n* Projection of a vector onto another (in the plane)\n* Consider the orthogonal projection of **b** onto **a**\n\n\n```python\nImage(filename = 'Orthogonal projection in the plane.png')\n```\n\n* Note that **p** falls on a line, which is a subspace of the plane ℝ2\n* Remember from the previous lecture that orthogonal subspaces have A**x** = **0**\n* Note that **p** is some scalar multiple of **a**\n* With **a** perpendicular to **e** and **e** = **b** - x**a**\n* Thus we have **a**T(**b** - x**a**) = 0 and x**a**T**a** = **a**T**b**\n* Since **a**T**a** is a number we can simplify\n$$ x=\\frac { { \\underline { a } }^{ T }\\underline { b } }{ { \\underline { a } }^{ T }\\underline { a } } $$\n\n* We also have **p** = **a**x\n$$ \\underline { p } =\\underline { a } x=\\underline { a } \\frac { { \\underline { a } }^{ T }\\underline { b } }{ { \\underline { a } }^{ T }\\underline { a } } $$\n\n* This equation is helpful\n * Doubling (or any other scalar multiple of) **b** doubles (or scalar multiplies) **p**\n * Doubling (or scalar multiple of) **a** has no effect\n\n* Eventually we are looking for proj**p** = P**b**, where P is the projection matrix\n$$ \\underline { p } =P\\underline { b } \\\\ P=\\frac { 1 }{ { \\underline { a } }^{ T }\\underline { a } } \\underline { a } { \\underline { a } }^{ T } $$\n\n* Properties of the projection matrix P\n * The columnspace of P (C(P)) is the line which contains **a**\n * The rank is 1, rank(P) = 1\n * P is symmetrix, i.e. PT = P\n * Applying the projection matrix a second time (i.e. P2) nothing changes, thus P2 = P\n\n## Why project?\n\n(projecting onto more than a one-dimensional line)\n\n* Because A**x** = **b** may not have a solution\n * **b** may not be in the columnspace\n * May have more equations than unknowns\n* Solve for the closest vector in the columnspace\n * This is done by solving for **p** instead, where **p** is the projection of **b** onto the columnsapce of A\n$$ A\\hat { x } =\\underline { p } $$\n\n* Now we have to get **b** orthogonally project (as **p**) onto the column(sub)space\n* This is done by calculating two bases vectors for the plane that contains **p**, i.e. **a**1 and **a**2\n\n* Going way back to the graph up top we note that **e** is perpendicular to the plane\n* So, we have:\n$$ A\\hat { x } =\\underline { p } $$\n* We know that both **a**1 and **a**2 is perpendicular to **e**, so:\n$$ { a }_{ 1 }^{ T }\\underline { e } =0;\\quad { a }_{ 2 }^{ T }\\underline { e } =0\\\\ \\because \\quad \\underline { e } =\\underline { b } -\\underline { p } \\\\ \\because \\quad \\underline { p } =A\\hat { x } \\\\ { a }_{ 1 }^{ T }\\left( \\underline { b } -A\\hat { x } \\right) =0;\\quad { a }_{ 2 }^{ T }\\left( \\underline { b } -A\\hat { x } \\right) =0 $$\n\n* We know that from ...\n$$ \\begin{bmatrix} { a }_{ 1 }^{ T } \\\\ { a }_{ 2 }^{ T } \\end{bmatrix}\\left( \\underline { b } -A\\hat { x } \\right) =\\begin{bmatrix} 0 \\\\ 0 \\end{bmatrix}\\\\ { A }^{ T }\\left( \\underline { b } -A\\hat { x } \\right) =0 $$\n* ... **e** must be in the nullspace of AT\n* Which is right because from the previous lecture the nullspace of AT is orthogonal to the columnspace of A\n\n* Simplifying the last equations we have\n$$ {A}^{T}{A} \\hat{x} = {A}^{T}{b} $$\n\n* Just look back at the plane example in ℝ2 example we started with\n* Simplifying things back to a column vector **a** instead of a matrix subspace A in this last equation does give us what we had in ℝ2\n\n* Solving this we have\n$$ \\hat { x } ={ \\left( { A }^{ T }A \\right) }^{ -1 }{ A }^{ T }\\underline { b } $$\n\n* Which leaves us with\n$$ \\underline { p } =A\\hat { x } \\\\ \\underline { p } =A{ \\left( { A }^{ T }A \\right) }^{ -1 }{ A }^{ T }\\underline { b } $$\n\n* Making the projection matrix P\n$$ P=A{ \\left( { A }^{ T }A \\right) }^{ -1 }{ A }^{ T } $$\n\n* Just note that for a square invertible matrix A, P is the identity matrix\n* Most of the time A is not square (and thus invertible) so we have to leave the equation as it is\n* Also, note that PT = P and P2 = P\n\n## Applications\n\n### Least squares\n\n* Given a set of data points in two dimensions, i.e. with variables (*t*,*b*)\n* We need to fit them onto the best line\n* So, as an example consider the points (1,1), (2,2), (3,2)\n\n* A best line in this instance means a straight line in the form\n$$ {b}={C}+{D}{t} $$\n* Using the three points above we get three equations\n$$ {C}+{D}=1 \\\\ {C}+{2D} = 2 \\\\ {C}+{3D}=2 $$\n\n* If the line goes through all points, we would give a solution\n* Instead we have the following\n$$ \\begin{bmatrix} 1 & 1 \\\\ 1 & 2 \\\\ 1 & 3 \\end{bmatrix}\\begin{bmatrix} C \\\\ D \\end{bmatrix}=\\begin{bmatrix} 1 \\\\ 2 \\\\ 2 \\end{bmatrix} $$\n* Three equation, two unknowns, no solution, **so** solve ...\n$$ { A }^{ T }A\\hat { x } ={ A }^{ T }b $$\n* ... which for the solution is\n$$ \\hat { x } ={ \\left( { A }^{ T }A \\right) }^{ -1 }{ A }^{ T }b $$\n\n\n```python\nA = Matrix([[1, 1], [1, 2], [1, 3]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 1\\\\1 & 2\\\\1 & 3\\end{matrix}\\right]$$\n\n\n\n\n```python\nb = Matrix([1, 2, 2])\nb\n```\n\n\n\n\n$$\\left[\\begin{matrix}1\\\\2\\\\2\\end{matrix}\\right]$$\n\n\n\n\n```python\n(A.transpose() * A).inv() * A.transpose() * b\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{2}{3}\\\\\\frac{1}{2}\\end{matrix}\\right]$$\n\n\n\n* Thus, the solution is:\n$$ b=\\frac { 2 }{ 3 } +\\frac { 1 }{ 2 } t $$\n\n\n```python\n\n```\n", "meta": {"hexsha": "5faadba48dcd7c34506408bd9a02876726b9e256", "size": 26716, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_15_Projection_onto_subspaces.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_15_Projection_onto_subspaces.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_15_Projection_onto_subspaces.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": 53.219123506, "max_line_length": 12416, "alphanum_fraction": 0.7032115586, "converted": true, "num_tokens": 2611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.18952109361853836, "lm_q1q2_score": 0.08737240419176645}} {"text": "```python\n%matplotlib inline\n```\n\n\nLink Prediction using Graph Neural Networks\n===========================================\n\nIn the [introduction](1_introduction.ipynb), you have already learned\nthe basic workflow of using GNNs for node classification,\ni.e. predicting the category of a node in a graph. This tutorial will\nteach you how to train a GNN for link prediction, i.e. predicting the\nexistence of an edge between two arbitrary nodes in a graph.\n\nBy the end of this tutorial you will be able to\n\n- Build a GNN-based link prediction model.\n- Train and evaluate the model on a small DGL-provided dataset.\n\n\n\n```python\nimport dgl\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport itertools\nimport numpy as np\nimport scipy.sparse as sp\n```\n\n Using backend: pytorch\n\n\nOverview of Link Prediction with GNN\n------------------------------------\n\nMany applications such as social recommendation, item recommendation,\nknowledge graph completion, etc., can be formulated as link prediction,\nwhich predicts whether an edge exists between two particular nodes. This\ntutorial shows an example of predicting whether a citation relationship,\neither citing or being cited, between two papers exists in a citation\nnetwork.\n\nThis tutorial formulates the link prediction problem as a binary classification\nproblem as follows:\n\n- Treat the edges in the graph as *positive examples*.\n- Sample a number of non-existent edges (i.e. node pairs with no edges\n between them) as *negative* examples.\n- Divide the positive examples and negative examples into a training\n set and a test set.\n- Evaluate the model with any binary classification metric such as Area\n Under Curve (AUC).\n\n
\n \n**Note**: The practice comes from\n [SEAL](https://papers.nips.cc/paper/2018/file/53f0d7c537d99b3824f0f99d62ea2428-Paper.pdf),\n although the model here does not use their idea of node labeling.\n\n
\n\nIn some domains such as large-scale recommender systems or information\nretrieval, you may favor metrics that emphasize good performance of\ntop-K predictions. In these cases you may want to consider other metrics\nsuch as mean average precision, and use other negative sampling methods,\nwhich are beyond the scope of this tutorial.\n\nLoading graph and features\n--------------------------\n\nFollowing the [introduction](1_introduction.ipynb), this tutorial\nfirst loads the Cora dataset.\n\n\n\n\n\n```python\nimport dgl.data\n\ndataset = dgl.data.CoraGraphDataset()\ng = dataset[0]\n```\n\n NumNodes: 2708\n NumEdges: 10556\n NumFeats: 1433\n NumClasses: 7\n NumTrainingSamples: 140\n NumValidationSamples: 500\n NumTestSamples: 1000\n Done loading data from cached files.\n\n\nPrepare training and testing sets\n---------------------------------\n\nThis tutorial randomly picks 10% of the edges for positive examples in\nthe test set, and leave the rest for the training set. It then samples\nthe same number of edges for negative examples in both sets.\n\n\n\n\n\n```python\n# Split edge set for training and testing\nu, v = g.edges()\n\neids = np.arange(g.number_of_edges())\neids = np.random.permutation(eids)\ntest_size = int(len(eids) * 0.1)\ntrain_size = g.number_of_edges() - test_size\ntest_pos_u, test_pos_v = u[eids[:test_size]], v[eids[:test_size]]\ntrain_pos_u, train_pos_v = u[eids[test_size:]], v[eids[test_size:]]\n\n# Find all negative edges and split them for training and testing\nadj = sp.coo_matrix((np.ones(len(u)), (u.numpy(), v.numpy())))\nadj_neg = 1 - adj.todense() - np.eye(g.number_of_nodes())\nneg_u, neg_v = np.where(adj_neg != 0)\n\nneg_eids = np.random.choice(len(neg_u), g.number_of_edges() // 2)\ntest_neg_u, test_neg_v = neg_u[neg_eids[:test_size]], neg_v[neg_eids[:test_size]]\ntrain_neg_u, train_neg_v = neg_u[neg_eids[test_size:]], neg_v[neg_eids[test_size:]]\n```\n\nWhen training, you will need to remove the edges in the test set from\nthe original graph. You can do this via ``dgl.remove_edges``.\n\n
\n \n**Note**: ``dgl.remove_edges`` works by creating a subgraph from the\n original graph, resulting in a copy and therefore could be slow for\n large graphs. If so, you could save the training and test graph to\n disk, as you would do for preprocessing.\n\n
\n\n\n\n\n\n```python\ntrain_g = dgl.remove_edges(g, eids[:test_size])\n```\n\nDefine a GraphSAGE model\n------------------------\n\nThis tutorial builds a model consisting of two\n[GraphSAGE](https://arxiv.org/abs/1706.02216) layers, each computes\nnew node representations by averaging neighbor information. DGL provides\n``dgl.nn.SAGEConv`` that conveniently creates a GraphSAGE layer.\n\n\n\n\n\n```python\nfrom dgl.nn import SAGEConv\n\n# ----------- 2. create model -------------- #\n# build a two-layer GraphSAGE model\nclass GraphSAGE(nn.Module):\n def __init__(self, in_feats, h_feats):\n super(GraphSAGE, self).__init__()\n self.conv1 = SAGEConv(in_feats, h_feats, 'mean')\n self.conv2 = SAGEConv(h_feats, h_feats, 'mean')\n \n def forward(self, g, in_feat):\n h = self.conv1(g, in_feat)\n h = F.relu(h)\n h = self.conv2(g, h)\n return h\n```\n\nThe model then predicts the probability of existence of an edge by\ncomputing a score between the representations of both incident nodes\nwith a function (e.g. an MLP or a dot product), which you will see in\nthe next section.\n\n\\begin{align}\\hat{y}_{u\\sim v} = f(h_u, h_v)\\end{align}\n\n\n\n\nPositive graph, negative graph, and ``apply_edges``\n---------------------------------------------------\n\nIn previous tutorials you have learned how to compute node\nrepresentations with a GNN. However, link prediction requires you to\ncompute representation of *pairs of nodes*.\n\nDGL recommends you to treat the pairs of nodes as another graph, since\nyou can describe a pair of nodes with an edge. In link prediction, you\nwill have a *positive graph* consisting of all the positive examples as\nedges, and a *negative graph* consisting of all the negative examples.\nThe *positive graph* and the *negative graph* will contain the same set\nof nodes as the original graph. This makes it easier to pass node\nfeatures among multiple graphs for computation. As you will see later,\nyou can directly fed the node representations computed on the entire\ngraph to the positive and the negative graphs for computing pair-wise\nscores.\n\nThe following code constructs the positive graph and the negative graph\nfor the training set and the test set respectively.\n\n\n\n\n\n```python\ntrain_pos_g = dgl.graph((train_pos_u, train_pos_v), num_nodes=g.number_of_nodes())\ntrain_neg_g = dgl.graph((train_neg_u, train_neg_v), num_nodes=g.number_of_nodes())\n\ntest_pos_g = dgl.graph((test_pos_u, test_pos_v), num_nodes=g.number_of_nodes())\ntest_neg_g = dgl.graph((test_neg_u, test_neg_v), num_nodes=g.number_of_nodes())\n```\n\nThe benefit of treating the pairs of nodes as a graph is that you can\nuse the ``DGLGraph.apply_edges`` method, which conveniently computes new\nedge features based on the incident nodes’ features and the original\nedge features (if applicable).\n\nDGL provides a set of optimized builtin functions to compute new\nedge features based on the original node/edge features. For example,\n``dgl.function.u_dot_v`` computes a dot product of the incident nodes’\nrepresentations for each edge.\n\n\n\n\n\n```python\nimport dgl.function as fn\n\nclass DotPredictor(nn.Module):\n def forward(self, g, h):\n with g.local_scope():\n g.ndata['h'] = h\n # Compute a new edge feature named 'score' by a dot-product between the\n # source node feature 'h' and destination node feature 'h'.\n g.apply_edges(fn.u_dot_v('h', 'h', 'score'))\n # u_dot_v returns a 1-element vector for each edge so you need to squeeze it.\n return g.edata['score'][:, 0]\n```\n\nYou can also write your own function if it is complex.\nFor instance, the following module produces a scalar score on each edge\nby concatenating the incident nodes’ features and passing it to an MLP.\n\n\n\n\n\n```python\nclass MLPPredictor(nn.Module):\n def __init__(self, h_feats):\n super().__init__()\n self.W1 = nn.Linear(h_feats * 2, h_feats)\n self.W2 = nn.Linear(h_feats, 1)\n\n def apply_edges(self, edges):\n \"\"\"\n Computes a scalar score for each edge of the given graph.\n\n Parameters\n ----------\n edges :\n Has three members ``src``, ``dst`` and ``data``, each of\n which is a dictionary representing the features of the\n source nodes, the destination nodes, and the edges\n themselves.\n\n Returns\n -------\n dict\n A dictionary of new edge features.\n \"\"\"\n h = torch.cat([edges.src['h'], edges.dst['h']], 1)\n return {'score': self.W2(F.relu(self.W1(h))).squeeze(1)}\n\n def forward(self, g, h):\n with g.local_scope():\n g.ndata['h'] = h\n g.apply_edges(self.apply_edges)\n return g.edata['score']\n```\n\n
\n \n**Note**: The builtin functions are optimized for both speed and memory.\n We recommend using builtin functions whenever possible.\n\n
\n\n
\n \n**Note**: If you have read the [message passing\n tutorial](3_message_passing.ipynb), you will notice that the\n argument ``apply_edges`` takes has exactly the same form as a message\n function in ``update_all``.\n\n
\n\n\n\n\nTraining loop\n-------------\n\nAfter you defined the node representation computation and the edge score\ncomputation, you can go ahead and define the overall model, loss\nfunction, and evaluation metric.\n\nThe loss function is simply binary cross entropy loss.\n\n\\begin{align}\\mathcal{L} = -\\sum_{u\\sim v\\in \\mathcal{D}}\\left( y_{u\\sim v}\\log(\\hat{y}_{u\\sim v}) + (1-y_{u\\sim v})\\log(1-\\hat{y}_{u\\sim v})) \\right)\\end{align}\n\nThe evaluation metric in this tutorial is AUC.\n\n\n\n\n\n```python\nmodel = GraphSAGE(train_g.ndata['feat'].shape[1], 16)\n# You can replace DotPredictor with MLPPredictor.\n#pred = MLPPredictor(16)\npred = DotPredictor()\n\ndef compute_loss(pos_score, neg_score):\n scores = torch.cat([pos_score, neg_score])\n labels = torch.cat([torch.ones(pos_score.shape[0]), torch.zeros(neg_score.shape[0])])\n return F.binary_cross_entropy_with_logits(scores, labels)\n\ndef compute_auc(pos_score, neg_score):\n scores = torch.cat([pos_score, neg_score]).numpy()\n labels = torch.cat(\n [torch.ones(pos_score.shape[0]), torch.zeros(neg_score.shape[0])]).numpy()\n return roc_auc_score(labels, scores)\n```\n\nThe training loop goes as follows:\n\n
\n \n**Note**: This tutorial does not include evaluation on a validation\n set. In practice you should save and evaluate the best model based on\n performance on the validation set.\n\n
\n\n\n\n\n\n```python\n# ----------- 3. set up loss and optimizer -------------- #\n# in this case, loss will in training loop\noptimizer = torch.optim.Adam(itertools.chain(model.parameters(), pred.parameters()), lr=0.01)\n\n# ----------- 4. training -------------------------------- #\nall_logits = []\nfor e in range(100):\n # forward\n h = model(train_g, train_g.ndata['feat'])\n pos_score = pred(train_pos_g, h)\n neg_score = pred(train_neg_g, h)\n loss = compute_loss(pos_score, neg_score)\n \n # backward\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if e % 5 == 0:\n print('In epoch {}, loss: {}'.format(e, loss))\n\n# ----------- 5. check results ------------------------ #\nfrom sklearn.metrics import roc_auc_score\nwith torch.no_grad():\n pos_score = pred(test_pos_g, h)\n neg_score = pred(test_neg_g, h)\n print('AUC', compute_auc(pos_score, neg_score))\n```\n\n In epoch 0, loss: 0.6184065937995911\n In epoch 5, loss: 0.6056914925575256\n In epoch 10, loss: 0.5802127122879028\n In epoch 15, loss: 0.5393418073654175\n In epoch 20, loss: 0.48020118474960327\n In epoch 25, loss: 0.4126580059528351\n In epoch 30, loss: 0.36391153931617737\n In epoch 35, loss: 0.32281294465065\n In epoch 40, loss: 0.2892597019672394\n In epoch 45, loss: 0.2589336931705475\n In epoch 50, loss: 0.23045368492603302\n In epoch 55, loss: 0.2066962718963623\n In epoch 60, loss: 0.18129807710647583\n In epoch 65, loss: 0.1579950898885727\n In epoch 70, loss: 0.1354110985994339\n In epoch 75, loss: 0.11393584311008453\n In epoch 80, loss: 0.0939987450838089\n In epoch 85, loss: 0.07589612156152725\n In epoch 90, loss: 0.0597052127122879\n In epoch 95, loss: 0.04581739008426666\n AUC 0.8605017856741763\n\n", "meta": {"hexsha": "0a94df041f0fd74e09154b4e86d9d5e69d993249", "size": 18259, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "4_link_predict.ipynb", "max_stars_repo_name": "Geniussh/WSDM21-Hands-on-Tutorial", "max_stars_repo_head_hexsha": "5343d54376940ea7b1e608aa110b922f2a5a0ce8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-03-08T07:27:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T10:17:00.000Z", "max_issues_repo_path": "4_link_predict.ipynb", "max_issues_repo_name": "Geniussh/WSDM21-Hands-on-Tutorial", "max_issues_repo_head_hexsha": "5343d54376940ea7b1e608aa110b922f2a5a0ce8", "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": "4_link_predict.ipynb", "max_forks_repo_name": "Geniussh/WSDM21-Hands-on-Tutorial", "max_forks_repo_head_hexsha": "5343d54376940ea7b1e608aa110b922f2a5a0ce8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-03-04T08:19:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T20:28:44.000Z", "avg_line_length": 33.4413919414, "max_line_length": 187, "alphanum_fraction": 0.5619146722, "converted": true, "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.18010667068774938, "lm_q1q2_score": 0.08724008432657912}} {"text": "# EOSC 576 Problems\n\n\n```python\n__author__ = 'Yingkai (Kyle) Sha'\n__email__ = 'yingkai@eos.ubc.ca'\n```\n\n\n```python\nfrom IPython.core.display import HTML\nHTML(open(\"../custom.css\", \"r\").read())\n```\n\n\n\n\n\n\n\n\n\n\n```python\nimport numpy as np\nimport sympy as sp\nimport matplotlib.pyplot as plt\n% matplotlib inline\n```\n\n#Content\n 1. [**Chapter 4 - Organic Matter Production**](#Chapter-4---Organic-Matter-Production)\n 1. [**Chapter 10 - Carbon Cycle, CO2, Climate**](#Chapter-10---Carbon-Cycle,-CO2,-Climate)\n\n# Chapter 4 - Organic Matter Production\n\n**4.10** Assume the composition of organic matter is $(CH_2)_{30}(CH_2O)_{76}(NH_3)_{16}(H_3PO_4)$\n\n(a) Calculate the C:N:P stoichiometric ratio of this organic matter\n\n*Ans:*\n$$\nC:N:P = 106:16:1 \n$$\n\n(b) Calculate the amount of $O_2$ that would be required to oxidize this material if $H_3PO_4$, $HNO_3$, $H_2O$, and $CO_2$ are the oxidation products of phosphorus, nitrogen, hydrogen, and carbon, respectively. Give the full equation for the oxidation reaction. ...\n\n*Ans:* Since organic matter has $C:N:P = 106:16:1$, 1mol organic reactant finally becomes 106mol $CO_2$, 16mol $HNO_3$, 1mol $H_3PO_4$. Then we add $H_2O$ to balance hydrogen, we will get: \n $$\n (CH_2)_{30}(CH_2O)_{76}(NH_3)_{16}(H_3PO_4) + 193O_2 \\longrightarrow 106CO_2 + 16HNO_3 + H_3PO_4 + 122H_2O\n $$\n\n(c) Suppose water upwelling to the surface has a total carbon concentration of $2000\\ mmol/m^3$, an oxygen concentration of $160\\ mmol/m^3$, a nitrate concentration of $5\\ mmol/m^3$, and a phosphate concentration of $1\\ mmol/m^3$. \n \n * Which of these nutrients is likely to limit production if the light supply is adequate and there is NO nitrogen fixation? \n * Which of the elements will limit production if nitrogen fixation is allowed? \n * In each case, calculate the concentration of the remaining nutrients after the limiting nutrient is exhausted. \n \n *Ans:* photosynthesis consume nutrients in the ratio of $C:N:P = 106:16:1$. So if there is no nitrogen fixation, nitrate is the main source of $N$ and it is the limiting nutrient, when nitrate runs out, we still have $1 - 5/16 = 0.6875\\ mmol/m^3$ phosphate.\n \n *Ans:* If nitrogen fixation is allowed, then atmospheric bi-nitrogen could also be a source of $N$ and this time phosphate is the limiting nutrient. The concentration of the remaining nutrients depends on the intensity of nitrogen fixation relative to photosynthesis.\n \n \n \n\n\n\n\n**4.11** Nitrate may serve as the terminal electron acceptor (i.e., oxidant) for the remineralization\nof organic matter if oxygen is not available. The nitrate loses its oxygen and is converted to\ndissolved N2, in the process of which it gains electrons. This is referred to as *denitrification*.\n\n(a) Write a balanced equation for the oxidation of the organic matter in problem 4.10 by\ndenitrification. Assume that the organic matter reacts with nitrate in the form $HNO_3$, and\nthat all the nitrogen present in both the organic matter and nitrate is converted to $N_2$. All\nother oxidation products are as in problem 4.10 (b)\n\n*Ans:*\n$$\n(CH_2)_{30}(CH_2O)_{76}(NH_3)_{16}(H_3PO_4) + 107HNO_3 \\longrightarrow 106CO_2 + 61.5N_2 + H_3PO_4 + 185H_2O\n$$\n\n(b) What fraction of the $N_2$ in (a) comes from nitrate?\n\n*Ans:*\n$$\n107/(61.5*2) = 0.8699\n$$\n\n**4.14** ... In this problem, you are to estimate the diurnally (24 hr) averaged light supply function $\\gamma_P(I_0)$ at the surface of the ocean, which we will define as\n$\\left<\\gamma_P(I_0)\\right>$. Assume that $I_n = 1000\\ W/m^2$, and that the diurnal variation of the irradiance function $f(\\tau)$ is given as a triangular function that increases linearly from 0 at 6 AM to 1 at noon, then back to 0 at 6 PM. Do this in two steps:\n\n(a) Starting with (4.2.13), give an equation for the surface irradiance, $I_0$ for the first 6 hours\nof daylight in terms of the time $t$ in hours, with $t$ set to 0 at daybreak. Assume that the\nfraction of photosynthetically active radiation (PAR) is $f_{PAR} = 0.4$ and that the cloud cover\ncoefficient $f(C) = 0.8$.\n\n*Ans*: Eq. (4.2.13) is\n\n$$\n I_0 = f_{PAR}\\cdot f(C) \\cdot f(\\tau) \\cdot I_n\n$$\n\nbased on the knowns, we have ($t$ in hours):\n\n\\begin{equation}\n I_0 = \\left\\{\n \\begin{array}{c}\n 320 \\times \\left(\\frac{1}{6}t-1\\right) \\qquad 6 < t < 12 \\\\\n 320 \\times \\left( 3-\\frac{1}{6}t\\right) \\qquad 12 < t < 18 \\\\\n 0 \\qquad 0 < t < 6, \\qquad 18 < t <24\n \\end{array}\n \\right.\n \\end{equation}\n\n(b) Calculate $\\left<\\gamma_P(I_0)\\right>$. Use the `Platt and Jassby` formulation (4.2.16). To calculate $I_k$ from\n(4.2.17), use for $V_P$ the typical $V_{max} = 1.4$ given in the text, and the representative value for $\\alpha$ of $0.025$. Solve the problem analytically by stepwise integration over the 24 hours of the day.\n\n*Ans*:\nBased on Eq. (4.2.17)\n$$\n I_k = \\frac{V_P}{\\alpha} = 56\\ W/m^2\n$$\n\nThen based on Eq. (4.2.16)\n$$\n \\gamma_P(I_0) = \\frac{I_0}{\\sqrt{I_k^2 + I_0^2}}\n$$\nSo we have:\n$$\n \\left<\\gamma_P(I_0)\\right> = \\frac1{24}\\int_0^{24}{\\gamma_P(I_0)dt}\n$$\nHere we solve it numerically:\n\n\n```python\nt = np.linspace(0, 24, 100)\nhit1 = (t>6)&(t<=12)\nhit2 = (t>12)&(t<=18)\nI0 = np.zeros(np.size(t))\nI0[hit1] = 320 * ((1./6) * t[hit1] - 1)\nI0[hit2] = 320 * (3 - (1./6) * t[hit2])\nIk = 56\nrI0 = I0/np.sqrt(Ik**2 + I0**2)\n```\n\n\n```python\nfig=plt.figure(figsize=(11, 5))\nax1=plt.subplot2grid((1, 2), (0, 0), colspan=1, rowspan=1)\nax2=plt.subplot2grid((1, 2), (0, 1), colspan=1, rowspan=1)\nax1.plot(t, I0, 'k-', linewidth=3); ax1.grid(); \nax1.set_xlabel('t in hours', fontweight=12)\nax1.set_ylabel('$I_0$', fontweight=12)\nax1.set_xlim(0, 24); ax1.set_ylim(0, 320)\nax2.plot(t, rI0, 'k-', linewidth=3); ax2.grid(); \nax2.set_xlabel('t in hours', fontweight=12)\nax2.set_ylabel('$\\gamma_P(I_0)$', fontweight=12)\nax2.set_xlim(0, 24); ax2.set_ylim(0, 1)\n```\n\n\n```python\ndelta_t = t[1]-t[0]\nresult = (1./24) * np.sum(rI0*delta_t)\nprint('Daily average of rI0 is: {}'.format(result))\n```\n\n Daily average of rI0 is: 0.420146160518\n\n\nSo light limits is important.\n\n**4.15** In this problem, you are to find the depth at which the diurnally averaged light supply $\\left<\\gamma_P\\left(I(z)\\right)\\right>$ crosses the threshold necessary for phytoplankton to achieve the minimum concentration at which zooplankton can survive, $0.60\\ mmol/m^3$. Use the temperature dependent growth rate given by the `Eppley relationship` (4.2.8) for a temperature of $10^\\circ C$, a mortality rate $\\lambda_P$ of $0.05\\ d^{-1}$, and a nitrate half-saturation constant $K_N$ of $0.1\\ mmol/m^3$. Assume that the total nitrate concentration $N_T$ is $10\\ mmol/m^3$. Do this in two steps:\n\n(a) Find the minimum light supply function $\\gamma_P(I)$ that is required in order for phytoplankton\nto cross the threshold concentration (assume zooplankton concentration $Z = 0$)\n\n*Ans:*\nThe steady state of phytoplankton in N-P-Z model:\n$$\nSMS(P) = 0 = V_{max}\\gamma_P(N)\\gamma_P(I) - \\lambda_P\n$$\n\nAnd now we try to solve light limits $\\gamma_P(I)$.\n\nThe threshold of phytoplankton $P = 0.60\\ mmol/m^3$, so we have the concentration of nutrient:\n$$\nN = N_T - P - Z = 9.4\\ mmol/m^3\n$$\nThen calling Eq. 4.2.11., nutrient limits is:\n$$\n\\gamma_P(N) = \\frac{N}{K_N+N} = 0.99\n$$\nFor the maximum growth rate, we have Eq. 4.2.8:\n$$\nV_{max} = V_P(T) = ab^{cT} = 0.6*1.066^{10} = 0.637\n$$\nThus the minimum light supply function is:\n$$\n\\gamma_P(I) = \\frac{\\lambda_P}{V_{max}\\gamma(N)} = 0.079\n$$\n\n(b) Assuming that $\\gamma_P(I)$ from (a) is equal to the diurnal average $\\left<\\gamma_P\\left(I(z)\\right)\\right>$, at what depth $H$ in\nthe ocean will the diurnally averaged light supply function cross the threshold you\nestimated in (a)? Assume that P is constant with depth and use a total attenuation\ncoefficient of $0.12\\ m^{-1}$.\n\n*Ans:*\n\nHere I borrowed 2 values from problem **4.14** $\\alpha = 0.025$, and $I_0 = 1000$.\n\nBased on Eq. (4.2.16), Eq. (4.2.17):\n\n$$\nI = \\frac{\\gamma_P(I)I_k}{\\sqrt{1-\\gamma_P(I)^2}}, \\qquad\\ I_k = \\frac{V_P}{\\alpha}\n$$\n\nFor the critical depth, growth equals to death, $V_P = \\lambda_P=0.05$, and we get $I = 0.1584$\n\nThen from Beer's Law:\n\n$$\nI = I_0\\exp(-KH), \\qquad\\ K=0.12\n$$\n\nSo we have:\n\n$$\nH = -\\frac1K\\ln\\frac{I}{I_0} = 72.92\\ m \n$$\n\nThis is the deepest place for zooplankton to survive, and phytoplankton has a concentration of $60\\ mmol/m^3$. \n\n#Chapter 10 - Carbon Cycle, CO2, Climate\n\n**10.4** Explain why the surface ocean concentration of anthropogenic CO2 is higher\nin low latitudes than it is in high latitudes. Why is it higher in the Atlantic\nthan in the Pacific ?\n\n*Ans:*\n\nThe basic idea is the variation of buffering factor $\\gamma_{DIC}$ is more important than the solubility of $\\mathrm{CO_2}$\n\nIf we integrate eq(10.2.16) begin with *Anthropocene*, $C_{ant}$ is a function of $\\gamma_{DIC}$:\n$$\n C_{ant}(t) = \\int_{t=t_\\pi}^{t_0}{\\frac{\\partial DIC}{\\partial t}dt} = \\frac1{\\gamma_{DIC}}\\frac{DIC}{pCO_2^{oc}}\\left(\\left.pCO_2^{atm}\\right|_{t_0}^{t_\\pi}\\right)\n$$\n\n * Tropics has low $\\gamma_{DIC}$ so high accumulated $C_{ant}$ takeup;\n * High-latitude regions has high $\\gamma_{DIC}$ so ...\n * Atlantic has a lower $\\gamma_{DIC}$ than Pacific due to its high *Alk* (see eq(10.2.11))\n\n**10.5** How long will it take for a pulse of $\\mathrm{CO_2}$ emitted into the atmosphere to be reduced to 50%, 20%, 10%, and 1% of its original value? For each answer list? which process is the primary one responsible for the removal of $\\mathrm{CO_2}$ from the atmosphere at the point in time the threshold is crossed.\n\n*Ans:*\n\nWe have many choices of impulse response functions (IRF), a simple one used by IPCC-SAR is: \n$$\nIRF = A_0 + \\sum_{i=1}^5{A_i\\exp\\left(-\\frac{t}{\\tau_i}\\right)}\n$$\n$A_i$ and $\\tau_i$ are empirical values, $t$ for \"year\" (details here)\n\n\n```python\ndef IRF_IPCC(A, tau, t):\n IRF = A[0]*np.ones(t.shape)\n for i in range(5):\n IRF = IRF + A[i+1]*np.exp(-1*t/tau[i])\n return IRF\n```\n\n\n```python\nA_std = np.array([0.1369, 0.1298, 0.1938, 0.2502, 0.2086, 0.0807])\ntau_std = np.array([371.6, 55.7, 17.01, 4.16, 1.33])\nt = np.linspace(0, 500, 501)\nIRF = IRF_IPCC(A_std, tau_std, t)\n```\n\n\n```python\nfig = plt.figure(figsize=(10, 4)); ax = fig.gca();ax.grid()\nplt.plot(t, IRF, 'k-', linewidth=3.5)\nax.set_title('IRF v.s. time', fontsize=14)\n```\n\n\n```python\nhit = np.flipud(t)[np.searchsorted(np.flipud(IRF), [0.5, 0.2])]\nprint('Time to reduced to 50% is {} year, to 20% is {} year'.format(hit[0], hit[1]))\n```\n\n Time to reduced to 50% is 16.0 year, to 20% is 276.0 year\n\n\nFor 50%, DIC buffering is dominate. For 20%, it costs 276 yr and DIC buffering is nearly saturate (see Fig.10.2.3), and $\\mathrm{CaCO_3}$ buffering begin to dominate.\n\n**10.8** Explain the apparent paradox that the tropical Pacific is viewed as being a\nlarge sink for anthropogenic $\\mathrm{CO_2}$, despite the fact that it is a region of net\noutgassing of $\\mathrm{CO_2}$.\n\n*Ans:*\n\nAccording to **10.4** we know that tropical ocean takes up more $Ant_{C}$ because it has a lower $\\gamma_{DIC}$. The outgassing in tropical Pacific is due to the upwelling and inefficient biological pump, these are the business of natural carbon (and since natural carbon cycle is in equilibrium, this outgassing is balanced by some other downwelling regions). \n\n**10.13**\n", "meta": {"hexsha": "765acb9e12488e74fb7e7bb7f010d9541b077d3c", "size": 67478, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "EOSC_576/EOSC_576_Problems.ipynb", "max_stars_repo_name": "yingkaisha/Homework", "max_stars_repo_head_hexsha": "fff00fb5a41513e0edf2b1f8d8a74687a1db7120", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-17T23:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T23:19:36.000Z", "max_issues_repo_path": "EOSC_576/EOSC_576_Problems.ipynb", "max_issues_repo_name": "yingkaisha/homework", "max_issues_repo_head_hexsha": "fff00fb5a41513e0edf2b1f8d8a74687a1db7120", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EOSC_576/EOSC_576_Problems.ipynb", "max_forks_repo_name": "yingkaisha/homework", "max_forks_repo_head_hexsha": "fff00fb5a41513e0edf2b1f8d8a74687a1db7120", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.5727109515, "max_line_length": 621, "alphanum_fraction": 0.7277927621, "converted": true, "num_tokens": 4361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.20434189993684582, "lm_q1q2_score": 0.08711536718406988}} {"text": "```javascript\n%%javascript\n$('#appmode-leave').hide();\n$('#copy-binder-link').hide();\n$('#visit-repo-link').hide();\n```\n\n# Water anomalies\nDespite its simple molecular structure, water is an exceptionally complicated fluid.\nMany of its properties do not follow the trends obeyed by other liquids and are often referred to as water anomalies.\nScientists often report more than 50 _anomalous_ properties of water, and some of the most well-known examples are\n1. Water has an unusually high melting point for a molecule of such a low molecular weight.\n2. Water has an unusually high boiling point for a molecule of such a low molecular weight.\n3. A liquid-liquid transition occurs at about 330 K.\n4. Pressure reduces ice's melting point.\n5. Cold liquid water has a high density that increases on warming (up to 3.984 °C).\n\nMost of these anomalous behaviours have been explained and there is ample scientific (and non-scientific) literature discussing them. As an example, this website [https://water.lsbu.ac.uk/water/water_anomalies.html](https://water.lsbu.ac.uk/water/water_anomalies.html) will provide a good overview, and plenty of references, on the topic.\n\nIn this numerical workshop you will use a computational technique called Molecular Dynamics (MD) to study the how the water density changes with temperature.\nMD is one of the most widely used type of atomistic simulations, and it is now routinely used in many research groups to complement experimental studies.\n\n## Molecular dynamics\nMolecular dynamics is conceptually very simple, an iterative solution of Newton's equations of motions at the atomic level, but subtly complicated to use for direct quantitative comparison with experiments.\nAlthough a detailed description of MD is beyond the scope of this laboratory, it is worth discussing some basic ideas for you to start appreciating the power and limitations of this technique. There are plenty of webpage and tutorials that describe the working principles of MD; Wikipedia has a fairly good an general overview of this topic [https://en.wikipedia.org/wiki/Molecular_dynamics]( https://en.wikipedia.org/wiki/Molecular_dynamics)\n\nIn MD the atoms are treated as point particles with a mass and a partial charge. Their interactions are described by simple empirical equations, such as the Coulomb and the van der Waals (dispersion) forces, supplemented with two-, three- or four-body interactions to better capture the covalent nature of the intramolecular bonds.\nFor example, in classical molecular dynamics the interaction *energy* between two non-bonded atoms separated by a distance, $r$, can be written as\n\n\\begin{equation}\nU_{ij} = \\frac{1}{4\\pi\\varepsilon_0}\\frac{q_i q_j}{r} + \\frac{A}{r^12} - \\frac{B}{r^6} \\tag{1}\n\\end{equation}\n\nWhere the first term is the Coulomb interaction and the last two the repulsive and attractive parts of the van der Waals interactions.\nOn the other hand the bonded two-, three- and four-body interactions between covalently bonded atoms are typically described by *harmonic* potentials\n\n\\begin{eqnarray}\nU_{ij}^b &=& K_b(b_{ij}-b_0)^2 \\tag{2} \\\\\nU_{ijk}^a &=& K_\\theta(\\theta_{ijk}-\\theta_0)^2 \\tag{3} \\\\\nU_{ijkl}^t &=& K_\\phi[1+\\cos(n\\phi_{jikl}-\\phi_0)]^2 \\tag{3} \\\\\n\\end{eqnarray}\n\nwhere $b_{ij}$, $\\theta_{ijk}$ and $\\phi_{jikl}$ are the bond lengths, angle and torsional angle between the atoms and the other quantities are fitting parameters, which are key to determine the accuracy of the simulations.\n\nOnce the interaction energy is known we can then compute the forces on the atoms as the sum of all pair-wise interactions\n\n\\begin{equation}\nF_i = \\sum_{j\\neq i} F_{ij} = -\\Bigg[\n \\sum \\frac{\\partial U_{ij}}{\\partial x_i} +\n \\sum \\frac{\\partial U_{ij}^a}{\\partial x_i} +\n \\sum \\frac{\\partial U_{ijk}^b}{\\partial x_i} +\n \\sum \\frac{\\partial U_{ijkl}^t}{\\partial x_i} \\Bigg] \\tag{5} \n\\end{equation}\n\nThen, by knowing the positions, velocities and forces for all the atoms at a certain time $t$, we can use the Newton's equations of motions to *predict* the positions and velocities of the particles after a certain (short) amount of time as passed\n\n\\begin{eqnarray}\na_i(t) &=& \\frac{F_i(t)}{m_i} \\tag{6} \\\\\nv_i(t+\\delta t) &=& v_i(t) + a_i(t)\\delta t \\tag{7} \\\\\nx_i(t+\\delta t) &=& x_i(t) + v_i(t)\\delta t + \\frac{1}{2}a_i(t)\\delta t^2 \\tag{8} \\\\\n\\end{eqnarray}\n\nwhere $a_i$, $v_i$ and $x_i$ are the acceleration, velocity and position of particle $i$, and $\\delta t$ is called the time step.\nThese three equations (or some variants of them) are usually called **equations of motions**.\nNow that we have the new atomic positions we can compute the new forces on the atoms, and use again the Newton's equations of motions to *propagate* the atoms' positions further. \nThis iterative procedure will generate a **trajectory** for the atoms, and by using energies and velocities collected along the way we will also get information about the temperature, pressure and other thermodynamic quantities of the system.\n\n\n### Importance of the time step\nThe time step is one of the most important quantities in MD, and it is key to understand the potentials and limitations of atomistic molecular dynamics simulations.\nIn fact, for the above equations of motions to be valid, the time step has to be short enough to describe the fastest **atomic** motion in the system, which in the case of water is the O-H stretching mode.\nThe O-H stretching has a vibrational frequency of approximately $1\\times10^{14}$Hz, *i.e* it takes about $1\\times10^{-14}$s to complete one oscillation. Therefore, if we want to describe this very fast atomic motion using discrete points in time we would need 10-20 snapshots. Hence the time step has to be of the order of 1~fs ($1\\times10^{-15}$s) or less.\n\nNow, let’s imagine running a simulation with a 1 fs time step and that the computer take 10 ms to calculate energies, forces and do one cycle of the equations of motions.\nIn the table below you can see how long it would you take to simulate a chemical or physical process depending on the time scale it experimentally occurs\n\n| Experimental time scale | Phenomenon | Simulation time \n| :-----: | :--------: |:---------\n| 10 fs | O-H vibration | 0.1 s\n| 1 ps | H-bond persistence | 10 s\n| 1 nm | Ion permeation through a membrane | 3 hours\n| 1$\\mu$s | Conformational rearrangement | 115 days \n| 1 ms | Protein folding (fast) | 317 days\n| 1 s | Protein folding (typical) | 317,000 days\n\nObviously, the time requires to do on MD cycles depends on the number of operations the computer has to perform, hence it increases with the system size.\nAlthough computational power has increased exponentially since MD was first introduced in the 1940s, we we can now afford to study systems of millions of atoms or hundreds of nm i size, there are still strong limitations to what can be reliably simulated due to the finite (small) number of atoms is included in the system (compared to Avogadro's number) and the short time scale that the simulation can span.\n\n### Ensemble\nMD codes are more complicated that a simple iterative solution of Newton's equations of motions and they include algorithms to control the temperature, pressure and other thermodynamics quantities of the system.\nOf particular relevance for this experience is the need to use **thermostats** and **barostats** to fix the boundary conditions of the simulations.\nFor this laboratory is not important to know the working details of these algorithms, but is key that you are aware that the variables relating to the temperature and pressure of the simulations are input parameters that may need to be changed.\n\n## Scope of the laboratory\nThe scope of this virtual experiment is to introduce you to atomistic molecular dynamics simulations and to compute the variations of the water density as a function of temperature, and to compare it with experimental values. As briefly mentioned above, the accuracy of the simulation depends on the parameters that are used to compute the intermolecular interactions. This laboratory will be run in groups and each of you will run individually MD calculations for a chosen water model and share the results with the other group members to be included in the final report (with proper acknowledgment of their origin).\n\nThe water models available for this laboratory are\n* SPC/E\n* TIP3P\n* TIP4P\n* TIP4P/ew\n* TIP5P\n\nwhich is a very small selections of the available models for water.\nThe models are listed in increasing level of complexity and one would reasonably expect that the more complex model gives more accurate results.\n\nYou will choose one model, in consultation with the other members of your team, and run a series of simulations to compute the water density at various conditions, to locate the water density maximum, if it exists for that model.\nEach simulation may take 5/10 minutes, you do not have to look at the simulation as it runs but it is important that your computed does not go to sleep or disconnect during the run time of the simulation. \nAlthough the files should remain on the server you should save a copy of the files on your local computer before disconnecting.\n\nYou can start by performing a few calculations around ambient conditions, say between 273 and 310 K, and then move to much lower temperature if needed.\n\nNote that the water will not freeze during your simulation even at fairly high undercooling, so you can go to quite low temperature without any real problems.\n\n## Final report\nThe final report for this experience should include your calculations for the water density as a function of temperature for a selection of the models, literature experimental data and a comparison with published MD results. Optionally you can also include data obtained by your peers for a different water potential.\nThe comparison with previous simulations should be done at least for the same water model that you have used in your simulations.\n\nYour report should show how you extracted the average density from the simulation output, and an estimate of the errors.\n\n\n## Launch virtual experiment\nLet's now have a look at the python notebook to run MD simulations\n[Molecular dynamics Simulation](md.ipynb)\n", "meta": {"hexsha": "f878d86de17cd17e70043c3641fca0ea05fb9b72", "size": 12439, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week_10_waterDensity/waterDensity.ipynb", "max_stars_repo_name": "blake-armstrong/TeachingNotebook", "max_stars_repo_head_hexsha": "30cdca5bffd552eaecc0368c3e92744c4d6d368c", "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": "week_10_waterDensity/waterDensity.ipynb", "max_issues_repo_name": "blake-armstrong/TeachingNotebook", "max_issues_repo_head_hexsha": "30cdca5bffd552eaecc0368c3e92744c4d6d368c", "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": "week_10_waterDensity/waterDensity.ipynb", "max_forks_repo_name": "blake-armstrong/TeachingNotebook", "max_forks_repo_head_hexsha": "30cdca5bffd552eaecc0368c3e92744c4d6d368c", "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": 67.2378378378, "max_line_length": 626, "alphanum_fraction": 0.6864699735, "converted": true, "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.20689404637077294, "lm_q1q2_score": 0.08662589777953476}} {"text": "```python\n#we may need some code in the ../python directory and/or matplotlib styles\nimport sys\nimport os\nsys.path.append('../python/')\n\n#set up matplotlib\nos.environ['MPLCONFIGDIR'] = '../mplstyles'\nprint(os.environ['MPLCONFIGDIR'])\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n#got smarter about the mpl config: see mplstyles/ directory\nplt.style.use('standard')\nprint(mpl.__version__) \nprint(mpl.get_configdir())\n\n\n#fonts\n# Set the font dictionaries (for plot title and axis titles)\ntitle_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',\n 'verticalalignment':'bottom'} # Bottom vertical alignment for more space\naxis_font = {'fontname':'Arial', 'size':'32'}\nlegend_font = {'fontname':'Arial', 'size':'22'}\n\n#fonts global settings\nmpl.rc('font',family=legend_font['fontname'])\n\n\n#set up numpy\nimport numpy as np\n```\n\n ../mplstyles\n 3.0.3\n /home/phys/villaa/analysis/misc/nrFano_paper2019/mplstyles\n\n\n# Summary\n\nIn this notebook we follow the logic for our analysis that defines an effective nuclear-recoil Fano factor for germanium. We use the other notebooks in this directory as supporting references and present the line of logic for our publication [REF]. \n\nIt is planned that all of the plots that go into the publication will be produced here from the data we have placed in the `data/` directory below this one. It is planned that all the data is referenced and where it came from is clear. \n\nThe basic idea of this analysis is that there are measurements in the literature that constrain the width (second moment) of the ionization distribution for various materials. This has also been predicted by Lindhard [REF]. This variance in the number of charges produced by a nuclear recoil of a given energy far exceeds what is measured from electron recoils. In the electron recoils this is parameterized by the Fano factor and so here we define the \"effective\" Fano factor for nuclear recoils. \n\nWhile the width of the ionization distribution has not been important in the past because of excellent discrimination between electron- and nuclear-recoil events above about 10 keV, it is becoming more important for dark matter searches interested in lower recoil energies [REF] (SuperCDMS low threshold) and discriminationless [REF] (CDMSlite & HVeV) searches. \n\n# 1. Lindhard has Predicted this Variance and Dougherty has Measured it for Silicon\n\nDougherty has measured this effect in silicon and shown that it is near the predicted values from Lindhard [[Dough92][Dough92]]. See the notebook `silicon_Fano.ipynb` for the details of how an effective Fano factor is extracted from this silicon measurement. \n\n[Dough92]: https://journals.aps.org/pra/abstract/10.1103/PhysRevA.45.2104 \"Dougherty paper 1992\"\n\nThe following table is a summary of those data along with the effective Fano estimate and uncertainty for each recoil energy data point measured in that publication.\n\nExperimental uncertainties are quoted as values following the \"$\\pm$\" symbol. The Observed width and Expected width are both in FWHM execpt for the 25.3 keV recoil energy point, which is quoted in half width at half max (HWHM). The excess fluctuation are given in 1$\\sigma$. \n\n## Table 1 of the paper:\n\nSi recoil energy (keV)|Observed ionization (keV)|Lindhard shift (keV)|Ionization efficiency (%)|Observed width (keV)|Expected width (keV)|Excess fluct. (%)| effective Fano\n:-|:-|:-|:-|:-|:-|:-|:-\n109.1$\\pm$0.7|55.5$\\pm$2|0.55|51.4$\\pm$2|16$\\pm$3|3.5$\\pm$0.4|6.1$\\pm$1.2|208$\\pm$40\n75.7 $\\pm$0.4|33.3$\\pm$0.4|0.31+0.94|45.6$\\pm$0.5|9.6$\\pm$1.0|1.1$\\pm$0.3|5.3$\\pm$0.6|123$\\pm$5\n25.3$\\pm$0.3|8.90$\\pm$0.1|0.074|35.5$\\pm$0.6|1.30$\\pm$0.04|0.75$\\pm$0.1|3.6$\\pm$0.3|24.3$\\pm$3.6\n7.50$\\pm$0.03|2.01$\\pm$0.02|0.012|26.9$\\pm$0.4|0.55$\\pm$0.07|0.24$\\pm$0.01|2.8$\\pm$0.4|5.75$\\pm$3.07\n4.15$\\pm$0.15|0.93$\\pm$0.02|0.008|22.5$\\pm$0.5|0.32$\\pm$0.06|0.236$\\pm$0.005|2.2$\\pm$0.9|2.35$\\pm$9.21\n\n\n```python\nimport dataPython as dp\nimport numpy as np\n\nlind_data0 = dp.getXYdata('data/lindhard2_OmegaepsD_fmt.txt')\nlind_data1 = dp.getXYdata('data/lindhard2_OmegaepsE_fmt.txt')\n\nlindD_e = np.asarray(lind_data0['xx'])\nlindD = np.asarray(lind_data0['yy'])\nlindE_e = np.asarray(lind_data1['xx'])\nlindE = np.asarray(lind_data1['yy'])\n```\n\n\n```python\nEsi = np.vectorize(lambda x: np.sqrt(2)*2*x/(6.87758e-5*1000))\n```\n\n\n```python\n#create a yield model\nimport lindhard as lind\n\n#lindhard\nlpar = lind.getLindhardPars('Si',True) #use the \"calculated\" value of k\nprint(lpar)\n#ylind = lind.getLindhard(lpar)\nylind = lind.getLindhardSi_k(0.15)\nylindv = np.vectorize(ylind) #careful, this expects inputs in eV\n```\n\n {'Z': 14, 'A': 28, 'k': 0.14600172346755985, 'a': 3.0, 'b': 0.15, 'c': 0.7, 'd': 0.6}\n\n\n\n```python\n#convert the vectors\nepsg = 3.8e-3 #keV average energy per electron-hole pair created\n\n\nF_D = Esi(lindD_e)*(1/(epsg*ylindv(1000*Esi(lindD_e))))*lindD\nF_E = Esi(lindE_e)*(1/(epsg*ylindv(1000*Esi(lindE_e))))*lindE\n```\n\n\n```python\n#get Dougherty Data\nddataY = dp.getXYdata_wXYerr('data/Dougherty_Yield.txt')\nddataFluct = dp.getXYdata_wXYerr('data/Dougherty_Fluct.txt')\n\nddataY_G = dp.getXYdata_wXYerr('data/Gerbier_Yield.txt')\nddataFluct_G = dp.getXYdata_wXYerr('data/Gerbier_Fluct.txt')\n\n#convert to numpy arrays\nddata_e = np.asarray(ddataFluct['xx'])\nddata_fluct = np.asarray(ddataFluct['yy'])\nddata_fluct_err = np.asarray(ddataFluct['ey'])\n\nddata_Y = np.asarray(ddataY['yy'])\nddata_Y_err = np.asarray(ddataY['ey'])\nprint(ddata_Y)\nprint(ddata_Y_err)\n\nddataG_e = np.asarray(ddataFluct_G['xx'])\nddataG_fluct = np.asarray(ddataFluct_G['yy'])/1000\nddataG_fluct_err = np.asarray(ddataFluct_G['ey'])/1000\nprint(ddataG_e)\nprint(ddataG_fluct)\n\nddataG_Y = np.asarray(ddataY_G['yy'])\nddataG_Y_err = np.asarray(ddataY_G['ey'])\nprint(ddataG_Y)\nprint(ddataG_Y_err)\n\nepsg = 3.8e-3 #epsilon-gamma for silicon in keV per pair\nddata_fluct_F = (ddata_fluct/100)**2 * (ddata_e/(epsg*(ddata_Y/100)))\n#ddata_fluct_F_err = (ddata_fluct_err/100)**2 * (ddata_e/(epsg*(ddata_Y/100)))\nddata_fluct_F_err = np.sqrt(((ddata_fluct/100)*(2*ddata_e/(epsg*(ddata_Y/100))))**2*(ddata_fluct_err/100)**2 \\\n +((ddata_fluct/100)**2*(ddata_e/(epsg*(ddata_Y/100)**2)))**2*(ddata_Y_err/100)**2 )\nprint(ddata_fluct_F_err)\nddata_fluct_F_err_A = np.sqrt(((ddata_fluct/100)*(2*ddata_e/(epsg*(ddata_Y/100))))**2*(ddata_fluct_err/100)**2)\nddata_fluct_F_err_B = np.sqrt(((ddata_fluct/100)**2*(ddata_e/(epsg*(ddata_Y/100)**2)))**2*(ddata_Y_err/100)**2 )\nddata_fluct_F_err = np.sqrt(ddata_fluct_F_err_A**2 + ddata_fluct_F_err_B**2)\n \nddata_fluct_F_G = (ddataG_fluct/ddataG_e)**2 * (ddataG_e/(epsg*(ddataG_Y/100)))\n#ddata_fluct_F_err = (ddata_fluct_err/100)**2 * (ddata_e/(epsg*(ddata_Y/100)))\nddata_fluct_F_err_G = np.sqrt(((ddataG_fluct/ddataG_e)*(2*ddataG_e/(epsg*(ddataG_Y/100))))**2*(ddataG_fluct_err/ddataG_e)**2 \\\n +((ddataG_fluct/ddataG_e)**2*(ddataG_e/(epsg*(ddataG_Y/100)**2)))**2*(ddataG_Y_err/100)**2 )\n\nddata_fluct_F_err_G_A = np.sqrt(((ddataG_fluct/ddataG_e)*(2*ddataG_e/(epsg*(ddataG_Y/100))))**2*(ddataG_fluct_err/ddataG_e)**2)\nddata_fluct_F_err_G_B = np.sqrt(((ddataG_fluct/ddataG_e)**2*(ddataG_e/(epsg*(ddataG_Y/100)**2)))**2*(ddataG_Y_err/100)**2 )\nddata_fluct_F_err_G = np.sqrt(ddata_fluct_F_err_G_A**2 + ddata_fluct_F_err_G_B**2) \n \nprint(ddata_fluct_F)\nprint(ddata_fluct_F_err)\nprint(ddata_fluct_F_G)\nprint(ddata_fluct_F_err_G)\n```\n\n [51.4 45.6 35.5 26.9 22.5]\n [2. 0.5 0.6 0.4 0.5]\n [21.7 19.5 13.5 8.6 4.7 4.15 3.9 3.3 ]\n [1. 1.101 0.601 0.348 0.185 0.166 0.241 0.131]\n [40.7 38.7 33.6 31.1 26.6 27.4 22.9 25.9]\n [0.5 0.7 0.7 0.5 0.8 0.8 2. 1.6]\n [82.17366352 27.81718869 4.07177705 1.64573833 1.92281409]\n [207.84410199 122.71543167 24.30600445 5.75229896 2.34923977]\n [82.17366352 27.81718869 4.07177705 1.64573833 1.92281409]\n [29.79629465 42.27128645 20.95522371 11.91560371 7.2041105 6.37725701\n 17.11395553 5.28378686]\n [3.53496608 8.32817692 2.96120797 0.91062459 2.81212102 3.00232178\n 9.49203685 4.44875839]\n\n\n## Figure 1 of the Paper:\n\n\n```python\n#set up a plot\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import InsetPosition\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nxmax=10\n\nax1.errorbar(ddata_e,ddata_fluct_F,yerr=[ddata_fluct_F_err,ddata_fluct_F_err], marker='o', markersize=8, \\\n ecolor='k',color='k', linestyle='none', label='Dougherty eff. F', linewidth=2)\nax1.errorbar(ddataG_e,ddata_fluct_F_G,yerr=[ddata_fluct_F_err_G,ddata_fluct_F_err_G], marker='^', markersize=8, \\\n ecolor='k',color='k', linestyle='none', label='Gerbier eff. F', linewidth=2)\n\n\n#ax1.plot (X, diff, 'm-', label='Thomas-Fermi (newgrad)')\n#ax1.plot (Esi(epr), 100*np.sqrt(f_Omega2_eta2(epr))*ylindv(1000*Esi(epr)), 'g-', label='$\\Omega/\\epsilon$ (NAC III approx. D)')\nax1.plot (Esi(lindD_e), F_D, 'k-', label='eff. F (Lind. approx. D)')\nax1.plot (Esi(lindE_e), F_E, 'k--', label='eff. F (Lind. approx. E)')\n\n\n\n\nax1.set_yscale('linear')\nax1.set_xscale('linear')\nax1.set_xlim(Esi(0), 150)\nax1.set_ylim(0.1,300)\nax1.set_xlabel('recoil energy ($E_r$) [keV]',**axis_font)\nax1.set_ylabel('effective Fano factor',**axis_font)\n#ax1.grid(True)\n#ax1.xaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=4,prop={'size':22})\n\n###Make inset\nbbox_ll_x = 0.07\nbbox_ll_y = -0.0225\nbbox_w = 1\nbbox_h = 1\neps = 0.01\naxins = inset_axes(ax1, height=\"35%\", width=\"55%\", bbox_to_anchor=(bbox_ll_x,bbox_ll_y,bbox_w-bbox_ll_x,bbox_h), loc='upper left',bbox_transform=ax1.transAxes)\n#ax1.add_patch(plt.Rectangle((bbox_ll_x, bbox_ll_y+eps), bbox_w-eps-bbox_ll_x, bbox_h-eps, ls=\"--\", ec=\"c\", fc=\"None\",\n# transform=ax1.transAxes))\n\n#axins = plt.axes([0,0,1,1])\n#axins_pos = InsetPosition(ax3, [0.25, 0.65, 0.7, 0.3])\n#axins.set_axes_locator(axins_pos)\n\n# larger region than the original image\nx1, x2, y1, y2 = 0, 10, 0, 20\naxins.set_xlim(x1, x2)\naxins.set_ylim(y1, y2)\n\n\n\naxins.errorbar(ddata_e,ddata_fluct_F,yerr=[ddata_fluct_F_err,ddata_fluct_F_err], marker='o', markersize=8, \\\n ecolor='k',color='k', linestyle='none', label='', linewidth=2)\naxins.errorbar(ddataG_e,ddata_fluct_F_G,yerr=[ddata_fluct_F_err_G,ddata_fluct_F_err_G], marker='^', markersize=8, \\\n ecolor='k',color='k', linestyle='none', label='', linewidth=2)\naxins.plot (Esi(lindD_e), F_D, 'k-', label='')\naxins.plot (Esi(lindE_e), F_E, 'k--', label='')\n\naxins.yaxis.grid(True,which='minor',linestyle='--')\naxins.xaxis.grid(True,which='minor',linestyle='--')\naxins.grid(True)\n####\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\n#plt.tight_layout()\nplt.savefig('figures/paper_figures/SiFano_Figure1.eps')\nplt.savefig('figures/paper_figures/SiFano_Figure1.pdf')\nplt.show()\n```\n\n# 2. Edelweiss has Observed Anomalous NR Widening in Germanium\n\nThe 2004 EDELWEISS publication [[Edw04][Edw04]] has published a detailed and complete analysis of the measured resolutions for 7 cryogenic germanium detectors that they used for dark matter searches about ~10 keV analysis thresholds. \n\nIn this paper it was recognized (in a similar way to the Doughterty measurement) that the measured ionization yield width was larger than expected. This effect remained even after estimating the nuclear recoil band widening based on multiple-scatters. The point in this section is to estimate how much wider the measured nuclear recoil band was than the _single-scatter_ prediction. \n\n[Edw04]: https://doi.org/10.1016/j.nima.2004.04.218 \"EDELWEISS 2004 Publication\"\n\nThe single-scatter prediction for the ionization yield width can be analytically estimated based on the ionization and heat channel resolutions. Each of those resolutions is extracted for each detector in the publication by the following functional forms (see the notebook `edelweiss_res.ipynb`):\n\n\\begin{equation}\n\\begin{aligned}\n\\sigma_I(E_I) &= \\sqrt{(\\sigma_I^0)^2 + (a'_I E_I)^2} \\\\\n\\sigma_H(E_H) &= \\sqrt{(\\sigma_H^0)^2 + (a'_H E_H)^2},\n\\end{aligned}\n\\end{equation}\n\nwhere $E_H$ is a recoil energy estimator (unbiased for electron-recoils) based on the heat signal, and $E_I$ is a recoil energy estimator (again unbiased for electron-recoils) based on the ionization signal. \n\nIn the EDELWEISS paper the recoil energy, an estimator for the true recoil energy of an event, is defined as follows:\n\n\\begin{equation}\nE_r = \\left(1+\\frac{V}{\\epsilon_{\\gamma}}\\right)E_H - \\frac{V}{\\epsilon_{\\gamma}} E_I, \n\\end{equation}\n\nwhere $V$ is the voltage, and $\\epsilon_{\\gamma}$ is the average energy to create a single electron-hole pair. Finally, the ionization yield, Q, is defined as:\n\n\\begin{equation}\nQ = \\frac{E_I}{E_r}\n\\end{equation}\n\nGiven these definitons, if one _assumes_ a normal distribution for the resulting ionization yield distribution and propagates the uncertainty on Q via the equations above and a first-order Taylor expansion the result is the one published by EDELWEISS [[Edw04][Edw04]]:\n\n\\begin{equation}\n\\sigma_{Q}^0(E_r) = \\sqrt{\\frac{1}{E^2_r} \\left( \\left(1+\\frac{V}{\\epsilon_{\\gamma}}\\langle Q\\rangle\\right)^2\\sigma_I^2 + \\left( 1+\\frac{V}{\\epsilon_{\\gamma}}\\right)^2\\langle Q\\rangle^2\\sigma_H^2\\right)},\n\\end{equation}\n\nwhere $\\langle Q \\rangle$ is the average ionization yield as a function of recoil energy. \n\n[Edw04]: https://doi.org/10.1016/j.nima.2004.04.218 \"EDELWEISS 2004 Publication\"\n\nIn order to discover how much the effective Fano factor for nuclear recoils is contributing we want to first see how much wider the nuclear recoil band is than this estimate. In the EDELWEISS paper [[Edw04][Edw04]], this is done by simply adding a constant in quadrature:\n\n\\begin{equation}\n\\sigma_{Q}(E_r) = \\sqrt{(\\sigma_{Q}^{0})^2 + C^2}\n\\end{equation}\n\nThe constant C comes out to be _around_ 0.04, and this is larger than the expected effect of multiple-scattering (see Section 3). \n\nTo duplicate this fit for the EDELWEISS detector \"GGA3\" and add fitting uncertainties, we have first computed the full non-normal ionization yield distribution from the resolutions, it shows that the EDELWEISS analytical form very slightly underpredicts the ionization yield width. We call this function $\\tilde{\\sigma}_{Q}^0$. \n\n[Edw04]: https://doi.org/10.1016/j.nima.2004.04.218 \"EDELWEISS 2004 Publication\"\n\n\n```python\n# import data from Edelweiss\nimport pandas as pds\nres_data = pds.read_csv(\"data/edelweiss_NRwidth_GGA3_data.txt\", skiprows=1, \\\n names=['E_recoil', 'sig_NR', 'E_recoil_err', 'sig_NR_err'], \\\n delim_whitespace=True)\n\nresER_data = pds.read_csv(\"data/edelweiss_ERwidth_GGA3_data.txt\", skiprows=1, \\\n names=['E_recoil', 'sig_ER', 'sig_ER_err'], \\\n delim_whitespace=True)\n\nresER_data = resER_data.sort_values(by='E_recoil')\n\nprint (res_data.head(10))\nE_recoil = res_data[\"E_recoil\"]\nsig_NR = res_data[\"sig_NR\"]\nsig_NR_err = res_data['sig_NR_err']\nE_recoil_ER = resER_data[\"E_recoil\"]\nsig_ER = resER_data[\"sig_ER\"]\nsig_ER_err = resER_data['sig_ER_err']\n```\n\n E_recoil sig_NR E_recoil_err sig_NR_err\n 0 16.1946 0.062345 0.946176 0.001157\n 1 16.4428 0.062345 0.945278 0.001157\n 2 44.2627 0.046528 0.992477 0.001543\n 3 24.5012 0.059397 0.992477 0.001185\n 4 97.7172 0.044847 1.033260 0.002783\n 5 58.4014 0.050082 0.991830 0.002288\n 6 34.2156 0.053417 1.033260 0.001102\n\n\n\n```python\nimport h5py\nfilename = 'data/sims.h5'\n#remove vars\nf = h5py.File(filename,'r')\n\n#save the results for the Edw fit\npath='{}/'.format('ER')\n\nxE = np.asarray(f[path+'xE'])\nqbootsigs = np.asarray(f[path+'qbootsigs'])\nqbootsigerrsu = np.asarray(f[path+'qbootsigerrsu'])\nqbootsigerrsl = np.asarray(f[path+'qbootsigerrsl'])\n\n\nf.close()\n```\n\n\n```python\n#get the resolutions for GGA3\nimport EdwRes as er\n\naH=0.0381\nV=4.0\nC=0.0\nsigHv,sigIv,sigQerv,sigH_NRv,sigI_NRv,sigQnrv = er.getEdw_det_res('GGA3',V,'data/edw_res_data.txt',aH,C)\n\nimport fano_calc as fc\n\n#recall defaults (filename='test.h5', \n#det='GGA3',band='ER',F=0.00001,V=4.0,alpha=(1/10000.0),aH=0.035,Erv=None,sigv=None,erase=False)\nE,sig = fc.RWCalc(filename='data/res_calc.h5')\n\nprint(np.shape(E))\n```\n\n (200,)\n\n\nIn the figure below, the functon $\\tilde{\\sigma}_{QER}^0$ is shown as the solid curve. This curve is the electron-recoil version of the correct single-scatter ionization yield width $\\tilde{\\sigma}_{Q}^0$. The dashed curve is the resolution predicted from the EDELWEISS publication assuming a normal distribution for the ionization at each measured recoil energy. \n\nBoth of these are using the adjusted resolution parameter $a_H^{\\prime}$ equal to:\n\n\\begin{equation}\na_H^{\\prime} = \\frac{0.0386}{2\\sqrt{2\\log(2)}}.\n\\end{equation}\n\nThis adjustment was done in the EDELWEISS publication to fit the measured width of the electron recoil band [[Edw04][Edw04]]. \n\n[Edw04]: https://doi.org/10.1016/j.nima.2004.04.218 \"EDELWEISS 2004 Publication\"\n\n\nAlso shown in the figure is a high-statistics set of simulated data with the same resolutions (same value of $a_H^{\\prime}$) and the experimental data of EDELWEISS [[Edw04][Edw04]].\n\n## Figure 2a of the Paper:\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nmask = [True, True, False, False, True, True, True, True, True]\n\n\n\nX=np.arange(0.1,200,0.1)\n\n\nax1.plot(X,sigQerv(X),color='r',linestyle=\"--\",linewidth=2, \\\n label='single-scatter res. model (ER) (aH={})'.format(aH))\nax1.plot(E,sig,color='r',linestyle=\"-\",linewidth=2, \\\n label='single-scatter res. model (ER) (aH={})'.format(aH))\nax1.errorbar(xE,qbootsigs, yerr=(qbootsigerrsl,qbootsigerrsu), \\\n color='k', marker='o',markersize=4,linestyle='none',label='ER scatters', linewidth=2)\nax1.errorbar(E_recoil_ER[mask],sig_ER[mask], yerr=sig_ER_err[mask], \\\n color='k', marker='^',markersize=8,linestyle='none',label='Edw. ER scatters', linewidth=2)\n\n\n\n\nymin = 0.04\nymax = 0.066\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(40, 200) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\nplt.savefig('figures/paper_figures/ERyieldWidth_Figure2a.eps')\nplt.savefig('figures/paper_figures/ERyieldWidth_Figure2a.pdf')\nplt.show()\n```\n\nWith the value of $a_H^{\\prime}$ specified by the fit above, it is possible to calculate the expected single-scatter nuclear recoil ionization yield width as a function of energy, $\\tilde{\\sigma}_{Q}^0(E_r)$. \n\nWith this function in hand, we can then repeat the fit done in the EDELWEISS paper using the corrected version of the equation above:\n\n\\begin{equation}\n\\sigma_{Q} = \\sqrt{(\\tilde{\\sigma}_{Q}^0)^2 + C^2}.\n\\end{equation}\n\nFurthermore, we allow the parameter C to be a linear function of energy, to improve the fit quality, $C = C_0 + mE_r$. This fit is displayed in the figure below. \n\n\n```python\nfilename = 'data/systematic_error_fits.h5'\n#remove vars\nf = h5py.File(filename,'r')\nfor i in f['mcmc/edwdata_sys_error']:\n print(i)\n\n#save the results for the Edw fit\npath='{}/{}/'.format('mcmc','edwdata_sys_error')\n\nCms = np.asarray(f[path+'Cms'])\nslope = np.asarray(f[path+'m'])\na_yield = np.asarray(f[path+'A'])\nb_yield = np.asarray(f[path+'B'])\naH = np.asarray(f[path+'aH'])\nscale = np.asarray(f[path+'scale'])\nsamples = np.asarray(f[path+'samples'])\nsampsize = np.asarray(f[path+'sampsize'])\nxl = np.asarray(f[path+'Er'])\nupvec = np.asarray(f[path+'Csig_u'])\ndnvec = np.asarray(f[path+'Csig_l'])\nSigtot = np.asarray(f[path+'Sigss'])\nSigss = np.sqrt(Sigtot**2 - (Cms+slope*xl)**2)\n\nprint(Cms)\nprint(samples[0:5,:])\nf.close()\nprint(np.shape(samples))\n```\n\n A\n B\n Cms\n Csig_l\n Csig_u\n Er\n Sigss\n aH\n m\n samples\n sampsize\n scale\n 0.0401182258\n [[1.65991113e-02 3.17938117e-02 1.72848169e-04 9.60623060e-01\n 2.53571472e-01 3.89854952e-02]\n [1.64140930e-02 3.62294874e-02 1.21912111e-04 9.89509101e-01\n 1.72416566e-01 1.04542858e-01]\n [1.64008065e-02 3.62266219e-02 1.25921253e-04 9.95054885e-01\n 1.72930975e-01 1.00686204e-01]\n [1.62507246e-02 3.65956482e-02 1.11214649e-04 1.00693739e+00\n 1.64393892e-01 1.03460830e-01]\n [1.61375604e-02 3.63839307e-02 1.10043601e-04 1.01873876e+00\n 1.64451219e-01 1.12642479e-01]]\n (470000, 6)\n\n\n## Figure 2b of the Paper:\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nprint(np.shape(samples[np.random.randint(len(samples), size=100)]))\n#for Cms_em, m_em in samples[np.random.randint(len(samples), size=100)]:\nfor aH_em, Cms_em, m_em, scale_em, A_em, B_em in samples[np.random.randint(len(samples), size=100)]:\n ax1.plot(xl, np.sqrt(Sigss**2+(Cms_em+m_em*xl)**2), color=\"orange\", alpha=0.1)\n\nax1.plot(xl,upvec,color='r',linestyle=\"--\",linewidth=2, \\\n label='1$\\sigma$ fluct.')\nax1.plot(xl,dnvec,color='r',linestyle=\"--\",linewidth=2, \\\n label='')\n\nax1.plot(xl,np.sqrt(Sigss**2+(Cms+xl*slope)**2),color='g',linestyle=\"-\",linewidth=3, \\\n label='(C$_0$={:01.3}; m={:01.2E})'.format(Cms,slope))\n\nax1.errorbar(E_recoil[2::],sig_NR[2::], yerr=sig_NR_err[2::], \\\n color='k', marker='o', markersize=4,linestyle='none',label='NR Edw. Measurement', linewidth=2)\n\nymin = 0.04\nymax = 0.1\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(10, 200) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\nplt.savefig('figures/paper_figures/EdwyieldWidthFit_Figure2b.eps')\nplt.savefig('figures/paper_figures/EdwyieldWidthFit_Figure2b.pdf')\nplt.show()\n```\n\n# 3. Multiple-Scattering Cannot Account for All of the Yield Broadening\n\nAn obvious candidate, _aside_ from an intrinsic effective Fano factor, that might account for the yield broadening observed over the single-scatter prediction is multiple-scattering. If a neutron enters the detector and scatters more than once, the known non-linearity of the average ionization yield for each collison **_guarantees_** that the total yield will fluctuate to lower values than expected given the **_total_** energy deposited. \n\nWe use a Monte Carlo simulation of neutron scattering from a $^{252}$Cf source to approximate this effect. The following empirical single-scatter yield model is used since it approximates the EDELWEISS data fairly well:\n\n\\begin{equation}\n\\langle Q \\rangle = 0.16E_r^{0.18}. \n\\end{equation}\n\nWe apply this yield model to _each individual scatter_ in the simulated data and then sum to obtain the expected measured ionization yield, also folding in the measured EDELWEISS sensor resolutions appropriately. \n\n\n```python\nimport observable_simulations as osim\n\nQ,Ernr,Q_ss,Ernr_ss = osim.simQEr()\n\nEmin = 20 \nEmax = 30\n\nimport histogram_yield as hy\n\nbindf, bindfE = hy.QEr_Ebin(Q, Ernr, bins=[Emin, Emax],silent=True)\n\nqbins = np.linspace(0,0.6,40)\nxcq = (qbins[:-1] + qbins[1:]) / 2\n\nfor i,Qv in enumerate(bindf):\n n,nx = np.histogram(Qv,bins=qbins)\n \n \nbindf_ss, bindfE_ss = hy.QEr_Ebin(Q_ss, Ernr_ss, bins=[Emin, Emax],silent=True)\n\nfor i,Qv in enumerate(bindf_ss):\n n_ss,nx_ss = np.histogram(Qv,bins=qbins)\n \n```\n\n## Figure 3a of the Paper:\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\n\nmshist = n/np.sum(n)/np.diff(xcq)[0]\nsshist = n_ss/np.sum(n_ss)/np.diff(xcq)[0]\n\nestring = r'${}\\mathrm{{keV}}< E_r \\leq {}\\mathrm{{keV}}$'.format(Emin,Emax)\n#print(estring)\nax1.step(xcq,mshist, where='mid',color='m', linestyle='-', \\\n label='multiple scatters {}'.format(estring), linewidth=2)\nax1.step(xcq,sshist, where='mid',color='b', linestyle='-', \\\n label='single scatters'.format(estring), linewidth=2)\n\nymin = 0.0\nymax = 10\n\nblue = '#118DFA'\nax1.fill_between(xcq,np.zeros(np.shape(xcq)),mshist,step='mid',facecolor='m',alpha=0.4, \\\n label='')\nax1.fill_between(xcq,np.zeros(np.shape(xcq)),sshist,step='mid',facecolor='b',alpha=0.4, \\\n label='')\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(0.0, 0.6) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'ionization yield',**axis_font)\nax1.set_ylabel('PDF',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\nplt.savefig('figures/paper_figures/MSyieldHist_Figure3a.eps')\nplt.savefig('figures/paper_figures/MSyieldHist_Figure3a.pdf')\nplt.show()\n```\n\n\n```python\nfilename = 'data/mcmc_fits.h5'\n#remove vars\nf = h5py.File(filename,'r')\n\n#save the results for the Edw fit\npath='{}/{}/'.format('mcmc','multiples')\n\nCms = np.asarray(f[path+'Cms'])\nslope = np.asarray(f[path+'m'])\nsamples = np.asarray(f[path+'samples'])\nsampsize = np.asarray(f[path+'sampsize'])\nxl = np.asarray(f[path+'Er'])\nupvec = np.asarray(f[path+'Csig_u'])\ndnvec = np.asarray(f[path+'Csig_l'])\nSigss = np.asarray(f[path+'Sigss'])\n\nf.close()\nprint(np.shape(samples))\n```\n\n (40000, 2)\n\n\n\n```python\nfilename = 'data/sims.h5'\n#remove vars\nf = h5py.File(filename,'r')\n\n#save the results for the Edw fit\npath='{}/'.format('NR')\n\nxE = np.asarray(f[path+'xE'])\nqbootsigs = np.asarray(f[path+'qbootsigs'])\nqbootsigerrsu = np.asarray(f[path+'qbootsigerrsu'])\nqbootsigerrsl = np.asarray(f[path+'qbootsigerrsl'])\n\n\nf.close()\n```\n\n## Figure 3b of the Paper:\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nfor Cms_em, m_em in samples[np.random.randint(len(samples), size=100)]:\n ax1.plot(xl, np.sqrt(Sigss**2+(Cms_em+m_em*xl)**2), color=\"orange\", alpha=0.1)\n\nax1.plot(xl,upvec,color='r',linestyle=\"--\",linewidth=2, \\\n label='1$\\sigma$ fluct.')\nax1.plot(xl,dnvec,color='r',linestyle=\"--\",linewidth=2, \\\n label='')\n\nax1.plot(xl,np.sqrt(Sigss**2+(Cms+xl*slope)**2),color='g',linestyle=\"-\",linewidth=3, \\\n label='(C$_0$={:01.3}; m={:01.2E})'.format(Cms,slope))\n\nax1.errorbar(xE,qbootsigs, yerr=(qbootsigerrsl,qbootsigerrsu), \\\n color='k', marker='o', markersize=4,linestyle='none',label='simulated NR scatters', linewidth=2)\n\nymin = 0.025\nymax = 0.045\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(10, 200) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\nplt.savefig('figures/paper_figures/MSyieldWidthFit_Figure3b.eps')\nplt.savefig('figures/paper_figures/MSyieldWidthFit_Figure3b.pdf')\nplt.show()\n```\n\n# 4. This Implies a Certain \"Effective\" Fano Factor\n\nIt is clear from the previous sections that the additions that need to be added to the account for the simulated multiple scatters are not as large as those required to explain the EDELWEISS data. This means that there is an \"extra\" unaccounted variance that needs to be added to the ionization yield. \n\nWe take the position that this variance is the intrinsic variance in the number of electron-hole pairs produced in a primary nuclear recoil reaction. Since this is analagous the the variance that is parameterized by the Fano factor for electron recoils, we call this the effective Fano factor for nuclear recoils. \n\nWe note that physically, this variance comes from a different mechanism than for electron recoils. In the nuclear recoil case most of the variance comes from the variation of the energy put into the phonon system from the primary recoil. In electron recoils there is little to no energy put into the phonon system from the primary recoil. Therefore, it is not surprising that the effective Fano factor can be significantly larger than the electron-recoil counterpart. \n\nSince we have accurately modeled the ionization yield variance without severe approximation (we do assume the number of electron-hole pairs is distributed normally; a very mild assumption when large numbers of pairs are expected), we can also include an intrinsic Fano factor in the modeling. Effectively we make the following replacement:\n\n\\begin{equation}\n\\tilde{\\sigma}_{Q}^0(E_r) \\rightarrow \\tilde{\\sigma}_{Q}^0(E_r;F_n),\n\\end{equation}\n\nWhere $F_n$ is the effective nuclear recoil Fano factor. \n\nTo extract the effective Fano factor for the nuclear recoils we need to come up with a parameter C$_F$ which is a function of recoil energy and is a corrected version of the measured \"widening\" parameter C from the EDELWEISS data and the widening parameter C$^{\\prime}$ from the effect of multiple-scattering. \n\nThe corrected parameter C$_F$ is assumed to be due to the effective Fano factor for nuclear recoils and is given by:\n\n\\begin{equation}\nC_F = \\sqrt{C^2 - C^{\\prime 2}}.\n\\end{equation}\n\nThis parameter can be used to extract the effective Fano factor at a given recoil energy by applying our $\\tilde{E}_r$-Q plane model (from `QEr_2D_joint.ipynb`), with an arbitrary Fano factor, until the correct ionization yield (Q) width is obtained (see `Qwidth_confirm.ipynb`). Mathematically this corresponds to adjusting F$_n$ until the following equality is satisfied:\n\n\\begin{equation}\n\\tilde{\\sigma}_{Q}^0(E_r;F_n) = \\sqrt{\\left(\\tilde{\\sigma}_{Q}^0(E_r)\\right)^2 + C_F^2}.\n\\end{equation}\n\n## Uncertainties on F$_n$\n\nSince both C and C$^{\\prime}$ have uncertainty it is necessary to propagate that uncertainty to F$_n$. If we call the uncertainty (1$\\sigma$) on C $\\sigma$ and on C$^{\\prime}$ $\\sigma^{\\prime}$, then the uncertainty on C$_F$ is given by:\n\n\\begin{equation}\n\\sigma_{C_F} = \\frac{1}{\\sqrt{C^2 - C^{\\prime 2}}} \\sqrt{C^2 \\sigma^2 + C^{\\prime 2} \\sigma^{\\prime 2}}.\n\\end{equation}\n\nThese uncertainties are propagated to the extracted F$_n$ by solving the following equality for F$^+_n$ and F$^-_n$ which represent the corresponding upper and lower boundaries on F$_n$. \n\n\\begin{equation}\n\\begin{aligned}\n\\tilde{\\sigma}_{Q}^0(E_r;F^+_n) &= \\sqrt{\\left(\\tilde{\\sigma}_{Q}^0(E_r)\\right)^2 + \\left(C_F + \\sigma_{C_F}\\right)^2} \\\\\n\\tilde{\\sigma}_{Q}^0(E_r;F^-_n) &= \\sqrt{\\left(\\tilde{\\sigma}_{Q}^0(E_r)\\right)^2 + \\left(C_F - \\sigma_{C_F}\\right)^2} \n\\end{aligned}\n\\end{equation}\n\n\n```python\nimport fano_calc as fc\n\n(Er,F,Fup,Fdn) = fc.RWCalcFMCMC('data/mcmc_fano.h5')\n```\n\n GGA3/4.0/5.556E-02/0.0381/\n True\n\n\n# Figure 4 of the Paper:\n\n\n```python\n#set up a plot\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import InsetPosition\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nxmax=10\n\n#ax1.errorbar(ddata_e,ddata_fluct_F,yerr=[ddata_fluct_F_err,ddata_fluct_F_err], marker='o', markersize=8, \\\n# ecolor='k',color='k', linestyle='none', label='Dougherty eff. F', linewidth=2)\n\n\n#ax1.plot (X, diff, 'm-', label='Thomas-Fermi (newgrad)')\n#ax1.plot (Esi(epr), 100*np.sqrt(f_Omega2_eta2(epr))*ylindv(1000*Esi(epr)), 'g-', label='$\\Omega/\\epsilon$ (NAC III approx. D)')\nax1.plot (Er, F, 'k-', label='extracted Ge eff. Fano')\nax1.plot (Er, Fup, 'b', label='')\nax1.plot (Er, Fdn, 'b', label='')\n\n\nblue = '#118DFA'\nax1.fill_between(Er,Fdn,Fup,facecolor=blue,alpha=0.5,label='1$\\sigma$ statistical region')\n\n\nax1.set_yscale('linear')\nax1.set_xscale('linear')\nax1.set_xlim(10, 200)\nax1.set_ylim(6,300)\nax1.set_xlabel('recoil energy ($E_r$) [keV]',**axis_font)\nax1.set_ylabel('effective Fano factor (F$_n$)',**axis_font)\n#ax1.grid(True)\n#ax1.xaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=4,prop={'size':22})\n\n\n###Make inset\nbbox_ll_x = 0.07\nbbox_ll_y = -0.0225\nbbox_w = 1\nbbox_h = 1\neps = 0.01\naxins = inset_axes(ax1, height=\"25%\", width=\"50%\", bbox_to_anchor=(bbox_ll_x,bbox_ll_y,bbox_w-bbox_ll_x,bbox_h), loc='upper left',bbox_transform=ax1.transAxes)\n#ax1.add_patch(plt.Rectangle((bbox_ll_x, bbox_ll_y+eps), bbox_w-eps-bbox_ll_x, bbox_h-eps, ls=\"--\", ec=\"c\", fc=\"None\",\n# transform=ax1.transAxes))\n\n#axins = plt.axes([0,0,1,1])\n#axins_pos = InsetPosition(ax3, [0.25, 0.65, 0.7, 0.3])\n#axins.set_axes_locator(axins_pos)\n\n# larger region than the original image\nx1, x2, y1, y2 = 7, 30, 0, 30\naxins.set_xlim(x1, x2)\naxins.set_ylim(y1, y2)\naxins.plot (Er, F, 'k-', label='')\naxins.plot (Er, Fup, 'b', label='')\naxins.plot (Er, Fdn, 'b', label='')\naxins.fill_between(Er,Fdn,Fup,facecolor=blue,alpha=0.5,label='')\naxins.yaxis.grid(True,which='minor',linestyle='--')\naxins.xaxis.grid(True,which='minor',linestyle='--')\naxins.grid(True)\n####\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n axins.spines[axis].set_linewidth(2)\n\n#plt.tight_layout()\n#plt.savefig('figures/figure.png')\nplt.savefig('figures/paper_figures/GeFano_Figure4.eps')\nplt.savefig('figures/paper_figures/GeFano_Figure4.pdf')\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "34d3bcb89156783a9014e6844769506a743bb5dd", "size": 669084, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "analysis_notebooks/nrFano_paper.ipynb", "max_stars_repo_name": "villano-lab/nrFano_paper2019", "max_stars_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:38:54.000Z", "max_issues_repo_path": "analysis_notebooks/nrFano_paper.ipynb", "max_issues_repo_name": "villano-lab/nrFano_paper2019", "max_issues_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "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": "analysis_notebooks/nrFano_paper.ipynb", "max_forks_repo_name": "villano-lab/nrFano_paper2019", "max_forks_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "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": 554.7960199005, "max_line_length": 178380, "alphanum_fraction": 0.9399567169, "converted": true, "num_tokens": 11207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.18476751738161779, "lm_q1q2_score": 0.08661728025350399}} {"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# Filtro de suavizado\n\n## El problema\n\nQueremos recuperar una imagen corrupta, es decir, una imagen que a traves de un proceso desconocido, perdió información.\n\nPero como te puedes imaginar la información simplemente no es recuperable de la nada, en esta ocasión intentaremos recuperar algo de la definición de la imagen tratando de minimizar los bordes visibles en imagen, es decir suavizarla.\n\nEmpecemos primero por mostrar nuestra imagen:\n\n\n```python\n# Se importan funciones para graficar y se inicializa con graficas en linea\n%matplotlib inline\nfrom matplotlib.pyplot import imshow, cm, figure\n```\n\n\n```python\n# Se importa funcion para cargar imagenes\nfrom scipy.ndimage import imread\n```\n\n\n```python\n# Se guardan las rutas a los archivos en variables para facil acceso\ncorrecta = \"imagenes/stones.jpg\"\ncorrupta = \"imagenes/stones_c.jpg\"\n```\n\n\n```python\n# Se lee la imagen del archivo a una variable de python y se grafica\nim_corrupta = imread(corrupta)\n\nf = figure(figsize=(8,6))\nax = imshow(im_corrupta, cmap=cm.gray, interpolation='none');\n\nax.axes.get_xaxis().set_visible(False)\nax.axes.get_yaxis().set_visible(False)\n\nax.axes.spines[\"right\"].set_color(\"none\")\nax.axes.spines[\"left\"].set_color(\"none\")\nax.axes.spines[\"top\"].set_color(\"none\")\nax.axes.spines[\"bottom\"].set_color(\"none\")\n```\n\nComo podemos ver la imagen a perdido definición al utilizar un metodo de compresión muy ingenuo, el cual simplemente repite la misma información una y otra vez, tomemos una muestra de los datos para ilustrar esto mejor:\n\n\n```python\ntamano_muestra = 12\nmuestra = im_corrupta[0:tamano_muestra, 0:tamano_muestra]\nmuestra\n```\n\n\n\n\n array([[44, 44, 44, 44, 33, 33, 33, 33, 17, 17, 17, 17],\n [44, 44, 44, 44, 33, 33, 33, 33, 17, 17, 17, 17],\n [44, 44, 44, 44, 33, 33, 33, 33, 17, 17, 17, 17],\n [44, 44, 44, 44, 33, 33, 33, 33, 17, 17, 17, 17],\n [43, 43, 43, 43, 34, 34, 34, 34, 20, 20, 20, 20],\n [43, 43, 43, 43, 34, 34, 34, 34, 20, 20, 20, 20],\n [43, 43, 43, 43, 34, 34, 34, 34, 20, 20, 20, 20],\n [43, 43, 43, 43, 34, 34, 34, 34, 20, 20, 20, 20],\n [45, 45, 45, 45, 34, 34, 34, 34, 26, 26, 26, 26],\n [45, 45, 45, 45, 34, 34, 34, 34, 26, 26, 26, 26],\n [45, 45, 45, 45, 34, 34, 34, 34, 26, 26, 26, 26],\n [45, 45, 45, 45, 34, 34, 34, 34, 26, 26, 26, 26]], dtype=uint8)\n\n\n\nLo cual graficamente se ve:\n\n\n```python\nimshow(muestra, cmap=cm.gray, interpolation='none');\n```\n\n## La solución\n\nMuy bien, es momento de pensar!\n\nSi lo que queremos es **minimizar** las *diferencias* entre dos valores contiguos, es decir\n\n$$\nx_{(i+1)j} - x_{ij}\n$$\n\npodemos empezar restandolos y ver que pasa:\n\n\n```python\nfrom numpy import matrix, eye, array\n```\n\n\n```python\n# Creamos una matriz identidad y la trasladamos para obtener el valor de la celda\n# contigua derecha\nI = eye(tamano_muestra, dtype=int).tolist()\n# Agregamos un vector cero, por el momento\nceros = [0 for i in range(tamano_muestra)]\nid_trasladada = matrix(array(I[1:tamano_muestra] + [ceros]))\nid_trasladada\n```\n\n\n\n\n matrix([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n\n\n\n\n```python\nmuestra_rest = matrix(muestra) * id_trasladada - matrix(muestra)\nmuestra_rest\n```\n\n\n\n\n matrix([[-44, 0, 0, 0, 11, 0, 0, 0, 16, 0, 0, 0],\n [-44, 0, 0, 0, 11, 0, 0, 0, 16, 0, 0, 0],\n [-44, 0, 0, 0, 11, 0, 0, 0, 16, 0, 0, 0],\n [-44, 0, 0, 0, 11, 0, 0, 0, 16, 0, 0, 0],\n [-43, 0, 0, 0, 9, 0, 0, 0, 14, 0, 0, 0],\n [-43, 0, 0, 0, 9, 0, 0, 0, 14, 0, 0, 0],\n [-43, 0, 0, 0, 9, 0, 0, 0, 14, 0, 0, 0],\n [-43, 0, 0, 0, 9, 0, 0, 0, 14, 0, 0, 0],\n [-45, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0],\n [-45, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0],\n [-45, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0],\n [-45, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0]])\n\n\n\nEsta matriz nos muestra la diferencia con el elemento contiguo, si lo analizamos graficamente:\n\n\n```python\nimshow(muestra_rest, cmap=cm.gray, interpolation='none');\n```\n\npodemos ver que solo hay diferencia entre los conjuntos de pixeles de la imagen que fueron eliminados.\n\nAhora, el punto es minimizar estas diferencias segun un factor de desempeño, y como pudiste notar en el ejemplo, pueden haber valores negativos, por lo que una buena idea es hacer el factor de desempeño un factor cuadratico:\n\n$$\n\\left|\\left| x_{(i+1)j} - x_{ij} \\right|\\right|^2\n$$\n\ny utilizando la forma matricial, que honestamente es mucho mas util en el caso de estas imagenes, nos queda:\n\n$$\n\\left|\\left| X (I_t - I) \\right|\\right|^2 = \\left|\\left| X D_1 \\right|\\right|^2\n$$\n\nen donde:\n\n$$\nI =\n\\begin{pmatrix}\n1 & 0 & 0 & \\dots & 0 & 0 & 0 \\\\\n0 & 1 & 0 & \\dots & 0 & 0 & 0 \\\\\n0 & 0 & 1 & \\dots & 0 & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & & \\vdots & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\dots & 1 & 0 & 0 \\\\\n0 & 0 & 0 & \\dots & 0 & 1 & 0\n\\end{pmatrix}\n$$\n\n$$\nI_t =\n\\begin{pmatrix}\n0 & 1 & 0 & \\dots & 0 & 0 & 0 \\\\\n0 & 0 & 1 & \\dots & 0 & 0 & 0 \\\\\n0 & 0 & 0 & \\dots & 0 & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & & \\vdots & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\dots & 0 & 1 & 0 \\\\\n0 & 0 & 0 & \\dots & 0 & 0 & 1\n\\end{pmatrix}\n$$\n\ny por lo tanto $D_1$ es de la forma:\n\n$$\nD_1 =\n\\begin{pmatrix}\n-1 & 1 & 0 & \\dots & 0 & 0 & 0 \\\\\n0 & -1 & 1 & \\dots & 0 & 0 & 0 \\\\\n0 & 0 & -1 & \\dots & 0 & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & & \\vdots & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\dots & -1 & 1 & 0 \\\\\n0 & 0 & 0 & \\dots & 0 & -1 & 1\n\\end{pmatrix}\n$$\n\n
\n\nCabe mencionar que $I$ e $I_t$ no son matrices cuadradas, ya que tienen una columna mas, principalmente para ajustar el hecho de que la operación de resta es binaria y necesitamos hacer una operación por cada uno de las $n$ columnas, por lo que necesitaremos $n + 1$ operandos; sin embargo al obtener el factor cuadrado, nos quedará una matriz de las dimensiones adecuadas. \n\n
\n\nAsi pues, este factor cuadrado, lo denotaremos por la función $f_1(X)$ de la siguiente manera:\n\n$$\nf_1(X) = \\left|\\left| X D_1 \\right|\\right|^2 = D_1^T X^T X D_1\n$$\n\ny de la misma manera obtendremos un operador para la diferencia entre los elementos contiguos verticalmente, el cual se verá:\n\n$$\nf_2(X) = \\left|\\left| D_2 X \\right|\\right|^2 = X^T D_2^T D_2 X\n$$\n\nen donde $D_2$ es de la forma:\n\n$$\nD_2 =\n\\begin{pmatrix}\n-1 & 0 & 0 & \\dots & 0 & 0 \\\\\n1 & -1 & 0 & \\dots & 0 & 0 \\\\\n0 & 1 & -1 & \\dots & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\dots & -1 & 0 \\\\\n0 & 0 & 0 & \\dots & 1 & -1 \\\\\n0 & 0 & 0 & \\dots & 0 & 1\n\\end{pmatrix}\n$$\n\nAsi pues, nuestro objetivo es minimizar la siguiente expresión:\n\n$$\n\\min_{X \\in \\mathbb{R}^{n \\times m}} f_1(X) + f_2(X)\n$$\n\nSin embargo tenemos que considerar que una optimización perfecta nos llevaria al caso en que todos los valores son exactamente iguales, por lo que agregaremos un termino para penalizar una diferencia demasiado grande con la imagen a suavizar, el cual simplemente es la diferencia entre la imagen obtenida y la imagen corrupta:\n\n$$\nf_3(X) = \\left|\\left| X - X_C \\right|\\right|^2\n$$\n\nPor lo que nuestra expresión a minimizar se vuelve:\n\n$$\n\\min_{X \\in \\mathbb{R}^{n \\times m}} V(X) = \\min_{X \\in \\mathbb{R}^{n \\times m}} \\delta \\left( f_1(X) + f_2(X) \\right) + f_3(X) \\quad \\delta > 0\n$$\n\nen donde $\\delta$ es la ponderación que le damos al termino *suavizante*.\n\n
\n $\\DeclareMathOperator{\\trace}{tr}$\n
\n\n
\n\nCabe hacer la aclaración de que hasta el momento hemos utilizado una norma matricial, normal, sin embargo ahora utilizaremos la norma de Frobenius, la cual se define como:\n\n$$\nf_1(X) = \\left|\\left| X D_1 \\right|\\right|_F^2 = \\trace{(D_1^T X^T X D_1)}\n$$\n\ny esta nos provee una manera facil de calcular la forma cuadratica que queremos. Mas aún, esta $f_1(X) \\in \\mathbb{R}$, por lo que podemos usar los conceptos de calculo variacional que hemos aprendido.\n\n
\n\nAhora empezamos a calcular el valor de estas funciones alrededor de $X$ con una variación $H$.\n\n$$\n\\begin{align}\nf_1(X + H) &= \\trace{\\left( D_1^T (X + H)^T (X + H) D_1 \\right)} \\\\\n&= \\trace{\\left( D_1^T (X^T + H^T) (X + H) D_1 \\right)} \\\\\n&= \\trace{\\left( D_1^T (X^T X + X^T H + H^T X + H^T H) D_1 \\right)} \\\\\n&= \\trace{\\left( D_1^T X^T X D_1 + D_1^T X^T H D_1 + D_1^T H^T X D_1 + D_1^T H^T H D_1 \\right)} \\\\\n&= \\trace{\\left( D_1^T X^T X D_1 \\right)} + \\trace{\\left( D_1^T X^T H D_1 \\right)} + \\trace{\\left( D_1^T H^T X D_1 \\right)} + \\trace{\\left( D_1^T H^T H D_1 \\right)} \\\\\n\\end{align}\n$$\n\nAqui hacemos notar que el primer termino es $f_1(X) = \\trace{\\left( D_1^T X^T X D_1 \\right)}$, el segundo y tercer termino son el mismo, ya que la traza es invariante ante la transposición y el ultimo termino es de orden superior, $o\\left(\\left|\\left|H\\right|\\right|_F\\right)$.\n\n
\n\nRecordemos que la variable con respecto a la que estamos haciendo estos calculos es la perturbación $H$, por lo que los terminos de orden superior estan relacionados a $H$ y no a $X$ la cual asumimos es nuestro optimo.\n\n
\n\n\nSi desarrollamos la expasión de la serie de Taylor alrededor de $X$ con una perturbación $H$, notaremos que los terminos que obtuvimos corresponden a los de esta expansión:\n\n$$\nf_1(X + H) = f_1(X) + f_1'(X) \\cdot H + o\\left(\\left|\\left| H \\right|\\right|_F\\right)\n$$\n\ny por lo tanto:\n\n$$\nf_1'(X) \\cdot H = 2 \\trace{\\left( D_1^T X^T H D_1 \\right)}\n$$\n\nSi expandimos las otras dos funciones alrededor de X con una perturbación $H$, podremos ver que:\n\n$$\nf_2'(X) \\cdot H = 2 \\trace{\\left( X^T D_2^T D_2 H \\right)}\n$$\n\n$$\nf_3'(X) \\cdot H = 2 \\trace{\\left( \\left( X - X_C \\right)^T H \\right)}\n$$\n\nAhora, por superposición podemos asegurar que nuestro criterio de desempeño $V(X)$ tiene una derivada de la forma:\n\n$$\n\\begin{align}\nV'(X) \\cdot H &= \\left( f_1'(X) \\cdot H + f_2'(X) \\cdot H \\right) \\delta + f_3'(X) \\cdot H \\\\\n&= \\left( 2 \\trace{\\left( D_1^T X^T H D_1 \\right)} + 2 \\trace{\\left( X^T D_2^T D_2 H \\right)} \\right) \\delta + 2 \\trace{\\left( \\left( X - X_C \\right)^T H \\right)} \\\\\n&= 2 \\trace{\\left[ \\left( \\left( D_1^T X^T H D_1 \\right) + \\left( X^T D_2^T D_2 H \\right) \\right) \\delta + \\left( X - X_C \\right)^T H \\right]}\n\\end{align}\n$$\n\ny al utilizar la condición de optimalidad de primer orden tenemos que:\n\n$$\nV'(X) \\cdot H = 2 \\trace{\\left[ \\left( \\left( D_1^T X^T H D_1 \\right) + \\left( X^T D_2^T D_2 H \\right) \\right) \\delta + \\left( X - X_C \\right)^T H \\right]} = 0\n$$\n\ny al hacer manipulación algebraica, obtenemos que:\n\n$$\n\\begin{align}\n\\trace{\\left[ \\left( \\left( D_1^T X^T H D_1 \\right) + \\left( X^T D_2^T D_2 H \\right) \\right) \\delta + \\left( X - X_C \\right)^T H \\right]} &= 0 \\\\\n\\trace{\\left[ \\left( \\left( D_1^T H^T X D_1 \\right) + \\left( H^T D_2^T D_2 X \\right) \\right) \\delta + H^T \\left( X - X_C \\right) \\right]} &= 0 \\\\\n\\trace{\\left[ \\left( \\left( H^T X D_1 D_1^T \\right) + \\left( H^T D_2^T D_2 X \\right) \\right) \\delta + H^T \\left( X - X_C \\right) \\right]} &= 0 \\\\\n\\trace{\\left[ H^T \\left( X D_1 D_1^T + D_2^T D_2 X \\right) \\delta + \\left( X - X_C \\right) \\right]} &= 0\n\\end{align}\n$$\n\nEn este punto nos preguntamos, para que condiciones de perturbación queremos que nuestra condición de optimalidad se cumpla, por lo que si exigimos que esto se cumpla para toda $H$, tenemos que:\n\n$$\n\\left( X D_1 D_1^T + D_2^T D_2 X \\right) \\delta + \\left( X - X_C \\right) = 0\n$$\n\nlo cual implica que:\n\n$$\nX \\delta D_1 D_1^T + ( \\delta D_2^T D_2 + I) X = X_C\n$$\n\nlo cual tiene la forma de la ecuación de Lyapunov:\n\n$$\nA X + X B = Q\n$$\n\nen donde $A$ y $B$ son de la forma:\n\n$$\nA = \\delta D_2^T D_2 + I \\quad B = \\delta D_1 D_1^T\n$$\n\npor lo que ya encontramos una forma de programar este algoritmo de suavizado, utilizando la función ```solve_sylvester``` proporcionada por el paquete Scipy.\n\nAhora regresemos a la programación; lo que tenemos que construir son las matrices $D_1$ y $D_2$ para incorporarlas a una función que calcule todo en linea.\n\nEmpecemos construyendo una de las filas de esta matriz. Recordemos que $D_1$ es de la forma:\n\n$$\nD_1 =\n\\begin{pmatrix}\n-1 & 1 & 0 & \\dots & 0 & 0 & 0 \\\\\n0 & -1 & 1 & \\dots & 0 & 0 & 0 \\\\\n0 & 0 & -1 & \\dots & 0 & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & & \\vdots & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\dots & -1 & 1 & 0 \\\\\n0 & 0 & 0 & \\dots & 0 & -1 & 1\n\\end{pmatrix}\n$$\n\npor lo que primero tenemos que construir un arreglo de la forma:\n\n$$\n\\begin{pmatrix}\n-1 & 1 & 0 & \\dots & 0 & 0 & 0\n\\end{pmatrix}\n$$\n\nLa siguiente función describe una manera **dificil** de conseguir esto, sin embargo para efectos de demostración servirá:\n\n\n```python\ndef fun(i, tot):\n '''Arreglo especial\n Esta funcion crea un arreglo de tamaño tot con un -1 en el elemento i y un\n 1 en el elemento i+1, siendo los demas lugares del arreglo ceros:\n\n indice -> 0, 1, ..., i-1, i, i+1, i+2, ..., tot\n arreglo -> [0, 0, ..., 0, -1, 1, 0, ..., 0].\n\n Ejemplo\n -------\n >>> fun(3, 5)\n array([ 0, 0, -1, 1, 0])\n '''\n\n # Se importan funciones necesarias\n from numpy import array\n\n # Se define el inicio del arreglo\n if i == 0:\n a = [-1]\n a.append(1)\n else:\n a = [0]\n\n # Se incluyen numeros restantes en el arreglo\n for t in range(tot - 1)[1:]:\n if i == t:\n a.append(-1)\n a.append(1)\n else:\n a.append(0)\n\n # Se convierte en arreglo de numpy el resultado\n return array(a)\n```\n\nCuando mandamos llamar esta función para que nos de un arreglo de diez elementos, con el $-1$ en el segundo lugar, obtendremos:\n\n\n```python\nfun(1, 10)\n```\n\n\n\n\n array([ 0, -1, 1, 0, 0, 0, 0, 0, 0, 0])\n\n\n\n
\n\nPython lista los arreglos, y en general todas sus estructuras, empezando en ```0```, por lo que el indice ```1``` corresponde al segundo lugar.\n\n
\n\nY ahora, utilizando una función especial de Python, crearemos un arreglo de arreglos, utilizando una sintaxis muy parecida a la de una definición matemática de la forma:\n\n$$\n\\left\\{ f(i) : i \\in [0, 10] \\right\\}\n$$\n\n\n```python\narreglo_de_arreglos = [fun(i, 11) for i in range(10)]\narreglo_de_arreglos\n```\n\n\n\n\n [array([-1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),\n array([ 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0]),\n array([ 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0]),\n array([ 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0]),\n array([ 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0]),\n array([ 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0]),\n array([ 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0]),\n array([ 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0]),\n array([ 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0]),\n array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1])]\n\n\n\nEsto se puede convertir facilmente en una matriz por medio de la instrucción ```matrix```.\n\n\n```python\nmatrix(arreglo_de_arreglos)\n```\n\n\n\n\n matrix([[-1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [ 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0],\n [ 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0],\n [ 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0],\n [ 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1]])\n\n\n\nPor lo que estamos listos para juntar todos estos elementos en una función que ejecute todo este flujo de trabajo:\n\n\n```python\ndef suavizado_imagen(imagen_corrupta, delta):\n '''Suavizado de imagen\n \n Esta funcion toma la imagen especificada en la primer variable por su ruta, y\n le aplica un suavizado en proporcion al flotante pasado a la segunda variable.\n \n Ejemplo\n -------\n >>> suavizado_imagen(\"ruta/de/la/imagen.png\", 0.1)\n '''\n \n # Se importan funciones necesarias\n from matplotlib.pyplot import imshow, cm, figure\n from scipy.linalg import solve_sylvester\n from scipy.ndimage import imread\n from numpy import matrix, eye, array\n \n # Se define funcion auxiliar para las filas de la matriz D\n def fun(i, tot):\n '''Arreglo especial\n Esta funcion crea un arreglo de tamaño tot con un -1 en el elemento i y un\n 1 en el elemento i+1, siendo los demas lugares del arreglo ceros:\n \n indice -> 0, 1, ..., i-1, i, i+1, i+2, ..., tot\n arreglo -> [0, 0, ..., 0, -1, 1, 0, ..., 0].\n \n Ejemplo\n -------\n >>> fun(3, 5)\n array([ 0, 0, -1, 1, 0])\n '''\n \n # Se importan funciones necesarias\n from numpy import array\n \n # Se define el inicio del arreglo\n if i == 0:\n a = [-1]\n a.append(1)\n else:\n a = [0]\n \n # Se incluyen numeros restantes en el arreglo\n for t in range(tot - 1)[1:]:\n if i == t:\n a.append(-1)\n a.append(1)\n else:\n a.append(0)\n \n # Se convierte en arreglo de numpy el resultado\n return array(a)\n \n # Se importa la imagen a tratar y se obtiene sus dimensiones\n im_corrupta = imread(imagen_corrupta)\n n = im_corrupta.shape[0]\n m = im_corrupta.shape[1]\n \n # Se obtienen las matrices D1 y D2\n D1 = matrix(array([fun(i, n + 1) for i in range(n)]))\n D2 = matrix(array([fun(i, m + 1) for i in range(m)]))\n \n # Se obtiene la imagen suavizada al resolver la ecuacion de Lyapunov (o Sylvester)\n imagen_suavizada = solve_sylvester(eye(n) + delta*D1*D1.T,\n delta*D2*D2.T,\n im_corrupta)\n \n # Se dibuja la imagen suavizada\n f = figure(figsize=(8,6))\n ax = imshow(imagen_suavizada, cmap=cm.gray, interpolation='none')\n \n # Se quitan bordes de la grafica\n ax.axes.get_xaxis().set_visible(False)\n ax.axes.get_yaxis().set_visible(False)\n \n # Se hacen transparentes las lineas de los bordes\n ax.axes.spines[\"right\"].set_color(\"none\")\n ax.axes.spines[\"left\"].set_color(\"none\")\n ax.axes.spines[\"top\"].set_color(\"none\")\n ax.axes.spines[\"bottom\"].set_color(\"none\")\n```\n\n\n```python\n# Se prueba la funcion con un suavizado de 10\nsuavizado_imagen(corrupta, 10)\n```\n\nY hemos obtenido el resultado deseado...\n\n## La cereza del pastel\n\nContentos con nuestros resultados podriamos irnos a descansar, pero aun queda un truco mas. Ya que hemos obtenido una función que ejecuta todo nuestro código, podemos hacer que IPython la ejecute en linea al momento de darle un parametro diferente.\n\nPara esto utilizaremos un Widget de IPython:\n\n\n```python\n# Se importan widgets de IPython para interactuar con la funcion\nfrom IPython.html.widgets import interact, fixed\n```\n\n :0: FutureWarning: IPython widgets are experimental and may change in the future.\n\n\nDada la función que obtuvimos, ahora solo tenemos que mandar llamar a la función:\n\n```python\ninteract(funcion_con_codigo,\n parametro_fijo=fixed(param),\n parametro_a_variar=(inicio, fin))\n```\n\n\n```python\n# Se llama a la funcion interactiva\ninteract(suavizado_imagen, imagen_corrupta=fixed(corrupta), delta=(0.0, 10.0))\n```\n\nCon lo que solo tenemos que mover el deslizador para cambiar ```delta``` y ver los resultados de estos cambios.\n\n\n```python\n# Se muestra la imagen correcta\nim_correcta = imread(correcta)\n\nf = figure(figsize=(8,6))\nax = imshow(im_correcta, cmap=cm.gray, interpolation='none');\n\nax.axes.get_xaxis().set_visible(False)\nax.axes.get_yaxis().set_visible(False)\n\nax.axes.spines[\"right\"].set_color(\"none\")\nax.axes.spines[\"left\"].set_color(\"none\")\nax.axes.spines[\"top\"].set_color(\"none\")\nax.axes.spines[\"bottom\"].set_color(\"none\")\n```\n\nEspero te hayas divertido con esta larga explicación y al final sepas un truco mas.\n\nSi deseas compartir este Notebook de IPython utiliza la siguiente dirección:\n\nhttp://bit.ly/1CJNEBn\n\no bien el siguiente código QR:\n\n\n\n\n```python\n# Codigo para generar codigo :)\nfrom qrcode import make\nimg = make(\"http://bit.ly/1CJNEBn\")\nimg.save(\"codigos/suave.jpg\")\n```\n", "meta": {"hexsha": "1a16af318906dfb9231e7a45c2f8c528f7771eb5", "size": 452272, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPythonNotebooks/Control Optimo/Filtro suavizado.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/Control Optimo/Filtro suavizado.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/Control Optimo/Filtro suavizado.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": 386.2271562767, "max_line_length": 175762, "alphanum_fraction": 0.9125570453, "converted": true, "num_tokens": 8957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.24798742624020276, "lm_q1q2_score": 0.08645961313932088}} {"text": "# Scientific documents with $\\LaTeX$\n\n## Introduction\n\nIn your research, you will produce papers, reports and—very importantly—your thesis. These documents can be written using a WYSIWYG (What You See Is What You Get) editor (e.g., Word). However, an alternative especially suited for scientific publications is LaTeX. In LaTeX, the document is written in a text file (`.tex`) with certain typesetting (tex) syntax. Text formatting is done using markups (like HTML). The file is then \"compiled\" (like source code of a programming language) into a file – typically in PDF.\n\n### Why $\\LaTeX$?\n\nA number of reasons: \n\n* The input is a small, portable text file\n* LaTeX compilers are freely available for all OS'\n* Exactly the same result on any computer (not true for Word, for example)\n* LaTeX produces beautiful, professional looking docs\n* Images are easy to embed and annotate \n* Mathematical formulas (esp complex ones) are easy to write\n* LaTeX is very stable – current version basically same since 1994! (9 major versions of MS Word since 1994 – with compatibility issues)\n* LaTeX is free!\n* You can focus on content, and not worry so much about formatting while writing \n* An increasing number of Biology journals provide $\\LaTeX$ templates, making formatting quicker. \n* Referencing (bibliography) is easy (and can also be version controlled) and works with tools like Mendeley and Zotero\n* Plenty of online support available – your question has probably already been answered\n* You can integrate LaTeX into a workflow to auto-generate lengthy and complex documents (like your thesis).\n\n---\n\n\n\n
LaTeX documents scale up better then WYSIWYG editors.
\n\n---\n\n### Limitations of $\\LaTeX$\n\n* It has a steeper learning curve.\n* Can be difficult to manage revisions with multiple authors – especially if they don't use LaTeX! (Cue: Windows on a virtual machine!)\n* Tracking changes are not available out of the box (but can be enabled using a suitable package) \n* Typesetting tables can be a bit complex.\n* Images and floats are easy to embed, and won't jump around like Word, but if you don't use the right package, they can be difficult to place where you want!\n\n### Installing LaTeX\n\nType this in terminal: \n\n```bash\nsudo apt-get install texlive-full texlive-fonts-recommended texlive-pictures texlive-latex-extra imagemagick\n```\nIt's a large installation, and will take some time. \n\nWe will use a text editor in this lecture, but you can use one of a number of dedicated editors (e.g., texmaker,\nGummi, TeXShop, etc.) There are also WYSIWYG frontends (e.g., Lyx, TeXmacs). \n\n[Overleaf](https://www.overleaf.com/) is also very good (and works with git), especially for collaborating with non LaTeX-ers (your university may have a blanket license for the pro version).\n\n## A first LaTeX example\n\n$\\star$ In your code editor type the following in a file called `FirstExample.tex` and save it in a suitable location in your coursework directory (e.g, `/Week1/Code/`):\n\n```tex\n\n\\documentclass[12pt]{article}\n\n\\title{A Simple Document}\n\n\\author{Your Name}\n\n\\date{}\n\n\\begin{document}\n \\maketitle\n \n \\begin{abstract}\n This paper must be cool!\n \\end{abstract}\n \n \\section{Introduction}\n Blah Blah!\n \n \\section{Materials \\& Methods}\n One of the most famous equations is:\n \\begin{equation}\n E = mc^2\n \\end{equation}\n This equation was first proposed by Einstein in 1905 \n \\cite{einstein1905does}.\n \n \\bibliographystyle{plain}\n \\bibliography{FirstBiblio}\n\\end{document}\n```\n\nNow, let's get a citation for this paper:\n\n$\\star$ In Google Scholar, go to \"settings\" (upper right corner) and choose BibTeX as bibliography manager. Then type \"energy of a body einstein 1905\"\n\nThe paper should be the one on the top.\n\nClick \"Import into BibTeX\" should show the following text, that you will save in the file `FirstBiblio.bib` (in the same directory as `FirstExample.tex`):\n\n```bash\n@article{einstein1905does,\n title={Does the inertia of a body depend upon its energy-content?},\n author={Einstein, A.},\n journal={Annalen der Physik},\n volume={18},\n pages={639--641},\n year={1905}\n}\n```\nNow we can create a `.pdf` of the article.\n\n$\\star$ In the terminal type (make sure you are the right directory!):\n\n``` bash\n pdflatex FirstExample.tex\n bibtex FirstExample\n pdflatex FirstExample.tex\n pdflatex FirstExample.tex\n```\nThis should produce the file `FirstExample.pdf`:\n\n\n\nIn the above bash script, we repeated the `pdflatex` command 3 times. Here's why:\n\n* The first `pdflatex` run generates two files:`FirstExample.log` and `FirstExample.aux` (and an incomplete `.pdf`). \n * At this step, all cite{...} arguments info that bibtex needs are written into the `.aux` file.\n* Then, running `bibtex` (followed by the filename without the `.tex` extension) results in bibtex reading the `.aux` file that was generated. It then produces two more files: `FirstExample.bbl` and `FirstExample.blg`\n * At this step, bibtex takes the citation info in the aux file and puts the relevant biblogrphic entries into the `.bbl` file (you can take a peek at all these files), formatted according to the instructions provided by the bibliography style that you have specified using `bibliographystyle{plain}`.\n* The second `pdflatex` run updates `FirstExample.log` and `FirstExample.aux` (and a still-incomplete `.pdf` - the citations are not correctly formatted yet)\n * At this step, the reference list in the `.bbl` generated in the above step is included in the document, and the correct labels for the in-text `cite{...}` commands are written in `.aux` file (but the non in the actual pdf).\n* The third and final `pdflatex` run then updates `FirstExample.log` and `FirstExample.aux` one last time, and now produces the complete `.pdf` file, with citations correctly formatted. \n * At this step, latex knows what the correct in-text citation labels are, and includes them in the pdf document.\n\nThroughout all this, the `.log` file plays no role except to record info about how the commands are running. \n\nPHEW! Why go through this repetitive sequence of commands? Well, \"it is what it is\" – $\\LaTeX$, with all its advantages does have its quirks. The reason why it is this way, is probably that back then (Donald Knuth's PhD Thesis writing days – late 1950's to early 1960's), computers had *tiny* memories (RAMs), and writing files to disk and then reading them back in for the next step of the algorithm/program was the best (and only) way to go. Why has this not been fixed? I am not sure - keep an eye out, and it might well be (and then, raise an issue on TheMulQuaBio's [Github](https://github.com/mhasoba/TheMulQuaBio/issues)!)\n\nAnyway, as such, you don't have to run these commands literally step by step, because you can create a bash script that does it for you, as we will now learn.\n\n### A bash script to compile LaTeX\n\nLet's write a useful little bash script to compile latex with bibtex.\n\n$\\star$ Type the following script and call it `CompileLaTeX.sh` (you know where to put it!):\n\n```bash\n#!/bin/bash\npdflatex $1.tex\nbibtex $1\npdflatex $1.tex\npdflatex $1.tex\nevince $1.pdf &\n\n## Cleanup\nrm *.aux\nrm *.log\nrm *.bbl\nrm *.blg\n```\nHow do you run this script? The same as your previous bash scripts, so:\n\n```bash\nbash CompileLaTeX.sh FirstExample\n```\n\n*Why have I not written the `.tex` extension of `FirstExample` in the command above? Can you make this bash script more convenient to use?*\n\n## A few $\\LaTeX$ basics\n\n### Spaces, new lines and special characters\n\n* Several spaces in your text editor are treated as one space in the typeset document\n* Several empty lines are treated as one empty line\n* One empty line defines a new paragraph\n* Some characters are \"special\": # $ % ^ & _ { } ~ \\\n\nTo type these special characters, you have to add a \"backslash\" in front, e.g., \\\\\\$ produces $\\$$.\n\n### Document structure:\n\n* Each LaTeX command starts with \\\\ . For example, to get $\\LaTeX$, you need `\\LaTeX`\n* The first command is always `\\\\`documentclass`` defining the type of document (e.g., `article, book, report, letter`).\n* You can set several options. For example, to set size of text to 10 points and the letter paper size: \n`\\documentclass[10pt,letterpaper]{article}`.\n* After having declared the type of document, you can specify packages you want to use. The most useful are:\n \n `\\usepackage{color}`: use colors for text in your document.\n\n `\\usepackage{amsmath,amssymb}`: American Mathematical Society formats and commands for typesetting mathematics.\n\n `\\usepackage{fancyhdr}`: fancy headers and footers.\n\n `\\usepackage{graphicx}`: include figures in pdf, ps, eps, gif and jpeg.\n\n `\\usepackage{listings}`: typeset source code for various programming languages.\n\n `\\usepackage{rotating}`: rotate tables and figures.\n\n `\\usepackage{lineno}`: line numbers.\n\n* Once you select the packages, you can start your document with `\\begin{document}`, and end it with `\\end{document}`.\n\n### Typesetting math\n\nThere are two ways to display math\n\n1. Inline mathematics (i.e., within the text).\n\n2. Stand-alone, numbered equations and formulae.\n\nFor inline math, the \"dollar\" sign flanks the math to be typeset. For example, the code:\n\n```\n$\\int_0^1 p^x (1-p)^y dp$\n```\n\nbecomes $\\int_0^1 p^x (1-p)^y dp$\n\nFor numbered equations (almost always a great idea), LaTeX provides the\n`equation` environment:\n\n```\n\\begin{equation}\n \\int_0^1 \\left(\\ln \\left( \\frac{1}{x} \\right) \n \\right)^y dx = y!\n\\end{equation}\n```\n\nbecomes \n\n$$\\int_0^1 \\left(\\ln \\left( \\frac{1}{x} \\right) \\right)^y dx = y!$$\n\n## LaTeX templates\n\nThere a lots of useful LaTeX templates out there. I have added some templates in the `TheMulQuaBio` repo that you should have a look and play around with. Or just google \"latex template\" along with the name of a journal you want! \n\n## A few more tips\n\nThe following tips might prove handy:\n\n* LaTeX has a full set of symbols and operators (plenty of lists online)\n* Long documents can be split into separate `.tex` documents and combined using `input`\n* Long documents can be split into separate `.tex` documents and Figures can be included using the `graphicx` package\n* You can use Mendeley or Zotero to export and maintain `.bib` files\n* You can redefine environments and commands in the preamble\n\n## Practicals\n\n### First $\\LaTeX$ example\n\nTest `CompileLaTeX.sh` with `FirstExample.tex` and bring it under verson control under`week1` in your repository. Make sure that `CompileLaTeX.sh` will work if somebody else ran it from their computer using `FirstExample.tex` as an input.\n\n### Practicals wrap-up\n\nMake sure you have your `Week 1` directory organized with `Data`, `Sandbox` and `Code` with the necessary files and this week's (functional!) scripts in there. Every script should run without errors on my computer. This includes the five solutions (single-line commands you came up with) in `UnixPrac1.txt`.\n\n*Commit and push every time you do some significant amount of coding work (after testing it), and then again before the given deadline (this will be announced in class).*\n\n## Readings & Resources\n\n### General \n\n* [http://en.wikibooks.org/wiki/LaTeX/Introduction](http://en.wikibooks.org/wiki/LaTeX/Introduction)\n* [The not so Short Introduction to LaTeX](https://ctan.org/tex-archive/info/lshort/english/)\n* [The Visual LaTeX FAQ: sometimes it is difficult to describe what you want to do!](http://mirror.las.iastate.edu/tex-archive/info/visualFAQ/visualFAQ.pdf)\n* [The Overleaf knowledge base](https://www.overleaf.com/learn), including\n * [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes)\n * [Presentations in LaTeX](https://www.overleaf.com/learn/latex/Beamer_Presentations:_A_Tutorial_for_Beginners_(Part_1)—Getting_Started)\n * [Bibliographies in LaTeX](https://www.overleaf.com/learn/latex/Bibliography_management_with_bibtex)\n\n### Templates\n* The [Overleaf templates](https://www.overleaf.com/latex/templates) \n * Includes many [Imperial College Dissertation templates](https://www.overleaf.com/latex/templates?addsearch=imperial%20college)).\n\n### $\\LaTeX$ Tables\n* [$\\LaTeX$ table generator](http://www.tablesgenerator.com/)\n", "meta": {"hexsha": "09c20255e81b3befe4ed515d57ac5a954fa78125", "size": 16962, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/notebooks/04-LaTeX.ipynb", "max_stars_repo_name": "nesbitm/VBiTE_2021", "max_stars_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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": "content/notebooks/04-LaTeX.ipynb", "max_issues_repo_name": "nesbitm/VBiTE_2021", "max_issues_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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": "content/notebooks/04-LaTeX.ipynb", "max_forks_repo_name": "nesbitm/VBiTE_2021", "max_forks_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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": 41.8814814815, "max_line_length": 653, "alphanum_fraction": 0.6209763, "converted": true, "num_tokens": 3136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242553269617778, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.08622953501916375}} {"text": "
\n
\n
\n

Natural Language Processing For Everyone

\n

Text Representation

\n

Bruno Gonçalves
\n www.data4sci.com
\n @bgoncalves, @data4sci

\n
\n\nIn this lesson we will see in some details how we can best represent text in our application. Let's start by importing the modules we will be using:\n\n\n```python\nimport string\nfrom collections import Counter\nfrom pprint import pprint\nimport gzip\n\nimport matplotlib\nimport matplotlib.pyplot as plt \nimport numpy as np\n\nimport watermark\n\n%matplotlib inline\n%load_ext watermark\n```\n\nList out the versions of all loaded libraries\n\n\n```python\n%watermark -n -v -m -g -iv\n```\n\n Python implementation: CPython\n Python version : 3.8.5\n IPython version : 7.19.0\n \n Compiler : Clang 10.0.0 \n OS : Darwin\n Release : 20.6.0\n Machine : x86_64\n Processor : i386\n CPU cores : 16\n Architecture: 64bit\n \n Git hash: ae641e141a1604bbe1639a2ded4ed2424660eab0\n \n numpy : 1.19.2\n matplotlib: 3.3.2\n json : 2.0.9\n watermark : 2.1.0\n \n\n\nSet the default style\n\n\n```python\nplt.style.use('./d4sci.mplstyle')\n```\n\nWe choose a well known nursery rhyme, that has the added distinction of having been the first audio ever recorded, to be the short snippet of text that we will use in our examples:\n\n\n```python\ntext = \"\"\"Mary had a little lamb, little lamb,\n little lamb. 'Mary' had a little lamb\n whose fleece was white as snow.\n And everywhere that Mary went\n Mary went, MARY went. Everywhere\n that mary went,\n The lamb was sure to go\"\"\"\n```\n\n## Tokenization\n\nThe first step in any analysis is to tokenize the text. What this means is that we will extract all the individual words in the text. For the sake of simplicity, we will assume that our text is well formed and that our words are delimited either by white space or punctuation characters.\n\n\n```python\nprint(string.punctuation)\n```\n\n !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n\n\n\n```python\ndef extract_words(text):\n temp = text.split() # Split the text on whitespace\n text_words = []\n\n for word in temp:\n # Remove any punctuation characters present in the beginning of the word\n while word[0] in string.punctuation:\n word = word[1:]\n\n # Remove any punctuation characters present in the end of the word\n while word[-1] in string.punctuation:\n word = word[:-1]\n\n # Append this word into our list of words.\n text_words.append(word.lower())\n \n return text_words\n```\n\nAfter this step we now have our text represented as an array of individual, lowercase, words:\n\n\n```python\ntext_words = extract_words(text)\nprint(text_words)\n```\n\n ['mary', 'had', 'a', 'little', 'lamb', 'little', 'lamb', 'little', 'lamb', 'mary', 'had', 'a', 'little', 'lamb', 'whose', 'fleece', 'was', 'white', 'as', 'snow', 'and', 'everywhere', 'that', 'mary', 'went', 'mary', 'went', 'mary', 'went', 'everywhere', 'that', 'mary', 'went', 'the', 'lamb', 'was', 'sure', 'to', 'go']\n\n\nAs we saw during the video, this is a wasteful way to represent text. We can be much more efficient by representing each word by a number\n\n\n```python\nword_dict = {}\nword_list = []\nvocabulary_size = 0\ntext_tokens = []\n\nfor word in text_words:\n # If we are seeing this word for the first time, create an id for it and added it to our word dictionary\n if word not in word_dict:\n word_dict[word] = vocabulary_size\n word_list.append(word)\n vocabulary_size += 1\n \n # add the token corresponding to the current word to the tokenized text.\n text_tokens.append(word_dict[word])\n```\n\nWhen we were tokenizing our text, we also generated a dictionary **word_dict** that maps words to integers and a **word_list** that maps each integer to the corresponding word.\n\n\n```python\nprint(\"Word list:\", word_list, \"\\n\\n Word dictionary:\")\npprint(word_dict)\n```\n\n Word list: ['mary', 'had', 'a', 'little', 'lamb', 'whose', 'fleece', 'was', 'white', 'as', 'snow', 'and', 'everywhere', 'that', 'went', 'the', 'sure', 'to', 'go'] \n \n Word dictionary:\n {'a': 2,\n 'and': 11,\n 'as': 9,\n 'everywhere': 12,\n 'fleece': 6,\n 'go': 18,\n 'had': 1,\n 'lamb': 4,\n 'little': 3,\n 'mary': 0,\n 'snow': 10,\n 'sure': 16,\n 'that': 13,\n 'the': 15,\n 'to': 17,\n 'was': 7,\n 'went': 14,\n 'white': 8,\n 'whose': 5}\n\n\nThese two datastructures already proved their usefulness when we converted our text to a list of tokens.\n\n\n```python\nprint(text_tokens)\n```\n\n [0, 1, 2, 3, 4, 3, 4, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 14, 0, 14, 0, 14, 12, 13, 0, 14, 15, 4, 7, 16, 17, 18]\n\n\nUnfortunately, while this representation is convenient for memory reasons it has some severe limitations. Perhaps the most important of which is the fact that computers naturally assume that numbers can be operated on mathematically (by addition, subtraction, etc) in a way that doesn't match our understanding of words.\n\n## One-hot encoding\n\nOne typical way of overcoming this difficulty is to represent each word by a one-hot encoded vector where every element is zero except the one corresponding to a specific word.\n\n\n```python\ndef one_hot(word, word_dict):\n \"\"\"\n Generate a one-hot encoded vector corresponding to *word*\n \"\"\"\n \n vector = np.zeros(len(word_dict))\n vector[word_dict[word]] = 1\n \n return vector\n```\n\nSo, for example, the word \"fleece\" would be represented by:\n\n\n```python\nfleece_hot = one_hot(\"fleece\", word_dict)\nprint(fleece_hot)\n```\n\n [0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n\n\nThis vector has every element set to zero, except element 6, since:\n\n\n```python\nprint(word_dict[\"fleece\"])\nfleece_hot[6] == 1\n```\n\n 6\n\n\n\n\n\n True\n\n\n\n\n```python\nprint(fleece_hot.sum())\n```\n\n 1.0\n\n\n## Bag of words\n\nWe can now use the one-hot encoded vector for each word to produce a vector representation of our original text, by simply adding up all the one-hot encoded vectors:\n\n\n```python\ntext_vector1 = np.zeros(vocabulary_size)\n\nfor word in text_words:\n hot_word = one_hot(word, word_dict)\n text_vector1 += hot_word\n \nprint(text_vector1)\n```\n\n [6. 2. 2. 4. 5. 1. 1. 2. 1. 1. 1. 1. 2. 2. 4. 1. 1. 1. 1.]\n\n\nIn practice, we can also easily skip the encoding step at the word level by using the *word_dict* defined above:\n\n\n```python\ntext_vector = np.zeros(vocabulary_size)\n\nfor word in text_words:\n text_vector[word_dict[word]] += 1\n \nprint(text_vector)\n```\n\n [6. 2. 2. 4. 5. 1. 1. 2. 1. 1. 1. 1. 2. 2. 4. 1. 1. 1. 1.]\n\n\nNaturally, this approach is completely equivalent to the previous one and has the added advantage of being more efficient in terms of both speed and memory requirements.\n\nThis is known as the __bag of words__ representation of the text. It should be noted that these vectors simply contains the number of times each word appears in our document, so we can easily tell that the word *mary* appears exactly 6 times in our little nursery rhyme.\n\n\n```python\ntext_vector[word_dict[\"mary\"]]\n```\n\n\n\n\n 6.0\n\n\n\nA more pythonic (and efficient) way of producing the same result is to use the standard __Counter__ module:\n\n\n```python\nword_counts = Counter(text_words)\npprint(word_counts)\n```\n\n Counter({'mary': 6,\n 'lamb': 5,\n 'little': 4,\n 'went': 4,\n 'had': 2,\n 'a': 2,\n 'was': 2,\n 'everywhere': 2,\n 'that': 2,\n 'whose': 1,\n 'fleece': 1,\n 'white': 1,\n 'as': 1,\n 'snow': 1,\n 'and': 1,\n 'the': 1,\n 'sure': 1,\n 'to': 1,\n 'go': 1})\n\n\nFrom which we can easily generate the __text_vector__ and __word_dict__ data structures:\n\n\n```python\nitems = list(word_counts.items())\n\n# Extract word dictionary and vector representation\nword_dict2 = dict([[items[i][0], i] for i in range(len(items))])\ntext_vector2 = [items[i][1] for i in range(len(items))]\n```\n\n\n```python\nword_counts['mary']\n```\n\n\n\n\n 6\n\n\n\nAnd let's take a look at them:\n\n\n```python\ntext_vector\n```\n\n\n\n\n array([6., 2., 2., 4., 5., 1., 1., 2., 1., 1., 1., 1., 2., 2., 4., 1., 1.,\n 1., 1.])\n\n\n\n\n```python\nprint(\"Text vector:\", text_vector2, \"\\n\\nWord dictionary:\")\npprint(word_dict2)\n```\n\n Text vector: [6, 2, 2, 4, 5, 1, 1, 2, 1, 1, 1, 1, 2, 2, 4, 1, 1, 1, 1] \n \n Word dictionary:\n {'a': 2,\n 'and': 11,\n 'as': 9,\n 'everywhere': 12,\n 'fleece': 6,\n 'go': 18,\n 'had': 1,\n 'lamb': 4,\n 'little': 3,\n 'mary': 0,\n 'snow': 10,\n 'sure': 16,\n 'that': 13,\n 'the': 15,\n 'to': 17,\n 'was': 7,\n 'went': 14,\n 'white': 8,\n 'whose': 5}\n\n\nThe results using this approach are slightly different than the previous ones, because the words are mapped to different integer ids but the corresponding values are the same:\n\n\n```python\nfor word in word_dict.keys():\n if text_vector[word_dict[word]] != text_vector2[word_dict2[word]]:\n print(\"Error!\")\n```\n\nAs expected, there are no differences!\n\n## Term Frequency\n\nThe bag of words vector representation introduced above relies simply on the frequency of occurence of each word. Following a long tradition of giving fancy names to simple ideas, this is known as __Term Frequency__.\n\nIntuitively, we expect the the frequency with which a given word is mentioned should correspond to the relevance of that word for the piece of text we are considering. For example, **Mary** is a pretty important word in our little nursery rhyme and indeed it is the one that occurs the most often:\n\n\n```python\nsorted(items, key=lambda x:x[1], reverse=True)\n```\n\n\n\n\n [('mary', 6),\n ('lamb', 5),\n ('little', 4),\n ('went', 4),\n ('had', 2),\n ('a', 2),\n ('was', 2),\n ('everywhere', 2),\n ('that', 2),\n ('whose', 1),\n ('fleece', 1),\n ('white', 1),\n ('as', 1),\n ('snow', 1),\n ('and', 1),\n ('the', 1),\n ('sure', 1),\n ('to', 1),\n ('go', 1)]\n\n\n\nHowever, it's hard to draw conclusions from such a small piece of text. Let us consider a significantly larger piece of text, the first 100 MB of the english Wikipedia from: http://mattmahoney.net/dc/textdata. For the sake of convenience, text8.gz has been included in this repository in the **data/** directory. We start by loading it's contents into memory as an array of words:\n\n\n```python\ndata = []\n\nfor line in gzip.open(\"data/text8.gz\", 'rt'):\n data.extend(line.strip().split())\n```\n\nNow let's take a look at the first 50 words in this large corpus:\n\n\n```python\ndata[:50]\n```\n\n\n\n\n ['anarchism',\n 'originated',\n 'as',\n 'a',\n 'term',\n 'of',\n 'abuse',\n 'first',\n 'used',\n 'against',\n 'early',\n 'working',\n 'class',\n 'radicals',\n 'including',\n 'the',\n 'diggers',\n 'of',\n 'the',\n 'english',\n 'revolution',\n 'and',\n 'the',\n 'sans',\n 'culottes',\n 'of',\n 'the',\n 'french',\n 'revolution',\n 'whilst',\n 'the',\n 'term',\n 'is',\n 'still',\n 'used',\n 'in',\n 'a',\n 'pejorative',\n 'way',\n 'to',\n 'describe',\n 'any',\n 'act',\n 'that',\n 'used',\n 'violent',\n 'means',\n 'to',\n 'destroy',\n 'the']\n\n\n\nAnd the top 10 most common words\n\n\n```python\ncounts = Counter(data)\n\nsorted_counts = sorted(list(counts.items()), key=lambda x: x[1], reverse=True)\n\nfor word, count in sorted_counts[:10]:\n print(word, count)\n```\n\n the 1061396\n of 593677\n and 416629\n one 411764\n in 372201\n a 325873\n to 316376\n zero 264975\n nine 250430\n two 192644\n\n\nSurprisingly, we find that the most common words are not particularly meaningful. Indeed, this is a common occurence in Natural Language Processing. The most frequent words are typically auxiliaries required due to gramatical rules.\n\nOn the other hand, there is also a large number of words that occur very infrequently as can be easily seen by glancing at the word freqency distribution.\n\n\n```python\ndist = Counter(counts.values())\ndist = list(dist.items())\ndist.sort(key=lambda x: x[0])\ndist = np.array(dist)\n\nnorm = np.dot(dist.T[0], dist.T[1])\n\nplt.loglog(dist.T[0], dist.T[1]/norm)\nplt.xlabel(\"count\")\nplt.ylabel(\"P(count)\")\nplt.title(\"Word frequency distribution\")\n```\n\n## Stopwords\n\nOne common technique to simplify NLP tasks is to remove what are known as Stopwords, words that are very frequent but not meaningful. If we simply remove the most common 100 words, we significantly reduce the amount of data we have to consider while losing little information.\n\n\n```python\nstopwords = set([word for word, count in sorted_counts[:100]])\n\nclean_data = []\n\nfor word in data:\n if word not in stopwords:\n clean_data.append(word)\n\nprint(\"Original size:\", len(data))\nprint(\"Clean size:\", len(clean_data))\nprint(\"Reduction:\", 1-len(clean_data)/len(data))\n```\n\n Original size: 17005207\n Clean size: 9006229\n Reduction: 0.470384041782026\n\n\n\n```python\nclean_data[:50]\n```\n\n\n\n\n ['anarchism',\n 'originated',\n 'term',\n 'abuse',\n 'against',\n 'early',\n 'working',\n 'class',\n 'radicals',\n 'including',\n 'diggers',\n 'english',\n 'revolution',\n 'sans',\n 'culottes',\n 'french',\n 'revolution',\n 'whilst',\n 'term',\n 'still',\n 'pejorative',\n 'way',\n 'describe',\n 'any',\n 'act',\n 'violent',\n 'means',\n 'destroy',\n 'organization',\n 'society',\n 'taken',\n 'positive',\n 'label',\n 'self',\n 'defined',\n 'anarchists',\n 'word',\n 'anarchism',\n 'derived',\n 'greek',\n 'without',\n 'archons',\n 'ruler',\n 'chief',\n 'king',\n 'anarchism',\n 'political',\n 'philosophy',\n 'belief',\n 'rulers']\n\n\n\nWow, our dataset size was reduced almost in half!\n\nIn practice, we don't simply remove the most common words in our corpus but rather a manually curate list of stopwords. Lists for dozens of languages and applications can easily be found online.\n\n## Term Frequency/Inverse Document Frequency\n\nOne way of determining of the relative importance of a word is to see how often it appears across multiple documents. Words that are relevant to a specific topic are more likely to appear in documents about that topic and much less in documents about other topics. On the other hand, less meaningful words (like **the**) will be common across documents about any subject.\n\nTo measure the document frequency of a word we will need to have multiple documents. For the sake of simplicity, we will treat each sentence of our nursery rhyme as an individual document:\n\n\n```python\nprint(text)\n```\n\n Mary had a little lamb, little lamb,\n little lamb. 'Mary' had a little lamb\n whose fleece was white as snow.\n And everywhere that Mary went\n Mary went, MARY went. Everywhere\n that mary went,\n The lamb was sure to go\n\n\n\n```python\ncorpus_text = text.split('.')\ncorpus_words = []\n\nfor document in corpus_text:\n doc_words = extract_words(document)\n corpus_words.append(doc_words)\n```\n\nNow our corpus is represented as a list of word lists, where each list is just the word representation of the corresponding sentence:\n\n\n```python\nprint(len(corpus_words))\n```\n\n 4\n\n\n\n```python\npprint(corpus_words)\n```\n\n [['mary', 'had', 'a', 'little', 'lamb', 'little', 'lamb', 'little', 'lamb'],\n ['mary',\n 'had',\n 'a',\n 'little',\n 'lamb',\n 'whose',\n 'fleece',\n 'was',\n 'white',\n 'as',\n 'snow'],\n ['and', 'everywhere', 'that', 'mary', 'went', 'mary', 'went', 'mary', 'went'],\n ['everywhere',\n 'that',\n 'mary',\n 'went',\n 'the',\n 'lamb',\n 'was',\n 'sure',\n 'to',\n 'go']]\n\n\nLet us now calculate the number of documents in which each word appears:\n\n\n```python\ndocument_count = {}\n\nfor document in corpus_words:\n word_set = set(document)\n \n for word in word_set:\n document_count[word] = document_count.get(word, 0) + 1\n\npprint(document_count)\n```\n\n {'a': 2,\n 'and': 1,\n 'as': 1,\n 'everywhere': 2,\n 'fleece': 1,\n 'go': 1,\n 'had': 2,\n 'lamb': 3,\n 'little': 2,\n 'mary': 4,\n 'snow': 1,\n 'sure': 1,\n 'that': 2,\n 'the': 1,\n 'to': 1,\n 'was': 2,\n 'went': 2,\n 'white': 1,\n 'whose': 1}\n\n\nAs we can see, the word __Mary__ appears in all 4 of our documents, making it useless when it comes to distinguish between the different sentences. On the other hand, words like __white__ which appear in only one document are very discriminative. Using this approach we can define a new quantity, the ___Inverse Document Frequency__ that tells us how frequent a word is across the documents in a specific corpus:\n\n\n```python\ndef inv_doc_freq(corpus_words):\n number_docs = len(corpus_words)\n \n document_count = {}\n\n for document in corpus_words:\n word_set = set(document)\n\n for word in word_set:\n document_count[word] = document_count.get(word, 0) + 1\n \n IDF = {}\n \n for word in document_count:\n IDF[word] = np.log(1+number_docs/document_count[word])\n \n return IDF\n```\n\nWhere we followed the convention of using the logarithm of the inverse document frequency. This has the numerical advantage of avoiding to have to handle small fractional numbers. \n\nWe can easily see that the IDF gives a smaller weight to the most common words and a higher weight to the less frequent:\n\n\n```python\ncorpus_words\n```\n\n\n\n\n [['mary', 'had', 'a', 'little', 'lamb', 'little', 'lamb', 'little', 'lamb'],\n ['mary',\n 'had',\n 'a',\n 'little',\n 'lamb',\n 'whose',\n 'fleece',\n 'was',\n 'white',\n 'as',\n 'snow'],\n ['and', 'everywhere', 'that', 'mary', 'went', 'mary', 'went', 'mary', 'went'],\n ['everywhere',\n 'that',\n 'mary',\n 'went',\n 'the',\n 'lamb',\n 'was',\n 'sure',\n 'to',\n 'go']]\n\n\n\n\n```python\nIDF = inv_doc_freq(corpus_words)\n\npprint(IDF)\n```\n\n {'a': 1.0986122886681098,\n 'and': 1.6094379124341003,\n 'as': 1.6094379124341003,\n 'everywhere': 1.0986122886681098,\n 'fleece': 1.6094379124341003,\n 'go': 1.6094379124341003,\n 'had': 1.0986122886681098,\n 'lamb': 0.8472978603872034,\n 'little': 1.0986122886681098,\n 'mary': 0.6931471805599453,\n 'snow': 1.6094379124341003,\n 'sure': 1.6094379124341003,\n 'that': 1.0986122886681098,\n 'the': 1.6094379124341003,\n 'to': 1.6094379124341003,\n 'was': 1.0986122886681098,\n 'went': 1.0986122886681098,\n 'white': 1.6094379124341003,\n 'whose': 1.6094379124341003}\n\n\nAs expected **Mary** has the smallest weight of all words 0, meaning that it is effectively removed from the dataset. You can consider this as a way of implicitly identify and remove stopwords. In case you do want to keep even the words that appear in every document, you can just add a 1. to the argument of the logarithm above:\n\n\\begin{equation}\n\\log\\left[1+\\frac{N_d}{N_d\\left(w\\right)}\\right]\n\\end{equation}\n\nWhen we multiply the term frequency of each word by it's inverse document frequency, we have a good way of quantifying how relevant a word is to understand the meaning of a specific document.\n\n\n```python\ndef tf_idf(corpus_words):\n IDF = inv_doc_freq(corpus_words)\n \n TFIDF = []\n \n for document in corpus_words:\n TFIDF.append(Counter(document))\n \n for document in TFIDF:\n for word in document:\n document[word] = document[word]*IDF[word]\n \n return TFIDF\n```\n\n\n```python\ntf_idf(corpus_words)\n```\n\n\n\n\n [Counter({'mary': 0.6931471805599453,\n 'had': 1.0986122886681098,\n 'a': 1.0986122886681098,\n 'little': 3.295836866004329,\n 'lamb': 2.5418935811616103}),\n Counter({'mary': 0.6931471805599453,\n 'had': 1.0986122886681098,\n 'a': 1.0986122886681098,\n 'little': 1.0986122886681098,\n 'lamb': 0.8472978603872034,\n 'whose': 1.6094379124341003,\n 'fleece': 1.6094379124341003,\n 'was': 1.0986122886681098,\n 'white': 1.6094379124341003,\n 'as': 1.6094379124341003,\n 'snow': 1.6094379124341003}),\n Counter({'and': 1.6094379124341003,\n 'everywhere': 1.0986122886681098,\n 'that': 1.0986122886681098,\n 'mary': 2.0794415416798357,\n 'went': 3.295836866004329}),\n Counter({'everywhere': 1.0986122886681098,\n 'that': 1.0986122886681098,\n 'mary': 0.6931471805599453,\n 'went': 1.0986122886681098,\n 'the': 1.6094379124341003,\n 'lamb': 0.8472978603872034,\n 'was': 1.0986122886681098,\n 'sure': 1.6094379124341003,\n 'to': 1.6094379124341003,\n 'go': 1.6094379124341003})]\n\n\n\nNow we finally have a vector representation of each of our documents that takes the informational contributions of each word into account. Each of these vectors provides us with a unique representation of each document, in the context (corpus) in which it occurs, making it posssible to define the similarity of two documents, etc.\n\n## Porter Stemmer\n\nThere is still, however, one issue with our approach to representing text. Since we treat each word as a unique token and completely independently from all others, for large documents we will end up with many variations of the same word such as verb conjugations, the corresponding adverbs and nouns, etc. \n\nOne way around this difficulty is to use stemming algorithm to reduce words to their root (or stem) version. The most famous Stemming algorithm is known as the **Porter Stemmer** and was introduced by Martin Porter in 1980 [Program 14, 130 (1980)](https://dl.acm.org/citation.cfm?id=275705)\n\nThe algorithm starts by defining consonants (C) and vowels (V):\n\n\n```python\nV = set('aeiouy')\nC = set('bcdfghjklmnpqrstvwxz')\n```\n\nThe stem of a word is what is left of that word after a speficic ending has been removed. A function to do this is easy to implement:\n\n\n```python\ndef get_stem(suffix, word):\n \"\"\"\n Extract the stem of a word\n \"\"\"\n \n if word.lower().endswith(suffix.lower()): # Case insensitive comparison\n return word[:-len(suffix)]\n\n return None\n```\n\nIt also defines words (or stems) to be sequences of vowels and consonants of the form:\n\n\\begin{equation}\n[C](VC)^m[V]\n\\end{equation}\n\nwhere $m$ is called the **measure** of the word and [] represent optional sections. \n\n\n```python\ndef measure(orig_word):\n \"\"\"\n Calculate the \"measure\" m of a word or stem, according to the Porter Stemmer algorthim\n \"\"\"\n \n word = orig_word.lower()\n\n optV = False\n optC = False\n VC = False\n\n m = 0\n pos = 0\n\n # We can think of this implementation as a simple finite state machine\n # looks for sequences of vowels or consonants depending of the state\n # in which it's in, while keeping track of how many VC sequences it\n # has encountered.\n # The presence of the optional V and C portions is recorded in the\n # optV and optC booleans.\n \n # We're at the initial state.\n # gobble up all the optional consonants at the beginning of the word\n while pos < len(word) and word[pos] in C:\n pos += 1\n optC = True\n\n while pos < len(word):\n # Now we know that the next state must be a vowel\n while pos < len(word) and word[pos] in V:\n pos += 1\n optV = True\n\n # Followed by a consonant\n while pos < len(word) and word[pos] in C:\n pos += 1\n optV = False\n \n # If a consonant was found, then we matched VC\n # so we should increment m by one. Otherwise, \n # optV remained true and we simply had a dangling\n # V sequence.\n if not optV:\n m += 1\n\n return m\n```\n\nLet's consider a simple example. The word __crepusculars__ should have measure 4:\n\n[cr] (ep) (usc) (ul) (ars)\n\nand indeed it does.\n\n\n```python\nword = \"crepusculars\"\nprint(measure(word))\n```\n\n 4\n\n\n(agr) = (VC)\n\n\n```python\nword = \"agr\"\nprint(measure(word))\n```\n\n 1\n\n\nThe Porter algorithm sequentially applies a series of transformation rules over a series of 5 steps (step 1 is divided in 3 substeps and step 5 in 2). The rules are only applied if a certain condition is true. \n\nIn addition to possibily specifying a requirement on the measure of a word, conditions can make use of different boolean functions as well: \n\n\n```python\ndef ends_with(char, stem):\n \"\"\"\n Checks the ending of the word\n \"\"\"\n return stem[-1] == char\n\ndef double_consonant(stem):\n \"\"\"\n Checks the ending of a word for a double consonant\n \"\"\"\n if len(stem) < 2:\n return False\n\n if stem[-1] in C and stem[-2] == stem[-1]:\n return True\n\n return False\n\ndef contains_vowel(stem):\n \"\"\"\n Checks if a word contains a vowel or not\n \"\"\"\n return len(set(stem) & V) > 0 \n```\n\nFinally, we define a function to apply a specific rule to a word or stem:\n\n\n```python\ndef apply_rule(condition, suffix, replacement, word):\n \"\"\"\n Apply Porter Stemmer rule.\n if \"condition\" is True replace \"suffix\" by \"replacement\" in \"word\"\n \"\"\"\n \n stem = get_stem(suffix, word)\n\n if stem is not None and condition is True:\n # Remove the suffix\n word = stem\n\n # Add the replacement suffix, if any\n if replacement is not None:\n word += replacement\n\n return word\n```\n\nNow we can see how rules can be applied. For example, this rule, from step 1b is successfully applied to __pastered__:\n\n\n```python\nword = \"plastered\"\nsuffix = \"ed\"\nstem = get_stem(suffix, word)\napply_rule(contains_vowel(stem), suffix, None, word)\n```\n\n\n\n\n 'plaster'\n\n\n\n\n```python\nstem\n```\n\n\n\n\n 'plaster'\n\n\n\n\n```python\ncontains_vowel(stem)\n```\n\n\n\n\n True\n\n\n\nWhile try applying the same rule to **bled** will fail to pass the condition resulting in no change.\n\n\n```python\nword = \"bled\"\nsuffix = \"ed\"\nstem = get_stem(suffix, word)\napply_rule(contains_vowel(stem), suffix, None, word)\n```\n\n\n\n\n 'bled'\n\n\n\n\n```python\nstem\n```\n\n\n\n\n 'bl'\n\n\n\n\n```python\ncontains_vowel(stem)\n```\n\n\n\n\n False\n\n\n\nFor a more complex example, we have, in Step 4:\n\n\n```python\nword = \"adoption\"\nsuffix = \"ion\"\nstem = get_stem(suffix, word)\napply_rule(measure(stem) > 1 and (ends_with(\"s\", stem) or ends_with(\"t\", stem)), suffix, None, word)\n```\n\n\n\n\n 'adopt'\n\n\n\n\n```python\nends_with(\"t\", stem)\n```\n\n\n\n\n True\n\n\n\n\n```python\nends_with(\"s\", stem)\n```\n\n\n\n\n False\n\n\n\n\n```python\nmeasure(stem)\n```\n\n\n\n\n 2\n\n\n\nIn total, the Porter Stemmer algorithm (for the English language) applies several dozen rules (see https://tartarus.org/martin/PorterStemmer/def.txt for a complete list). Implementing all of them is both tedious and error prone, so we abstain from providing a full implementation of the algorithm here. High quality implementations can be found in all major NLP libraries such as [NLTK](http://www.nltk.org/howto/stem.html).\n\nThe dificulties of defining matching rules to arbitrary text cannot be fully resolved without the use of Regular Expressions (typically implemented as Finite State Machines like our __measure__ implementation above), a more advanced topic that is beyond the scope of this course.\n\n
\n \n
\n", "meta": {"hexsha": "b4542b6a6fb3e4297891dfb1fd45accc5a7a5419", "size": 267051, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1. Text Representation.ipynb", "max_stars_repo_name": "millsgt/NLP", "max_stars_repo_head_hexsha": "200da19d1372a8520625681edd5e0011a727be43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 97, "max_stars_repo_stars_event_min_datetime": "2019-05-06T13:27:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T17:36:22.000Z", "max_issues_repo_path": "1. Text Representation.ipynb", "max_issues_repo_name": "millsgt/NLP", "max_issues_repo_head_hexsha": "200da19d1372a8520625681edd5e0011a727be43", "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": "1. Text Representation.ipynb", "max_forks_repo_name": "millsgt/NLP", "max_forks_repo_head_hexsha": "200da19d1372a8520625681edd5e0011a727be43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 78, "max_forks_repo_forks_event_min_datetime": "2019-05-06T12:14:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T10:57:28.000Z", "avg_line_length": 134.1290808639, "max_line_length": 216456, "alphanum_fraction": 0.8812024669, "converted": true, "num_tokens": 7761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.21733751597763015, "lm_q1q2_score": 0.08608046831716423}} {"text": "# Homework 1\n\n**For exercises in the week 22-28.10.19**\n\n**Points: 7 + 2 bonus point**\n\nPlease solve the problems at home and bring to class a [declaration form](http://ii.uni.wroc.pl/~jmi/Dydaktyka/misc/kupony-klasyczne.pdf) to indicate which problems you are willing to present on the backboard.\n\n\n\n### Declartation\n\n| Exercise || 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |\n|----------||---|---|---|---|---|---|---|---|\n| Points || 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 |\n\n## Problem 1 (McKay 4.1) [1p]\n\nYou are given a set of 12 balls in which:\n- 11 balls are equal\n- 1 ball is different (either heavier or lighter).\n\nYou have a two-pan balance. How many weightings you must use to detect toe odd ball?\n\n*Hint:* A weighting can be seen as a random event. You can design them to maximize carry the most information, i.e. to maximize the entropy of their outcome.\n\n## Answ 1:\n\n\nhttp://learning.eng.cam.ac.uk/pub/Public/Turner/Teaching/ml-lecture-1-slides.pdf\n\n## Problem 2 [1p]\n\nBayes' theorem allows to reason about conditional probabilities of causes and their effects:\n\n\\begin{equation}\np(A,B)=p(A|B)p(B)=p(B|A)p(A)\n\\end{equation}\n\n\\begin{equation}\np(A|B) = \\frac{p(B|A)p(A)}{p(B)}\n\\end{equation}\n\nBayes' theorem allows us to reason about probabilities of causes, when\nwe observe their results. Instead of directly answering the hard\nquestion $p(\\text{cause}|\\text{result})$ we can instead separately\nwork out the marginal probabilities of causes $p(\\text{cause})$ and\ncarefully study their effects $p(\\text{effect}|\\text{cause})$.\n\nSolve the following using Bayes' theorem.\n\n1. There are two boxes on the table: box \\#1 holds two\n black balls and eight red ones, box \\#2 holds 5 black ones and\n 5 red ones. We pick a box at random (with equal probabilities),\n and then a ball from that box.\n 1. What is the probability, that the\n ball came from box \\#1 if we happened to pick a red ball?\n \n1. The government has started a preventive program of\n mandatory tests for the Ebola virus. Mass testing method is\n imprecise, yielding 1% of false positives (healthy, but the test\n indicates the virus) and 1% of false negatives (\n having the virus but healthy according to test results).\n As Ebola is rather infrequent, lets assume that it occurs in\n one in a million people in Europe.\n 1. What is the probability,\n that a random European, who has been tested positive for Ebola\n virus, is indeed a carrier?\n 2. Suppose we have an additional information, that the person has just\n arrived from a country where one in a thousand people is a carrier.\n How much will be the increase in probability?\n 3. How accurate should be the test, for a 80% probability of true\n positive in a European?\n\n## Ans 2:\n\n1A.\n$$ \\frac{\\frac{8}{10} * \\frac{1}{2}}{\\frac{13}{20}} $$\n2A.\n$$ \\frac{\\frac{99}{100} * \\frac{1}{1 000 000}}{\\frac{1}{1 000 000} * 0.99 + (1-\\frac{1}{1 000 000}) * 0.01} $$\n\n\n```python\nacc = .99\nD = 10**-6\nppb = lambda acc, D: (acc * D)/(D * acc + (1 - D) * (1 - acc) )\nP1 = ppb(acc, D)\n\nD = 10**-3\n\nP2 = ppb(acc, D)\n\nprint(f\"P1: {P1}, P2: {P2}\")\n\nfor i in range(10):\n acc = 1 - 1/10**i\n print(acc, ppb(acc, 10**-6)) \nacc=0.9999997499999\nprint(acc, ppb(acc, 10**-6))\n```\n\n P1: 9.899029895070276e-05, P2: 0.09016393442622944\n 0.0 0.0\n 0.9 8.999928000575998e-06\n 0.99 9.899029895070276e-05\n 0.999 0.0009980039920159671\n 0.9999 0.009900019604000295\n 0.99999 0.09090834710646178\n 0.999999 0.49999999999281103\n 0.9999999 0.9090909835145884\n 0.99999999 0.9900990195566637\n 0.999999999 0.9990010000262294\n 0.9999997499999 0.8000000560288553\n\n\n## Problem 3 [1.5p]\n\nGiven observations $x_1,\\ldots,x_n$\n coming from a certain distribution,\n prove that MLE of a particular parameter of that distribution is equal to the sample mean $\\frac{1}{n}\\sum_{i=1}^n x_i$:\n1. Bernoulli distribution with success probability $p$ and MLE $\\hat{p}$,\n2. Gaussian distribution $\\mathcal{N}(\\mu,\\sigma)$ and MLE $\\hat{\\mu}$,\n3. Poisson distribution $\\mathit{Pois}(\\lambda)$ and MLE $\\hat{\\lambda}$.\n\n\n```python\n\n```\n\n## Problem 4 [1.5p]\n\n1D Gaussian manipulatoin for Kalman filters.\n\nA [1D Kalman filter](https://en.wikipedia.org/wiki/Kalman_filter) tracks the location of an object given imprecise measurements of its location. At its core it performs an update of the form:\n\n$$\n p(x|m) = \\frac{p(m|x)p(x)}{p(m)} = \\frac{p(m|x)p(x)}{Z},\n$$\n\nwhere:\n- $p(x|m)$ is the updated belief about the location,\n- $p(x) = \\mathcal{N}(\\mu=\\mu_x, \\sigma=\\sigma_x)$ is the belief about the location,\n- $p(m|x) = \\mathcal{N}(\\mu=x, \\sigma=\\sigma_m)$ is the noisy measurement, centered on the location of the object,\n- $Z = p(m) =\\int p(m|x)p(x) dx$ is a normalization constant not dependent on $x$.\n\nCompute $p(x|m)$.\n\n*Hint:* The product $\\mathcal{N}(x;\\mu_1, \\sigma_1)\\mathcal{N}(x;\\mu_2, \\sigma_2)$ ressembles an unnormalized probability distribution, which one? Can you normalize it by computing the mean and standard deviation and fitting it to a knoen PDF?\n\n## Problem 5 (Murphy, 2.17) [1p]\n\nExpected value of the minimum.\n\nLet $X, Y$ be sampled uniformily on the interval $[0,1]$. What is the expected value of $\\min(X,Y)$?\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.random.rand(10000)\n\nx = np.min(np.random.rand(2,100000000), axis=0)\nx.shape\n# plt.scatter(range(len(x)), np.sort(x))\nnp.mean(x)\n```\n\n\n\n\n 0.33335897927530145\n\n\n\nhttp://premmi.github.io/expected-value-of-minimum-two-random-variables\n\n## Problem 6 (Kohavi) [1p]\n\nThe failure of leave-one-out evaluation. \n\nConsider a binary classification dataset in which the labels are assigned completely at random, with 50% probability given to either class. Assume you have a collected a dataset with 100 records in which exactly 50 of them belong to class 0 and 50 to class 1. \n\nWhat will be the leave-one-out accuracy of the majority voting classifier?\n\nNB: sometimes it is useful to equalize the number of classes in each fold of cross-validation, e.g. using the [StratifiedKFold](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html) implementation from SKlearn.\n\n## Ans 6:\n\n0, because everytime the majority decides, and majority is always different than the one which left.\n\n## Problem 7 [1pb]\nDo Problem 7a from [Assignment 1](https://github.com/janchorowski/ml_uwr/blob/fall2019/assignment1/Assignment1.ipynb).\n\n## Problem 8 [1bp]\n\nMany websites ([Reddit](reddit.com), [Wykop](wykop.pl), [StackOverflow](stackoverflow.com)) provide sorting of comments based on user votes. Discuss what are the implications when sorting by:\n- difference between up- and down-votes\n- mean score\n- lower or upper confidence bound of the score\n\nAt least for Reddit the sorting algorithm can be found online, what is it?\n\n## Ans 8:\n### 1:\n\n\n### 2:\n\n\n### 4:\n\n\n#ruby\nrequire 'statistics2'\n\ndef ci_lower_bound(pos, n, confidence)\n if n == 0\n return 0\n end\n z = Statistics2.pnormaldist(1-(1-confidence)/2)\n phat = 1.0*pos/n\n (phat + z*z/(2*n) - z * Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)\nend", "meta": {"hexsha": "1b9d894c71405318b992eac58e588c76e64a9f42", "size": 359251, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homework1/Homework1.ipynb", "max_stars_repo_name": "iCarrrot/ML", "max_stars_repo_head_hexsha": "05177012d36ca64a5b2730287b3ae5b086306197", "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": "homework1/Homework1.ipynb", "max_issues_repo_name": "iCarrrot/ML", "max_issues_repo_head_hexsha": "05177012d36ca64a5b2730287b3ae5b086306197", "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": "homework1/Homework1.ipynb", "max_forks_repo_name": "iCarrrot/ML", "max_forks_repo_head_hexsha": "05177012d36ca64a5b2730287b3ae5b086306197", "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": 874.0900243309, "max_line_length": 176996, "alphanum_fraction": 0.9526236531, "converted": true, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1732882037945951, "lm_q1q2_score": 0.08596720862259781}} {"text": "
\n\n*Practical Data Science*\n\n# Feature Engineering\n\nNikolai Stein
\nChair of Information Systems and Management\n\nWinter Semester 21/22\n\n

Table of Contents

\n\n\n__Credits__\n\nParts of the material of this lecture are adopted from www.kaggle.com\n\n## Introduction\n\n**This lecture provides an overview on different feature engineering techniques.**\n\nStarting with a baseline dataset, we will\n\n- modify existing variables \n- add additional features to our dataset \n- train a predictive model \n\n**Feature engineering** is an essential part of building a powerful predictive model. \n\nEach problem is domain specific and better features (suited to the problem) are often the deciding factor of the performance of your system. \n\nFeature Engineering requires experience as well as creativity and this is the reason **Data Scientists often spend the majority of their time** in the data preparation phase before modeling.\n\n_\"Coming up with features is difficult, time-consuming, requires expert knowledge. Applied machine learning is basically feature engineering.\"_\n\nProf. Andrew Ng.\n\n_\"Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data.\"_\n\nDr. Jason Brownlee\n\n_\"At the end of the day, some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used.\"_\n\nProf. Pedro Domingos\n\n## Loading the Data\nThis week, we will work with a sample of the [adult dataset](https://archive.ics.uci.edu/ml/datasets/adult) which has some census information on individuals. We'll use it to train a model to predict whether salary is greater than \\$50k or not. Again, our first step is to load and familiarize ourself with the data. To this end, we can use the pandas library and load the dataset with the following commands:\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\nfile_path = 'https://github.com/NikoStein/pds_data/raw/main/data/adult.csv'\nadult_data = pd.read_csv(file_path)\nadult_data.head()\n```\n\n## Select Variables and Split Dataset\n\nBefore we start to engineer new features, we select the feature and target variables. \n\nThe (binary) variable ``salary`` describes if a person earns more or less that \\\\$50k. We replace the labels with numeric values (0: Salary < \\\\$50k, 1: Salary > \\\\$50k) and subsequently select it as our target variable y.\n\n\n```python\nadult_data = adult_data.assign(salary=(adult_data['salary']=='>=50k').astype(int))\ny = adult_data['salary']\n```\n\nThe remaining columns serve as our features X.\n\n\n```python\nX = adult_data.drop('salary', axis=1)\n```\n\nNext, we perform a train-test split to train and evaluate our machine learning models for the model validation.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state = 0)\n```\n\nNow we are ready to start preparing and enhancing our numerical and categorical features!\n\n## Feature Engineering on Numeric Data\n\nBy Numeric data we mean continuous data and not discrete data which is typically represented as categorical data. Integers and floats are the most common and widely used numeric data types for continuous numeric data. Even though numeric data can be directly fed into machine learning models, we still have to engineer and preprocess features which are relevant to the scenario, problem, domain and machine learning model.\n\nTo this end, we can distinguish between preprocessing and feature generation.\n\nTo work on our numeric features, we have to identify all numeric columns in our dataset:\n\n\n```python\nnumCols = [cname for cname in train_X.columns if train_X[cname].dtype != \"object\"]\nnumCols\n```\n\nTo avoid problems with missing values we use a ``SimpleImputer`` for the numeric columns before we continue:\n\n\n```python\nfrom sklearn.impute import SimpleImputer\n\nsimple_imputer = SimpleImputer()\n\ntrain_X_num = pd.DataFrame(simple_imputer.fit_transform(train_X[numCols]), columns=numCols, index=train_X.index)\nval_X_num = pd.DataFrame(simple_imputer.transform(val_X[numCols]), columns=numCols, index=val_X.index)\n```\n\n### Preprocessing\n\nOur dataset may contain attributes with a mixture of scales for various quantities. However, many machine learning methods require or at least are more effective if the data attributes have the same scale. \n\nFor example, ``capital gain`` and ``capital loss`` is measured in USD while age is measured in years in our dataset at hand.\n\nTo avoid having numeric values from different scales we can use two popular data scaling methods: normalization and standardization.\n\n#### Normalization\n\nNormalization refers to rescaling numeric attributes into the range 0 and 1. It is useful to scale the input attributes for a model that relies on the magnitude of values, such as distance measures used in k-nearest neighbors and in the preparation of coefficients in regression.\n\nUsing Scikit-learn's ``MinMaxScaler`` we can rescale an attribute according to the following formula:\n\n\n\\begin{equation}\n X = \\frac{(X - min(X))}{(max(X) - min(X))}\n\\end{equation}\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\n\nscaler = MinMaxScaler()\n\ntrain_X_num_normalized = pd.DataFrame(scaler.fit_transform(train_X_num), \n columns=train_X_num.columns, index=train_X_num.index)\nval_X_num_normalized = pd.DataFrame(scaler.transform(val_X_num), \n columns=train_X_num.columns, index=val_X_num.index)\n\ntrain_X_num_normalized\n```\n\n#### Standardization\n\nIn contrast to normalization, we could also use standardization for our numerical variables. In this context, standardization refers to shifting the distribution of each attribute to have a mean of zero and a standard deviation of one. It is useful to standardize attributes for a model that relies on the distribution of attributes such as Gaussian processes.\n\nUsing Scikit-learn's ```StandardScaler``` we can rescale an attribute according to the following formula:\n\n\n\\begin{equation}\n X = \\frac{(X - mean(X))}{\\sqrt{var(X)}}\n\\end{equation}\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\n\ntrain_X_num_standardized = pd.DataFrame(scaler.fit_transform(train_X_num), \n columns=train_X_num.columns, index=train_X_num.index)\nval_X_num_standardized = pd.DataFrame(scaler.transform(val_X_num), \n columns=train_X_num.columns, index=val_X_num.index)\n\ntrain_X_num_standardized.head()\n```\n\n#### Summary\n\nData rescaling is an important part of data preparation before applying machine learning algorithms. However, it is hard to know whether normalization or standardization of the data will improve the performance of a predictive model in advance. \n\nA good tip for a practical application is to create rescaled copies of your dataset and evaluate them against each other. This process can quickly show which rescaling method will improve your selected models in the problem at hand.\n\n### Binarization\n\nFor some problems raw frequencies or counts may not be relevant for building a model. In these cases it is only relevant if a numeric value exceeds a specific threshold (e.g. a person is at least 40 years old). Hence we do not require the number of times the action was performed but only a binary feature.\n\nWe can binarize a feature using Scikit-learn's ``Binarizer`` function (Note that we use the raw dataset for this example - clearly we could normalize or standardize the dataframe afterwards):\n\n\n```python\nfrom sklearn.preprocessing import Binarizer\n\ntrain_X_binary_age = train_X_num.copy()\nval_X_binary_age = val_X_num.copy()\n\nbinarizer = Binarizer(threshold=40)\n\ntrain_X_binary_age['40Plus'] = binarizer.transform([train_X_binary_age['age']])[0]\nval_X_binary_age['40Plus'] = binarizer.transform([val_X_binary_age['age']])[0]\n\ntrain_X_binary_age.head()\n```\n\n### Binning\n\nThe problem of working with raw, numeric features is that often the distribution of values in these features will be skewed. This signifies that some values will occur quite frequently while some will be quite rare. Hence there are strategies to deal with this, which include binning. \n\nBinning is used for transforming continuous numeric features into discrete ones. These discrete values can be interpreted as categories or bins into which the raw values are grouped into. Each group represents a specific degree of intensity and hence a specific range of continuous numeric values fall into it.\n\nLet's again use the age variable to perform two different types of binning.\n\n#### Fixed-Width Binning\n\nIn fixed-width binning, specific fixed widths for each bin are defined by the user. Each bin has a fixed range of values which should be assigned to that bin on the basis of some domain knowledge.\n\nWe can use Pandas ```cut``` function to bin the age into predefined groups and assign labels:\n\n\n```python\ntrain_X_bin_age = train_X_num.copy()\nval_X_bin_age = val_X_num.copy()\n\nbin_ranges = [0, 25, 60, 999]\nbin_labels = [0, 1, 2]\n\ntrain_X_bin_age['AgeBinned'] = pd.cut(train_X_bin_age['age'], \n bins=bin_ranges, labels=bin_labels)\nval_X_bin_age['AgeBinned'] = pd.cut(val_X_bin_age['age'], \n bins=bin_ranges, labels=bin_labels)\n\ntrain_X_bin_age.head()\n```\n\n#### Adaptive Binning\n\nThe major drawback in using fixed-width binning is unbalanced bin sizes. As we manually decide the bin ranges, we can end up with irregular bins which are not uniform based on the number of data points. Some bins (such as \"young (0)\" and \"old (2)\") might be sparsely populated while some (such as \"medium (1)\") are densely populated.\n\nTo overcome this issues we can use adaptive binning based on the distribution of the data.\n\nTo cut the space into equal partitions we can use the quantiles as cut-points:\n\n\n```python\nquantile_list = [0, 0.33, 0.66, 1]\nquantile_labels = [0, 1, 2]\n\ntrain_X_bin_age['AgeBinnedAdaptive'] = pd.qcut(train_X_bin_age['age'], \n q=quantile_list, labels=quantile_labels)\nval_X_bin_age['AgeBinnedAdaptive'] = pd.qcut(val_X_bin_age['age'], \n q=quantile_list, labels=quantile_labels)\n\ntrain_X_bin_age.head(5)\n```\n\n### Statistical Transformations\n\nMany variables, such as ``capital-gain`` or ``fnlwgt`` (sampling weight) span several orders of magnitude. While the vast majority of persons has very small capital-gains, a few people have very high gains. To work with such skewed variables we can use the log transformation. \n\nLog transforms are useful when applied to skewed distributions as they tend to expand the values which fall in the range of lower magnitudes and tend to compress or reduce the values which fall in the range of higher magnitudes. This tends to make the skewed distribution as normal-like as possible.\n\n\n```python\nimport numpy as np\n\ntrain_X_logGains = train_X_num.copy()\nval_X_logGains = val_X_num.copy()\n\ntrain_X_logGains['logfnlwgt'] = np.log1p(train_X_logGains['fnlwgt'])\nval_X_logGains['logfnlwgt'] = np.log1p(val_X_logGains['fnlwgt'])\n```\n\nWe can see this effect plotting both histograms:\n\n\n```python\n%matplotlib inline\ntrain_X_logGains[['fnlwgt', 'logfnlwgt']].hist();\n```\n\n### Evaluation\n\nWe can train support vector machines (``SVC``) using the different datasets and feature engineering techniques to evaluate their impact on the model performance. Note that we could (and should) combine these techniques to train powerful models and apply them in real-world problems.\n\n\n```python\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\n\ndef score_dataset(X_train, X_valid, y_train, y_valid):\n model = SVC(gamma='auto', random_state=0)\n model.fit(X_train, y_train)\n preds = model.predict(X_valid)\n return accuracy_score(y_valid, preds)\n```\n\n\n```python\nprint(\"Raw Features: {}\".\n format(score_dataset(train_X_num, val_X_num, train_y, val_y)))\nprint(\"Normalized Features: {}\".\n format(score_dataset(train_X_num_normalized, val_X_num_normalized, train_y, val_y)))\nprint(\"Standardized Features: {}\".\n format(score_dataset(train_X_num_standardized, val_X_num_standardized, train_y, val_y)))\nprint(\"Binary Age: {}\".format(score_dataset(train_X_binary_age, val_X_binary_age, train_y, val_y)))\nprint(\"Binned Age: {}\".format(score_dataset(train_X_bin_age, val_X_bin_age, train_y, val_y)))\nprint(\"Log FNLWGT: {}\".format(score_dataset(train_X_logGains, val_X_logGains, train_y, val_y)))\n```\n\n## Feature Engineering on Categorical Data\n\nIn contrast to continuous numeric data we mean discrete values which belong to a specific finite set of categories or classes when we talk about categorical data. These discrete values can be text or numeric in nature and there are two major classes of categorical data, nominal and ordinal.\n\nWhile a lot of advancements have been made in state of the art machine learning frameworks to accept categorical data types like text labels. Typically any standard workflow in feature engineering involves some form of transformation of these categorical values into numeric labels and then applying some encoding scheme on these values.\n\n### Label and One-Hot-Encoding\n\nLast week, we already talked about label and one-hot-encoding to prepare our categorical features for machine learning models. To get started, we will impute missing values and encode all categorical features using the ``OrdinalEncoder``:\n\n\n```python\nfrom sklearn.preprocessing import OrdinalEncoder\n```\n\nAgain, we will use a helper function to evaluate the performance of our models. This time, we will rely on a random forest model.\n\n\n```python\ncatCols = [cname for cname in train_X.columns if train_X[cname].dtype == \"object\"]\n\ntrain_X_cat = train_X[catCols].copy()\nval_X_cat = val_X[catCols].copy()\n\nsimple_imputer = SimpleImputer(strategy='most_frequent')\n\ntrain_X_labelenc = pd.DataFrame(simple_imputer.fit_transform(train_X_cat), columns=train_X_cat.columns, index=train_X_cat.index)\nval_X_labelenc = pd.DataFrame(simple_imputer.transform(val_X_cat), columns=val_X_cat.columns, index=val_X_cat.index)\n\nordinal_encoder = OrdinalEncoder()\ntrain_X_labelenc = pd.DataFrame(ordinal_encoder.fit_transform(train_X_labelenc), columns=train_X_cat.columns, index=train_X_cat.index)\nval_X_labelenc = pd.DataFrame(ordinal_encoder.transform(val_X_labelenc), columns=val_X_cat.columns, index=val_X_cat.index)\n\ntrain_X_labelenc.head()\n```\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef score_dataset(X_train, X_valid, y_train, y_valid):\n model = RandomForestClassifier(n_estimators=100, random_state=0)\n model.fit(X_train, y_train)\n preds = model.predict(X_valid)\n return accuracy_score(y_valid, preds)\n```\n\nTo evaluate the model we combine the raw numerical data and the encoded categorical variables.\n\n\n```python\ntrain_X_label_num = train_X_num_standardized.join(train_X_labelenc.add_suffix(\"_labelenc\"))\nval_X_label_num = val_X_num_standardized.join(val_X_labelenc.add_suffix(\"_labelenc\"))\n\n\nprint(\"Label encoded categorical + raw numeric: {}\".\n format(score_dataset(train_X_label_num, val_X_label_num, train_y, val_y)))\n```\n\n### Count Encodings\n\nWhile label and one-hot encoding often yield good results, there are also a lot of other (more complex) techniques to encode categorical variables. The package [categorical-encoding](https://github.com/scikit-learn-contrib/categorical-encoding) offers implementations of many different techniques.\n\nOne prominent variant is called count encoding. Count encoding replaces each categorical value with the number of times it appears in the dataset. For example, if the value \"USA\" occures 50 times in the country feature, then each \"USA\" would be replaced with the number 50.\n\n\n```python\n!pip install category_encoders\n```\n\nor\n\n\n```python\n!conda install -c conda-forge category_encoders -y\n```\n\n\n```python\nfrom category_encoders import CountEncoder\n\ncount_encoder = CountEncoder(handle_unknown=0, handle_missing='value')\n\ntrain_X_countenc = count_encoder.fit_transform(train_X_cat)\nval_X_countenc = count_encoder.transform(val_X_cat)\n\ntrain_X_count_num = train_X_num.join(train_X_countenc.add_suffix(\"_countenc\"))\nval_X_count_num = val_X_num.join(val_X_countenc.add_suffix(\"_countenc\"))\n\nprint(\"Count encoded categorical + raw numeric: {}\".\n format(score_dataset(train_X_count_num, val_X_count_num, train_y, val_y)))\n```\n\n### Target Encodings\n\nTarget encoding is another advanced (but sometimes dangerous) approach to encode categorical features. It replaces a categorical value with the average value of the target for that value of the feature. \n\nFor example, given the country value \"GER\", you'd calculate the average outcome for all the rows with country == 'GER'. This value is often blended with the target probability over the entire dataset to reduce the variance of values with few occurences.\n\nThis technique uses the targets to create new features. So including the validation or test data in the target encodings would be a form of target leakage. Instead, you should learn the target encodings from the training dataset only and apply it to the other datasets (as we did with all other encoding methods).\n\n\n```python\nfrom category_encoders import TargetEncoder\n\ntarget_encoder = TargetEncoder()\n\ntrain_X_targetenc = target_encoder.fit_transform(train_X_cat, train_y)\nval_X_targetenc = target_encoder.transform(val_X_cat)\n\ntrain_X_target_num = train_X_num.join(train_X_targetenc.add_suffix(\"_targetenc\"))\nval_X_target_num = val_X_num.join(val_X_targetenc.add_suffix(\"_targetenc\"))\n\nprint(\"Target encoded categorical + raw numeric: {}\".\n format(score_dataset(train_X_target_num, val_X_target_num, train_y, val_y)))\n```\n\n### CatBoost Encoding\n\nFinally, we'll look at CatBoost encoding. This is similar to target encoding in that it's based on the target probablity for a given value. However with CatBoost, for each row, the target probability is calculated only from the rows before it.\n\n\n```python\nfrom category_encoders import CatBoostEncoder\n\ncatboost_encoder = CatBoostEncoder()\n\ntrain_X_catboostenc = catboost_encoder.fit_transform(train_X_cat, train_y)\nval_X_catboostenc = catboost_encoder.transform(val_X_cat)\n\ntrain_X_catboost_num = train_X_num.join(train_X_catboostenc.add_suffix(\"_targetenc\"))\nval_X_catboost_num = val_X_num.join(val_X_catboostenc.add_suffix(\"_targetenc\"))\n\nprint(\"CatBoost encoded categorical + raw numeric: {}\".\n format(score_dataset(train_X_catboost_num, val_X_catboost_num, train_y, val_y)))\n```\n\n### Warning\n\nTarget encoding is a powerful but dangerous way to improve on your machine learning methods. \n\nAdvantages: \n* Compact transformation of categorical variables\n* Powerful basis for feature engineering\n\nDisadvantages:\n* Careful validation is required to avoid overfitting\n* Significant performance improvements only on some datasets\n\n## Conclusion\n\nToday, we have seen a variety of ways to encode numerical and categorical features to improve the performance of our machine learning models. To try even more encoding methods you can try the implementations in the categorical-encoding package on [github](https://github.com/scikit-learn-contrib/categorical-encoding).\n\nWhile the approaches we have talked about today have the potential to create powerful models, they require a lot of manual tuning and testing. \n", "meta": {"hexsha": "63cdf736fba9fbbb562e0fcb3ba41cdf86ddff22", "size": 36428, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nbs/04_Feature_Engineering.ipynb", "max_stars_repo_name": "pds2122/course", "max_stars_repo_head_hexsha": "962801729cc3c72c2566d0aea77a6089aac71683", "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": "nbs/04_Feature_Engineering.ipynb", "max_issues_repo_name": "pds2122/course", "max_issues_repo_head_hexsha": "962801729cc3c72c2566d0aea77a6089aac71683", "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": "nbs/04_Feature_Engineering.ipynb", "max_forks_repo_name": "pds2122/course", "max_forks_repo_head_hexsha": "962801729cc3c72c2566d0aea77a6089aac71683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T18:03:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T18:03:51.000Z", "avg_line_length": 34.5944919278, "max_line_length": 3806, "alphanum_fraction": 0.6246843088, "converted": true, "num_tokens": 5401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.19930798839207908, "lm_q1q2_score": 0.08573180275883076}} {"text": "\n\n---\n \nこのファイルは PyTorch のチュートリアルにあるファイル を翻訳して,加筆修正したもの\nです。\n\nすぐれたチュートリアルの内容,コードを公開された PyTorch 開発陣と Transfomer の原著論文著者陣 (Vaswani ら) に敬意を表します。\n\n- Original: https://pytorch.org/tutorials/beginner/transformer_tutorial.html\n- Date: 2020-0807\n- Translated and modified: Shin Asakawa \n\n---\n\n\n```python\n# 2020年8月11日現在,torchtext を upgrade しないとこのチュートリアルは動作しない\n!pip install --upgrade torchtext\n```\n\n Collecting torchtext\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/b9/f9/224b3893ab11d83d47fde357a7dcc75f00ba219f34f3d15e06fe4cb62e05/torchtext-0.7.0-cp36-cp36m-manylinux1_x86_64.whl (4.5MB)\n \u001b[K |████████████████████████████████| 4.5MB 4.8MB/s \n \u001b[?25hRequirement already satisfied, skipping upgrade: tqdm in /usr/local/lib/python3.6/dist-packages (from torchtext) (4.41.1)\n Collecting sentencepiece\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)\n \u001b[K |████████████████████████████████| 1.1MB 59.0MB/s \n \u001b[?25hRequirement already satisfied, skipping upgrade: torch in /usr/local/lib/python3.6/dist-packages (from torchtext) (1.6.0+cu101)\n Requirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from torchtext) (1.18.5)\n Requirement already satisfied, skipping upgrade: requests in /usr/local/lib/python3.6/dist-packages (from torchtext) (2.23.0)\n Requirement already satisfied, skipping upgrade: future in /usr/local/lib/python3.6/dist-packages (from torch->torchtext) (0.16.0)\n Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (2020.6.20)\n Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (1.24.3)\n Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (2.10)\n Requirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (3.0.4)\n Installing collected packages: sentencepiece, torchtext\n Found existing installation: torchtext 0.3.1\n Uninstalling torchtext-0.3.1:\n Successfully uninstalled torchtext-0.3.1\n Successfully installed sentencepiece-0.1.91 torchtext-0.7.0\n\n\n\n```python\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\n# from https://github.com/dmlc/xgboost/issues/1715\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n```\n\n\n```python\n%matplotlib inline\n```\n\n## ``nn.Transformer`` と ``TorchText`` を用いた Seq2Seq (系列-to-系列) モデル\n\n\nこのチュートリアルでは,[nn.Transformer](https://pytorch.org/docs/master/nn.html?highlight=nn%20transformer#torch.nn.Transformer) モジュールを用いた sequence-to-sequnce (訳注:日本語では `seq2seq モデル` などと呼ばれます) モデルの訓練方法を示します。\n\n\n\nPyTorch リリース 1.2 には,[Attention is All You Need](https://arxiv.org/pdf/1706.03762.pdf) (訳注:初めてトランスフォーマーを提案した論文) に基づいた標準的なトランスフォーマーモジュールが含まれます。\nトランスフォーマーは並列化が容易で,seq2seq モデルを凌ぐ性能が示されています。\n``nn.Transfomer`` モジュールは,注意機構に基づいて,入出力情報間大域的依存性を解消する機構です\n(最近の別実装は [nn.MultiheadAttention](https://pytorch.org/docs/master/nn.html?highlight=multiheadattention#torch.nn.MultiheadAttention))。\n``nn.Transformer`` は単一要素で構成されており,本チュートリアル内の [nn.TransformerEncoder](https://pytorch.org/docs/master/nn.html?highlight=nn%20transformerencoder#torch.nn.TransformerEncoder) のごとく,修正,構成が容易です。\n\n\n
\n\n\n\n\n\n# モデルの定義\n\n\n\n\n本チュートリアルでは 言語モデル課題で ``nn.TransformerEncoder`` モデルを学習します。\n言語モデル課題とは 任意の単語 (または単語系列) が与えられた場合に,後続する単語の尤度(確率)を割り当てること指します。\n文章を表す一連のトークン系列は,埋め込み層に入力され その後,単語の順番を符号化した位置符号化層の情報が付加されます(詳細は次パラグラフ参照)。\n``nn.TransformerEncoder`` は [nn.TransformerEncoderLayer](https://pytorch.org/docs/master/nn.html?highlight=transformerencoderlayer#torch.nn.TransformerEncoderLayer) を構成要素とする複数層からなるニューラルネットワークです。\n``nn.TransformerEncoder`` の自己注意層は 入力系列の初頭に近い位置にしか注意を払うことができないため、入力系列に対する マスク化注意機構が必要となります。\n言語モデル課題では 将来の位置トークンがマスクされるます。\n実際の単語を得るため ``nn.TransformerEncoder`` モデルの出力は最終線形層に送られ 最終層として 対数ソフトマックス関数が設けられています。\n\n\n\n\n\n\n```python\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass TransformerModel(nn.Module):\n\n def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):\n super(TransformerModel, self).__init__()\n from torch.nn import TransformerEncoder, TransformerEncoderLayer\n self.model_type = 'Transformer'\n self.src_mask = None\n self.pos_encoder = PositionalEncoding(ninp, dropout)\n encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)\n self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n self.decoder = nn.Linear(ninp, ntoken)\n\n self.init_weights()\n\n def _generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src):\n if self.src_mask is None or self.src_mask.size(0) != len(src):\n device = src.device\n mask = self._generate_square_subsequent_mask(len(src)).to(device)\n self.src_mask = mask\n\n src = self.encoder(src) * math.sqrt(self.ninp)\n src = self.pos_encoder(src)\n output = self.transformer_encoder(src, self.src_mask)\n output = self.decoder(output)\n return output\n```\n\n\n\n位置符号化器 ``PositionalEncoding`` モジュールを用いることで,系列中のトークンの相対位置や絶対位置に関する情報を付加されます。\n位置符号化器は埋め込みと同一次元を持ち 両者 を合算してトランスフォーマーへの入力とします。\nここでは 異なる周波数の ``sine``(正弦波) と ``cosine`` (余弦波) 関数を利用します。\n\n### (訳注) Transformer: Attention is all you need\n原著論文中の 位置符号化器は以下のように定義されている:\nまず,マルチヘッド自己注意 (MHSA) は,クエリ,キー,バリューベクトルを学習すべきベクトルとして次式で定義される:\n\n$$\n\\text{MultiHead}\\left(Q,K,V\\right)=\\text{Concat}\\left(\\mathop{head}_1,\\ldots,\\mathop{head}_h\\right)W^O\n$$\n\nここで,各ヘッドは, $\\text{head}_i =\\text{Attention}\\left(QW_i^Q,KW_i^K,VW_i^V\\right)$ である。\n\nそれぞれの次元は以下のとおりである:\n\n\n- $W_i^Q\\in\\mathbb{R}^{d_{\\mathop{model}}\\times d_k}$,\n- $W_i^K \\in\\mathbb{R}^{d_{\\mathop{model}}\\times d_k}$,\n- $W_i^V\\in\\mathbb{R}^{d_{\\mathop{model}}\\times d_v}$, \n- $W^O\\in\\mathbb{R}^{hd_v\\times d_{\\mathop{model}}}$. $h=8$\n- $d_k=d_v=\\frac{d_{\\mathop{model}}}{h}=64$\n\n$$\\text{FFN}(x)=\\max\\left(0,xW_1+b_1\\right)W_2+b_2$$\n\n\n\n### (続 訳注) 位置符号器 Position encoders\nトランスフォーマーの入力には,上述の単語表現に加えて,位置符号器からの信号も重ね合わされる。\n位置 $i$ の信号は次式で周波数領域へと変換される:\n\n$$\n\\begin{align}\n\\text{PE}_{(\\text{pos},2i)} &= \\sin\\left(\\frac{\\text{pos}}{10000^{\\frac{2i}{d_{\\text{model}}}}}\\right)\\\\\n\\text{PE}_{(\\text{pos},2i+1)} &= \\cos\\left(\\frac{\\text{pos}}{10000^{\\frac{2i}{d_{\\text{model}}}}}\\right)\n\\end{align}\n$$\n\n位置符号器による位置表現は,$i$ 番目の位置情報をワンホット表現するのではなく,周波数領域に変換することで周期情報を表現する試みと見なし得る。\n\n\n\n```python\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n```\n\n\n```python\n#help(nn.Dropout)\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nPE = PositionalEncoding(max_len=100, dropout=0., d_model=10)\n\n#PE(torch.rand(4))\n#torch.ones(4)\nX = PE(torch.Tensor((1,0,0,0,0,0,0,0,0,0))).detach().numpy()\n#plt.plot(range(len(X[0])), X[0])\nplt.plot(X[1][0])\nplt.plot(X[2][0])\nplt.plot(X[3][0])\n\n```\n\n\n\n# データのロードとバッチ化\n\n\n\n訓練には ``torchtext`` の Wikitext-2 データセットを使用します。\nvocab オブジェクトは訓練データセットに基づいて構築され,トークンをテンソルへと数値化するために使用されます。\n系列データから ``batchify()`` 関数を使ってデータを列 column に配置し ``batch_size`` の大きさのバッチに分割した後に残ったトークンを切り取ります。\n例えば アルファベットをシーケンス (全長26) とし バッチサイズを 4 とすると アルファベットを長さ 6 の 4 つのシーケンスに分割することになります。\n\n\\begin{align}\\begin{bmatrix}\n \\text{A} & \\text{B} & \\text{C} & \\ldots & \\text{X} & \\text{Y} & \\text{Z}\n \\end{bmatrix}\n \\Rightarrow\n \\begin{bmatrix}\n \\begin{bmatrix}\\text{A} \\\\ \\text{B} \\\\ \\text{C} \\\\ \\text{D} \\\\ \\text{E} \\\\ \\text{F}\\end{bmatrix} &\n \\begin{bmatrix}\\text{G} \\\\ \\text{H} \\\\ \\text{I} \\\\ \\text{J} \\\\ \\text{K} \\\\ \\text{L}\\end{bmatrix} &\n \\begin{bmatrix}\\text{M} \\\\ \\text{N} \\\\ \\text{O} \\\\ \\text{P} \\\\ \\text{Q} \\\\ \\text{R}\\end{bmatrix} &\n \\begin{bmatrix}\\text{S} \\\\ \\text{T} \\\\ \\text{U} \\\\ \\text{V} \\\\ \\text{W} \\\\ \\text{X}\\end{bmatrix}\n \\end{bmatrix}\\end{align}\n\n\n\nこれらの列はモデルによって独立したものとして扱われ ``G`` と ``F`` の依存性を学習することはできませんが、より効率的なバッチ処理が可能になります。\n\n\n\n\n\n```python\nimport torchtext\nfrom torchtext.data.utils import get_tokenizer\nTEXT = torchtext.data.Field(tokenize=get_tokenizer(\"basic_english\"),\n init_token='',\n eos_token='',\n lower=True)\ntrain_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)\nTEXT.build_vocab(train_txt)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef batchify(data, bsz):\n data = TEXT.numericalize([data.examples[0].text])\n # Divide the dataset into bsz parts.\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1).t().contiguous()\n return data.to(device)\n\nbatch_size = 20\neval_batch_size = 10\ntrain_data = batchify(train_txt, batch_size)\nval_data = batchify(val_txt, eval_batch_size)\ntest_data = batchify(test_txt, eval_batch_size)\n```\n\n /usr/local/lib/python3.6/dist-packages/torchtext/data/field.py:150: UserWarning: Field class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.\n warnings.warn('{} class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.'.format(self.__class__.__name__), UserWarning)\n\n\n downloading wikitext-2-v1.zip\n\n\n wikitext-2-v1.zip: 100%|██████████| 4.48M/4.48M [00:00<00:00, 8.65MB/s]\n\n\n extracting\n\n\n /usr/local/lib/python3.6/dist-packages/torchtext/data/example.py:78: UserWarning: Example class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.\n warnings.warn('Example class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.', UserWarning)\n\n\n### 入力系列とターゲット系列を生成するための関数\n\n\n\n\n関数 ``get_batch()`` はトランスフォーマモデルの入力系列と目標系列とを生成します。\nソースデータを長さ ``bptt`` のチャンクに細分化します。\n言語モデル課題では,モデルは ``Target`` として以下の単語を必要とします。\n例えば、 ``bptt`` の値が 2 の場合、 ``i`` = 0 の場合,以下の 2 つの変数が得られます。\n\n\n\n\n\n\n\nチャンクは寸法 0 に沿っており、トランスフォーマーモデルの ``S`` 寸法と一致していることに注意する必要があります。\nバッチ次元 ``N`` は次元 1 に沿っています。\n\n\n\n\n\n```python\nbptt = 35\ndef get_batch(source, i):\n seq_len = min(bptt, len(source) - 1 - i)\n data = source[i:i+seq_len]\n target = source[i+1:i+1+seq_len].view(-1)\n return data, target\n```\n\n\n\n# インスタンスの初期化\n\n\n\nモデルは以下のハイパーパラメータで設定されています。\n語彙サイズはボキャブオブジェクトの長さに等しいです。\n\n\n```python\nntokens = len(TEXT.vocab.stoi) # the size of vocabulary\nemsize = 200 # embedding dimension\nnhid = 200 # the dimension of the feedforward network model in nn.TransformerEncoder\nnlayers = 2 # the number of nn.TransformerEncoderLayer in nn.TransformerEncoder\nnhead = 2 # the number of heads in the multiheadattention models\ndropout = 0.2 # the dropout value\nmodel = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to(device)\n```\n\n\n\n# モデルの実行\n\n\n\n損失を追跡するために [CrossEntropyLoss](https://pytorch.org/docs/master/nn.html?highlight=crossentropyloss#torch.nn.CrossEntropyLoss) を適用し [SGD](https://pytorch.org/docs/master/optim.html?highlight=sgd#torch.optim.SGD) は最適化器として確率的勾配降下法を実装しています。\n初期学習率は 5.0 に設定されています。\n[StepLR](https://pytorch.org/docs/master/optim.html?highlight=steplr#torch.optim.lr_scheduler.StepLR) はエポック単位で学習率を調整するために適用されている。\n学習中は [nn.utils.clip_grad_norm](https://pytorch.org/docs/master/nn.html?highlight=nn%20utils%20clip_grad_norm#torch.nn.utils.clip_grad_norm_) 関数を用いて、爆発しないように全ての勾配をまとめてスケーリングしています。\n\n\n\n\n```python\ncriterion = nn.CrossEntropyLoss()\nlr = 5.0 # learning rate\noptimizer = torch.optim.SGD(model.parameters(), lr=lr)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)\n\nimport time\ndef train():\n model.train() # Turn on the train mode\n total_loss = 0.\n start_time = time.time()\n ntokens = len(TEXT.vocab.stoi)\n for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):\n data, targets = get_batch(train_data, i)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output.view(-1, ntokens), targets)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n total_loss += loss.item()\n log_interval = 200\n if batch % log_interval == 0 and batch > 0:\n cur_loss = total_loss / log_interval\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches | '\n 'lr {:02.2f} | ms/batch {:5.2f} | '\n 'loss {:5.2f} | ppl {:8.2f}'.format(\n epoch, batch, len(train_data) // bptt, scheduler.get_lr()[0],\n elapsed * 1000 / log_interval,\n cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\ndef evaluate(eval_model, data_source):\n eval_model.eval() # Turn on the evaluation mode\n total_loss = 0.\n ntokens = len(TEXT.vocab.stoi)\n with torch.no_grad():\n for i in range(0, data_source.size(0) - 1, bptt):\n data, targets = get_batch(data_source, i)\n output = eval_model(data)\n output_flat = output.view(-1, ntokens)\n total_loss += len(data) * criterion(output_flat, targets).item()\n return total_loss / (len(data_source) - 1)\n```\n\n\nエポックをループします。\n検証の損失がこれまでのところ最高であればモデルを保存します。\n各エポックの後に学習率を調整します。\n\n\n\n\n```python\nbest_val_loss = float(\"inf\")\nepochs = 3 # The number of epochs\nbest_model = None\n\nfor epoch in range(1, epochs + 1):\n epoch_start_time = time.time()\n train()\n val_loss = evaluate(model, val_data)\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n val_loss, math.exp(val_loss)))\n print('-' * 89)\n\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_model = model\n\n scheduler.step()\n```\n\n /usr/local/lib/python3.6/dist-packages/torch/optim/lr_scheduler.py:351: UserWarning: To get the last learning rate computed by the scheduler, please use `get_last_lr()`.\n \"please use `get_last_lr()`.\", UserWarning)\n\n\n | epoch 1 | 200/ 2981 batches | lr 5.00 | ms/batch 18.39 | loss 7.98 | ppl 2930.49\n | epoch 1 | 400/ 2981 batches | lr 5.00 | ms/batch 16.38 | loss 6.78 | ppl 882.26\n | epoch 1 | 600/ 2981 batches | lr 5.00 | ms/batch 16.43 | loss 6.36 | ppl 577.99\n | epoch 1 | 800/ 2981 batches | lr 5.00 | ms/batch 16.50 | loss 6.23 | ppl 506.77\n | epoch 1 | 1000/ 2981 batches | lr 5.00 | ms/batch 16.51 | loss 6.12 | ppl 453.77\n | epoch 1 | 1200/ 2981 batches | lr 5.00 | ms/batch 16.57 | loss 6.09 | ppl 440.96\n | epoch 1 | 1400/ 2981 batches | lr 5.00 | ms/batch 16.56 | loss 6.04 | ppl 418.54\n | epoch 1 | 1600/ 2981 batches | lr 5.00 | ms/batch 16.69 | loss 6.04 | ppl 420.40\n | epoch 1 | 1800/ 2981 batches | lr 5.00 | ms/batch 16.68 | loss 5.95 | ppl 385.45\n | epoch 1 | 2000/ 2981 batches | lr 5.00 | ms/batch 16.71 | loss 5.95 | ppl 385.00\n | epoch 1 | 2200/ 2981 batches | lr 5.00 | ms/batch 16.77 | loss 5.84 | ppl 344.93\n | epoch 1 | 2400/ 2981 batches | lr 5.00 | ms/batch 16.83 | loss 5.89 | ppl 360.86\n | epoch 1 | 2600/ 2981 batches | lr 5.00 | ms/batch 16.85 | loss 5.90 | ppl 365.97\n | epoch 1 | 2800/ 2981 batches | lr 5.00 | ms/batch 16.87 | loss 5.80 | ppl 328.75\n -----------------------------------------------------------------------------------------\n | end of epoch 1 | time: 52.53s | valid loss 5.72 | valid ppl 303.92\n -----------------------------------------------------------------------------------------\n | epoch 2 | 200/ 2981 batches | lr 4.51 | ms/batch 17.11 | loss 5.79 | ppl 326.93\n | epoch 2 | 400/ 2981 batches | lr 4.51 | ms/batch 17.00 | loss 5.76 | ppl 318.27\n | epoch 2 | 600/ 2981 batches | lr 4.51 | ms/batch 17.09 | loss 5.58 | ppl 266.30\n | epoch 2 | 800/ 2981 batches | lr 4.51 | ms/batch 17.12 | loss 5.63 | ppl 277.53\n | epoch 2 | 1000/ 2981 batches | lr 4.51 | ms/batch 17.13 | loss 5.58 | ppl 264.12\n | epoch 2 | 1200/ 2981 batches | lr 4.51 | ms/batch 17.20 | loss 5.60 | ppl 271.37\n | epoch 2 | 1400/ 2981 batches | lr 4.51 | ms/batch 17.28 | loss 5.61 | ppl 274.10\n | epoch 2 | 1600/ 2981 batches | lr 4.51 | ms/batch 17.30 | loss 5.65 | ppl 283.50\n | epoch 2 | 1800/ 2981 batches | lr 4.51 | ms/batch 17.41 | loss 5.57 | ppl 261.41\n | epoch 2 | 2000/ 2981 batches | lr 4.51 | ms/batch 17.43 | loss 5.61 | ppl 272.49\n | epoch 2 | 2200/ 2981 batches | lr 4.51 | ms/batch 17.44 | loss 5.50 | ppl 244.07\n | epoch 2 | 2400/ 2981 batches | lr 4.51 | ms/batch 17.55 | loss 5.57 | ppl 261.60\n | epoch 2 | 2600/ 2981 batches | lr 4.51 | ms/batch 17.67 | loss 5.58 | ppl 265.11\n | epoch 2 | 2800/ 2981 batches | lr 4.51 | ms/batch 17.66 | loss 5.50 | ppl 245.18\n -----------------------------------------------------------------------------------------\n | end of epoch 2 | time: 54.18s | valid loss 5.59 | valid ppl 266.66\n -----------------------------------------------------------------------------------------\n | epoch 3 | 200/ 2981 batches | lr 4.29 | ms/batch 17.67 | loss 5.54 | ppl 254.90\n | epoch 3 | 400/ 2981 batches | lr 4.29 | ms/batch 17.40 | loss 5.55 | ppl 256.32\n | epoch 3 | 600/ 2981 batches | lr 4.29 | ms/batch 17.41 | loss 5.36 | ppl 211.86\n | epoch 3 | 800/ 2981 batches | lr 4.29 | ms/batch 17.35 | loss 5.41 | ppl 223.17\n | epoch 3 | 1000/ 2981 batches | lr 4.29 | ms/batch 17.34 | loss 5.37 | ppl 215.28\n | epoch 3 | 1200/ 2981 batches | lr 4.29 | ms/batch 17.27 | loss 5.41 | ppl 223.75\n | epoch 3 | 1400/ 2981 batches | lr 4.29 | ms/batch 17.23 | loss 5.43 | ppl 228.14\n | epoch 3 | 1600/ 2981 batches | lr 4.29 | ms/batch 17.23 | loss 5.47 | ppl 236.73\n | epoch 3 | 1800/ 2981 batches | lr 4.29 | ms/batch 17.21 | loss 5.40 | ppl 222.20\n | epoch 3 | 2000/ 2981 batches | lr 4.29 | ms/batch 17.22 | loss 5.43 | ppl 228.46\n | epoch 3 | 2200/ 2981 batches | lr 4.29 | ms/batch 17.21 | loss 5.32 | ppl 205.26\n | epoch 3 | 2400/ 2981 batches | lr 4.29 | ms/batch 17.23 | loss 5.39 | ppl 220.26\n | epoch 3 | 2600/ 2981 batches | lr 4.29 | ms/batch 17.25 | loss 5.41 | ppl 223.05\n | epoch 3 | 2800/ 2981 batches | lr 4.29 | ms/batch 17.27 | loss 5.34 | ppl 209.39\n -----------------------------------------------------------------------------------------\n | end of epoch 3 | time: 54.08s | valid loss 5.50 | valid ppl 244.09\n -----------------------------------------------------------------------------------------\n\n\n\n\n# テストデータセットを用いたモデルの評価\nモデルをテストデータセットで評価します。\n\n\n\n\n\n\n```python\ntest_loss = evaluate(best_model, test_data)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\nprint('=' * 89)\n```\n\n =========================================================================================\n | End of training | test loss 5.40 | test ppl 221.43\n =========================================================================================\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "a7ed2f6f05d5bed66ef64f246ecc65d337c80b3f", "size": 65652, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/01PyTorchTEXT_transformer_tutorial.ipynb", "max_stars_repo_name": "JPA-BERT/jpa-bert.github.io", "max_stars_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "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": "notebooks/01PyTorchTEXT_transformer_tutorial.ipynb", "max_issues_repo_name": "JPA-BERT/jpa-bert.github.io", "max_issues_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "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": "notebooks/01PyTorchTEXT_transformer_tutorial.ipynb", "max_forks_repo_name": "JPA-BERT/jpa-bert.github.io", "max_forks_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "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": 69.6203605514, "max_line_length": 23866, "alphanum_fraction": 0.6781057698, "converted": true, "num_tokens": 9434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1755380800931169, "lm_q1q2_score": 0.08571232975157927}} {"text": "

Métodos Numéricos

\n

Capítulo 1: Error y Representación de números en el computador

\n

2021/02

\n

MEDELLÍN - COLOMBIA

\n\n\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***Docente:*** Carlos Alberto Álvarez Henao, I.C. D.Sc.\n\n***e-mail:*** carlosalvarezh@gmail.com\n\n***skype:*** carlos.alberto.alvarez.henao\n\n***Linkedin:*** https://www.linkedin.com/in/carlosalvarez5/\n\n***github:*** https://github.com/carlosalvarezh/Metodos_Numericos\n\n***Herramienta:*** [Jupyter](http://jupyter.org/)\n\n***Kernel:*** Python 3.8\n\n\n***\n\n\n\n

Tabla de Contenidos

\n\n\n***Comentario:*** este capítulo está basado en parte de las notas del curso del profesor [Kyle T. Mandli](https://github.com/mandli/intro-numerical-methods) (en inglés)\n\n

\n \n

\n\n\n\n\n```python\n#Bibliotecas a ser utilizadas en el Notebook\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sympy\nimport scipy.special\n\n```\n\n## Fuentes de error\n\nLos cálculos numéricos, que involucran el uso de máquinas (análogas o digitales) presentan una serie de errores que provienen de diferentes fuentes:\n\n- del Modelo\n\n- de los datos\n\n- de truncamiento\n\n- de representación de los números (punto flotante)\n\n- $ \\ldots$\n\n***Meta:*** Categorizar y entender cada tipo de error y explorar algunas aproximaciones simples para analizarlas.\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Error en el modelo y los datos\n\nErrores en la formulación fundamental\n\n- Error en los datos: imprecisiones en las mediciones o incertezas en los parámetros\n\nInfortunadamente no tenemos control de los errores en los datos y el modelo de forma directa pero podemos usar métodos que pueden ser más robustos en la presencia de estos tipos de errores.\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Error de truncamiento\n\nLos errores surgen de la expansión de funciones con una función simple, por ejemplo, $sin(x) \\approx x$ para $|x|\\approx0$.\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Error de representación de punto fotante\n\nLos errores surgen de aproximar números reales con la representación en precisión finita de números en el computador.\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Definiciones básicas\n\nDado un valor verdadero de una función $f$ y una solución aproximada $F$, se define:\n\n#### Error absoluto\n\n$$e_a=|f-F|$$\n\n\n***Ejemplo:*** se realiza una medición y se obtiene un valor aproximado de $29.99$ *m*. Asumiendo que el valor exacto de dicha medición debería ser de $30.00$ *m*, ¿cuál es el error absoluto obtenido? Cuál sería el error absoluto si se disminuye un orden de magnitud las cantidades?\n\n\n```python\nf = 30.0\nF = 29.9\n```\n\n\n```python\nea = abs(f - F)\nprint(\"{0:6.4f}\".format(ea)) \n```\n\n\n```python\n# reduciendo un órden de magnitud las cantidades\n\nf = 3.0\nF = 2.9\n```\n\n\n```python\nea = abs(f - F)\nprint(\"{0:6.4f}\".format(ea)) \n```\n\nSe observa que el valor del error absoluto es igual ($\\approx 0.1$), independiente de la magnitud de las cantidades. \n\n[Volver a la Tabla de Contenido](#TOC)\n\n#### Error relativo\n\n$$e_r (\\%)= \\frac{e_a}{|f|}=\\frac{|f-F|}{|f|} \\times 100 \\%$$\n\n\n***Ejemplo:*** Repetir el ejemplo anterior, pero calculando el error relativo porcentual.\n\n\n```python\nf = 30.0\nF = 29.9\n```\n\n\n```python\ner = abs(f - F) / f * 100\nprint(\"{0:6.4f}%\".format(er))\n```\n\n\n```python\n# reduciendo un órden de magnitud las cantidades\n\nf = 3.0\nF = 2.9\n```\n\n\n```python\ner = abs(f - F) / f * 100\nprint(\"{0:6.4f}%\".format(er))\n```\n\nSe observa que los resultados son diferentes y es mayor cuando las cantidades medidas son menores.\n\nEntre las dos formas de representar el error, la relativa es más consistente con la magnitud de lo que se está midiendo.\n\n[Volver a la Tabla de Contenido](#TOC)\n\n## Notación $\\text{Big}-\\mathcal{O}$\n\nsea $$f(x)= \\mathcal{O}(g(x)) \\text{ cuando } x \\rightarrow a$$\n\nsi y solo si\n\n$$|f(x)|\\leq M|g(x)| \\text{ cuando } |x-a| < \\delta \\text{ donde } M, a > 0$$\n\n\nEn la práctica, usamos la notación $\\text{Big}-\\mathcal{O}$ para decir algo sobre cómo se pueden comportar los términos que podemos haber dejado fuera de una serie. Veamos el siguiente ejemplo de la aproximación de la serie de Taylor:\n\n***Ejemplo:***\n\nsea $f(x) = \\sin(x)$ con $x_0 = 0$ entonces\n\n$$T_N(x) = \\sum^N_{n=0} (-1)^{n} \\frac{x^{2n+1}}{(2n+1)!}$$\n\nPodemos escribir $f(x)$ como\n\n$$f(x) = x - \\frac{x^3}{6} + \\frac{x^5}{120} + \\mathcal{O}(x^7)$$\n\nEsto se vuelve más útil cuando lo vemos como lo hicimos antes con $\\Delta x$:\n\n$$f(x) = \\Delta x - \\frac{\\Delta x^3}{6} + \\frac{\\Delta x^5}{120} + \\mathcal{O}(\\Delta x^7)$$\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Reglas para el error de propagación basado en la notación $\\text{Big}-\\mathcal{O}$\n\nEn general, existen dos teoremas que no necesitan prueba y se mantienen cuando el valor de $x$ es grande:\n\nSea\n\n$$\\begin{aligned}\n f(x) &= p(x) + \\mathcal{O}(x^n) \\\\\n g(x) &= q(x) + \\mathcal{O}(x^m) \\\\\n k &= \\max(n, m)\n\\end{aligned}$$\n\nEntonces\n\n$$\n f+g = p + q + \\mathcal{O}(x^k)\n$$\n\ny\n\n\\begin{align}\n f \\cdot g &= p \\cdot q + p \\mathcal{O}(x^m) + q \\mathcal{O}(x^n) + O(x^{n + m}) \\\\\n &= p \\cdot q + \\mathcal{O}(x^{n+m})\n\\end{align}\n\nDe otra forma, si estamos interesados en valores pequeños de $x$, $\\Delta x$, la expresión puede ser modificada como sigue:\n\n\\begin{align}\n f(\\Delta x) &= p(\\Delta x) + \\mathcal{O}(\\Delta x^n) \\\\\n g(\\Delta x) &= q(\\Delta x) + \\mathcal{O}(\\Delta x^m) \\\\\n r &= \\min(n, m)\n\\end{align}\n\nentonces\n\n$$\n f+g = p + q + O(\\Delta x^r)\n$$\n\ny\n\n\\begin{align}\n f \\cdot g &= p \\cdot q + p \\cdot \\mathcal{O}(\\Delta x^m) + q \\cdot \\mathcal{O}(\\Delta x^n) + \\mathcal{O}(\\Delta x^{n+m}) \\\\\n &= p \\cdot q + \\mathcal{O}(\\Delta x^r)\n\\end{align}\n\n***Nota:*** En este caso, supongamos que al menos el polinomio con $k=max(n,m)$ tiene la siguiente forma:\n\n$$\n p(\\Delta x) = 1 + p_1 \\Delta x + p_2 \\Delta x^2 + \\ldots\n$$\n\no\n\n$$\n q(\\Delta x) = 1 + q_1 \\Delta x + q_2 \\Delta x^2 + \\ldots\n$$\n\npara que $\\mathcal{O}(1)$ \n\n\nde modo que hay un término $\\mathcal{O}(1)$ que garantiza la existencia de $\\mathcal{O}(\\Delta x^r)$ en el producto final.\n\nPara tener una idea de por qué importa más la potencia en $\\Delta x$ al considerar la convergencia, la siguiente figura muestra cómo las diferentes potencias en la tasa de convergencia pueden afectar la rapidez con la que converge nuestra solución. Tenga en cuenta que aquí estamos dibujando los mismos datos de dos maneras diferentes. Graficar el error como una función de $\\Delta x$ es una forma común de mostrar que un método numérico está haciendo lo que esperamos y muestra el comportamiento de convergencia correcto. Dado que los errores pueden reducirse rápidamente, es muy común trazar este tipo de gráficos en una escala log-log para visualizar fácilmente los resultados. Tenga en cuenta que si un método fuera realmente del orden $n$, será una función lineal en el espacio log-log con pendiente $n$.\n\n\n```python\ndx = np.linspace(1.0, 1e-4, 100)\n\nfig = plt.figure()\nfig.set_figwidth(fig.get_figwidth() * 2.0)\naxes = []\naxes.append(fig.add_subplot(1, 2, 1))\naxes.append(fig.add_subplot(1, 2, 2))\n\nfor n in range(1, 5):\n axes[0].plot(dx, dx**n, label=\"$\\Delta x^%s$\" % n)\n axes[1].loglog(dx, dx**n, label=\"$\\Delta x^%s$\" % n)\n\naxes[0].legend(loc=2)\naxes[1].set_xticks([10.0**(-n) for n in range(5)])\naxes[1].set_yticks([10.0**(-n) for n in range(16)])\naxes[1].legend(loc=4)\nfor n in range(2):\n axes[n].set_title(\"Crecimiento del Error vs. $\\Delta x^n$\")\n axes[n].set_xlabel(\"$\\Delta x$\")\n axes[n].set_ylabel(\"Error Estimado\")\n axes[n].set_title(\"Crecimiento de las diferencias\")\n axes[n].set_xlabel(\"$\\Delta x$\")\n axes[n].set_ylabel(\"Error Estimado\")\n\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n## Error de truncamiento\n\n***Teorema de Taylor:*** Sea $f(x) \\in C^{m+1}[a,b]$ y $x_0 \\in [a,b]$, para todo $x \\in (a,b)$ existe un número $c = c(x)$ que se encuentra entre $x_0$ y $x$ tal que\n\n$$ f(x) = T_N(x) + R_N(x)$$\n\ndonde $T_N(x)$ es la aproximación del polinomio de Taylor\n\n$$T_N(x) = \\sum^N_{n=0} \\frac{f^{(n)}(x_0)\\times(x-x_0)^n}{n!}$$\n\ny $R_N(x)$ es el residuo (la parte de la serie que obviamos)\n\n$$R_N(x) = \\frac{f^{(n+1)}(c) \\times (x - x_0)^{n+1}}{(n+1)!}$$\n\nOtra forma de pensar acerca de estos resultados consiste en reemplazar $x - x_0$ con $\\Delta x$. La idea principal es que el residuo $R_N(x)$ se vuelve mas pequeño cuando $\\Delta x \\rightarrow 0$.\n\n$$T_N(x) = \\sum^N_{n=0} \\frac{f^{(n)}(x_0)\\times \\Delta x^n}{n!}$$\n\ny $R_N(x)$ es el residuo (la parte de la serie que obviamos)\n\n$$ R_N(x) = \\frac{f^{(n+1)}(c) \\times \\Delta x^{n+1}}{(n+1)!} \\leq M \\Delta x^{n+1}$$\n\n***Ejemplo 1:***\n\n$f(x) = e^x$ con $x_0 = 0$\n\nUsando esto podemos encontrar expresiones para el error relativo y absoluto en función de $x$ asumiendo $N=2$.\n\nDerivadas:\n$$\\begin{aligned}\n f'(x) &= e^x \\\\\n f''(x) &= e^x \\\\ \n f^{(n)}(x) &= e^x\n\\end{aligned}$$\n\nPolinomio de Taylor:\n$$\\begin{aligned}\n T_N(x) &= \\sum^N_{n=0} e^0 \\frac{x^n}{n!} \\Rightarrow \\\\\n T_2(x) &= 1 + x + \\frac{x^2}{2}\n\\end{aligned}$$\n\nRestos:\n$$\\begin{aligned}\n R_N(x) &= e^c \\frac{x^{n+1}}{(n+1)!} = e^c \\times \\frac{x^3}{6} \\quad \\Rightarrow \\\\\n R_2(x) &\\leq \\frac{e^1}{6} \\approx 0.5\n\\end{aligned}$$\n\nPrecisión:\n$$\n e^1 = 2.718\\ldots \\\\\n T_2(1) = 2.5 \\Rightarrow e \\approx 0.2 ~~ r \\approx 0.1\n$$\n\n¡También podemos usar el paquete `sympy` que tiene la capacidad de calcular el polinomio de *Taylor* integrado!\n\n\n```python\nx = sympy.symbols('x')\nf = sympy.symbols('f', cls=sympy.Function)\n\nf = sympy.exp(x)\nf.series(x0=0, n=11)\n```\n\n\n```python\na = 1.1**500\n\nprint(a)\n```\n\nGraficando\n\n\n```python\nx = np.linspace(-5, 5, 100)\nT_N = 1.0 + x + x**2 / 2.0 + x**3 / 6.0 + x**4 / 24.0 + x**5 / 120.0 + x**6 / 720.0 + x**7 / 5040.0 + x**8 / 40320.0 + x**9 / 362880\nR_N = np.exp(1) * x**10 / 3628800.0\n\nplt.plot(x, T_N, 'r', x, np.exp(x), 'k', x, R_N, 'b')\nplt.plot(0.0, 1.0, 'o', markersize=10)\nplt.grid(True)\nplt.xlabel(\"x\")\nplt.ylabel(\"$f(x)$, $T_N(x)$, $R_N(x)$\")\nplt.legend([\"$T_N(x)$\", \"$f(x)$\", \"$R_N(x)$\"], loc=2)\nplt.show()\n```\n\n\n```python\nR_N\n```\n\n***Ejemplo 2:***\n\nAproximar\n\n$$ f(x) = \\frac{1}{x} \\quad x_0 = 1,$$\n\nusando $x_0 = 1$ para el tercer termino de la serie de Taylor.\n\n$$\\begin{aligned}\n f'(x) &= -\\frac{1}{x^2} \\\\\n f''(x) &= \\frac{2}{x^3} \\\\\n f^{(n)}(x) &= \\frac{(-1)^n n!}{x^{n+1}}\n\\end{aligned}$$\n\n$$\\begin{aligned}\n T_N(x) &= \\sum^N_{n=0} (-1)^n (x-1)^n \\Rightarrow \\\\\n T_2(x) &= 1 - (x - 1) + (x - 1)^2\n\\end{aligned}$$\n\n$$\\begin{aligned}\n R_N(x) &= \\frac{(-1)^{n+1}(x - 1)^{n+1}}{c^{n+2}} \\Rightarrow \\\\\n R_2(x) &= \\frac{-(x - 1)^{3}}{c^{4}}\n\\end{aligned}$$\n\n\n```python\nx = np.linspace(0.8, 2, 100)\nT_N = 1.0 - (x-1) + (x-1)**2\nR_N = -(x-1.0)**3 / (1.1**4)\n\nplt.plot(x, T_N, 'r', x, 1.0 / x, 'k', x, R_N, 'b')\nplt.plot(1.0, 1.0, 'o', markersize=10)\nplt.grid(True)\nplt.xlabel(\"x\")\nplt.ylabel(\"$f(x)$, $T_N(x)$, $R_N(x)$\")\n\nplt.legend([\"$T_N(x)$\", \"$f(x)$\", \"$R_N(x)$\"], loc=8)\nplt.show()\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Laboratorio Numérico 1\n\n
\n$\\color{red}{\\textbf{Ejercicio:}}$ Realice la expansión de la serie de Taylor para los dos ejemplos anteriores con 3, 4 y 5 términos. Cuál es el error que se tiene a medida que se adicionan más términos? Realice una gráfica comparativa del Residuo que se obtiene para cada término adicional. Haga un análisis de lo que sucede. Si extendemos hasta el \"infinito\" dicho residuo qué pueden concluir?\n
\n\n\n[Volver a la Tabla de Contenido](#TOC)\n\n## Error de punto flotante\n\nErrores surgen de aproximar 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***Ej.:*** considere la representación de $\\sqrt{2}=1.4142 \\ldots$. Como sabemos, éste es un número irracional, es decir, tiene una cantidad infinita de dígitos decimales. El computador almacena de forma incompleta la represenación de ese valor empleando cierta cantidad de números decimales\n\n$$2 - (\\sqrt{2})^2$$\n\n\n```python\na = np.sqrt(2)\nprint(\"a: \", a)\n```\n\n a: 1.4142135623730951\n\n\n\n```python\nb = abs(2-a**2)\nprint(\"|2-a^2| = \", b)\n```\n\n |2-a^2| = 4.440892098500626e-16\n\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Aritmética de punto flotante\n\nLos números en sistemas de [punto flotante](https://en.wikipedia.org/wiki/Floating-point_arithmetic \"Floating point arithmetic\") se representan como una serie de bits que representan diferentes partes de un número. En los sistemas de punto flotante normalizados, existen algunas convenciones estándar para el uso de estos bits. En general, los números se almacenan dividiéndolos en la forma\n\n$$fl(x) = \\pm (0.d_1 d_2 d_3 \\ldots d_p)_\\beta \\times \\beta^E$$\n\ndonde los digitos $\\{d_i\\}_{i=1}^p$ son enteros tales que $0\\leq d_i \\leq \\beta-1$ y $d_1 \\neq 0$\n\nEl sistema se caracteriza por cuatro números enteros:\n\n- la *base* $\\beta>1$. Para el sistema binario $\\beta = 2$, para decimal $\\beta = 10$, etc.\n\n\n- La precisión $p \\geq 1$, que representa la cantidad de dígitos significativos, y\n\n\n- el *exponente* $E$, que es un entero en el rango $[E_{\\min}, E_{\\max}]$\n\n\n$\\pm$ es un bit único y representa el signo del número.\n\nLos puntos importantes en cualquier sistema de punto flotante son:\n\n1. Existe un conjunto discreto y finito de números representables.\n\n\n2. Estos números representables no están distribuidos uniformemente en la línea real\n\n\n3. La aritmética en sistemas de punto flotante produce resultados diferentes de la aritmética de precisión infinita (es decir, matemática \"real\")\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Notación de punto flotante\n\nEs común encontrar la siguiente notación para representar un conjunto de números de punto flotante:\n\n$$F(\\beta, p, E_{min}, E_{max})$$\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Propiedades de los sistemas de punto flotante\n\nTodos los sistemas de punto flotante se caracterizan por varios números importantes\n\n- Número normalizado reducido ([*underflow*](https://en.wikipedia.org/wiki/Arithmetic_underflow) si está por debajo, relacionado con números sub-normales alrededor de cero)\n\n\n- Número normalizado más grande ([*overflow*](https://en.wikipedia.org/wiki/Integer_overflow))\n\n\n- Cero\n\n\n- $\\epsilon$ o $\\epsilon_{mach}$\n\n\n- `Inf` y `nan`\n\n***Ejemplo: Sistema de juguete***\n\nConsidere el sistema decimal de 2 digitos de precisión (normalizado)\n\n$$F(10,2,-2,0)$$\n\n$$f = \\pm 0.d_1d_2 \\times 10^E$$\n\ncon $E \\in [-2, 0]$.\n\n**Numero y distribución de números**\n\n\n1. Cuántos números pueden representarse con este sistema?\n\n\n2. Cuál es la distribución en la línea real?\n\n\n3. Cuáles son los límites underflow y overflow?\n\nCuántos números pueden representarse con este sistema?\n\n$$f = \\pm 0.d_1d_2 \\times 10^E ~~~ \\text{con} ~~~ E \\in [-2, 0]$$\n\n$$2 \\times 9 \\times 10 \\times 3 + 1 = 541$$\n\nCuál es la distribución en la recta \"real\"?\n\n\n```python\nd_1_values = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nd_2_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nE_values = [0, -1, -2]\n\nfig = plt.figure(figsize=(10.0, 1.0))\naxes = fig.add_subplot(1, 1, 1)\n\nfor E in E_values:\n for d1 in d_1_values:\n for d2 in d_2_values:\n axes.plot( (d1 + d2 * 0.1) * 10**E, 0.0, 'r+', markersize=20)\n axes.plot(-(d1 + d2 * 0.1) * 10**E, 0.0, 'r+', markersize=20)\n \naxes.plot(0.0, 0.0, '+', markersize=20)\naxes.plot([-10.0, 10.0], [0.0, 0.0], 'k')\n\naxes.set_title(\"Distribución de Valores\")\naxes.set_yticks([])\naxes.set_xlabel(\"x\")\naxes.set_ylabel(\"\")\naxes.set_xlim([-0.1, 0.1])\nplt.show()\n```\n\nCuáles son los límites superior (overflow) e inferior (underflow)?\n\n- El menor número que puede ser representado (underflow) es: $1.0 \\times 10^{-2} = 0.01$\n\n\n- El mayor número que puede ser representado (overflow) es: $9.9 \\times 10^0 = 9.9$\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Sistema Binario\n\nConsidere el sistema en base 2 de 2 dígitos de precisión\n\n$$F(2,2,-1,1)$$\n\n$$F=\\pm 0.d_1d_2 \\times 2^E \\quad \\text{con} \\quad E \\in [-1, 1]$$\n\n\n#### Numero y distribución de números\n\n1. Cuántos números pueden representarse con este sistema?\n\n\n2. Cuál es la distribución en la línea real?\n\n\n3. Cuáles son los límites underflow y overflow?\n\nCuántos números pueden representarse en este sistema?\n\n\n$$f=\\pm 0.d_1d_2 \\times 2^E ~~~~ \\text{con} ~~~~ E \\in [-1, 1]$$\n\n$$ 2 \\times 1 \\times 2 \\times 3 + 1 = 13$$\n\nCuál es la distribución en la línea real?\n\n\n```python\nd_1_values = [1]\nd_2_values = [0, 1]\nE_values = [1, 0, -1]\n\nfig = plt.figure(figsize=(10.0, 1.0))\naxes = fig.add_subplot(1, 1, 1)\n\nfor E in E_values:\n for d1 in d_1_values:\n for d2 in d_2_values:\n axes.plot( (d1 + d2 * 0.5) * 2**E, 0.0, 'r+', markersize=20)\n axes.plot(-(d1 + d2 * 0.5) * 2**E, 0.0, 'r+', markersize=20)\n \naxes.plot(0.0, 0.0, 'r+', markersize=20)\naxes.plot([-4.5, 4.5], [0.0, 0.0], 'k')\n\naxes.set_title(\"Distribución de Valores\")\naxes.set_yticks([])\naxes.set_xlabel(\"x\")\naxes.set_ylabel(\"\")\naxes.set_xlim([-3.5, 3.5])\nplt.show()\n```\n\nCuáles son los límites superior (*overflow*) e inferior (*underflow*)?\n\n- El menor número que puede ser representado (*underflow*) es: $1.0 \\times 2^{-1} = 0.5$\n\n\n\n\n- El mayor número que puede ser representado (*overflow*) es: $1.1 \\times 2^1 = 3$\n\nObserve que estos números son en sistema binario. \n\nUna rápida regla de oro:\n\n$$2^3 2^2 2^1 2^0 . 2^{-1} 2^{-2} 2^{-3}$$\n\ncorresponde a\n\n8s, 4s, 2s, 1s . mitades, cuartos, octavos, $\\ldots$\n\n[Volver a la Tabla de Contenido](#TOC)\n\n***Ejercicio:*** Cuál sería la representación en punto flotante del siguiente conjunto de números:\n\n$$F(2,3,-1,3)$$\n\n- Cuántos números se pueden representar?\n\n\n- Cuál sería el menor número representable?\n\n\n- Cuál sería el mayor número?\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Sistema real - [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) sistema binario de punto flotante\n\n#### Precisión simple\n\n\n\n- Almacenamiento total es de 32 bits\n\n\n- Exponente de 8 bits $\\Rightarrow E \\in [-126, 127]$\n\n\n- Fracción 23 bits ($p = 24$)\n\n\n```\ns EEEEEEEE FFFFFFFFFFFFFFFFFFFFFFF\n0 1 8 9 31\n```\n\nOverflow $= 2^{127} \\approx 3.4 \\times 10^{38}$\n\nUnderflow $= 2^{-126} \\approx 1.2 \\times 10^{-38}$\n\n$\\epsilon_{\\text{machine}} = 2^{-23} \\approx 1.2 \\times 10^{-7}$\n\n\n[Volver a la Tabla de Contenido](#TOC)\n\n#### Precisión doble\n\n- Almacenamiento total asignado es 64 bits\n\n- Exponenete de 11 bits $\\Rightarrow E \\in [-1022, 1024]$\n\n- Fracción de 52 bits ($p = 53$)\n\n```\ns EEEEEEEEEE FFFFFFFFFF FFFFFFFFFF FFFFFFFFFF FFFFFFFFFF FFFFFFFFFF FF\n0 1 11 12 63\n```\nOverflow $= 2^{1024} \\approx 1.8 \\times 10^{308}$\n\nUnderflow $= 2^{-1022} \\approx 2.2 \\times 10^{-308}$\n\n$\\epsilon_{\\text{machine}} = 2^{-52} \\approx 2.2 \\times 10^{-16}$\n\n[Volver a la Tabla de Contenido](#TOC)\n\n\n### Acceso de Python a números de la IEEE\n\nAccede a muchos parámetros importantes, como el epsilon de la máquina\n\n```python\nimport numpy as np\nnp.finfo(float).eps\n```\n\n\n```python\nnp.finfo(float).eps\n\nprint(np.finfo(np.float16))\nprint(np.finfo(np.float32))\nprint(np.finfo(float))\n```\n\n[Volver a la Tabla de Contenido](#TOC)\n\n### Calculo \"manual\" del $\\epsilon_{mach}$\n\nLa determinación \"manual\" del $\\epsilon_{mach}$ es muy simple. Veamos el siguiente algoritmo\n\n\n```python\neps = 1.0\n\nwhile 1.0 + eps > 1.0:\n eps = eps / 2.0\n \nprint(eps)\n```\n\nSi lo comparamos con el valor obtenido en el numeral anterior para `float64`, `2.2204460492503131e-16`, se observa que es del orden de dos veces menor, por qué?\n\n[Volver a la Tabla de Contenido](#TOC)\n\n## Por qué debería importarnos esto?\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?]() for an example.\n", "meta": {"hexsha": "9b9dbba0799185b184e053cfea1c1160dec18ed7", "size": 294557, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial/ptranking_gbm.ipynb", "max_stars_repo_name": "ii-research-ranking/ptranking", "max_stars_repo_head_hexsha": "2794e6e086bcd87ce177f40194339e9b825e9f4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2018-09-19T17:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T07:54:04.000Z", "max_issues_repo_path": "tutorial/ptranking_gbm.ipynb", "max_issues_repo_name": "ii-research-ranking/ptranking", "max_issues_repo_head_hexsha": "2794e6e086bcd87ce177f40194339e9b825e9f4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-09-27T06:59:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-05T12:35:12.000Z", "max_forks_repo_path": "tutorial/ptranking_gbm.ipynb", "max_forks_repo_name": "ii-research-ranking/ptranking", "max_forks_repo_head_hexsha": "2794e6e086bcd87ce177f40194339e9b825e9f4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-09-28T07:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T06:28:35.000Z", "avg_line_length": 839.1937321937, "max_line_length": 272432, "alphanum_fraction": 0.9441907678, "converted": true, "num_tokens": 4877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353745, "lm_q2_score": 0.21206879937726764, "lm_q1q2_score": 0.08558393814012225}} {"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\n# Examples: \n# Factored form: 1/(x**2*(x**2 + 1))\n# Expanded form: 1/(x**4+x**2)\n\nimport sympy as sym\nfrom IPython.display import Latex, display, Markdown, Javascript, clear_output\nfrom ipywidgets import widgets, Layout # Interactivity module\n```\n\n## Razcep na parcialne ulomke\n\nOb uporabi Laplaceove transformacije za analizo sistema, dobimo Laplaceovo transformacijo izstopnega signala z množenjem prenosne funkcije in Laplaceove transformacije vstopnega signala. Rezultat tega množenja je pogosto težak za razumevanje. Z namenom izvedbe inverzne Laplaceove transformacije je najprej potrebno izvesti razcep na parcialne ulomke. Ta interaktivni primer prikazuje način izvedbe razcepa.\n\n---\n\n### Kako upravljati s tem interaktivnim primerom?\nPreklapljaš lahko med opcijama *Vnos funkcije* ali *Vnos koeficientov polinoma*.\n\n1. *Vnos funkcije*:\n* Primer: Če želiš vnesti funkcijo $\\frac{1}{x^2(x^2 + 1)}$ (faktorizirana oblika) vnesi 1/(x\\*\\*2\\*(x\\*\\*2 + 1)); če želiš vnesti isto funkcijo a v razširjeni obliki ($\\frac{1}{x^4+x^2}$) type 1/(x\\*\\*4+x\\*\\*2).\n
\n\n2. *Vnos koeficientov polinoma*:\n* Z uporabo drsnikov izberi stopnji števca in imenovalca izbrane racionalne funkcije.\n* Vnesi vrednost koeficientov števa in imenovalca v ustrezna besedilna polja; za potrditev klikni na gumb *Potrdi*.\n\n\n\n\n\n\n```python\n## System selector buttons\nstyle = {'description_width': 'initial'}\ntypeSelect = widgets.ToggleButtons(\n options=[('Vnos funkcije', 0), ('Vnos koeficientov polinoma', 1),],\n description='Izberi: ',style={'button_width':'230px'})\n\nbtnReset=widgets.Button(description=\"Ponastavi\")\n\n# function\ntextbox=widgets.Text(description=('Vnesi funkcijo:'),style=style)\nbtnConfirmFunc=widgets.Button(description=\"Potrdi\") # ex btnConfirm\n\n# poly\nbtnConfirmPoly=widgets.Button(description=\"Potrdi\") # ex btn\n\ndisplay(typeSelect)\n\ndef on_button_clickedReset(ev):\n display(Javascript(\"Jupyter.notebook.execute_cells_below()\"))\n\ndef on_button_clickedFunc(ev):\n eq = sym.sympify(textbox.value)\n\n if eq==sym.factor(eq):\n display(Markdown('Vnešena funkcija $%s$ je zapisana v faktorizirani obliki. ' %sym.latex(eq) + 'Njena razširjena oblika je enaka $%s$.' %sym.latex(sym.expand(eq))))\n \n else:\n display(Markdown('Vnešena funkcija $%s$ je zapisana v razširjeni obliki. ' %sym.latex(eq) + 'Njena faktorizirana oblika je enaka $%s$.' %sym.latex(sym.factor(eq))))\n \n display(Markdown('Rezultat razcepa na parcialne ulomke: $%s$' %sym.latex(sym.apart(eq)) + '.'))\n display(btnReset)\n \ndef transfer_function(num,denom):\n num = np.array(num, dtype=np.float64)\n denom = np.array(denom, dtype=np.float64)\n len_dif = len(denom) - len(num)\n if len_dif<0:\n temp = np.zeros(abs(len_dif))\n denom = np.concatenate((temp, denom))\n transferf = np.vstack((num, denom))\n elif len_dif>0:\n temp = np.zeros(len_dif)\n num = np.concatenate((temp, num))\n transferf = np.vstack((num, denom))\n return transferf\n\ndef f(orderNum, orderDenom):\n global text1, text2\n text1=[None]*(int(orderNum)+1)\n text2=[None]*(int(orderDenom)+1)\n display(Markdown('2. Vnesi koeficiente polinoma v števcu.'))\n for i in range(orderNum+1):\n text1[i]=widgets.Text(description=(r'a%i'%(orderNum-i)))\n display(text1[i])\n display(Markdown('3. Vnesi koeficiente polinoma v imenovalcu.')) \n for j in range(orderDenom+1):\n text2[j]=widgets.Text(description=(r'b%i'%(orderDenom-j)))\n display(text2[j])\n global orderNum1, orderDenom1\n orderNum1=orderNum\n orderDenom1=orderDenom\n\ndef on_button_clickedPoly(btn):\n clear_output()\n global num,denom\n enacbaNum=\"\"\n enacbaDenom=\"\"\n num=[None]*(int(orderNum1)+1)\n denom=[None]*(int(orderDenom1)+1)\n for i in range(int(orderNum1)+1):\n if text1[i].value=='' or text1[i].value=='Vnesi koeficient':\n text1[i].value='Vnesi koeficient'\n else:\n try:\n num[i]=int(text1[i].value)\n except ValueError:\n if text1[i].value!='' or text1[i].value!='Vnesi koeficient':\n num[i]=sym.var(text1[i].value)\n \n for i in range (len(num)-1,-1,-1):\n if i==0:\n enacbaNum=enacbaNum+str(num[len(num)-i-1])\n elif i==1:\n enacbaNum=enacbaNum+\"+\"+str(num[len(num)-i-1])+\"*x+\"\n elif i==int(len(num)-1):\n enacbaNum=enacbaNum+str(num[0])+\"*x**\"+str(len(num)-1)\n else:\n enacbaNum=enacbaNum+\"+\"+str(num[len(num)-i-1])+\"*x**\"+str(i) \n \n for j in range(int(orderDenom1)+1):\n if text2[j].value=='' or text2[j].value=='Vnesi koeficient':\n text2[j].value='Vnesi koeficient'\n else:\n try:\n denom[j]=int(text2[j].value)\n except ValueError:\n if text2[j].value!='' or text2[j].value!='Vnesi koeficient':\n denom[j]=sym.var(text2[j].value)\n \n for i in range (len(denom)-1,-1,-1):\n if i==0:\n enacbaDenom=enacbaDenom+\"+\"+str(denom[len(denom)-i-1])\n elif i==1:\n enacbaDenom=enacbaDenom+\"+\"+str(denom[len(denom)-i-1])+\"*x\"\n elif i==int(len(denom)-1):\n enacbaDenom=enacbaDenom+str(denom[0])+\"*x**\"+str(len(denom)-1)\n else:\n enacbaDenom=enacbaDenom+\"+\"+str(denom[len(denom)-i-1])+\"*x**\"+str(i)\n \n funcSym=sym.sympify('('+enacbaNum+')/('+enacbaDenom+')')\n\n DenomSym=sym.sympify(enacbaDenom)\n NumSym=sym.sympify(enacbaNum)\n DenomSymFact=sym.factor(DenomSym);\n funcFactSym=NumSym/DenomSymFact;\n \n if DenomSym==sym.expand(enacbaDenom):\n if DenomSym==DenomSymFact:\n display(Markdown('Vnešena funkcija je enaka $%s$. Števca ni moč razcepiti.' %sym.latex(funcSym)))\n else:\n display(Markdown('Vnešena funkcija je enaka $%s$. Števca ni moč razcepiti. Isto funkcijo lahko zapišemo v faktorizirani obliki kot $%s$.' %(sym.latex(funcSym), sym.latex(funcFactSym))))\n\n if sym.apart(funcSym)==funcSym:\n display(Markdown('Razcepa na parcialne ulomke ni možno izvesti.'))\n else:\n display(Markdown('Rezultat razcepa na parcialne ulomke je enak $%s$' %sym.latex(sym.apart(funcSym)) + '.'))\n \n btnReset.on_click(on_button_clickedReset)\n display(btnReset)\n \ndef partial_frac(index):\n\n if index==0:\n x = sym.Symbol('x') \n display(widgets.HBox((textbox, btnConfirmFunc)))\n btnConfirmFunc.on_click(on_button_clickedFunc)\n btnReset.on_click(on_button_clickedReset)\n \n elif index==1:\n display(Markdown('1. Določi stopnji polinomov v števcu (orderNum) in imenovalcu (orderDenom).'))\n widgets.interact(f, orderNum=widgets.IntSlider(min=0,max=10,step=1,value=0),\n orderDenom=widgets.IntSlider(min=0,max=10,step=1,value=0));\n btnConfirmPoly.on_click(on_button_clickedPoly)\n display(btnConfirmPoly) \n\ninput_data=widgets.interactive_output(partial_frac,{'index':typeSelect})\ndisplay(input_data)\n```\n\n\n ToggleButtons(description='Izberi: ', options=(('Vnos funkcije', 0), ('Vnos koeficientov polinoma', 1)), style…\n\n\n\n Output()\n\n", "meta": {"hexsha": "713ffddf48bf30475bba7e36078343efc8a48325", "size": 12863, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/02/.ipynb_checkpoints/TD-09-Razcep_na_parcialne_ulomke-checkpoint.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/02/TD-09-Razcep_na_parcialne_ulomke.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/02/TD-09-Razcep_na_parcialne_ulomke.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": 39.5784615385, "max_line_length": 430, "alphanum_fraction": 0.5438855632, "converted": true, "num_tokens": 2662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.27512972976675254, "lm_q1q2_score": 0.08548126520593556}} {"text": "\n\n# Condições Gerais\n\nEsta avaliação tem como objetivo avaliar os conhecimentos adquiridos durante a disciplina de Mecânica dos Sólidos.\n\nEssa forma de avaliação tem por objetivo promover a discussão dos exercícios entre os membros do grupo (e eventualmente entre grupos) e ampliar a diversidade de exercícios a serem realizados.\n\n---\n\nAs condicões abaixo devem ser observadas: \n\n1. Serão formadas equipes e cada uma delas com no mínimo 3 e no máximo 4 integrantes. \n\n2. A avaliação será realizada por meio da entrega de uma cópia deste notebook com as soluções desenvolvidas até a data estipulada de entrega.\n\n\n3. Da entrega da avaliação.\n * Os documentos necessários para a entrega do trabalho são (1) os códigos desenvolvidos pela equipe. \n * A equipe deve usar este modelo de notebook para desenvolver os códigos. \n * Os códigos podem ser desenvolvidos combinado a linguagem LaTeX e computação simbólica via python quando necessário.\n\n4. Da distribuição das questões.\n * Serão atribuídas para cada grupo até 9 questões referentes ao capítulo 2 do \n livro texto. \n * A quantidade de questões será a mesma para cada grupo. \n * A distribuição das questões será aleatória. \n * A pontuacão referente a cada questão será igualitária e o valor total da avaliação será 100 pontos.\n\n5. As equipes devem ser formadas até às **18 horas o dia 23/11/2021** por meio do preenchimento da planilha [[MAC005] Formação das Equipes](https://docs.google.com/spreadsheets/d/1j59WVAl1cMzXgupwG86WFNGAQhbtVtc0b5aIQSbqGQE/edit?usp=sharing).\n\n6. A formação das equipes pode ser acompanhada arquivo [[MAC005] Formação das Equipes](https://docs.google.com/spreadsheets/d/1j59WVAl1cMzXgupwG86WFNGAQhbtVtc0b5aIQSbqGQE/edit?usp=sharing). Cada equipe será indentificada por uma letra em ordem alfabética seguida do número 1 (A1, B1, C1, e assim por diante). O arquivo está aberto para edição e pode ser alterado pelos alunos até a data estipulada.\n\n7. Equipes formadas após a data estabelecida para a formação das equipes terão a nota da avaliação multiplicada por um coeficiente de **0.80**.\n\n8. A equipe deve indicar no arquivo [[MAC005] Formação das Equipes](https://docs.google.com/spreadsheets/d/1j59WVAl1cMzXgupwG86WFNGAQhbtVtc0b5aIQSbqGQE/edit?usp=sharing) um responsável pela entrega do projeto. \n * Somente o responsável pela entrega deve fazer o upload do arquivo na plataforma\n\n9. A entrega dos projetos deve ocorrer até às **23:59 do dia 30/11/2021** na plataforma da disciplina pelo responsável pela entrega. \n * Caso a entrega seja feita por outro integrante diferente daquele indicado pela pela equipe a avaliação será desconsiderada e não será corrigida até que a a condição de entrega seja satisfeita.\n\n10. Quaisquer dúvidas ou esclarecimentos devem ser encaminhadas pela sala de aula virtual.\n\n\n\n#Exercicios\n\n2.3, 2.5, 2.7, 2.10, 2.19, 2.21, 2.25, 2.27, 2.46\n\n[Link do Livro](http://fn.iust.ac.ir/files/fnst/ssadeghzadeh_52bb7/files/Introduction_to_continuum_mechanics_-Lai-2010-4edition%281%29.pdf)\n\n## Solução do problema 2.3 (inserir número e enunciado)\n\n\n\n###a) 1 - Montamos e resolvemos o sistema de equações para a primeira equação: $b_i = B_{ij} a_j$
\n\n$b_1 = B_{1j} a_j$
\n$b_2 = B_{2j} a_j$
\n$b_3 = B_{3j} a_j$

\n\n$b_1 = B_{11} a_1 + B_{12} a_2 + B_{13} a_3$
\n$b_2 = B_{21} a_1 + B_{22} a_2 + B_{23} a_3$
\n$b_3 = B_{31} a_1 + B_{32} a_2 + B_{33} a_3$

\n\n$b_1 = 2*1 + 3*0 + 0*2 = 2$
\n$b_2 = 0*1 + 5*0 + 1*2 = 2$
\n$b_3 = 0*1 + 2*0 + 1*2 = 2$

\n\n$\nb = \n\\begin{bmatrix}\n b_1 \\\\\n b_2 \\\\\n b_3 \n\\end{bmatrix}\n=\n\\begin{bmatrix}\n 2 \\\\\n 2 \\\\\n 2 \n\\end{bmatrix}\n$\n


\n2 - Multiplicamos as matrizes para a segunda equação: $[b] = [B][a]$\n\n\n```python\nimport numpy as np\nimport sympy as sp\nsp.init_printing()\n\nB = np.matrix([[2,3,0],[0,5,1],[0,2,1]])\na = np.matrix([[1],[0],[2]])\nb = sp.Matrix(B*a)\n\nprint(\"Dessa forma, as duas equações (do passo 1 e 2) são equivalentes\")\nb\n```\n\n Dessa forma, as duas equações (do passo 1 e 2) são equivalentes\n\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2\\\\2\\\\2\\end{matrix}\\right]$\n\n\n\n###b) 1 - Montamos e resolvemos o sistema de equações para a primeira equação: $s = B_{ij} a_i a_j$
\n\n$s = B_{11} a_1 a_1 + B_{12} a_1 a_2 + B_{13} a_1 a_3 + B_{21} a_2 a_1 + B_{22} a_2 a_2 + B_{23} a_2 a_3 + B_{31} a_3 a_1 + B_{32} a_3 a_2 + B_{33} a_3 a_3 $\n\n$s = 2*1*1 + 3*1*0 + 0*1*2 + 0*0*1* + 5*0*0 + 1*0*2 + 0*2*1 + 2*2*0 + 1*2*2 $\n\n$s = 2 + 4 = 6$\n\n
\n2 - Multiplicamos as matrizes para a segunda equação: $s=[a]^t[B][a]$\n\n\n```python\nimport numpy as np\nimport sympy as sp\nsp.init_printing()\n\nB = np.matrix([[2,3,0],[0,5,1],[0,2,1]])\na = np.matrix([[1],[0],[2]])\nat = np.transpose(a)\n\n#calculo da segunda equação\nb = sp.Matrix(at*B*a)\n\nprint(\"Dessa forma, as duas equações (do passo 1 e 2) são equivalentes\")\nb\n```\n\n Dessa forma, as duas equações (do passo 1 e 2) são equivalentes\n\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}6\\end{matrix}\\right]$\n\n\n\n## Solução do problema 2.5 (inserir número e enunciado)\n\n\n\n(a)\n\n$s = A_1^{2} + A_2^{2} + A_3^{2}$ \\\\\n$s = (A_1.A_1) + (A_2.A_2) + (A_3.A_3)$ \\\\\n$s = A_iA_i$\n\n(b)\n\n$\n\\frac{\\partialΦ}{\\partial x_1^2} + \\frac{\\partialΦ}{\\partial x_2^2} + \n\\frac{\\partialΦ}{\\partial x_3^2}$\n\n$\n\\frac{\\partialΦ}{\\partial x_1 . x_1} + \\frac{\\partialΦ}{\\partial x_2 . x_2} + \n\\frac{\\partialΦ}{\\partial x_3 . x_3} = $\n$\\frac{\\partialΦ}{\\partial x_i . x_i}$\n\n## Solução do problema 2.7 (inserir número e enunciado)\n\n\n\n### Para escrever $a_i$ em forma longa temos que expandir a equação $a_i = ∂v_i/∂t + v_j∂v_i/∂x_j$ para os indices $j = 1, j = 2, j = 3$:\n$a_1 = ∂v_1/∂t + v_1∂v_1/∂x_1 + ∂v_1/∂t + v_2∂v_1/∂x_2 + ∂v_1/∂t + v_3∂v_1/∂x_3$\n$a_2 = ∂v_2/∂t + v_1∂v_2/∂x_1 + ∂v_2/∂t + v_2∂v_2/∂x_2 + ∂v_2/∂t + v_3∂v_2/∂x_3$\n$a_3 = ∂v_3/∂t + v_1∂v_3/∂x_1 + ∂v_3/∂t + v_2∂v_3/∂x_2 + ∂v_3/∂t + v_3∂v_3/∂x_3$\n\n## Solução do problema 2.10 (inserir número e enunciado)\n\n\n\n### 1 - Primeiro vamos encontrar a matriz $[d{i}]$, sabendo que $d_k = ε_{ijk} a_i b_j$:\n\n$d_1 = ε_{ij1} a_i b_j$
\n$d_2 = ε_{ij2} a_i b_j$
\n$d_3 = ε_{ij1} a_i b_j$

\n$d_1 = ε_{231} a_2 b_3 + ε_{321} a_3 b_2$
\n$d_2 = ε_{312} a_3 b_1 + ε_{132} a_1 b_3$
\n$d_3 = ε_{123} a_1 b_2 + ε_{213} a_2 b_1$

\n### Sabemos que $ε_{ijk}$ é o simbolo de permutação é:
$ε_{123}$ = $ε_{231}$ = $ε_{312}$ = +1
$ε_{213}$ = $ε_{321}$ = $ε_{132}$ = -1
$ε_{111}$ = $ε_{222}$ = $ε_{333}$ = 0
Então os valores de $d_1,d_2,d_3$ ficam :\n$d_1 = a_2 b_3 - a_3 b_2 = (2)(3) - (0)(2) = 6$
\n$d_2 = a_3 b_1 - a_1 b_3 = (0)(0) - (1)(3) = -3$
\n$d_3 = a_1 b_2 - a_2 b_1 = (1)(2) - (2)(0) = 2$

\n\n### Portanto:\n$\n[d_i] = \n\\begin{bmatrix}\n d_1 \\\\\n d_2 \\\\\n d_3 \n\\end{bmatrix}\n=\n\\begin{bmatrix}\n 6 \\\\\n -3 \\\\\n 2 \n\\end{bmatrix}\n$\n


\n### 2 - Agora encontraremos a matriz $[d{i}]$, sabendo que $d_k = (a$ x $b). e_k$ :
Sabemos que $a$ x $b$ = $(a_ie_i)$ x $(b_je_j) = a_ib_jε_{ijk}e_k$, então:\n$d_1 = a_ib_jε_{ij1}e_1.e_1$
\n$d_2 = a_ib_jε_{ij2}e_2.e_2$
\n$d_3 = a_ib_jε_{ij3}e_3.e_3$

\n$d_1 = a_2b_3ε_{231}e_1.e_1 + a_3b_2ε_{321}e_1.e_1$
\n$d_2 = a_1b_3ε_{132}e_2.e_2 + a_3b_1ε_{312}e_2.e_2$
\n$d_3 = a_1b_2ε_{123}e_3.e_3 + a_2b_1ε_{213}e_3.e_3$

\n$d_1 = a_2b_3 - a_3b_2 = (2)(3) - (0)(2) = 6$
\n$d_2 = a_3b_1 - a_1b_3 = (0)(0) - (1)(3) = -3$
\n$d_3 = a_1 b_2 - a_2 b_1 = (1)(2) - (2)(0) = 2$

\n### Resultando em:\n$\n[d_i] = \n\\begin{bmatrix}\n d_1 \\\\\n d_2 \\\\\n d_3 \n\\end{bmatrix}\n=\n\\begin{bmatrix}\n 6 \\\\\n -3 \\\\\n 2 \n\\end{bmatrix}\n$\n


\n### Comparando as matrizes encontradas em 1 e 2 vemos que os resultados são iguais.\n\n\n## Solução do problema 2.19 (inserir número e enunciado)\n\n\n\n### Uma transformação T opera em qualquer vetor $a$ para dar $Ta = \\frac{a}{|a|}$, onde $|a|$ é a magnitude de $a$. Mostre que T não é uma transformação linear.\n\nComo $Ta = \\frac{a}{|a|}$ para todos os valores de $a$, então podemos fazer:\n\n$T(a + b) = \\frac{(a + b)}{|a+b|}$\n\nCom isso, escrevemos:\n\n$Ta + Tb = \\frac{a}{|a|} + \\frac{b}{|b|}$\n\nNesse momento, já podemos notar que $T(a + b) \\neq Ta + Tb$\n\nOu seja, T não é uma transformação linear.\n\n## Solução do problema 2.21 (inserir número e enunciado)\n\n\n\n### Usar propriedade linear de $T$ para achar:\n### A) $Ta$\n\nUsando as informações passadas no enunciado, podemos fazer\n\n$Ta = T(2e1 + 3e2)$\n\n$T(2e1 + 3e2) = 2Te1 + 3Te2$\n\nComo $Te1 = e1 + e2$ e $Te2 = e1 − e2$, então fazemos:\n\n$2Te1 + 3Te2 = 2(e1 + e2) + 3(e1 − e2)$\n\n$2(e1 + e2) + 3(e1 − e2) = 2e1 + 2e2 + 3e1 - 3e2$\n\nO que nos dá $5e1 -e2$. Ou seja, $Ta = 5e1 -e2$.\n\n### B) $Tb$\n\n$Tb = T(3e1 + 2e2)$\n\n$T(3e1 + 2e2) = 3Te1 + 2Te2$\n\nComo $Te1 = e1 + e2$ e $Te2 = e1 − e2$, então fazemos:\n\n$3Te1 + 2Te2 = 3(e1 + e2) + 2(e1 − e2)$\n\n$3(e1 + e2) + 2(e1 − e2) = 3e1 + 3e2 + 2e1 - 2e2$\n\nO que nos dá $5e1 + e2$. Ou seja, $Tb = 5e1 + e2$.\n\n### B) $T(a+b)$\n\n$T(a+b) = T(2e1 + 3e2 + 3e1 + 2e2)$\n\n$T(a+b) = T(5e1 + 5e2)$\n\nComo $T(5e1 + 5e2) = 5(Te1 + Te2)$, então $5(Te1 + Te2) = 5(e1 + e2 + e1 − e2)$\n\nDessa forma, temos $5(e1 + e2 + e1 − e2) = 5e1 + 5e1 + 5e2 - 5e2$\n\nPortanto, $T(a+b) = 10e1$\n\n## Solução do problema 2.25 (inserir número e enunciado)\n\n\n\n(a) \n$ e_i' = Re_i = R_{mi}e_m\\\\ \n e_1' = R_{11}e_1 + R_{21}e_2 + R_{31}e_3 \\\\\n e_2' = R_{12}e_1 + R_{22}e_2 + R_{32}e_3 \\\\\n e_3' = R_{13}e_1 + R_{23}e_2 + R_{33}e_3 \\\\\n \\text{Dessa forma:} \\\\\n R_{im}R_{jm} = R_{mi}R_{mj} = \\delta_{ij} \\\\\n R_{11} = e_1.Re_1 = e_1 . e_1' = cos(e_1,e_1') \\\\\n R_{12} = e_1.Re_2 = e_1 . e_2' = cos(e_1,e_2') \\\\\n R_{13} = e_1.Re_3 = e_1 . e_3' = cos(e_1,e_3')\n \\text{, logo:} \\\\\n R_{ij} = cos(e_i,e_j') \\\\\n\\text{De acordo com a demonstração acima:} \\\\\nR = \n\\begin{bmatrix}\nR_{11} & R_{12} & R_{13}\\\\\n R_{21} & R_{22} & R_{23} \n \\\\ R_{31} & R_{32} & R_{33} \n\\end{bmatrix} \\text{, será:} \\\\\nR = \n\\begin{bmatrix}\n1 & 0 & 0\\\\\n0 & cos\\theta & sen\\theta \n \\\\ 0 & -sen\\theta & cos\\theta \n\\end{bmatrix}\n$\n\n(b)\n\n$\n\\text{Analogamente à letra \"a\":} \\\\\nR = \n\\begin{bmatrix}\ncos\\theta & 0 & -sen\\theta\\\\\n0 & 1 & 0 \n \\\\ sen\\theta & 0 & cos\\theta \n\\end{bmatrix}\n$\n\n\n\n\n\n## Solução do problema 2.27 (inserir número e enunciado)\n\n\n\n### Pelo produto diádico temos que :\n$Tr = r - 2(r.n)n = r - 2(nn)r$\n### Multiplicando pela matriz Identidade $I$ :\n$Tr = (Ir - 2(nn)r) = (I - 2nn)r$
\n$T = I - 2nn$

\n### Agora vamos encontrar a matriz $T$ :
Como foi dito no enunciado :\n$n = (e_1 + e_2 + e_3)/√3$\n###Então :\n$\n[2nn] = 2/3\n\\begin{bmatrix}\n 1 \\\\\n 1 \\\\\n 1 \n\\end{bmatrix}\n\\begin{bmatrix}\n 1 & 1 & 1\\\\\n\\end{bmatrix}\n= 2/3\n\\begin{bmatrix}\n 1 & 1 & 1 \\\\\n 1 & 1 & 1 \\\\\n 1 & 1 & 1 \n\\end{bmatrix}\n$\n


\n###Substituindo na equação $T = I - 2nn$ :\n$\n[T] = [I] - 2/3\n\\begin{bmatrix}\n 1 & 1 & 1 \\\\\n 1 & 1 & 1 \\\\\n 1 & 1 & 1 \n\\end{bmatrix}\n$

\n$\n[T] = \n\\begin{bmatrix}\n 1 & 0 & 0 \\\\\n 0 & 1 & 0 \\\\\n 0 & 0 & 1 \n\\end{bmatrix} - \n\\begin{bmatrix}\n 2/3 & 2/3 & 2/3 \\\\\n 2/3 & 2/3 & 2/3 \\\\\n 2/3 & 2/3 & 2/3 \n\\end{bmatrix}\n$

\n$\n[T] = \n\\begin{bmatrix}\n 1/3 & -2/3 & -2/3 \\\\\n -2/3 & 1/3 & -2/3 \\\\\n -2/3 & -2/3 & 1/3 \n\\end{bmatrix} = 1/3\n\\begin{bmatrix}\n 1 & -2 & -2 \\\\\n -2 & 1 & -2 \\\\\n -2 & -2 & 1\n\\end{bmatrix}\n$

\n\n\n## Solução do problema 2.46 (inserir número e enunciado)\n\n\n\n\n###a) Dado qualquer vetor $a$ e qualquer tensor $T$, mostrar que $a T^A a = 0$, onde $T^A$ e $T^S$ são simétricos e antisimétricos por parte de T.\n\nR: Dado que $T^A$ é antissimétrico, então $(T^A)^T = -T^A$. Dessa forma, podemos calcular:\n\n$aT^Aa = a(T^A)^Ta$ \n\n$aT^Aa = -aT^Aa$\n\n$2aT^Aa = 0$\n\n$aT^Aa = 0$\n\n###b) Dado qualquer vetor $a$ e qualquer tensor $T$, mostrar que $a T a = a T^S a$, onde $T^A$ e $T^S$ são simétricos e antisimétricos por parte de T.\n\nR: Dado que qualquer Tensor $T$ pode ser decomposto na soma de um tensor simétrico $T^S$ e um antissimétrico $T^A$. Temos: $T = T^S + T^A$\n\nSendo assim, podemos calcular:\n\n$a T a = a(T^S + T^A)a$\n\n$a T a = (a T^S + a T^A) a$\n\n$a T a = a T^S a + a T^A a$\n\nSubstituindo o valor encontrado na alternativa a ($aT^Aa = 0$), temos: \n\n$a T a = a T^S a + 0$\n\n$a T a = a T^S a$\n", "meta": {"hexsha": "523656fd08b1ca83dfaa848845029b56022f6ada", "size": 444465, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "[MAC005] - Trabalho 01.ipynb", "max_stars_repo_name": "MathewsJosh/mecanica-solidos", "max_stars_repo_head_hexsha": "68b167c4cf760fcb6601dd053a45454fdf73347a", "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": "[MAC005] - Trabalho 01.ipynb", "max_issues_repo_name": "MathewsJosh/mecanica-solidos", "max_issues_repo_head_hexsha": "68b167c4cf760fcb6601dd053a45454fdf73347a", "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": "[MAC005] - Trabalho 01.ipynb", "max_forks_repo_name": "MathewsJosh/mecanica-solidos", "max_forks_repo_head_hexsha": "68b167c4cf760fcb6601dd053a45454fdf73347a", "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": 583.2874015748, "max_line_length": 88262, "alphanum_fraction": 0.9374213943, "converted": true, "num_tokens": 5461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.1993080074160125, "lm_q1q2_score": 0.08496930712906148}} {"text": "```python\n%matplotlib notebook\n%matplotlib inline\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n# Nuclear Models\n\n## Learning objectives\n\n- Summarize the history of atomic theory development.\n- Recognize the radiation signatures that drove early atomic theory.\n- List atomic models: Plum Pudding, Rutherford, Bohr, Bohr with Elliptical Orbits, Quantum Mechanical\n- Differentiate various atomic models by name and physics.\n- List nuclear models: Proton-electron, Proton-neutron, Liquid-Drop, Shell\n- Differentiate nuclear models by name and physics.\n- Identify the physics captured by various nuclear models.\n- Explain the reason for the structure of most likely decays in the chart of the nuclides\n\n## Discovery of Radioactivity\n\nElectrically charged plates impose a magnetic field (out of the page). \n\n\n\n21.3 Radioactive Decay by Rice University is licensed under a Creative Commons Attribution 4.0 International License, except where otherwise noted. (https://opentextbc.ca/chemistry/chapter/21-3-radioactive-decay/)\n\n\n- Alpha $(\\alpha)$ particles are attracted to the negative plate and deflected by a relatively small amount.\n- Beta $(\\beta)$ particles are attracted to the positive plate and deflected by a larger amount.\n- Gamma $(\\gamma)$ particles seem to be unaffected.\n\n### Exercise: Think-pair-share\n\nBased on these experimental results:\n\n1. What can one determine about the charges of the alpha, beta, and gamma particles?\n2. What can one determine about the weights of the particles?\n\n\n### Plum Pudding Model\n\nJ.J. Thomson correctly identified the beta rays as electrons. \nSo, electrons must be somewhere in the atom. However, atoms seemed be generally electrically neutral. \nBeing british, J.J. Thomson equated this to plum pudding:\n\n\n\n\nHe had no reason to believe that the charges were not uniformly distributed.\n\n\n\n\nExplains:\n\n- electrically neutral atoms\n- size of the atom $(10^{-10} m)$\n- an ion is an atom from which an electron has been lost\n- charge of a singly ionized atom is exactly one \n- number of electrons equals approximately half of the atomic weight of the atom\n\n\n### Rutherford Model\n\nGold foil experiment by Geiger and Marsden. Alpha particles bombarded a very thin gold sheet/foil. Reflected alphas were very unlikely to be observed if the Thomson model was correct.\n\n\n\n\nIn **1911** Rutherford surmised that a dense, positively charged thing must be at the center of the atom, perhaps with a diameter of $10^{-14}m$ or less.\n\nDeficiency of Rutherford’s model:\nThe accelerating charge (electron) would radiate away their kinetic energy and the atom will collapse. \n\n\n### Bohr Model\n\nIn the 1880s, Balmer, Rydberg, and others had observed **discrete lines** in the wavelength spectrum of atomic hydrogen when atoms are excited.\n\n\n\nThe equation explaining these emission lines was well known by the early 1900s.\n\n\\begin{align}\n\\frac{1}{\\lambda} &= R_H \\left[\\frac{1}{n_o^2} - \\frac{1}{n^2} \\right]\\\\\n\\mbox{where }&\\\\\n\\lambda &= \\mbox{the wavelength of electromagnetic radiation emitted in vacuum}\\\\\nR_H &= \\mbox{the Rydberg constant } \\\\\n&\\simeq 1.097373156850865 \\times 10^7 m^{-1} \\\\\n\\implies \\frac{1}{R} &=912 \\mbox{ angstrom}\\\\\n\\end{align}\n\nIn the Bohr model, then, electrons were allowed only in certain orbits. Specifically only those orbits whose angular momentum satisfied the following relation:\n\n\\begin{align}\n\\frac{m_ev^2}{r} &= \\frac{Ze^2}{4\\pi\\epsilon_or^2}\\\\\nL &\\equiv m_evr = n\\frac{h}{2\\pi}\\\\\n\\mbox{where }&\\\\\nn&=1,2,3...\\\\\nL&=\\mbox{angular momentum}\\\\\nv&=\\mbox{velocity of the electron}\\\\\nr&=\\mbox{radius of the electron orbit}\\\\\n\\epsilon_o&=\\mbox{permittivity of free space}\\\\\n&= 8.85418782 \\times 10^{-12} m^{-3} kg^{-1} s^4 A^2\n\\end{align}\n\nSolving those relations for $r$ and $v$ :\n\n\\begin{align}\nv_n &= \\frac{Ze^2}{2\\epsilon_onh}\\\\\nr_n &= \\frac{n^2h^2\\epsilon_o}{\\pi m_e Z e^2}\n\\end{align}\n\n\nThis explained the discreteness, as electrons might radiate energy only when moving from one allowed orbit to another.\n\n\n\n\nElectron’s total energy under a certain orbit:\n\n\\begin{align}\nE_n &= \\frac{-m_e(Ze^2)^2}{8\\epsilon_o^2 n^2 h^2}\\\\\n\\end{align}\n\n\nEnergy difference between two allowed orbits:\n\n\\begin{align}\n\\Delta E_{n\\rightarrow n_o} &= h\\nu_{n\\rightarrow n_o} \\\\\n &= \\frac{-m_e(Ze^2)^2}{8\\epsilon_o^2 h^2}\\left[\\frac{1}{n_o^2} - \\frac{1}{n^2}\\right]\\\\\n\\end{align}\n\n\nThis model explained a lot.\n\n\n\n### Bohr Model : Elliptic Orbits\n\nFine structure: Spectral lines are consisted of a number of lines very close together.\n\n- Except the quantum number $n$, there are some energy levels lying close to one another. \n- Sommerfeld postulated elliptic orbits as well as circular orbits and introduced another quantum number to describe the **angular momentum** of orbits. \n\nHowever, Sommerfeld’s theory predicted more lines than were observed in experiments.\n\nThus, a new quantum number $n$ needed an _ad hoc_ selection rule to limit the number of predicted lines.\n\n\n\n\n\nSplitting of the spectral lines was observed: A third quantum number $m$ needed to be introduced to revise Bohr’s model. also predicted more lines\n\nThe theory failed to applied to more complicated atoms (multiplet structure is observed).\n\nFurther change of Bohr’s theory can no longer resolve the difficulties. \n\n### Quantum Mechanical Model\n\nThe electrons are no longer modeled as particles moving in orbits. Instead, they are modeled as a standing wave around the nucleus. The magnitude of that wave reflects the probability of finding the electron in that locations.\n\n- Schrodinger’s new approach: **the wave function**\n- The electrons are no longer point particles; they are visualized as a standing wave around the nucleus.\n\nThe three quantum numbers ($n$, $l$ , $m$) arose from the theory naturally - no ad hoc selection rules were needed. \n\nA fourth quantum number $m_s$ was introduced to explain:\n- Multiple fine-line structure\n- Splitting of lines in a strong magnetic field ( the **anomalous Zeeman effect**)\n\n\n\nThe $m_s$ quantum number accounted for the inherent angular momentum of the electron equal to $\\pm\\frac{h}{2\\pi}. Later, in 1928, Dirac would show that this fourth quantum number also arises from the wave equation.\n\n## Nuclear Models\n\n\n### Fundamental properties of the nucleus \n\nSome simple facts were determined about the mass of the nucleus.\n\n1. The **masses of atoms** were very nearly whole numbers if one defines the atomic mass unit as:\n\\begin{align}\n1 u = \\frac{1}{12}M(^{12}C)\n\\end{align}\n2. The **mass contribution from electrons** is quite **small**\n - In $^{12}C$, the six electrons together only weigh $0.00329u$\n \n \nAlso, electron scattering experiments yielded details about the density of the nucleus and its components.\n**The density of protons** inside the spherical nuclei was well understood to be a function of the radius, dropping off appreciably at the boundary of the nucleus.\n\n\\begin{align}\n\\rho_p(r) &= \\frac{\\rho_p^o}{1+e^{\\frac{(r-R)}{a}}} \\left[\\frac{\\mbox{protons}}{fm^3}\\right]\\\\\n\\mbox{where }&\\\\\nr &= \\mbox{distance to center of nucleus}\\\\\nR &= \\mbox{total 'radius' of the nucleus}\\\\\na &= \\mbox{surface thickness}\\\\\n\\rho_p^o &= \\int\\int\\int \\rho_p(r)dV\\\\\n&= 4\\pi\\int_0^\\infty r^2\\rho_p(r)dr\\\\\n&= Z\n\\end{align}\n\nAlso, the R value, the radius of the nucleus was seen empirically to be proportional to $A^{1/3}$.\n\n\n```python\ndef rho_p(r, rho_po, radius, a):\n denom = 1 + math.exp((r - radius)/a)\n return rho_po/denom\n```\n\n\n```python\n# For 16O (from table 3.2)\no_rho_po = 0.156 # fm^{-3}\no_radius = 2.61 # fm\no_a = 0.513\n\n# For 109Ag (from table 3.2)\nag_rho_po = 0.157 # fm^{-3}\nag_radius = 5.33 # fm\nag_a = 0.523\n\n# For 208Pb (from table 3.2)\npb_rho_po = 0.159 # fm^{-3}\npb_radius = 6.65 # fm\npb_a = 0.526\n\nr = np.arange(0, 10, 0.1)\nto_plot_o = np.arange(0., 100.)\nto_plot_ag = np.arange(0., 100.)\nto_plot_pb = np.arange(0., 100.)\n\nfor i in range(0, 100):\n to_plot_o[i] = rho_p(r[i], o_rho_po, o_radius, o_a)\n to_plot_ag[i] = rho_p(r[i], ag_rho_po, ag_radius, ag_a)\n to_plot_pb[i] = rho_p(r[i], pb_rho_po, pb_radius, pb_a)\n\nplt.plot(r, to_plot_o, label=\"$^{16}O$\")\nplt.plot(r, to_plot_ag, label=\"$^{109}Ag$\")\nplt.plot(r, to_plot_pb, label=\"$^{208}Pb$\")\nplt.ylabel(\"Proton density ($fm^{-3}$)\")\nplt.xlabel(\"distance from center $(fm)$\")\nplt.legend()\n```\n\n### Proton Electron Model\n\nThis model sought primarily to explain the wholeness of mass numbers. To do so, it simply assumed that all heavier nuclei were composed of multiples of the hydrogen nucleus (assumed to be a single proton), which has the smallest mass(1 amu).\n\nFor this to match what was known about atomic charge, electrons would need to be in the nucleus to cancel some, but not all, of the positive charge from the protons.\n\n**In this model** an atom $^A_ZX$ would have a nucleus containing A protons and (A − Z) electrons with Z electrons surrounding the nucleus. This postulated extra electrons -- to explain it, the mass of the electrons was assumed to make a negligible contribution.\n\nTwo difficulties with this P-E Model:\n\n1. Predicted angular momentum (spin) of the nuclei did not always agree with experiment. \n **Protons and electrons both have half integer spin**, so when an even number are combined, whole integer spin should result. For example, **the model predicted integer spin for Beryllium, while experiments predicted half-integer spin.** Similarly, **the model predicted half-integer spin in nitrogen but experimental results show nitrogen has integer spin.**\n\n2. Uncertainty Principle \n\n\\begin{align}\n\\Delta p \\Delta x &\\ge \\frac{h}{4\\pi}\n\\end{align}\n \n\nIf an electron is in the nucleus, then $\\Delta x\\simeq10^{-14}m$. Accordingly:\n\\begin{align}\nmin(\\Delta_p) = 1.1\\times 10^{-20}J m^{-1}s\n\\end{align}\nSince the electron’s total energy is\n\\begin{align}\nE &= T +m_oc^2 \\\\\n&=\t\\sqrt{p^2c^2 +m^2_oc^4}\\\\\n\\implies &\\\\\n&\\forall p = \\Delta p : E \\simeq T = 20 MeV\\\\\n\\end{align}\n\nSince the electron's rest-mass energy is 0.51 MeV and beta particles emitted by atoms seldom have energies above a few MeV, something was wrong with this calculation.\n\nYou can do the same calculation for the proton. Because it has a much higher mass, there is no discrepancy. The energy of a free proton confined to a nucleus is its rest-mass energy (931 MeV), with $T<1MeV$.\n\n### 1932: Chadwick discovers the neutron\n\nChadwick discovers the existence of a chargeless particle with a mass just slightly greater than that of the proton.\n\n\\begin{align}\nm_n &= 1.008665 u\\\\\nm_p &= 1.007276 u\n\\end{align}\n\n\n\n### Proton-Neutron Model\n\n- **1932** Chadwick discovered the neutron. \n- **1932** Heisenberg first suggested every nucleus is composed of only protons and neutrons.\n\n**In this model**, a nucleus with a mass number A contains Z protons and N = A − Z neutrons. \n\n- This P-N Model avoids the failures of the P-E model. \n- Also is consistent with experimental results regarding radioactivity \n- Since the neutron has half-integral spin, the A neutrons and protons give appropriate spin for the total atom in all cases.\n\nChallenges for this model:\n\n- Because of Coulombic repulsive forces in the nucleus, a 'nuclear force' must hold the nucleus together\n- To hold the protons and neutrons together: \n nuclear force : p-n , n-n , p-p\n 1. inside the nucleus: nuclear force (attractive)\n 2. outside the nucleus: Coulombic force (repulsive)\n\nThe energy needed to separate nucleus into $p_s$ & $n_s$ : binding energy\n\n\nIn the image below, the nuclear potential well is shown.\n\n\n**The above image was reproduced from Shultis, J. K. and Faw, R. E. “Fundamentals of Nuclear Science and Engineering” (2016).**\n\n## Nuclear Stability\n\n\n\n**Figure** Graph of isotopes by type of nuclear decay. Orange and blue nuclides are unstable, with the black squares between these regions representing stable nuclides. The unbroken line passing below many of the nuclides represents the theoretical position on the graph of nuclides for which proton number is the same as neutron number. The graph shows that elements with more than 20 protons must have more neutrons than protons, in order to be stable.\n\n\n\n**The above image was reproduced from Shultis, J. K. and Faw, R. E. “Fundamentals of Nuclear Science and Engineering” (2016).**\n\n- many more stable isotopes with even N and/or Z\n- in a heavy nucleus, the neutrons and protons tend to group themselves into subunits of 2 neutrons and 2 protons.\n- when either Z or N equals 8, 20, 50, 82, or 126, there are relatively greater numbers of stable nuclides. \n\n### Liquid Drop Model\n\n\n1. volume term: volume binding energy is proportional to the number of nucleons (i.e. # of nucleons.)\n\n2. Surface term: Nucleons near the surface of the nucleus are not completely surrounded by other nucleons as interior nucleons.\n\n3. Coulomb term: Coulombic repulsive force decrease the stability of nucleons (reduces the BE ).\n\n4. asymmetry term: a departure from symmetry (N=Z) tends to reduce nuclear stability. (Fig.3.10 )\n\n5. pairing term : pairing neutrons and protons are more stable. (even N or Z; odd N or Z ; even N (Z), odd Z (N)) (Fig.3.11 & Fig.3.12)\n\n\n\n\nHigher binding energy $\\implies$ a more stable nuclide.\n\n### Shell Model\n\nThe liquid drop model cannot explain the abnormal high stable nuclides(magic numbers:2,8,20,28,50,82,126).\nThe shell model assume: (Shrodinger’s wave eq.)\nEach nucleon moves independently.\nEach nucleon moves in a potential well.\n\nWhen the model’s quantum-mechanical wave eq. is solved, the nucleons are found to distribute themselves into a number of energy levels.\nFilled shells are indicated by large gaps between each adjacent energy level.\n\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8a9e4e156a4462a60a6c0c7a661ace783a69e1ea", "size": 51470, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nuclear_models/00-nuclear-models.ipynb", "max_stars_repo_name": "katyhuff/npr247", "max_stars_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T06:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T17:14:51.000Z", "max_issues_repo_path": "nuclear_models/00-nuclear-models.ipynb", "max_issues_repo_name": "katyhuff/npr247", "max_issues_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-29T17:27:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T17:46:50.000Z", "max_forks_repo_path": "nuclear_models/00-nuclear-models.ipynb", "max_forks_repo_name": "katyhuff/npr247", "max_forks_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-08-25T20:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T03:05:26.000Z", "avg_line_length": 86.5042016807, "max_line_length": 26752, "alphanum_fraction": 0.7933553526, "converted": true, "num_tokens": 4235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.24798742068237775, "lm_q1q2_score": 0.08470816298594798}} {"text": "\n\n## Data-driven Design and Analyses of Structures and Materials (3dasm)\n\n## Lecture 8\n\n### Miguel A. Bessa | M.A.Bessa@tudelft.nl | Associate Professor\n\n**What:** A lecture of the \"3dasm\" course\n\n**Where:** This notebook comes from this [repository](https://github.com/bessagroup/3dasm_course)\n\n**Reference for entire course:** Murphy, Kevin P. *Probabilistic machine learning: an introduction*. MIT press, 2022. Available online [here](https://probml.github.io/pml-book/book1.html)\n\n**How:** We try to follow Murphy's book closely, but the sequence of Chapters and Sections is different. The intention is to use notebooks as an introduction to the topic and Murphy's book as a resource.\n* If working offline: Go through this notebook and read the book.\n* If attending class in person: listen to me (!) but also go through the notebook in your laptop at the same time. Read the book.\n* If attending lectures remotely: listen to me (!) via Zoom and (ideally) use two screens where you have the notebook open in 1 screen and you see the lectures on the other. Read the book.\n\n**Optional reference (the \"bible\" by the \"bishop\"... pun intended 😆) :** Bishop, Christopher M. *Pattern recognition and machine learning*. Springer Verlag, 2006.\n\n**References/resources to create this notebook:**\n* [Car figure](https://korkortonline.se/en/theory/reaction-braking-stopping/)\n\nApologies in advance if I missed some reference used in this notebook. Please contact me if that is the case, and I will gladly include it here.\n\n## **OPTION 1**. Run this notebook **locally in your computer**:\n1. Confirm that you have the 3dasm conda environment (see Lecture 1).\n\n2. Go to the 3dasm_course folder in your computer and pull the last updates of the [repository](https://github.com/bessagroup/3dasm_course):\n```\ngit pull\n```\n3. Open command window and load jupyter notebook (it will open in your internet browser):\n```\nconda activate 3dasm\njupyter notebook\n```\n4. Open notebook of this Lecture.\n\n## **OPTION 2**. Use **Google's Colab** (no installation required, but times out if idle):\n\n1. go to https://colab.research.google.com\n2. login\n3. File > Open notebook\n4. click on Github (no need to login or authorize anything)\n5. paste the git link: https://github.com/bessagroup/3dasm_course\n6. click search and then click on the notebook for this Lecture.\n\n\n```python\n# Basic plotting tools needed in Python.\n\nimport matplotlib.pyplot as plt # import plotting tools to create figures\nimport numpy as np # import numpy to handle a lot of things!\nfrom IPython.display import display, Math # to print with Latex math\n\n%config InlineBackend.figure_format = \"retina\" # render higher resolution images in the notebook\nplt.style.use(\"seaborn\") # style for plotting that comes from seaborn\nplt.rcParams[\"figure.figsize\"] = (8,4) # rescale figure size appropriately for slides\n```\n\n## Outline for today\n\n* Parameter estimation from training with data (model fitting)\n - Posterior approximation by Dirac delta \"distribution\"\n - Point estimates for the Dirac delta \"distribution\"\n * MAP: Maximum A Posterior estimate\n * MLE: Maximum Likelihood Estimation \n - Negative log likelihood (NLL) \n* Why some people do not adopt a Bayesian (probabilistic) perspective of ML\n\n**Reading material**: This notebook + Chapter 4\n\n## Summary of past lectures\n\nBayesian inference:\n* predicts a **quantity of interest** (e.g. $y$) while treating **unknown** information as rv's (e.g. $z$)\n\n* it is based on establishing a model (observation distribution + prior) and evaluating it on data (joint likelihood normalized by marginal likelihood) to update our belief about the unknown (posterior)\n\n* from the posterior, we can then predict a distribution for the quantity of interest (the PPD) that results from marginalizing (integrating out) the unknown\n\n### The good and the bad\n\nIn short: Bayesian inference results from interpreting the unknown as rv's of a model, and then evaluating the impact of all possible values of the rv's (within the constraints imposed by the model!) by marginalizing them (integrating them out).\n\n* **The good**: This is powerful because even if our assumptions are wrong, we can at least take different values for the rv's and their respective impact on the predictions. This alleviates problems such as overfitting and overconfidence, that we will encounter in the remaining of the course.\n\n* **The bad**: Bayesian inference can be difficult. We solved one of the simplest problems in the last lectures, and we saw that those integrals are a bit ugly...\n - In most cases, the integrals (to compute the marginal likelihood, and the PPD) cannot even be solved analytically.\n - Numerical strategies exist to approximate the integration, but they tend to be **slow when accurate** or **fast but innacurate** (a dangerous generalization: forgive me Bayesians!)\n\n**Very Important Question (VIQ)**: What if we don't calculate these integrals at all?\n\n## Machine Learning without going fully Bayesian\n\nAvoiding integration is possible by noting that:\n\n1. Computing the PPD is trivial if the **posterior distribution becomes the Dirac delta**\n\n\n2. The marginal likelihood is just a **constant**\n\nLet's explore these two remarks.\n\n### 1. PPD when the posterior is a Dirac delta\n\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = \\int \\underbrace{p(y|z)}_{\\text{observation}\\\\ \\text{distribution}} \\overbrace{p(z|y=\\mathcal{D}_y)}^{\\text{posterior}} dz\n$$\n\nWhat happens if the posterior is the Dirac delta \"distribution\"?\n\n$$\np(z|y=\\mathcal{D}_y) = \\delta(z-\\hat{z})\n$$\n\nwhere $\\hat{z}$ is our best estimate for the value that $z$ should have.\n\n$$\\require{color}\n\\begin{align}\n{\\color{orange}p(y|\\mathcal{D}_y)} &= \\int \\underbrace{p(y|z)}_{\\text{observation}\\\\ \\text{distribution}} \\overbrace{p(z|y=\\mathcal{D}_y)}^{\\text{posterior}} dz\\\\\n&= \\int p(y|z) \\delta(z-\\hat{z}) dz \\\\\n&= p(y|z=\\hat{z})\n\\end{align}\n$$\n\n**Conclusion**: The PPD becomes the **observation distribution** where the unknown $z$ becomes our **best estimate** $\\hat{z}$ (in other words: $z = \\hat{z} =$ const)\n\n* But what is our \"**best estimate**\" $\\hat{z}$?\n - There are different estimates and different strategies to get there!\n\n### 2. Finding the \"best estimate\" $\\hat{z}$ without computing the marginal likelihood\n\nRemember: the Bayes' rule determines the posterior,\n\n$\\require{color}$\n$$\n{\\color{green}p(z|y=\\mathcal{D}_y)} = \\frac{ {\\color{blue}p(y=\\mathcal{D}_y|z)}{\\color{red}p(z)} } {p(y=\\mathcal{D}_y)}\n$$\n\nand the marginal likelihood $p(y=\\mathcal{D}_y)$ is just a constant.\n\nIf we want to reduce the posterior to the Dirac delta \"distribution\",\n\n$$\np(z|y=\\mathcal{D}_y) = \\delta(z-\\hat{z})\n$$\n\nwhat is the only parameter that we need to find?\n\n* We just need to find $\\hat{z}$ to completely characterize $\\delta(z-\\hat{z})$\n\nNote that this is not the case if the posterior is a different distribution!\n\nFor example, we saw in the previous lectures that the posterior for the car stopping distance problem was a **Gaussian**.\n\n* How many parameters do you need to characterize the Gaussian distribution?\n\nIndeed... Two!\n\nAnd if the posterior distribution is more complicated, you may need a lot more parameters! In some cases, the posterior does not even have an analytical description!\n\nAnyway, the question still remains: what should be the value $\\hat{z}$?\n\nLet's go back to the two problems we have seen in Lecture 6 and Lecture 7.\n\nRecall our reflection on the differences between the posterior for the two priors we used.\n\n* When using the noninformative Uniform prior $p(z) = \\frac{1}{C_z}$ (Lecture 6):\n\n$$\\require{color}\\begin{align}\n{\\color{green}p(z|y=\\mathcal{D}_y)}\n&= \\mathcal{N}(z|\\mu, \\sigma^2)\n\\end{align}\n$$\n\n* When using a Gaussian prior $p(z) = \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle <}{\\mu}_z, \\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right)$ (Lecture 7):\n\n$$\\require{color}\\begin{align}\n{\\color{green}p(z|y=\\mathcal{D}_y)} &= \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle >}{\\mu}_z, \\overset{\\scriptscriptstyle >}{\\sigma}_z^2\\right) = \\mathcal{N}\\left(z\\left|\\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2} + \\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right), \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}}\\right.\\right)\n\\end{align}\n$$\n\nThe posterior is still a Gaussian but its mean and variance have been updated by the influence of the prior!\n\nLet's play a simple game:\n* Choose where to place the Dirac delta \"distribution\" for those two posteriors we found before.\n\n\n```python\n# This cell is hidden during the presentation\nfrom scipy.stats import norm # import the normal dist, as we learned before!\ndef samples_y_with_2rvs(N_samples,x): # observations/measurements/samples for car stop. dist. prob. with 2 rv's\n mu_z1 = 1.5; sigma_z1 = 0.5;\n mu_z2 = 0.1; sigma_z2 = 0.01;\n samples_z1 = norm.rvs(mu_z1, sigma_z1, size=N_samples) # randomly draw samples from the normal dist.\n samples_z2 = norm.rvs(mu_z2, sigma_z2, size=N_samples) # randomly draw samples from the normal dist.\n samples_y = samples_z1*x + samples_z2*x**2 # compute the stopping distance for samples of z_1 and z_2\n return samples_y # return samples of y\n```\n\n\n```python\n# This cell is hidden during the presentation\n\n# -------------------------------------------------------------------------------\n# PARAMETERS YOU CAN CHANGE! PLAY A BIT WITH THIS ;)\nx = 75 # keeping the car velocity constant at 75 m/s as we have done before\nmu_z2 = 0.1; sigma_z2 = 0.01 # parameters of z_2 distribution\nN_samples = 3 # Let's say our data is composed of 3 samples (empirical observations)\nmu_prior_z = 3; sigma_prior_z = 2 # parameters of the Gaussian prior distribution (used only in case 2)\n# -------------------------------------------------------------------------------\n\n\nempirical_y = samples_y_with_2rvs(N_samples, x) # Our data (empirical measurements of N_samples at x=75)\n\n# Compute all the constants needed to plot the posterior for Lecture 6 and for Lecture 7\nw = x\nb = mu_z2*x**2\nsigma_yGIVENz = np.sqrt((x**2*sigma_z2)**2) # sigma_y|z (comes from the stochastic influence of the z_2 rv)\n# Empirical mean and std directly calculated from observations:\nempirical_mu_y = np.mean(empirical_y); empirical_sigma_y = np.std(empirical_y); \n#\n# Parameters of the likelihood function (not a distribution because it is not normalized):\nsigma = np.sqrt(sigma_yGIVENz**2/(w**2*N_samples)) # std arising from the likelihood\nmu = empirical_mu_y/w - b/w # mean arising from the likelihood (product of Gaussian densities for the data)\n# -------------------------------------------------------------------------------\n# Case 1: using a noninformative Uniform prior (Lecture 6):\n# Posterior parameters:\n# These parameters are obvious in this case but I just want to highlight that the mean and std of this posterior\n# are the same as the parameters of the likelihood because posterior = likelihood / const )\nsigma_posterior_UniformPrior = sigma # std of posterior (same as likelihood)\nmu_posterior_UniformPrior = mu # mean of posterior (same as likelihood)\n#\n# PPD parameters:\nPPD_mu_y_UniformPrior = mu*w + b # same result if using: np.mean(empirical_y)\nPPD_sigma_y_UniformPrior = np.sqrt(w**2*sigma**2+sigma_yGIVENz**2) # same as: np.sqrt((x**2*sigma_z2)**2*(1/N_samples + 1))\n\n# z values for plot of case 1:\nzrange_case1 = np.linspace(-3*sigma_posterior_UniformPrior+mu_posterior_UniformPrior,\n 3*sigma_posterior_UniformPrior+mu_posterior_UniformPrior, 200)\n# Posterior values for plot of case 1:\nposterior_pdf_values_case1 = norm.pdf(zrange_case1, mu, sigma)\n# Probability density of posterior at the mean for case 1:\npdf_at_mean_case1 = norm.pdf(mu_posterior_UniformPrior,mu_posterior_UniformPrior,sigma_posterior_UniformPrior)\n# MAP estimate (maximum a posterior estimate) is the same as MLE (maximum likelihood estimation) for case 1:\npdf_at_mode_case1 = pdf_at_mean_case1 # in this case it's the same as mean (no calculation needed)\n# -------------------------------------------------------------------------------\n#\n# -------------------------------------------------------------------------------\n# CASE 2: using a Gaussian prior (Lecture 7):\n# Posterior parameters:\nsigma_posterior_GaussianPrior = np.sqrt( (sigma_prior_z**2*sigma**2)/(sigma_prior_z**2+sigma**2) )# std of posterior\nmu_posterior_GaussianPrior = sigma_posterior_GaussianPrior**2*(mu/(sigma**2)+mu_prior_z/(sigma_prior_z**2)) # mean of posterior\n# PPD parameters:\nPPD_mu_y_GaussianPrior = mu_posterior_GaussianPrior*w + b\nPPD_sigma_y_GaussianPrior = np.sqrt(w**2*sigma_posterior_GaussianPrior**2+sigma_yGIVENz**2)\n#\n# z values for plot:\nzrange_case2 = np.linspace(-3*sigma_posterior_GaussianPrior+mu_posterior_GaussianPrior,\n 3*sigma_posterior_GaussianPrior+mu_posterior_GaussianPrior, 200)\n# Posterior values for plot of case 2:\nposterior_pdf_values_case2 = norm.pdf(zrange_case2, mu_posterior_GaussianPrior,\n sigma_posterior_GaussianPrior) # values of posterior for plotting\n# Probability density of posterior at the mean for case 2:\npdf_at_mean_case2 = norm.pdf(mu_posterior_GaussianPrior,mu_posterior_GaussianPrior,sigma_posterior_GaussianPrior)\n# MAP estimate (maximum a posterior estimate) for case 2:\npdf_at_mode_case2 = pdf_at_mean_case2 # in this case it's the same as mean (no calculation needed)\n# -------------------------------------------------------------------------------\n \n\n# Plot the posteriors that we calculate above and the Dirac delta at different z_hat\ndef Posteriors_and_Dirac_delta(z_hat_case1=mu_posterior_UniformPrior-2*sigma_posterior_UniformPrior,\n z_hat_case2=mu_posterior_GaussianPrior-2*sigma_posterior_GaussianPrior):\n fig_Dirac, (ax_case1, ax_case2) = plt.subplots(1,2)\n #\n ax_case1.plot(zrange_case1, posterior_pdf_values_case1,\n label=r\"Posterior: $p(z|\\mathcal{D}_y) = \\mathcal{N}\\left(z| \\mu, \\sigma^2\\right)$\")\n ax_case1.set_ylim(0, 1.3*pdf_at_mode_case1)\n ax_case1.plot(mu_posterior_UniformPrior, pdf_at_mean_case1,\n 'g^', markersize=25, linewidth=2,\n label=r'mode: $\\underset{z}{\\mathrm{argmax}}\\; p(z|\\mathcal{D}_y)=\\mu$')\n ax_case1.plot(mu_posterior_UniformPrior, pdf_at_mode_case1,\n 'k*', markersize=20, linewidth=2,\n label=r'mean: $\\mathbb{E}[z|\\mathcal{D}_y]=\\mu$')\n ax_case1.annotate(\"\",\n xy=(z_hat_case1, 0), xycoords='data',\n xytext=(z_hat_case1, 1.3*pdf_at_mode_case1), textcoords='data',\n arrowprops=dict(arrowstyle=\"<-\",\n connectionstyle=\"arc3\", color='r', lw=2),\n )\n ax_case1.text(z_hat_case1, pdf_at_mode_case1*1.05, 'Dirac $\\delta$', rotation = -90, fontsize = 15)\n ax_case1.text(z_hat_case1, 0, ('$\\hat{z}=%1.2f$' % z_hat_case1), fontsize = 15)\n ax_case1.set_xlabel(\"z\", fontsize=20)\n ax_case1.set_ylabel(\"probability density\", fontsize=20)\n ax_case1.legend(loc='center right', fontsize=12)\n ax_case1.set_title(\"Posterior using noninformative Uniform prior (Lecture 6)\", fontsize=20)\n #\n ax_case2.plot(zrange_case2, posterior_pdf_values_case2,\n label=r\"Posterior: $p(z|\\mathcal{D}_y) = \\mathcal{N}\\left(z| \\overset{>}{\\mu}_z, \\overset{>}{\\sigma}_z^2\\right)$\")\n \n ax_case2.set_ylim(0, 1.3*pdf_at_mode_case2)\n ax_case2.plot(mu_posterior_GaussianPrior, pdf_at_mean_case2,\n 'g^', markersize=25, linewidth=2,\n label=r'mode: $\\underset{z}{\\mathrm{argmax}}\\; p(z|\\mathcal{D}_y)=\\overset{>}{\\mu}_z$')\n ax_case2.plot(mu_posterior_GaussianPrior, pdf_at_mean_case2,\n 'k*', markersize=20, linewidth=2,\n label=r'mean: $\\mathbb{E}[z|\\mathcal{D}_y]=\\overset{>}{\\mu}_z$')\n ax_case2.annotate(\"\",\n xy=(z_hat_case2, 0), xycoords='data',\n xytext=(z_hat_case2, 1.3*pdf_at_mode_case2), textcoords='data',\n arrowprops=dict(arrowstyle=\"<-\",\n connectionstyle=\"arc3\", color='r', lw=2),\n )\n ax_case2.text(z_hat_case2, pdf_at_mode_case2*1.05, 'Dirac $\\delta$', rotation = -90, fontsize = 15)\n ax_case2.text(z_hat_case2, 0, ('$\\hat{z}=%1.2f$' % z_hat_case2), fontsize = 15)\n ax_case2.set_xlabel(\"z\", fontsize=20)\n ax_case2.set_ylabel(\"probability density\", fontsize=20)\n ax_case2.legend(loc='center right', fontsize=12)\n ax_case2.set_title(\"Posterior using Gaussian prior (Lecture 7)\", fontsize=20)\n fig_Dirac.set_size_inches(15, 6) # scale figure to be wider (since there are 2 subplots)\n```\n\n\n```python\n# Static plot (I skip this cell in presentations, but use it when printing slides to PDF)\nPosteriors_and_Dirac_delta(z_hat_case1=mu_posterior_UniformPrior-2*sigma_posterior_UniformPrior,\n z_hat_case2=mu_posterior_GaussianPrior-2*sigma_posterior_GaussianPrior)\n```\n\n\n```python\n# Showing posteriors and Dirac delta with interactive plot. Code is hidden in presentation.\nfrom ipywidgets import interactive # so that we can interact with the plot\ninteractive_plot = interactive(Posteriors_and_Dirac_delta,\n z_hat_case1=(min(zrange_case1), max(zrange_case1), 6/10*sigma_posterior_UniformPrior),\n z_hat_case2=(min(zrange_case2), max(zrange_case2), 6/10*sigma_posterior_GaussianPrior) )\ninteractive_plot\n```\n\n\n interactive(children=(FloatSlider(value=0.2645198973023184, description='z_hat_case1', max=2.429583406763415, …\n\n\nProbably you didn't hesitate to place the Dirac delta \"distribution\" at the mean or mode (they are the same for a Gaussian distribution)!\n\nWhat if the Posterior distribution is something else? For example, a Gamma distribution\n\n\n```python\n# This cell is hidden during the presentation\n\n# You may recall that we plotted the Gamma distribution in Lecture 1\n# -------------------------------------------------------------------------------\n# PARAMETERS YOU CAN CHANGE! PLAY A BIT WITH THIS ;)\nx = 75 # keeping the car velocity constant at 75 m/s as we have done before\nmu_z2 = 0.1; sigma_z2 = 0.01 # parameters of z_2 distribution\nN_samples = 3 # Let's say our data is composed of 3 samples (empirical observations)\nmu_prior_z = 3; sigma_prior_z = 2 # parameters of the Gaussian prior distribution (used only in case 2)\n# -------------------------------------------------------------------------------\n\nfrom scipy.stats import gamma # import from scipy.stats the Gamma distribution\nfrom scipy.optimize import minimize # import minimizer to calculate mode\n\na = 2.0 # this is the only input parameter needed for this distribution\n\n# Define the support of the distribution (its domain) by using the\n# inverse of the cdf (called ppf) to get the lowest z of the plot that\n# corresponds to Pr = 0.01 and the highest z of the plot that corresponds\n# to Pr = 0.99:\nzrange_min = gamma.ppf(0.01, a)\nzrange_max = gamma.ppf(0.99, a)\nzrange = np.linspace(zrange_min, zrange_max, 200) \n\nmu_posterior, var_posterior = gamma.stats(2.0, moments='mv') # This computes the mean and variance of the pdf\n\nposterior_pdf_values = gamma.pdf(zrange, a)\n\npdf_at_mean = gamma.pdf(mu_posterior, a)\n\n# Finding the maximum of a function can be done by minimizing\n# the negative gamma pdf. So, we create a function that outputs\n# the negative of the gamma pdf given the parameter a=2.0:\ndef neg_gamma_given_a(z): return -gamma.pdf(z,a)\n\n# Use the default optimizer of scipy (L-BFGS) to find the\n# maximum (by minimizing the negative gamma pdf). Note\n# that we need to give an initial guess for the value of z,\n# so we can use, for example, z=mu_z:\nmode_posterior = minimize(neg_gamma_given_a,mu_posterior).x # in general this is a vector, but for Gamma it's just a scalar\n\npdf_at_mode = gamma.pdf(mode_posterior, a) # in general this is a vector, but for Gamma is just a scalar\n\n# Plot the posteriors that we calculate above and the Dirac delta at different z_hat\ndef Gamma_Posterior_and_Dirac_delta(z_hat=0.5):\n fig_Gamma, ax = plt.subplots()\n ax.plot(zrange, posterior_pdf_values, label=r\"Posterior: $p(z|\\mathcal{D}_y) = \\Gamma(z|a)$\")\n\n ax.plot(mu_posterior, pdf_at_mean, 'r*', markersize=15, linewidth=2,\n label=r'Posterior mean: $\\mathbb{E}[z|\\mathcal{D}_y]$')\n\n ax.plot(mode_posterior, pdf_at_mode[0],'g^', markersize=15,\n linewidth=2,label=r'Posterior mode: $\\underset{z}{\\mathrm{argmax}}\\; p(z|\\mathcal{D}_y)$')\n ax.annotate(\"\",\n xy=(z_hat, 0), xycoords='data',\n xytext=(z_hat, 1.3*pdf_at_mode[0]), textcoords='data',\n arrowprops=dict(arrowstyle=\"<-\",\n connectionstyle=\"arc3\", color='r', lw=2),\n )\n ax.text(z_hat, pdf_at_mode[0]*1.05, 'Dirac $\\delta$', rotation = -90, fontsize = 15)\n ax.text(z_hat, 0, ('$\\hat{z}=%1.2f$' % z_hat) , fontsize = 15)\n ax.set_ylim(0, 1.3*pdf_at_mode[0])\n ax.set_xlabel(\"z\", fontsize=20)\n ax.set_ylabel(\"probability density\", fontsize=20)\n ax.legend(loc='upper right', fontsize=15)\n ax.set_title(\"Posterior being a Gamma pdf for $a=2.0$\", fontsize=20)\n```\n\n\n```python\n# Static plot (I skip this cell in presentations, but use it when printing slides to PDF)\nGamma_Posterior_and_Dirac_delta(z_hat=0.5)\n```\n\n\n```python\n# Showing posteriors and Dirac delta with interactive plot. Code is hidden in presentation.\ninteractive_plot = interactive(Gamma_Posterior_and_Dirac_delta,z_hat=(0.5, 6.5, 0.5 ) )\ninteractive_plot\n```\n\n\n interactive(children=(FloatSlider(value=0.5, description='z_hat', max=6.5, min=0.5, step=0.5), Output()), _dom…\n\n\nMaybe now you are hesitating where to place it?\n\nBoth are used in practice! And there are other estimates...\n\nThese are called **point estimates**.\n\n* They reduce each unknown rv $z$ to a point $\\hat{z}$ (transforming the posterior distribution into the Dirac delta \"distribution\").\n\nOf course, as everything in life, some choices are better than others...\n\nCommon point estimates for determining $\\hat{z}$:\n* Maximum Likelihood Estimation (MLE):\n - You choose the mode (the maximum) of the posterior but you used a Uniform prior\n* Maximum A Posterior (MAP) estimate:\n - You choose the mode (the maximum) of the posterior (and your prior is **not** Uniform)\n* Posterior mean estimate (no accronym!):\n - You choose the mean of the posterior.\n* ... and so on\n\nCalculating the **Posterior mean estimate** is not new to us (see Lecture 1):\n\n$$\n\\mathbb{E}[z|\\mathcal{D}]= \\int_{\\mathcal{Z}}z p(z|\\mathcal{D}) dz\n$$\n\nBut I told you that today we are all about avoiding integrals!\n\nSo, let's focus on two very common point estimates: **MAP** and **MLE**.\n\nBoth are obtained by finding the **mode** of the posterior (i.e. maximum location in the posterior):\n\n$$\n\\require{color}\\hat{\\mathbf{z}} = \\underset{z}{\\mathrm{argmax}}\\; {\\color{green}p(z|\\mathcal{D})}\n$$\n\nIn other words, we need to solve an optimization problem.\n\nBut finding the mode of the posterior involves a few simple \"tricks\"...\n\n$$\\require{color}\n{\\color{green}p(z|y=\\mathcal{D}_y)} = \\frac{ {\\color{blue}p(y=\\mathcal{D}_y|z)}{\\color{red}p(z)} } {p(y=\\mathcal{D}_y)}\n$$\n\n#### Calculating the mode of posterior: Trick 1 (taking the $\\log$)\n\nWe can separate the three terms of the posterior if we work with its $\\log$:\n\n$$\n\\log{{\\color{green}p(z|y=\\mathcal{D}_y)}} = \\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} + \\log{{\\color{red}p(z)}} - \\log{p(y=\\mathcal{D}_y)}\n$$\n\n* Note: $\\log$ is a monotone function, so the $\\mathrm{argmax}$ of a function is the same as the $\\mathrm{argmax}$ of the $\\log$ of the function! Mathematically:\n\n$$\n\\require{color}\\hat{\\mathbf{z}} = \\underset{z}{\\mathrm{argmax}}\\; {\\color{green}p(z|\\mathcal{D})} = \\underset{z}{\\mathrm{argmax}}\\; \\log{{\\color{green}p(z|\\mathcal{D})}}\n$$\n\n#### Calculating the mode: Trick 2 (maximizing by minimizing the negative $\\log$)\n\n**Maximizing a function** is the same as **minimizing the negative of a function** (flipping the sign in the end).\n\nMathematically:\n\n$$\n\\require{color}\\hat{\\mathbf{z}} = \\underset{z}{\\mathrm{argmax}}\\; \\log{{\\color{green}p(z|\\mathcal{D})}} = \\underset{z}{\\mathrm{argmin}} \\left[-\\log{{\\color{green}p(z|\\mathcal{D})}}\\right]\n$$\n\n* In numerical optimization, this is very common practice!\n - Most optimization algorithms are designed to *minimize* functions.\n - In general, when we are optimizing (whether maximizing or minimizing) functions we call them \"**objective**\" functions. Yet, in particular:\n * when we are *minimizing* functions we call them \"**loss**\" or \"cost\" functions.\n * when we are *maximizing* functions we call them \"**reward**\" or \"score\" functions.\n\n#### Calculating the mode: focusing on each $\\log$ term\n\n$$\\require{color}\n\\begin{align}\n\\hat{\\mathbf{z}} &= \\underset{z}{\\mathrm{argmax}}\\left[\\log{{\\color{green}p(z|y=\\mathcal{D}_y)}}\\right] \\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{green}p(z|y=\\mathcal{D}_y)}}\\right] \\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} - \\log{{\\color{red}p(z)}} + \\log{p(y=\\mathcal{D}_y)}\\right]\\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} - \\log{{\\color{red}p(z)}}+\\text{constant}\\right]\\\\\n\\end{align}\n$$\n\n* The last line can be further simplified because a constant does not change the location of the minimum.\n\nSo, we get: $\\require{color}\n\\hat{\\mathbf{z}} = \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} - \\log{{\\color{red}p(z)}}\\right]$\n\nAt this point, recall that the likelihood is usually calculated assuming the training examples (observations) are sampled independently from the observation distribution $p(y|z)$:\n\n$$\np(y=\\mathcal{D}_y | z) = \\prod_{i=1}^{N} p(y=y_i|z)\n$$\n\nwhich is known as the **i.i.d.** assumption (independent and identically distributed).\n\nThis means that the $\\log$ likelihood usually has a very convenient form:\n\n$$\n\\mathrm{LL}(z) = \\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} = \\sum_{i=1}^{N} \\log{p(y=y_i|z)}\n$$\n\nwhich decomposed into a sum of terms, one per example (observation).\n\n**In summary**, the mode of the posterior is calculated as:\n\n$\\require{color}\n\\hat{\\mathbf{z}} = \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} - \\log{{\\color{red}p(z)}}\\right]$\n\nwhere the first term is called **negative log likelihood**:\n\n$\\mathrm{NLL}(z) = -\\mathrm{LL}(z) = -\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}}=-\\sum_{i=1}^{N} \\log{p(y=y_i|z)}$\n\n#### Maximum A Posterior (MAP) estimate\n\nIf we choose any prior distribution **except** the Uniform distribution, then the estimate is called MAP:\n\n$\\require{color}\n\\hat{\\mathbf{z}}_{\\text{map}} = \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} - \\log{{\\color{red}p(z)}}\\right]$\n\nwhere $p(z)$ is **not** the Uniform distribution.\n\n#### Maximum Likelihood Estimation (MLE)\n\nIn the special case of choosing the prior to be a **Uniform distribution**, $p(z) \\propto 1$, then the mode of the posterior becomes the same as the mode of the (log) likelihood:\n\n$$\\require{color}\n\\hat{\\mathbf{z}} = \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}} - \\log{{\\color{red}p(z)}}\\right] = \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}}\\right]\n$$\n\nand we say that we are using the Maximum Likelihood Estimation (MLE) for the unknown $z$:\n\n$$\n\\hat{\\mathbf{z}}_{\\text{mle}} = \\underset{z}{\\mathrm{argmin}}\\left[-\\log{{\\color{blue}p(y=\\mathcal{D}_y|z)}}\\right] = \\underset{z}{\\mathrm{argmin}}\\left[-\\sum_{i=1}^{N}\\log{ p(y=y_i|z)}\\right]\n$$\n\nwhere, again, the argument of this expression is called the **negative log likelihood** $\\mathrm{NLL}(z)$.\n\n## Summary of Machine Learning without going fully Bayesian\n\n1. Approximate posterior by a **Dirac delta** \"distribution\" $\\delta(z-\\hat{z})$ where $\\hat{z}$ is a chosen **Point estimate**:\n * MLE: $\\hat{\\mathbf{z}}_{\\text{mle}} = \\underset{z}{\\mathrm{argmin}}\\left[-\\sum_{i=1}^{N}\\log{ p(y=y_i|z)}\\right]$\n * MAP: $\\hat{\\mathbf{z}}_{\\text{map}} = \\underset{z}{\\mathrm{argmin}}\\left[-\\sum_{i=1}^{N}\\log{ p(y=y_i|z)}- \\log{p(z)}\\right] $\n * etc.\n\n\n2. Compute the PPD using the Point estimate $\\hat{z}$ and without calculating any integrals:\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = \\int p(y|z) \\delta(z-\\hat{z}) dz = p(y|z=\\hat{z})\n$$\n\n\n# HOMEWORK\n\n1. Using the MLE point estimate, predict the PPD for the car stopping distance problem (Lecture 6).\n\n\n2. Using the MAP estimate, predict the PPD for the car stopping distance problem considering the Gaussian prior of Lecture 7.\n\n\n3. Create a plot of the two PPD's and compare them with the PPD's obtained in Lecture 6 and Lecture 7.\n * Note: create these plots of the PPD's such that the abscissa (horizontal) axis is the $y$ rv and the ordinate (vertical axis) is the probability density.\n\n\"Teaser\": PPD obtained with the MLE **versus** PPD obtained in Lecture 6 (Uniform prior)\n\n\n```python\n# This cell is hidden during presentation. It's just to define a function to plot the governing model of\n# the car stopping distance problem. Defining a function that creates a plot allows to repeatedly run\n# this function on cells used in this notebook.\ndef car_fig_2rvs(ax):\n x = np.linspace(3, 83, 1000)\n mu_z1 = 1.5; sigma_z1 = 0.5; # parameters of the \"true\" p(z_1)\n mu_z2 = 0.1; sigma_z2 = 0.01; # parameters of the \"true\" p(z_2)\n mu_y = mu_z1*x + mu_z2*x**2 # From Homework of Lecture 4\n sigma_y = np.sqrt( (x*sigma_z1)**2 + (x**2*sigma_z2)**2 ) # From Homework of Lecture 4\n ax.set_xlabel(\"x (m/s)\", fontsize=20) # create x-axis label with font size 20\n ax.set_ylabel(\"y (m)\", fontsize=20) # create y-axis label with font size 20\n ax.set_title(\"Car stopping distance problem with two rv's\", fontsize=20); # create title with font size 20\n ax.plot(x, mu_y, 'k:', label=\"Governing model $\\mu_y$\")\n ax.fill_between(x, mu_y - 1.9600 * sigma_y,\n mu_y + 1.9600 * sigma_y,\n color='k', alpha=0.2,\n label='95% confidence interval ($\\mu_y \\pm 1.96\\sigma_y$)') # plot 95% credence interval\n ax.legend(fontsize=15)\n```\n\n\n```python\n# This cell is hidden during presentation\ndef MLE_versus_Bayesian_PPD_for_UniformPrior(N_samples):\n fig_car_PPD_UniformPrior, ax_car_PPD_UniformPrior = plt.subplots(1,2)\n x = 75\n mu_z2 = 0.1; sigma_z2 = 0.01\n # Observation of N_samples from the true data:\n empirical_y = samples_y_with_2rvs(N_samples, x) # Empirical measurements of N_samples at x=75\n # Empirical mean and std directly calculated from observations:\n empirical_mu_y = np.mean(empirical_y); empirical_sigma_y = np.std(empirical_y); \n #\n # --------------------------------------------------------------------------------------------\n # PPD calculated in Lecture 6 (Uniform prior)\n # Now define all the constants needed in the calculation of the PPD's obtained with each prior.\n w = x\n b = mu_z2*x**2\n sigma_yGIVENz = np.sqrt((x**2*sigma_z2)**2) # sigma_y|z (comes from the stochastic influence of the z_2 rv)\n sigma = np.sqrt(sigma_yGIVENz**2/(w**2*N_samples)) # std arising from the likelihood\n mu = empirical_mu_y/w - b/w # mean arising from the likelihood (product of Gaussian densities for the data)\n #\n # Now, calculate PPD when using a UNIFORM prior (Lecture 6):\n PPD_mu_y_UniformPrior = mu*w + b # same result if using: np.mean(empirical_y)\n PPD_sigma_y_UniformPrior = np.sqrt(w**2*sigma**2+sigma_yGIVENz**2) # same as: np.sqrt((x**2*sigma_z2)**2*(1/N_samples + 1))\n # --------------------------------------------------------------------------------------------\n \n \n # --------------------------------------------------------------------------------------------\n # MLE:\n z_mle = mu # in this case it also coincides with the mean of the likelihood.\n PPD_mu_y_mle = w*z_mle + b # same as empirical mean (also same as mean of Bayesian PPD for Uniform prior)\n PPD_sigma_y_mle = sigma_yGIVENz # NOT the same as Bayesian PPD for Uniform prior (only in the limit)\n # --------------------------------------------------------------------------------------------\n \n \n car_fig_2rvs(ax_car_PPD_UniformPrior[0]) # a function I created to include the background plot of the governing model\n for i in range(2): # create two plots (one is zooming in on the error bar)\n ax_car_PPD_UniformPrior[i].errorbar(x , empirical_mu_y,yerr=1.96*empirical_sigma_y, fmt='m*',\n markersize=30, elinewidth=9);\n ax_car_PPD_UniformPrior[i].errorbar(x , PPD_mu_y_UniformPrior,yerr=1.96*PPD_sigma_y_UniformPrior,\n color='#F39C12', fmt='*', markersize=15, elinewidth=6);\n ax_car_PPD_UniformPrior[i].errorbar(x , PPD_mu_y_mle,yerr=1.96*PPD_sigma_y_mle,\n fmt='w*', markersize=10, elinewidth=3);\n ax_car_PPD_UniformPrior[i].scatter(x*np.ones_like(empirical_y),empirical_y, s=150,facecolors='none',\n edgecolors='k', linewidths=2.0)\n print(\"Ground truth : mean[y] = 675 & std[y] = 67.6\")\n print(\"Empirical values (purple) : mean[y] = %.2f & std[y] = %.2f\" % (empirical_mu_y,empirical_sigma_y) )\n print(\"PPD with Uniform Prior (orange): mean[y] = %.2f & std[y] = %.2f\" % (PPD_mu_y_UniformPrior, PPD_sigma_y_UniformPrior))\n print(\"PPD from MLE (white) : mean[y] = %.2f & std[y] = %.2f\" % (PPD_mu_y_mle,PPD_sigma_y_mle))\n fig_car_PPD_UniformPrior.set_size_inches(15, 6) # scale figure to be wider (since there are 2 subplots)\n```\n\n\n```python\nMLE_versus_Bayesian_PPD_for_UniformPrior(N_samples=2)\n```\n\n\"Teaser\": PPD obtained with the MLE **versus** PPD obtained in Lecture 7 (Gaussian prior)\n\n\n```python\n# This cell is hidden during presentation\ndef MAP_versus_Bayesian_PPD_for_GaussianPrior(N_samples):\n fig_car_PPD_GaussianPrior, ax_car_PPD_GaussianPrior = plt.subplots(1,2)\n x = 75\n mu_z2 = 0.1; sigma_z2 = 0.01\n # Observation of N_samples from the true data:\n empirical_y = samples_y_with_2rvs(N_samples, x) # Empirical measurements of N_samples at x=75\n # Empirical mean and std directly calculated from observations:\n empirical_mu_y = np.mean(empirical_y); empirical_sigma_y = np.std(empirical_y); \n #\n # --------------------------------------------------------------------------------------------\n # PPD calculated in Lecture 7 (Gaussian prior)\n w = x\n b = mu_z2*x**2\n sigma_yGIVENz = np.sqrt((x**2*sigma_z2)**2) # sigma_y|z (comes from the stochastic influence of the z_2 rv)\n sigma = np.sqrt(sigma_yGIVENz**2/(w**2*N_samples)) # std arising from the likelihood\n mu = empirical_mu_y/w - b/w # mean arising from the likelihood (product of Gaussian densities for the data)\n #\n mu_prior_z = 3; sigma_prior_z = 2 # parameters of the Gaussian prior distribution \n sigma_posterior_z = np.sqrt( (sigma_prior_z**2*sigma**2)/(sigma_prior_z**2+sigma**2) )# std of posterior\n mu_posterior_z = sigma_posterior_z**2*( mu/(sigma**2) + mu_prior_z/(sigma_prior_z**2) ) # mean of posterior\n PPD_mu_y_GaussianPrior = mu_posterior_z*w + b\n PPD_sigma_y_GaussianPrior = np.sqrt(w**2*sigma_posterior_z**2+sigma_yGIVENz**2)\n # --------------------------------------------------------------------------------------------\n \n \n # --------------------------------------------------------------------------------------------\n # MAP:\n z_map = mu_posterior_z # in this case it also coincides with the mean of the posterior\n PPD_mu_y_map = w*z_map + b # same as empirical mean (also same as mean of Bayesian PPD for Uniform prior)\n PPD_sigma_y_map = sigma_yGIVENz # NOT the same as Bayesian PPD for Uniform prior (only in the limit)\n # --------------------------------------------------------------------------------------------\n\n #\n car_fig_2rvs(ax_car_PPD_GaussianPrior[0]) # a function I created to include the background plot of the governing model\n for i in range(2): # create two plots (one is zooming in on the error bar)\n ax_car_PPD_GaussianPrior[i].errorbar(x , empirical_mu_y,yerr=1.96*empirical_sigma_y, fmt='m*',\n markersize=30, elinewidth=9);\n ax_car_PPD_GaussianPrior[i].errorbar(x , PPD_mu_y_GaussianPrior,yerr=1.96*PPD_sigma_y_GaussianPrior,\n fmt='b*', markersize=15, elinewidth=6);\n ax_car_PPD_GaussianPrior[i].errorbar(x , PPD_mu_y_map,yerr=1.96*PPD_sigma_y_map,\n fmt='c*', markersize=10, elinewidth=3);\n ax_car_PPD_GaussianPrior[i].scatter(x*np.ones_like(empirical_y),empirical_y, s=150,facecolors='none',\n edgecolors='k', linewidths=2.0)\n print(\"Ground truth : mean[y] = 675 & std[y] = 67.6\")\n print(\"Empirical values (purple) : mean[y] = %.2f & std[y] = %.2f\" % (empirical_mu_y,empirical_sigma_y) )\n print(\"PPD with Gaussian Prior (blue): mean[y] = %.2f & std[y] = %.2f\" % (PPD_mu_y_GaussianPrior,PPD_sigma_y_GaussianPrior))\n print(\"PPD from MAP (cyan) : mean[y] = %.2f & std[y] = %.2f\" % (PPD_mu_y_map, PPD_sigma_y_map))\n fig_car_PPD_GaussianPrior.set_size_inches(15, 6) # scale figure to be wider (since there are 2 subplots)\n```\n\n\n```python\nMAP_versus_Bayesian_PPD_for_GaussianPrior(N_samples=3)\n```\n\n## Final reflection: what strategy should we choose?\n\nApproximating the PPD using a Point estimate is usually much simpler and faster than marginalizing unknown rv's such as $z$ (integrals!).\n\nThis is true analytically as well as numerically.\n\nThis explains why many ML practitioners choose Point estimates like MLE or MAP.\n\nBut in general the predictions of the PPD have different robustness:\n\n* PPD calculated from Posterior distribution > PPD from Point estimates\n - We can also say that within the Point estimates: Posterior mean estimate > MAP > MLE\n\nWe will see evidence in favor of this in the remaining of the course.\n\n## Final reflection: Bayesian versus non-Bayesian perspective on ML\n\nWe can do one last simplification (but it can **mislead** us into believing that ML is not probabilistic!)\n\nWhen the PPD is approximated by the observation distribution for a Point estimate $\\hat{z}$,\n\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = p(y|z=\\hat{z})\n$$\n\nwe can decide to focus on only making a prediction for the **mean** of the PPD and even forget that it is a distribution (we forget uncertainties!).\n\nThis is very common in ML literature! But, I think it's advantageous not to think about it that way...\n\n\n## Solution to the Homework of this Lecture\n\n1. The PPD using the MLE for problem in Lecture 6 is:\n\n$$\np(y\\mid y=\\mathcal{D}_y) = p(y \\mid z=\\hat{z}_{\\text{mle}}) = \\mathcal{N}\\left(y| \\mu_{y|z}=w \\hat{z}_{\\text{mle}}+b,\\, \\sigma_{y|z}^2 \\right)\n$$\n\nwhere the MLE of $z$ is obtained as follows:\n\n$$\n\\begin{align}\n\\hat{\\mathbf{z}}_{\\text{mle}} &= \\underset{z}{\\mathrm{argmin}}\\left[-\\sum_{i=1}^{N}\\log{ p(y=y_i|z)}\\right] \\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[-\\sum_{i=1}^{N}\\log{\\left( \\frac{1}{|w|}\\frac{1}{\\sqrt{2\\pi \\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}} \\exp\\left\\{ -\\frac{1}{2\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\left[z-\\left(\\frac{y_i-b}{w}\\right)\\right]^2\\right\\}\\right)}\\right]\\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[-\\sum_{i=1}^{N}\\left(\\log{\\left( \\frac{1}{|w|}\\frac{1}{\\sqrt{2\\pi \\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}}\\right)} -\\frac{1}{2\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\left[z-\\left(\\frac{y_i-b}{w}\\right)\\right]^2\\right)\\right] \\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[\\frac{1}{2\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\sum_{i=1}^{N} \\left[z-\\left(\\frac{y_i-b}{w}\\right)\\right]^2\\right] \\\\\n\\end{align}\n$$\n\nTo find the minimum location we need to take the derivative wrt $z$ and equal it to zero:\n\n$$\n\\frac{1}{\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\sum_{i=1}^{N} \\left[z-\\left(\\frac{y_i-b}{w}\\right)\\right] = 0\n$$\n\n$$\nN z - \\sum_{i=1}^{N} \\frac{y_i-b}{w}=0\n$$\n\n$$\nz = \\frac{1}{N} \\sum_{i=1}^{N} \\frac{y_i-b}{w}\n$$\n\nSo, we conclude that:\n\n$$\n\\hat{z}_{\\text{mle}} = \\frac{1}{N} \\sum_{i=1}^{N} \\frac{y_i-b}{w} = \\mu\n$$\n\n**This result should be very familiar to you**!\n\nHere's why: Remember that in Lecture 5 (and 6) we already calculated the likelihood to be ${\\color{blue}p(y=\\mathcal{D}_y | z)} = \\frac{1}{|w|^N} \\cdot C \\cdot \\frac{1}{\\sqrt{2\\pi \\sigma^2}} \\exp\\left[ -\\frac{1}{2\\sigma^2}(z-\\mu)^2\\right]$, so it is obvious that this is maximized at the mean value of $z=\\mu$ because the mode of a Gaussian is the same as the mean. This is why in the code above, I already knew the result without doing any calculation 😉\n\n2. The PPD using the MAP for the Gaussian prior of Lecture 7 is:\n\n$$\np(y\\mid y=\\mathcal{D}_y) = p(y \\mid z=\\hat{z}_{\\text{map}}) = \\mathcal{N}\\left(y| \\mu_{y|z}=w \\hat{z}_{\\text{map}}+b,\\, \\sigma_{y|z}^2 \\right)\n$$\n\nwhere the MAP of $z$ is obtained as follows:\n\n$$\n\\begin{align}\n\\hat{\\mathbf{z}}_{\\text{map}} &= \\underset{z}{\\mathrm{argmin}}\\left[-\\sum_{i=1}^{N}\\log{ p(y=y_i|z)}-\\log{p(z)}\\right] \\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[\\frac{1}{2\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\sum_{i=1}^{N} \\left[z-\\left(\\frac{y_i-b}{w}\\right)\\right]^2 - \\log{\\frac{1}{\\sqrt{2\\pi \\overset{\\scriptscriptstyle <}{\\sigma}_z^2}}\\exp\\left\\{-\\frac{1}{2\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\left(z-\\overset{\\scriptscriptstyle <}{\\mu}_z\\right)^2\\right\\}}\\right] \\\\\n&= \\underset{z}{\\mathrm{argmin}}\\left[\\frac{1}{2\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\sum_{i=1}^{N} \\left[z-\\left(\\frac{y_i-b}{w}\\right)\\right]^2+\\frac{1}{2\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\left(z-\\overset{\\scriptscriptstyle <}{\\mu}_z\\right)^2\\right] \\\\\n\\end{align}\n$$\n\nSimilarly, to find the minimum location we need to take the derivative wrt $z$ and equal it to zero:\n\n$$\n\\frac{1}{\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\sum_{i=1}^{N} \\left[z-\\left(\\frac{y_i-b}{w}\\right)\\right] + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\left(z-\\overset{\\scriptscriptstyle <}{\\mu}_z\\right)= 0\n$$\n\n$$\n\\frac{N w^2}{\\sigma_{y|z}^2} z - \\frac{w^2}{\\sigma_{y|z}^2} \\sum_{i=1}^{N} \\frac{y_i-b}{w} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2} z - \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\overset{\\scriptscriptstyle <}{\\mu}_z =0\n$$\n\nNoting that $\\sum_{i=1}^{N} \\frac{y_i-b}{w} = N\\mu$ and that $\\frac{N w^2}{\\sigma_{y|z}^2} = \\frac{1}{\\sigma^2}$,\n\n$$\n\\frac{1}{\\sigma^2} z - \\frac{1}{\\sigma^2}\\mu + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2} z - \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\overset{\\scriptscriptstyle <}{\\mu}_z =0\n$$\n\n$$\nz = \\frac{1}{\\frac{1}{\\sigma^2}+\\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2}+\\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right)\n$$\n\nSo, we conclude that:\n\n$$\n\\hat{z}_{\\text{map}} = \\frac{1}{\\frac{1}{\\sigma^2}+\\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2}+\\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right)\n$$\n\nOnce again, **this result should be very familiar to you**!\n\nHere's why: Remember that in Lecture 7 we already calculated the posterior to be ${\\color{green}p(z|y=\\mathcal{D}_y)} = \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle >}{\\mu}_z, \\overset{\\scriptscriptstyle >}{\\sigma}_z^2\\right) = \\mathcal{N}\\left(z\\left|\\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2} + \\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right), \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}}\\right.\\right)$, so it is obvious that this is maximized at the mean value of $z=\\overset{\\scriptscriptstyle >}{\\mu}_z$ because the mode of a Gaussian is the same as the mean. Again, this is why in the code above, I already knew the result without doing any calculation 😉\n\n3. Finally, we can plot the PPD's for question 1 and 2 and compare them with what we obtained in Lecture 7.\n\nWe already have computed the parameters in the last 2 plots of this lecture. This question is just asking to show these distributions in a different way.\n\n\n```python\nfig_HW, ax_HW = plt.subplots()\n\nN_samples=3\nx = 75\nmu_z2 = 0.1; sigma_z2 = 0.01\n#\n# Observation of N_samples from the true data:\nempirical_y = samples_y_with_2rvs(N_samples, x) # Empirical measurements of N_samples at x=75\n# Empirical mean and std directly calculated from observations:\nempirical_mu_y = np.mean(empirical_y); empirical_sigma_y = np.std(empirical_y); \n#\n# --------------------------------------------------------------------------------------------\n# PPD calculated in Lecture 6 (Uniform prior)\n# Now define all the constants needed in the calculation of the PPD's obtained with each prior.\nw = x\nb = mu_z2*x**2\nsigma_yGIVENz = np.sqrt((x**2*sigma_z2)**2) # sigma_y|z (comes from the stochastic influence of the z_2 rv)\nsigma = np.sqrt(sigma_yGIVENz**2/(w**2*N_samples)) # std arising from the likelihood\nmu = empirical_mu_y/w - b/w # mean arising from the likelihood (product of Gaussian densities for the data)\n#\n# Now, calculate PPD when using a UNIFORM prior (Lecture 6):\nPPD_mu_y_UniformPrior = mu*w + b # same result if using: np.mean(empirical_y)\nPPD_sigma_y_UniformPrior = np.sqrt(w**2*sigma**2+sigma_yGIVENz**2) # same as: np.sqrt((x**2*sigma_z2)**2*(1/N_samples + 1))\n# --------------------------------------------------------------------------------------------\n\n\n# --------------------------------------------------------------------------------------------\n# MLE:\nz_mle = mu # in this case it also coincides with the mean of the likelihood.\nPPD_mu_y_mle = w*z_mle + b # same as empirical mean (also same as mean of Bayesian PPD for Uniform prior)\nPPD_sigma_y_mle = sigma_yGIVENz # NOT the same as Bayesian PPD for Uniform prior (only in the limit)\n# --------------------------------------------------------------------------------------------\n\n# --------------------------------------------------------------------------------------------\n# PPD calculated in Lecture 7 (Gaussian prior)\nw = x\nb = mu_z2*x**2\nsigma_yGIVENz = np.sqrt((x**2*sigma_z2)**2) # sigma_y|z (comes from the stochastic influence of the z_2 rv)\nsigma = np.sqrt(sigma_yGIVENz**2/(w**2*N_samples)) # std arising from the likelihood\nmu = empirical_mu_y/w - b/w # mean arising from the likelihood (product of Gaussian densities for the data)\n#\nmu_prior_z = 3; sigma_prior_z = 2 # parameters of the Gaussian prior distribution \nsigma_posterior_z = np.sqrt( (sigma_prior_z**2*sigma**2)/(sigma_prior_z**2+sigma**2) )# std of posterior\nmu_posterior_z = sigma_posterior_z**2*( mu/(sigma**2) + mu_prior_z/(sigma_prior_z**2) ) # mean of posterior\nPPD_mu_y_GaussianPrior = mu_posterior_z*w + b\nPPD_sigma_y_GaussianPrior = np.sqrt(w**2*sigma_posterior_z**2+sigma_yGIVENz**2)\n# --------------------------------------------------------------------------------------------\n\n\n# --------------------------------------------------------------------------------------------\n# MAP:\nz_map = mu_posterior_z # in this case it also coincides with the mean of the posterior\nPPD_mu_y_map = w*z_map + b # same as empirical mean (also same as mean of Bayesian PPD for Uniform prior)\nPPD_sigma_y_map = sigma_yGIVENz # NOT the same as Bayesian PPD for Uniform prior (only in the limit)\n# --------------------------------------------------------------------------------------------\n\n\n# --------------------------------------------------------------------------------------------\n# I will also include the real distribution p(y)\n# Note: we found this in Homework of Lecture 4 (solution shown in Lecture 5)\nmu_z1 = 1.5\nsigma_z1 = 0.5\nreal_mu_y = x*mu_z1 + mu_z2*x**2\nreal_sigma_y = np.sqrt((x*sigma_z1)**2 + (x**2*sigma_z2)**2)\n# --------------------------------------------------------------------------------------------\n\n# We can establish the limits of the plot based on the real distribution:\nymin = real_mu_y - 3*real_sigma_y\nymax = real_mu_y + 3*real_sigma_y\nyrange = np.linspace(ymin, ymax, 200) # to plot\n\nax_HW.plot(yrange, norm.pdf(yrange, PPD_mu_y_UniformPrior, PPD_sigma_y_UniformPrior),\n '--', linewidth = 3, color='#F39C12', label='Bayesian PPD for Uniform prior')\nax_HW.plot(yrange, norm.pdf(yrange, PPD_mu_y_mle, PPD_sigma_y_mle),\n '-', linewidth = 3, color='#F39C12', label='PPD using MLE')\nax_HW.plot(yrange, norm.pdf(yrange, PPD_mu_y_GaussianPrior, PPD_sigma_y_GaussianPrior),\n 'b--', linewidth = 3, label='Bayesian PPD for Gaussian prior')\nax_HW.plot(yrange, norm.pdf(yrange, PPD_mu_y_map, PPD_sigma_y_map),\n 'b-', linewidth = 3, label='PPD using MAP')\nax_HW.plot(yrange, norm.pdf(yrange, real_mu_y, real_sigma_y),\n 'k-', linewidth = 3, label='Real distribution $p(y)$')\nax_HW.set_xlabel(\"y\", fontsize=20)\nax_HW.set_ylabel(\"probability density\", fontsize=20)\nax_HW.legend(fontsize=15, loc='upper left');\nfig_HW.set_size_inches(15, 6)\n```\n\n### See you next class\n\nHave fun **but do your HOMEWORK**!\n", "meta": {"hexsha": "bbb6f59f2fe1788ebd78945ebd4aa05e6cb80df6", "size": 869780, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures/Lecture8/3dasm_Lecture8.ipynb", "max_stars_repo_name": "shushu-qin/3dasm_course", "max_stars_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-07T18:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T21:45:27.000Z", "max_issues_repo_path": "Lectures/Lecture8/3dasm_Lecture8.ipynb", "max_issues_repo_name": "shushu-qin/3dasm_course", "max_issues_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "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": "Lectures/Lecture8/3dasm_Lecture8.ipynb", "max_forks_repo_name": "shushu-qin/3dasm_course", "max_forks_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2022-02-07T18:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T19:30:17.000Z", "avg_line_length": 490.5696559504, "max_line_length": 241376, "alphanum_fraction": 0.9320425855, "converted": true, "num_tokens": 14418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000709974589314, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.0846834045648824}} {"text": "```python\n%matplotlib inline\n\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = (12, 9)\nplt.rcParams[\"font.size\"] = 18\n```\n\n## Binary Nuclear Reactions\n\n### Learning Objectives:\n\n- Connect concepts in particle collisions and decay to binary reactions\n- Categorize nuclear reactions using standard nomenclature\n- Apply conservation of nucleons to binary nuclear reactions\n- Formulate Q value equations for binary nuclear reactions\n- Apply conservation of energy and linear momentum to scattering\n- Apply coulombic threshold\n- Apply kinematic threshold\n- Determine when coulombic and kinematic thresholds apply or do not\n\n## Recall from Weeks 3 & 4\n\nTo acheive these objectives, we need to recall 3 major themes from weeks three and four. \n\n### 1: Compare Exothermic and Endothermic reactions\n\n- In **_exothermic_** or **_exoergic_** reactions, energy is **emitted** ($Q>0$)\n- In **_endothermic_** or **_endoergic_** reactions, energy is **absorbed** ($Q<0$)\n\n\n\n\n
(credit: BBC)
\n\n### 2: Relate energy and mass $E=mc^2$\n\nWhen the masses of reactions change, this is tied to a change in energy from whence we learn the Q value.\nThis change in mass is equivalent to a change in energy because **$E=mc^2$**\n\n\\begin{align}\nA + B + \\cdots &\\rightarrow C + D + \\cdots\\\\\n\\mbox{(reactants)} &\\rightarrow \\mbox{(products)}\\\\\n\\implies \\Delta M &= (\\mbox{reactants}) - (\\mbox{products})\\\\\n &= (M_A + M_B + \\cdots) - (M_C + M_D + \\cdots)\\\\\n\\implies \\Delta E &= \\left[(M_A + M_B + \\cdots) - (M_C + M_D + \\cdots)\\right]c^2\\\\\n\\end{align}\n\n\n### 3: Apply conservation of energy and momentum to scattering collisions\n\nConservation of total energy and linear momentum can inform Compton scattering reactions. X-rays scattered from electrons had a change in wavelength $\\Delta\\lambda = \\lambda' - \\lambda$ proportional to $(1-\\cos{\\theta_s})$\n\n\n\nWe used the law of cosines:\n\n\\begin{align}\np_e^2 &= p_\\lambda^2 + p_{\\lambda'}^2 - 2p_\\lambda p_{\\lambda'}\\cos{\\theta_s}\n\\end{align}\n\n\nAnd we also used conservation of energy:\n\\begin{align}\np_\\lambda c+m_ec^2 &= p_{\\lambda'}c + mc^2\\\\\n\\mbox{where }&\\\\\nm_e&=\\mbox{rest mass of the electron}\\\\\nm &= \\mbox{relativistic electron mass after scattering}\n\\end{align}\n\nCombining these with our understanding of photon energy ($E=h\\nu=pc$) gives:\n\n\\begin{align}\n\\lambda' - \\lambda &= \\frac{h}{m_ec}(1-\\cos{\\theta_s})\\\\\n\\implies \\frac{1}{E'} - \\frac{1}{E} &= \\frac{1}{m_ec^2}(1-\\cos{\\theta_s})\\\\\n\\implies E' &= \\left[\\frac{1}{E} + \\frac{1}{m_ec^2}(1-\\cos{\\theta_s})\\right]^{-1}\\\\\n\\end{align}\n\n## More Types of Reactions\n\nPreviously we were interested in fundamental particles striking one another (e.g. the electron and proton in Compton scattering) or nuclei emitting such particles (e.g. $\\beta^\\pm$ decay).\n\n**Today:** We are interested in myriad additional reactants and/or products. In particular, we're interested in:\n\n- neutron absorption and production reactions \n- _binary, two-product nuclear reactions_ in which two products emerge with new energies after the collision.\n\n\n```python\n# The below IFrame displays Page 162 of your textbook:\n# Shultis, J. K. (2016). Fundamentals of Nuclear Science and Engineering Third Edition, \n# 3rd Edition. [Vitalsource]. Retrieved from https://bookshelf.vitalsource.com/#/books/9781498769303/\n\nfrom IPython.display import IFrame\nIFrame(\"https://bookshelf.vitalsource.com/books/9781498769303/pageid/162\", width=1000, height=500)\n\n```\n\n\n\n\n\n\n\n\n\n\n## Reaction Nomenclature\n\n**Transfer Reactions:** Nucleons (1 or 2) are transferred between the projectile and product.\n\n**Scattering reactions:** The projectile and product emerge from a collision with the same identities as when they started, exchanging only kinetic energy. \n\n**Knockout reactions:** The projectile directly interacts with the target nucleus and is re-emitted **along with** nucleons from the target nucleus.\n\n**capture reactions:** The projectile is absorbed, typically exciting the nucleus. The excited nucleus may emit that energy decaying via photon emission.\n\n**nuclear photoeffect:** A photon projectile liberates a nucleon from the target nucleus.\n\n### Think Pair Share : categorize these reactions\n\nOne example of each of the above appears below. Use the definitions to categorize them.\n\n- $(n, n)$\n- $(n, \\gamma)$\n- $(n, 2n)$\n- $(\\gamma, n)$\n- $(\\alpha, n)$\n\n\n## Binary, two-product nuclear reactions\n\n**Two initial nuclei collide to form two product nuclei.**\n\n\\begin{align}\n^{A_1}_{Z_1}X_1 + ^{A_2}_{Z_2}X_2 \\longrightarrow ^{A_3}_{Z_3}X_3 + ^{A_4}_{Z_4}X_4\n\\end{align}\n\n#### Applying Conservation of Neutrons and Protons\n\nThe total number of nucleons is always conserved.\nIf the `______________` force is not involved, we can also apply this conservation separately.\n\n\nIn most binary, two-product nuclear reactions, this is the case, so the number of protons and neutrons are conserved. Thus:\n\n\\begin{align}\nZ_1 + Z_2 = Z_3 + Z_4\\\\\nA_1 + A_2 = A_3 + A_4\n\\end{align}\n\nApply this to the following:\n\n\\begin{align}\n^{3}_{1}H + ^{16}_{8}O \\longrightarrow \\left(X\\right)^* \\longrightarrow ^{16}_{7}N + ^{A_4}_{Z_4}X_4\n\\end{align}\n\n### Think Pair Share:\n\nWhat are :\n\n- $A_4$ \n- $Z_4$\n- $X_4$?\n\n- Bonus: What is $\\left(X\\right)^*$?\n\n\n### An Aside on Nuclear Energy in the Media\n\n\n
Prof. Huff's first job was at the LANSCE ICE HOUSE, 2003 & 2004
\n\n\n
This image linked above is a screenshot from Spiderman 2, in 2004.
\nIt is owned and copyright 2004 by Marvel comics.
\nIt shows Dr. Octopus and the fuel for his fusion reactor.
\n\n#### Applying conservation of mass and energy.\n\nThe Q-value calculation is the same as it has been before. \nThe Q value represents the `________` in kinetic energy and, equivalently, a `________` in the rest masses.\n\n\\begin{align}\nQ &= E_y + E_Y − E_x − E_X \\\\\n &= (m_x + m_X − m_y − m_Y )c^2\\\\\n &= \\left(m\\left(^{A_1}_{Z_1}X_1\\right) + m\\left(^{A_2}_{Z_2}X_2\\right) - m\\left(^{A_3}_{Z_3}X_3\\right) - m\\left(^{A_4}_{Z_4}X_4\\right)\\right)c^2\\\\\n\\end{align}\n\nIf proton numbers are conserved (true for everything but electron capture or reactions involving the weak force.), we can use the approximation that $m(X) = M(X)$.\n\n\\begin{align}\nQ &= E_y + E_Y − E_x − E_X \\\\\n &= (m_x + m_X − m_y − m_Y )c^2\\\\\n &= (M_x + M_X − M_y − M_Y )c^2\\\\\n &= \\left(M\\left(^{A_1}_{Z_1}X_1\\right) + M\\left(^{A_2}_{Z_2}X_2\\right) - M\\left(^{A_3}_{Z_3}X_3\\right) - M\\left(^{A_4}_{Z_4}X_4\\right)\\right)c^2\\\\\n\\end{align}\n\n\n```python\ndef q(m_reactants, m_products):\n \"\"\"Returns Q\n \n Parameters\n ----------\n m_reactants: list (of doubles)\n the masses of the reactant atoms [amu]\n m_products : list (of doubles)\n the masses of the product atoms [amu]\n \"\"\"\n amu_to_mev = 931.5 # MeV/amu conversion\n m_difference = sum(m_reactants) - sum(m_products)\n return m_difference*amu_to_mev\n\n\n# Look up the masses:\nh_3_mass = 3.0160492675\no_16_mass = 15.9949146221\nhe_3_mass = 3.0160293097\nn_16_mass = 16.0061014\n\nm_react = [h_3_mass, o_16_mass]\nm_prods = [he_3_mass, n_16_mass]\n\nprint(\"Q: \", q(m_react, m_prods))\n```\n\n Q: -10.401892923148063\n\n\n#### Applying conservation of linear momentum\n\nLet's get back to collision kinematics. \n\nFirst, we'll assume the target nucleus ($X_2$) is initially at rest.\n\n##### Question: How do we handle the case when the incident and target nuclei both have initial velocity?\n\n##### Harder Question: How do we handle the case when the incident and target nuclei are accelerating with respect to each other?\n\n\n\nIf $E_i$ is the kinetic energy of the $i^{th}$ nucleus.\n\n\\begin{align}\nEx = Ey + EY − Q.\n\\end{align}\n\n\n \n\n\n```python\n# The below IFrame displays Page 162 of your textbook:\n# Shultis, J. K. (2016). Fundamentals of Nuclear Science and Engineering Third Edition, \n# 3rd Edition. [Vitalsource]. Retrieved from https://bookshelf.vitalsource.com/#/books/9781498769303/\n\nfrom IPython.display import IFrame\nIFrame(\"https://bookshelf.vitalsource.com/books/9781498769303/pageid/162\", width=1000, height=500)\n```\n\n\n\n\n\n\n\n\n\n\n# Kinematic Threshold\n\nRelying on a combination of kinetic energies $E_i$ and corresponding linear momenta:\n\n\\begin{align}\np_i = \\sqrt{2m_iE_i}\n\\end{align}\n\nWe can determine that some reactions aren't possible without a certain minimum quantity of kinetic energy. \n\nThe solution to $E_3$ can become nonphysical if :\n\n- $\\cos{\\theta_3} < 0$\n- $Q < 0$\n- $m_4 - m_1 < 0$\n\n## For Exoergic Reactions ($Q>0$)\n\nFor $Q>0$ and $m_{4} > m_{1}$, $E_{3} = (a + \\sqrt{a^2+b^2})^2$ is the only real, positive, meaningful solution. \n\nThe kinetic energy of $E_3$ is, at minimum, the energy arrived at when $p_1 = 0$. Thus:\n\n\\begin{align}\nE_3 \\longrightarrow& \\frac{m_4}{m_3 + m_4}Q\\\\\n&\\mbox{ when } Q>0, p_1=0\n\\end{align}\n\nSo, no exoergic reactions are restricted by kinetics, as $Q = E_3 + E_4$, for the minimum linear momentum case, which is real and positive. \n\n## For Endoergic Reactions ($Q<0$)\nSome $Q<0$ reactions aren't possible without a certain minimum quantity of kinetic energy. \n\n\nFor $Q<0$ and $m_{4} > m_{1}$, some values of $E_{1}$ are too small to carry forward a real, positive solution. That is, the incident projectile must supply a minimum amount of kinetic energy before the reaction can occur. Without this energy, the solution for $E_3$ results in physically meaningless values. This minimum energy can be found from eqn 6.11 in your book and is :\n\n\\begin{align}\nE_1^{th,k} = -\\frac{m_3 + m_4}{m_3 + m_4 - m_1}Q.\n\\end{align}\n\nOne can often simplify this (assuming $m_i >> Q/c^2$ and $m_3 + m_4 - m_1 \\simeq m_2$) :\n\n\n\\begin{align}\nE_1^{th,k} \\simeq - \\left( 1 + \\frac{m_1}{m_2} \\right)Q.\n\\end{align}\n\n\n```python\ndef kinematic_threshold(m_1, m_3, m_4, Q):\n \"\"\"Returns the kinematic threshold energy [MeV]\n \n Parameters\n ----------\n m_1: double\n mass of incident projectile\n m_3: double\n mass of first product \n m_3: double\n mass of second product \n Q : double\n Q-value for the reaction [MeV]\n \"\"\"\n num = -(m_3 + m_4)*Q\n denom = m_3 + m_4 - m_1\n return num/denom\n\ndef kinematic_threshold_simple(m_1, m_2, Q):\n \"\"\"Returns the coulombic threshold energy [MeV]\n \n Parameters\n ----------\n m_1: double\n mass of incident projectile\n m_2: double\n mass of target \n Q : double\n Q-value for the reaction [MeV]\n \"\"\"\n to_return = -(1 + m_1/m_2)*Q\n return to_return\n```\n\n# Coulombic Threshold\n\nCoulomb forces repel a projectile if it is:\n\n- a positively charged nucleus\n- a proton\n\nThe force between the projectile (particle 1) and the target nucleus (particle 2) is :\n\n\\begin{align}\n&F_C = \\frac{Z_1Z_2e^2}{4\\pi\\epsilon_0r^2}\\\\\n\\mbox{where}&&\\\\\n&\\epsilon_0 = \\mbox{the permittivity of free space.}\n\\end{align}\n\n### Think pair share:\nWhat are the other terms in the above equation:\n\n- $Z_1$ ?\n- $Z_2$ ?\n- $e$ ?\n- $r$ ?\n\n\nBy evaluating the work function for approach to the nucleus with a coulomb barrier, we can establish that the coulombic threshold energy (in MeV) is :\n\n\\begin{align}\nE_1^{th,C} \\simeq 1.20 \\frac{Z_1Z_2}{A_1^{1/3}+A_2^{1/3}}\n\\end{align}\n\n\n```python\ndef colombic_threshold(z_1, z_2, a_1, a_2):\n \"\"\"Returns the coulombic threshold energy [MeV]\n \n Parameters\n ----------\n z_1: int\n proton number of incident projectile\n z_2: int\n proton number of target \n a_1 : int or double\n mass number of the incident projectile [amu]\n a_2 : int or double\n mass number of the target [amu]\n \"\"\"\n num = 1.20*z_1*z_2\n denom = pow(a_1, 1/3) + pow(a_2, 1/3)\n return num/denom\n```\n\n### Think Pair Share \n\nWhich thresholds apply to the below situations:\n\n- A chargeless incident particle, reaction $Q>0$\n- A chargeless incident particle, reaction $Q<0$\n- A positively charged incident particle, reaction $Q>0$\n- A positively charged incident particle, reaction $Q<0$\n\n## Overall threshold\n\nFor the case where both thresholds apply, the minimum energy for the reaction to occur is the highest of the two thresholds. \n\n\\begin{align}\n\\min{\\left(E_1^{th}\\right)}\t= \\max{\\left(E^{th,C}_1,E_1^{th,k}\\right)}.\n\\end{align}\n\n## Example\n\nTake the (p, n) reaction from $^{9}Be\\longrightarrow^{9}B$. We will need to calculate:\n\n- The Q value\n- The kinematic threshold (if it applies)\n- The coulombic threshold (if it applies)\n- Determine which one is higher\n\n\n```python\n# Q value\n# Look up the masses:\nbe_9_mass = 9.0121821\nb_9_mass = 9.0133288\nn_mass = 1.0086649158849\np_mass = 1.007825032 # hydrogen nucleus!\n\nm_react = [be_9_mass, p_mass]\nm_prods = [b_9_mass, n_mass]\n\nq_example = q(m_react, m_prods)\nprint(\"Q: \", q_example)\n```\n\n Q: -1.8505028887843764\n\n\n\n```python\n# Kinematic Threshold\n# Which particles were which again?\nm_1 = p_mass\nm_2 = be_9_mass\nm_3 = n_mass\nm_4 = b_9_mass\n\n# Calculate using both regular and simpler methods\nE_k_th = kinematic_threshold(m_1, m_3, m_4, q_example)\nE_k_th_simple = kinematic_threshold_simple(m_1, m_2, q_example)\nprint(\"E_k_th: \", E_k_th)\nprint(\"E_k_th (simplified): \", E_k_th_simple)\n```\n\n E_k_th: 2.0573975230549033\n E_k_th (simplified): 2.0574431294953586\n\n\n\n```python\n# Coulombic Threshold\n# Need some charge info and mass numbers\nz_1 = 1 # proton\nz_2 = 4 # Be\na_1 = 1 # proton\na_2 = 9 # Be\n\nE_c_th = colombic_threshold(z_1, z_2, a_1, a_2)\n\nprint(\"E_c_th: \", E_c_th)\n```\n\n E_c_th: 1.558399146177754\n\n\n\n```python\n## Which one is higher?\n\nprint(\"Total threshold: \", max(E_c_th, E_k_th))\n```\n\n Total threshold: 2.0573975230549033\n\n\n# Applications: Neutron Detection\nNeutron's don't tend to directly ionize matter as they pass through. However, they can instigate nuclear reactions which produce charged products. These products, in turn, can be detected due to the ionization they create. The scheme for a Boron Trifluoride detector is below (hosted at https://www.orau.org/ptp/collection/proportional%20counters/bf3info.htm).\n\n\n\nThe wall effect results in the following spectrum (approximately):\n\n\nIn (n,p) reactions, for example, variation in emission angle of particle 3 can be used to determine the energy of the original incident neutron.\n\n# Applications: Neutron Production\nSpecific neutron energies can be targetted by collecting them at a certain angle away from the production collision.\n\n\n\n
The accelerator and spallation target at LANSCE and other spallation experiments rely on this fact.
Prof. Huff's first job was at the LANSCE ICE HOUSE, 2003 & 2004
\n\n\n## Two energies\n\nIn (p,n) reactions, for example, certain proton energies may result in more than one neutron energy observed at a single angle. How? \n\nRecall the equation (Shultis and Faw 6.11):\n\n\\begin{align}\n\\sqrt{E_y}=&\\sqrt{\\frac{m_xm_yE_x}{(m_y + m_Y)^2}}\\cos\\theta_y \\\\\n&\\pm \\sqrt{\\frac{m_xm_yE_x}{(m_y + m_Y)^2}\\cos^2\\theta_y + \\left[\\frac{m_Y-m_x}{(m_y + m_Y)}E_x + \\frac{m_YQ}{(m_y + m_Y)}\\right]}\n\\end{align}\n\nProf. Huff prefers this notation: \n\\begin{align}\n\\sqrt{E_3}=&\\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}}\\cos\\theta_3 \\\\\n&\\pm \\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}\\cos^2\\theta_3 + \\left[\\frac{m_4-m_1}{(m_3 + m_4)}E_1 + \\frac{m_4Q}{(m_3 + m_4)}\\right]}\n\\end{align}\n\n## Heavy Particle scattering from an electron\n\nMuch like the Compton reaction we saw between photons and electrons, we can see a similar reaction with heavy particles. Occaisionally, a heavy particle (e.g. a small nucleus, like an $\\alpha$ particle) strikes the orbital electrons in atoms of a medium.\n\nThus: particles 2 and 3 are the electron. So:\n\n\\begin{align} \nm_2 &= m_3 = m_e = \\mbox{(the electron mass)}\\\\\nE_3 &= E_e = \\mbox{(the recoil electron energy)}\\\\\nm_1 &= m_4 = \\mbox{(the mass of the heavy particle)}\\\\\nE_1 &= E_4 = \\mbox{(the kinetic energy of the incident heavy particle)}\n\\end{align}\n\nFor this scattering process, there is no change in the rest masses of the reactants, so Q = 0. \n\nWe can use the Shutlis and Faw 6.11 equation above to arrive at:\n\n\\begin{align}\n\\sqrt{E_e}=& \\frac{2}{m_4 + m_e}\\sqrt{m_4m_eE_4}\\cos{\\theta_e}\n\\end{align}\n\nWe can approximate that $m_4 >> m_e$ such that the electron recoil energy becomes:\n\n\\begin{align}\n\\implies E_e =& 4\\frac{m_e}{m_4}E_4\\cos^2{\\theta_e}\n\\end{align}\n\n## Think Pair Share\nWhat angle, $\\theta_e$, corresponds to the maximimum loss of kinetic energy by the incident heavy particle?\n\n\n\nAt $\\theta_e=0$, we find that:\n\n\\begin{align}\n(E_e)_{max} = 4\\frac{m_e}{m_4}E_4\n\\end{align}\n\n\n```python\nimport math \ndef recoil_energy(m_4, e_4, theta_e):\n m_e = 0.0005486 # amu\n num = 4*m_e*e_4*pow(math.cos(theta_e), 2)\n return num/m_4\n\n```\n\n\n```python\nth = [math.radians(-90),\n math.radians(-75),\n math.radians(-60),\n math.radians(-45),\n math.radians(-30),\n math.radians(-15),\n math.radians(0), \n math.radians(15),\n math.radians(30),\n math.radians(45),\n math.radians(60),\n math.radians(75),\n math.radians(90)]\n\nm_4 = 4.003 # alpha particle\n\nto_plot_4 = np.arange(0.,len(th))\nto_plot_10 = np.arange(0.,len(th))\n\nfor k, v in enumerate(th):\n to_plot_4[k] = (recoil_energy(m_4, 4, v))\n to_plot_10[k] = (recoil_energy(m_4, 10, v))\n\n\nplt.plot(th, to_plot_4, label=\"$4MeV$\")\nplt.plot(th, to_plot_10, label=\"$10MeV$\")\n\nplt.ylabel(\"Electron Recoil Energy ($MeV$)\")\nplt.xlabel(\"Angle (radians)\")\nplt.legend(loc=2)\n```\n\n\n```python\n\nth = 0\nm_4 = 4.003 # alpha particle\ne_4 = 4 # MeV\n\nprint(\"Max (4MeV alpha): \", recoil_energy(m_4, e_4, th))\n```\n\n Max (4MeV alpha): 0.002192755433424931\n\n\n## Neutron Scattering\n\n### Neutron interactions with matter.\n\n\\begin{align}\n^1_0n + {^a_z}X \\longrightarrow \n\\begin{cases}\n^1_0n + {^a_z}X & \\mbox{Elastic Scattering}\\\\\n^1_0n + \\left({^a_z}X\\right)^* & \\mbox{Inlastic Scattering}\n\\end{cases}\n\\end{align}\n\n\n\nUsing the ubiquitous equation 6.11 for a neutron scatter:\n\n\\begin{align}\n\\sqrt{E_3}=&\\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}}\\cos\\theta_3 \\\\\n&\\pm \\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}\\cos^2\\theta_3 + \\left[\\frac{m_4-m_1}{(m_3 + m_4)}E_1 + \\frac{m_4Q}{(m_3 + m_4)}\\right]}\\\\\n\\end{align}\n\nWe can define our particles as a neutron hitting a nucleus and changing in its energy.\n\n\\begin{align}\nm_1 = m_3 = m_n\\\\\nE_1 = E_n\\\\\nE_3 = E_n'\\\\\n\\end{align}\n\nSuch that:\n\n\\begin{align}\n\\sqrt{E_n'} =&\\sqrt{\\frac{m_nm_nE_n}{(m_n + m_4)^2}}\\cos\\theta_s \\\\\n&\\pm \\sqrt{\\frac{m_nm_nE_n}{(m_n + m_4)^2}\\cos^2\\theta_s + \\left[\\frac{m_4-m_n}{(m_n + m_4)}E_n + \\frac{m_4Q}{(m_n + m_4)}\\right]}\n\\end{align}\n\nWe can also agree that $m_2=m_4$, which is some nucleus with a mass that is approximately the same at the beginning and end of the scatter (approximate if the scattering is inelastic) . This gives, with some rearrangement:\n\n\\begin{align}\n\\sqrt{E_n'} &= \\frac{1}{m_4 + m_n}\\times\\\\ &\\left[\\sqrt{m_n^2E_n}\\cos{\\theta_s} \\pm \\sqrt{E(m_4^2 + m_n^2\\cos^2{\\theta_s} − m_n^2) + m_4 ( m_4 + m_n ) Q }\\right]\n\\end{align}\n\nAnd, for elastic scattering ($Q=0$):\n\n\\begin{align}\nE' = \\frac{1}{(A+1)^2}\\left[\\sqrt{E}\\cos{\\theta_s} + \\sqrt{E(A^2 - 1 + \\cos{\\theta_s}^2)}\\right]^2\n\\end{align}\n\n\n\n```python\ndef scattered_neutron_energy(A, E, th):\n \"\"\"Returns the energy of a scattered neutron [MeV]\n Parameters\n ----------\n A: int or double\n mass number of medium\n E: double\n kinetic energy of the incident neutron [MeV]\n th : double\n scattering angle, in degrees\n \"\"\"\n cos_th = math.cos(math.radians(th))\n term1 = 1/((A+1)**2)\n term2 = math.sqrt(E)*cos_th\n term3 = math.sqrt(E*(A**2 - 1 + cos_th**2))\n return term1*((term2 + term3)**2)\n```\n\n\n```python\nth = [math.radians(-90),\n math.radians(-75),\n math.radians(-60),\n math.radians(-45),\n math.radians(-30),\n math.radians(-15),\n math.radians(0), \n math.radians(15),\n math.radians(30),\n math.radians(45),\n math.radians(60),\n math.radians(75),\n math.radians(90)]\n\ne_initial = 2.0 # 2 MeV is special\na_light = 4.003 # alpha particle\na_heavy = 235.0 # uranium atom\n\nto_plot_light = np.arange(0.,len(th))\nto_plot_heavy = np.arange(0.,len(th))\n\nfor k, v in enumerate(th):\n to_plot_light[k] = (scattered_neutron_energy(a_light, e_initial, v))\n to_plot_heavy[k] = (scattered_neutron_energy(a_heavy, e_initial, v))\n\nplt.plot(th, to_plot_light, label=\"light\")\nplt.plot(th, to_plot_heavy, label=\"heavy\")\n\nplt.ylabel(\"Scattered Neutron Energy ($MeV$)\")\nplt.xlabel(\"Angle (radians)\")\nplt.legend(loc=2)\n```\n\n## Average Energy Loss\n\nFor elastic scattering (Q = 0), we see the minimum and maxium energies occur at the maximum and minimum angles. \n\n\\begin{align}\nE'_{max} &= E'(\\theta_{s,min})\\\\\n &= E'(\\theta_{s}=0)\\\\\n &= E\\\\\nE'_{min} &= E'(\\theta_{s,max})\\\\\n &= E'(\\theta_{s}=\\pi)\\\\\n &= \\frac{(A-1)^2}{(A+1)^2} E\\\\\n &\\equiv \\alpha E\\\\\n\\end{align}\n\nFor isotropic scattering, we can find the average loss:\n\n\n\\begin{align}\n(\\Delta E)_{av} &\\equiv E - E'_{av}\\\\\n&= E− 1(E+\\alpha E)\\\\\n& = 1(1- \\alpha)E\n\\end{align}\n\n\n```python\ndef alpha(a):\n \"\"\"Returns the average energy loss of a \n scattered neutron [MeV]\n Parameters\n ----------\n A: int or double\n mass number of medium\n \"\"\"\n num = (a-1)**2\n denom = (a+1)**2\n return num/denom\n \ndef average_energy_loss(A, E):\n \"\"\"Returns the average energy loss of a scattered neutron [MeV]\n Parameters\n ----------\n A: int or double\n mass number of medium\n E: double\n kinetic energy of the incident neutron [MeV]\n \"\"\"\n return 1*(1-alpha(A))*E\n```\n\n\n```python\ne_initial = np.arange(0, 2, 0.001)\n\nto_plot_light = np.arange(0.,len(e_initial))\nto_plot_heavy = np.arange(0.,len(e_initial))\n\nfor k, v in enumerate(e_initial):\n to_plot_light[k] = (average_energy_loss(a_light, v))\n to_plot_heavy[k] = (average_energy_loss(a_heavy, v))\n\nplt.plot(e_initial, to_plot_light, label=\"light atom\")\nplt.plot(e_initial, to_plot_heavy, label=\"heavy atom\")\n\nplt.ylabel(\"Average Neutron Energy Loss ($MeV$)\")\nplt.xlabel(\"Initial neutron energy ($MeV$)\")\nplt.legend(loc=2)\n```\n\n## Logarithmic Energy Loss\n\nIt turns out, on a logarithmic energy scale, a neutron loses the same amount of logarithmic energy per elastic scatter, regardless of its initial energy. So, this is a helpful term, particularly since neutron energies can range by many orders of magnitude. So, we often use 'logarithmic energy loss' when discussing this downscattering. This is also called \"lethargy\".\n\n\\begin{align}\n\\left(\\ln{(E)} - \\ln{(E')}\\right)_{av} & = \\overline{\\ln{\\left(\\frac{E}{E'}\\right)}} \\\\\n&= 1 + \\frac{\\alpha}{1-\\alpha}\\\\\n&= \\xi\\\\\n&= \\mbox{average logarithmic energy loss per elastic scatter}\\\\\n&= \\mbox{lethargy}\n\\end{align}\n\n\n```python\ndef lethargy(a): \n \"\"\"Returns the average logarithmic energy \n loss per elastic scatter\n Parameters\n ----------\n A: int or double\n mass number of medium\n \"\"\"\n return 1.0 + alpha(a)/(1-alpha(a)) \n```\n\n\n```python\na = np.arange(1, 240)\nplt.plot([lethargy(i) for i in a])\nplt.ylabel(\"$\\\\xi$\")\nplt.xlabel(\"A($amu$)\")\n\n```\n\n\n```python\n# The below IFrame displays Page 172 of your textbook:\n# Shultis, J. K. (2016). Fundamentals of Nuclear Science and Engineering Third Edition, \n# 3rd Edition. [Vitalsource]. Retrieved from https://bookshelf.vitalsource.com/#/books/9781498769303/\n\nfrom IPython.display import IFrame\nIFrame(\"https://bookshelf.vitalsource.com/books/9781498769303/pageid/172\", width=1000, height=500)\n```\n\n\n\n\n\n\n\n\n\n\n## Thermal Neutrons\n\n1. a fast neutron slows down\n2. may eventually come into thermal equilibrium with the medium \n3. thermal motion of atoms in medium are in Maxwellian distribution \n4. neutron may gain kinetic energy upon scattering from a rapidly moving nucleus \n5. neutron may lose energy upon scattering from a slowly moving nucleus.\n\n\n\n\nAt room temperature, 293 K:\n- the most probable kinetic energy of thermal neutrons is 0.025 eV\n- 0.025 eV corresponds to a neutron speed of about 2200 m/s.\n\n## Epithermal\n\nNeutrons that are faster than thermal neutrons, but aren't quite \"fast\" are called _epithermal_. ($0.2eV < E_{epi} < 1 MeV$)\n\n## Fast\n\n$> 1MeV$\n\n\n## Neutron Capture \n\n- Free neutrons will eventually be absorbed by a nucleus (or escape the domain of interest)\n- Neutron capture leaves the nucleus excited \n- Actually, very excited (Recall: what is a typical binding energy per nucleon?)\n- When it's released as a $\\gamma$ that energy can be very hazardous\n\nNeutron slowing down can help us to reduce very high energy $\\gamma$ emissions.\n\n## Fission Reactions\n\nSome nuclei spontaneously fission (e.g. $^{252}Cf$). However, this isn't common.\n\n\n\n\\begin{align}\n^1_0n + ^{235}_{92}U \\longrightarrow \\left( ^{236}_{92}U \\right)^*\n\\begin{cases}\n^{235}_{92}U + ^1_0n & \\mbox{Elastic Scattering}\\\\\n^{235}_{92}U + ^1_0n' + \\gamma & \\mbox{Inelastic Scattering}\\\\\n^{236}_{92}U + \\gamma & \\mbox{Radiative Capture}\\\\\n^{A_H}_{Z_H}X_H + ^{A_L}_{Z_L}X_L + ^1_0n + \\cdots & \\mbox{Fission}\n\\end{cases}\n\\end{align}\n\n### Recall: Cross sections\n\nThe likelihood of each of these scattering events is captured by cross sections. \n\n- $\\sigma_x = $ microscopic cross section $[cm^2]$\n- $\\Sigma_x = $ macroscopic cross section $[1/length]$\n- $\\Sigma_x = N\\sigma_x $\n- $N = $ number density of target atoms $[\\#/volume]$\n\n\n### Cross sections are in units of area. Explain this to your neighbor.\n\n### What energy neutron do we prefer for fission in $^{235}U$?\n\n\nNuclei that undergo neutron induced fission can be categorized into three types:\n\n- fissile: can fission with a slow neutron ($^{235}U$, $^{233}U$, $^{239}Pu$)\n- fissionable: require high energy (>1MeV) neutron ($^{238}U$, $^{240}Pu$)\n- fertile: can be converted into fissile or fissionable nuclide (breeding reactions)\n\nKey breeding reactions are :\n\n\\begin{align}\n{^{232}_{90}}Th + ^1_0n \\longrightarrow {^{233}_{90}}Th \\overset{\\beta^-}{\\longrightarrow} {^{233}_{91}}Pa \\overset{\\beta^-}{\\longrightarrow} {^{233}_{92}}U\\\\\n{^{238}_{92}}U + ^1_0n \\longrightarrow {^{239}_{92}}U \\overset{\\beta^-}{\\longrightarrow} {^{239}_{93}}Np \\overset{\\beta^-}{\\longrightarrow} {^{239}_{94}}Pu\\\\\n\\end{align}\n\n## The fission process\n\n\\begin{align}\n^1_0n + ^{235}_{92}U \\longrightarrow \\left( ^{236}_{92}U \\right)^* \\longrightarrow X_H + X_L + \\nu_p\\left(^1_0n\\right) + \\gamma_p\n\\end{align}\n\nConserving neutrons and protons:\n\n\\begin{align}\nA_L + A_H + \\nu_p &= 236\\\\\nN_L + N_H + \\nu_p &= 144\\\\\nZ_L + Z_H &= 92\\\\\n\\end{align}\n\n\n\n## Fission Product Decay\n\nThe fission fragments end up very neutron rich.\n\n### Think Pair Share\nRecall the chart of the nuclides. How will these fission products likely decay?\n\n\n\n\n\n\n### Fission Spectrum\n\n$\\chi(E)$ is an empirical probability density function describing the energies of prompt fission neutrons. \n\n\\begin{align}\n\\chi (E) &= 0.453e^{-1.036E}\\sinh\\left(\\sqrt{2.29E}\\right)\\\\\n\\end{align}\n\n\n```python\nimport numpy as np\nimport math\ndef chi(energy):\n return 0.453*np.exp(-1.036*energy)*np.sinh(np.sqrt(2.29*energy))\n\nenergies = np.arange(0.0,10.0, 0.1)\n\nplt.plot(energies, chi(energies))\nplt.title(r'Prompt Neutron Energy Distribution $\\chi(E)$')\nplt.xlabel(\"Prompt Neutron Energy [MeV]\")\nplt.ylabel(\"probability\")\n```\n\n\n```python\n#### Questions about this plot:\n\n- What is the most likely prompt neutron energy?\n- Can you write an equation for the average neutron energy?\n\n```\n\n Object `energy` not found.\n Object `energy` not found.\n\n\n\n```python\n- Can you write an equation for the average neutron energy\n```\n\n\n```python\nprint(max([chi(e) for e in energies]), chi(0.7))\n```\n\n 0.358102702287 0.358102702287\n\n\n#### Expectation Value\n\nRecall that the average energy will be the expectation value of the probability density function.\n\n\n\\begin{align}\n &= \\int E\\chi(E)dE\\\\\n&= E \\chi(E)\n\\end{align}\n\n\n```python\nplt.plot(energies, [chi(e)*e for e in energies])\n```\n\n## Prompt and Delayed neutrons\n\n- Most of the neutrons in fission are emitted within $10^{-14}s$. \n - **prompt** neutrons\n - $\\nu_p$\n- Some, ($<1\\%$) are produced by delayed decay of fission products. \n - **delayed** neutrons\n - $\\nu_d$\n \nWe define the delayed neutron fraction as :\n\n\\begin{align}\n\\beta \\equiv \\frac{\\nu_d}{\\nu_d + \\nu_p}\n\\end{align}\n\n## Energy from fission\n\n\n```python\n# The below IFrame displays Page 183 of your textbook:\n# Shultis, J. K. (2016). Fundamentals of Nuclear Science and Engineering Third Edition, \n# 3rd Edition. [Vitalsource]. Retrieved from https://bookshelf.vitalsource.com/#/books/9781498769303/\n\nfrom IPython.display import IFrame\nIFrame(\"https://bookshelf.vitalsource.com/books/9781498769303/pageid/183\", width=1000, height=500)\n\n```\n\n\n\n\n\n\n\n\n\n\n### Reaction Rates\n\n- The microscopic cross section is just the likelihood of the event per unit area. \n- The macroscopic cross section is just the likelihood of the event per unit area of a certain density of target isotopes.\n- The reaction rate is the macroscopic cross section times the flux of incident neutrons.\n\n\\begin{align}\nR_{i,j}(\\vec{r}) &= N_j(\\vec{r})\\int dE \\phi(\\vec{r},E)\\sigma_{i,j}(E)\\\\\nR_{i,j}(\\vec{r}) &= \\mbox{reactions of type i involving isotope j } [reactions/cm^3s]\\\\\nN_j(\\vec{r}) &= \\mbox{number of nuclei participating in the reactions } [\\#/cm^3]\\\\\nE &= \\mbox{energy} [MeV]\\\\\n\\phi(\\vec{r},E)&= \\mbox{flux of neutrons with energy E at position i } [\\#/cm^2s]\\\\\n\\sigma_{i,j}(E)&= \\mbox{cross section } [cm^2]\\\\\n\\end{align}\n\n\nThis can be written more simply as $R_x = \\Sigma_x I N$, where I is intensity of the neutron flux.\n\n\n### Source term\n\nThe source of neutrons in a reactor are the neutrons from fission. \n\n\\begin{align}\ns &=\\nu \\Sigma_f \\phi\n\\end{align}\n\nwhere\n\n\\begin{align}\ns &= \\mbox{neutrons available for next generation of fissions}\\\\\n\\nu &= \\mbox{the number born per fission}\\\\\n\\Sigma_f &= \\mbox{the number of fissions in the material}\\\\\n\\phi &= \\mbox{initial neutron flux}\n\\end{align}\n\nThis can also be written as:\n\n\\begin{align}\ns &= \\nu\\Sigma_f\\phi\\\\\n &= \\nu\\frac{\\Sigma_f}{\\Sigma_{a,fuel}}\\frac{\\Sigma_{a,fuel}}{\\Sigma_a}{\\Sigma_a} \\phi\\\\\n &= \\eta f {\\Sigma_a} \\phi\\\\\n\\eta &= \\frac{\\nu\\Sigma_f}{\\Sigma_{a,fuel}} \\\\\n &= \\mbox{number of neutrons produced per neutron absorbed by the fuel, \"neutron reproduction factor\"}\\\\\nf &= \\frac{\\Sigma_{a,fuel}}{\\Sigma_a} \\\\\n &= \\mbox{number of neutrons absorbed in the fuel per neutron absorbed anywhere, \"fuel utilization factor\"}\\\\\n\\end{align}\n\nThis absorption and flux term at the end seeks to capture the fact that some of the neutrons escape. However, if we assume an infinite reactor, we know that all the neutrons are eventually absorbed in either the fuel or the coolant, so we can normalize by $\\Sigma_a\\phi$ and therefore:\n\n\n\\begin{align}\nk_\\infty &= \\frac{\\eta f \\Sigma_a\\phi}{\\Sigma_a \\phi}\\\\\n&= \\eta f\n\\end{align}\n", "meta": {"hexsha": "be74233cd6fea5859ebfbd80fa18d92767ab7f56", "size": 293624, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "binary_reactions/binary-reactions.ipynb", "max_stars_repo_name": "katyhuff/npr247", "max_stars_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T06:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T17:14:51.000Z", "max_issues_repo_path": "binary_reactions/binary-reactions.ipynb", "max_issues_repo_name": "katyhuff/npr247", "max_issues_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-29T17:27:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T17:46:50.000Z", "max_forks_repo_path": "binary_reactions/binary-reactions.ipynb", "max_forks_repo_name": "katyhuff/npr247", "max_forks_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-08-25T20:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T03:05:26.000Z", "avg_line_length": 160.3626433643, "max_line_length": 58120, "alphanum_fraction": 0.8742166853, "converted": true, "num_tokens": 9848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776781576105304, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.08466560168440133}} {"text": "\n*This notebook contains course material from [CBE30338](https://jckantor.github.io/CBE30338)\nby Jeffrey Kantor (jeff at nd.edu); the content is available [on Github](https://github.com/jckantor/CBE30338.git).\nThe text is released under the [CC-BY-NC-ND-4.0 license](https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode),\nand code is released under the [MIT license](https://opensource.org/licenses/MIT).*\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\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\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 \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
XYFaciesPorosityPerm
010090010.1153595.736104
110080010.13642517.211462
210060010.13581043.724752
310050000.0944141.609942
410010000.11304910.886001
520080010.154648106.491795
620070010.153113140.976324
720050010.12616712.548074
820040000.0947501.208561
920010010.15096144.687430
1030080010.1992271079.709291
1130070010.154220179.491695
1230050010.13750238.164911
\n
\n\n\n\n#### Summary Statistics for Tabular Data\n\nThe table includes X and Y coordinates (meters), Facies 1 and 2 (1 is sandstone and 0 interbedded sand and mudstone), Porosity (fraction), and permeability as Perm (mDarcy). \n\nThere are a lot of efficient methods to calculate summary statistics from tabular data in DataFrames. The describe command provides count, mean, minimum, maximum, and quartiles all in a nice data table. We use transpose just to flip the table so that features are on the rows and the statistics are on the columns.\n\n\n```python\ndf.describe().transpose()\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 \n \n \n \n \n
countmeanstdmin25%50%75%max
X289.0475.813149254.2775300.000000300.000000430.000000670.000000990.000000
Y289.0529.692042300.8953749.000000269.000000549.000000819.000000999.000000
Facies289.00.8131490.3904680.0000001.0000001.0000001.0000001.000000
Porosity289.00.1347440.0377450.0585480.1063180.1261670.1542200.228790
Perm289.0207.832368559.3593500.0758193.63408614.90897071.4544245308.842566
\n
\n\n\n\n#### Visualizing Tabular Data with Location Maps \n\nIt is natural to set the x and y coordinate and feature ranges manually. e.g. do you want your color bar to go from 0.05887 to 0.24230 exactly? Also, let's pick a color map for display. I heard that plasma is known to be friendly to the color blind as the color and intensity vary together (hope I got that right, it was an interesting Twitter conversation started by Matt Hall from Agile if I recall correctly). We will assume a study area of 0 to 1,000m in x and y and omit any data outside this area.\n\n\n```python\nxmin = 0.0; xmax = 1000.0 # range of x values\nymin = 0.0; ymax = 1000.0 # range of y values\npormin = 0.05; pormax = 0.25; # range of porosity values\nnx = 100; ny = 100; csize = 10.0\ncmap = plt.cm.plasma # color map\n```\n\nLet's try out locmap. This is a reimplementation of GSLIB's locmap program that uses matplotlib. I hope you find it simpler than matplotlib, if you want to get more advanced and build custom plots lock at the source. If you improve it, send me the new code. Any help is appreciated. To see the parameters, just type the command name:\n\n\n```python\nGSLIB.locmap\n```\n\n\n\n\n \n\n\n\nNow we can populate the plotting parameters and visualize the porosity data.\n\n\n```python\nplt.subplot(111)\nGSLIB.locmap_st(df,'X','Y','Porosity',xmin,xmax,ymin,ymax,pormin,pormax,'Well Data - Porosity','X(m)','Y(m)','Porosity (fraction)',cmap)\nplt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.2, wspace=0.2, hspace=0.2)\nplt.show()\n```\n\nLet's get some declustering weights. For more information see the demonstration on declustering.\n\n\n```python\nwts, cell_sizes, dmeans = geostats.declus(df,'X','Y','Porosity',iminmax = 1, noff= 10, ncell=100,cmin=10,cmax=2000)\ndf['Wts'] = wts # add weights to the sample data DataFrame\ndf.head() # preview to check the sample data DataFrame\n```\n\n There are 289 data with:\n mean of 0.13474387540138408 \n min and max 0.058547873 and 0.228790002\n standard dev 0.03767982164385207 \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
XYFaciesPorosityPermWts
010090010.1153595.7361043.064286
110080010.13642517.2114621.076608
210060010.13581043.7247520.997239
310050000.0944141.6099421.165119
410010000.11304910.8860011.224164
\n
\n\n\n\n#### Trend by Convolution / Local Window Average\n\nLet's first attempt a convolution-based trend model, this is a moving window average of the local data.\n\nWe have a convenience function that takes data with X and Y locations in a DataFrame and makes a sparse 2D array. All cells without a data value are assigned to NumPy's NaN (null values, missing value). Let's see the inputs for this command.\n\n\n```python\nGSLIB.DataFrame2ndarray\n```\n\n\n\n\n \n\n\n\nLet's make an sparse array with the appropriate parameters. The reason we are doing this is that convolution programs in general work with ndarrays and not from DataFrames.\n\n\n```python\npor_grid = GSLIB.DataFrame2ndarray(df,'X','Y','Porosity',xmin, xmax, ymin, ymax, csize, nx, ny)\n```\n\nWe have a ndarray (por_grid) with the data assigned to grid cells. Now we need a kernel. The kernel represents the weights within the moving window. If we use constant 1.0 in the moving window will get discontinuities in our trend model. A Gaussian kernel (weights highest in the middle of the window and decreasing to 0,0 at the edge) is useful to get a smooth trend. We can use the SciPy package's signal functions. Of course we will have to import that package and then we can make our kernel. Here's an example below. There shouldnt be any surprises. \n\n\n```python\ngkern1d = signal.gaussian(53,5).reshape(53, 1)\ngkern2d = np.outer(gkern1d, gkern1d)\nprint('We have made a kernel of size, number of grid cells (ny, nx) ' + str(gkern2d.shape))\n\nplt.subplot(111)\nGSLIB.pixelplt_st(gkern2d,xmin=-265,xmax=265,ymin=-265,ymax=265,step=10,vmin=0,vmax=1,title='Kernel',xlabel='X(m)',ylabel='Y(m)',vlabel='weight',cmap=cmap)\nplt.subplots_adjust(left=0.0, bottom=0.0, right=0.6, top=0.8, wspace=0.2, hspace=0.2)\nplt.show()\n```\n\nNow we need to convolve our sparse data assigned to a ndarray with our Gaussian kernel. There are many functions available for convolution. But we have a problem as we want to apply our Gaussian kernel to a sparse ndarray full of missing values. It turns out this is a common issue for our friends in Astronomy and so their Astropy package has a convolution method that will work well. I figured out the following (so you don't have to!).\n\n\n```python\nimport astropy.convolution.convolve as convolve\nporosity_trend = convolve(por_grid,gkern2d,boundary='extend',nan_treatment='interpolate',normalize_kernel=True)\n```\n\nNo errors? It worked? Let's look at the results. We can plot and compare the original porosity data and the resulting trend to check for consistency.\n\n\n```python\nplt.subplot(131)\nGSLIB.locmap_st(df,'X','Y','Porosity',xmin,xmax,ymin,ymax,pormin,pormax,'Well Data - Porosity','X(m)','Y(m)','Porosity (fraction)',cmap)\n\nplt.subplot(132)\nGSLIB.pixelplt_st(porosity_trend,xmin,xmax,ymin,ymax,csize,pormin,pormax,'Porosity Trend','X(m)','Y(m)','Porosity (fraction)',cmap)\n\nplt.subplot(133)\nGSLIB.locpix_st(porosity_trend,xmin,xmax,ymin,ymax,csize,pormin,pormax,df,'X','Y','Porosity','Porosity Data and Trend','X(m)','Y(m)','Porosity (fraciton)',cmap)\n\nplt.subplots_adjust(left=0.0, bottom=0.0, right=3.0, top=1.2, wspace=0.2, hspace=0.2)\nplt.show()\n\n```\n\n#### Other Methods for Trend Calculation\n\nThere are a variety of other methods for trend calculation. I will just mention them here.\n\n1. hand-drawn, expert interpretation - many 3D modeling packages allow for experts to draw trends and allow for fast interpolation to build an exhaustive trend model.\n2. kriging - kriging provides best linear unbiased estimates between data given a spatial continuity model (more on this when we cover spatial estimation). One note of caution is that kriging is exact; therefore it will over fit unless it is use with averaged data values (e.g. over the vertical) or with a block kriging option (kriging at a volume support larger than the data).\n3. regression - fit a function as a function of X, Y coordinates. This could be extended to more complicated prediction models from machine learning.\n\n#### Trend Diagnotistics\n\nLet's go back to the convolution trend and check it (to demonstrate the method of trend checking). Note, I haven't tried to perfect the result. I'm just demonstrating the method. \n\nIn addition to the previous visualization, let's look at the distributions and summary statistics of the original declustered porosity data and the trend.\n\n\n```python\nplt.subplot(121)\nGSLIB.hist_st(df['Porosity'],pormin,pormax,False,False,20,df['Wts'],'Porosity (fraction)','Declustered Porosity')\n\nplt.subplot(122)\nGSLIB.hist_st(porosity_trend.flatten(),pormin,pormax,False,False,20,None,'Porosity Trend (fraction)','Porosity Trend')\n\nplt.subplots_adjust(left=0.0, bottom=0.0, right=3.0, top=1.5, wspace=0.2, hspace=0.2)\nplt.show()\n```\n\nWe can also look at the summary statistics. Here's a function that calculates the weighted standard deviation (and the average). We can use this with the data and declustering weights and figure out the allocation of variance between the trend and the residual. \n\n\n```python\n# Weighted average and standard deviation\ndef weighted_avg_and_std(values, weights): # from Eric O Lebigot, stack overflow\n average = np.average(values, weights=weights)\n variance = np.average((values-average)**2, weights=weights)\n return (average, math.sqrt(variance))\n\nwavg_por,wstd_por = weighted_avg_and_std(df['Porosity'],df['Wts']) \n\nwavg_por_trend = np.average(porosity_trend)\nwstd_por_trend = np.std(porosity_trend)\n\nprint('Declustered Porosity Data: Average ' + str(round(wavg_por,4)) + ', Var ' + str(round(wstd_por**2,5)))\nprint('Porosity Trend: Average ' + str(round(wavg_por_trend,4)) + ', Var ' + str(round(wstd_por_trend**2,5)))\nprint('Proportion Trend / Known: ' + str(round(wstd_por_trend**2/(wstd_por**2),3)))\nprint('Proportion Residual / Unknown: ' + str(round((wstd_por**2 - wstd_por_trend**2)/(wstd_por**2),3)))\n```\n\n Declustered Porosity Data: Average 0.1212, Var 0.00102\n Porosity Trend: Average 0.1233, Var 0.00064\n Proportion Trend / Known: 0.631\n Proportion Residual / Unknown: 0.369\n\n\nInteresting, we have 63% of the variance being treated as known, modeled by trend, and 37% of the variance being treated as unknown, modeled by residual. \n\n#### Adding Trend to DataFrame\n\nLet's add the porosity trend to our DataFrame. We have a sample program in GeostatsPy that takes a 2D ndarray and extracts the values at the data locations and adds them as a new column. Then we can do a little math to calculate and add the porosity residual also and visualize this all together as a final check.\n\n\n```python\ndf = GSLIB.sample(porosity_trend,xmin,xmax,ymin,ymax,nx,ny,csize,\"Por_Trend\",df,'X','Y')\ndf['Por_Res'] = df['Porosity'] - df['Por_Trend'] # calculate the residual and add to DataFrame\n```\n\nLet's check out the DataFrame and confirm that we have everything now. We will need trend and residual in our DataFrame to support all subsequent modeling steps.\n\n\n```python\ndf.head()\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 \n \n \n \n \n
XYFaciesPorosityPermWtsPor_TrendPor_Res
010090010.1153595.7361043.0642860.117365-0.002006
110080010.13642517.2114621.0766080.1239380.012487
210060010.13581043.7247520.9972390.1284350.007375
310050000.0944141.6099421.1651190.112399-0.017985
410010000.11304910.8860011.2241640.1027910.010258
\n
\n\n\n\nThat looks good. A quick check, confirm that the Porosity column is equal to the Por_Trend + the Por_Res columns. As a final check let's visualize the original porosity data, porosity trends at the data locations and the porosity residuals. \n\n\n```python\nplt.subplot(131)\nGSLIB.locmap_st(df,'X','Y','Porosity',xmin,xmax,ymin,ymax,pormin,pormax,'Well Data - Porosity','X(m)','Y(m)','Porosity (fraction)',cmap)\n\nplt.subplot(132)\nGSLIB.locmap_st(df,'X','Y','Por_Trend',xmin,xmax,ymin,ymax,pormin,pormax,'Well Data - Porosity Trend','X(m)','Y(m)','Porosity (fraction)',cmap)\n\nplt.subplot(133)\nGSLIB.locmap_st(df,'X','Y','Por_Res',xmin,xmax,ymin,ymax,-0.01,0.01,'Well Data - Porosity Residual','X(m)','Y(m)','Porosity (fraction)',cmap)\n\nplt.subplots_adjust(left=0.0, bottom=0.0, right=3.0, top=1.2, wspace=0.2, hspace=0.2)\nplt.show()\n```\n\nDoes it look correct? There is a strong degree of consistency between the porosity data and trend and the porosity residual no longer has a trend, it has been detrended.\n\n#### Comments\n\nThis was a basic demonstration of trend modeling. Much more could be done, I have other demonstrations on the basics of working with DataFrames, ndarrays, univariate statistics, plotting data, declustering, data transformations and many other workflows available at https://github.com/GeostatsGuy/PythonNumericalDemos and https://github.com/GeostatsGuy/GeostatsPy. \n \nI hope this was helpful,\n\n*Michael*\n\nMichael Pyrcz, Ph.D., P.Eng. Associate Professor The Hildebrand Department of Petroleum and Geosystems Engineering, Bureau of Economic Geology, The Jackson School of Geosciences, The University of Texas at Austin\n\n#### More Resources Available at: [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", "meta": {"hexsha": "093241dcbaded407b3bc5636605bd5f96b77b39a", "size": 644594, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "GeostatsPy_trends.ipynb", "max_stars_repo_name": "caf3676/PythonNumericalDemos", "max_stars_repo_head_hexsha": "206a3d876f79e137af88b85ba98aff171e8d8e06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 403, "max_stars_repo_stars_event_min_datetime": "2017-10-15T02:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:27:14.000Z", "max_issues_repo_path": "GeostatsPy_trends.ipynb", "max_issues_repo_name": "caf3676/PythonNumericalDemos", "max_issues_repo_head_hexsha": "206a3d876f79e137af88b85ba98aff171e8d8e06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-08-21T10:35:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-04T04:57:13.000Z", "max_forks_repo_path": "GeostatsPy_trends.ipynb", "max_forks_repo_name": "caf3676/PythonNumericalDemos", "max_forks_repo_head_hexsha": "206a3d876f79e137af88b85ba98aff171e8d8e06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276, "max_forks_repo_forks_event_min_datetime": "2018-06-27T11:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T16:04:24.000Z", "avg_line_length": 553.2995708155, "max_line_length": 235348, "alphanum_fraction": 0.936648495, "converted": true, "num_tokens": 8149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.1778108672995868, "lm_q1q2_score": 0.08404825893606313}} {"text": "\n# Infinite matter, from the electron gas to nuclear matter, background material\n\n \n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/), National Superconducting Cyclotron Laboratory and Department of Physics and Astronomy, Michigan State University, East Lansing, MI 48824, USA & Department of Physics, University of Oslo, Oslo, Norway**\n\nDate: **Jul 10, 2018**\n\n## Introduction to studies of infinite matter\n\n\nStudies of infinite nuclear matter play an important role in nuclear physics. The aim of this part of the lectures is to provide the necessary ingredients for perfoming studies of neutron star matter (or matter in $\\beta$-equilibrium) and symmetric nuclear matter. We start however with the electron gas in two and three dimensions for both historical and pedagogical reasons. Since there are several benchmark calculations for the electron gas, this small detour will allow us to establish the necessary formalism. Thereafter we will study infinite nuclear matter \n* at the Hartree-Fock with realistic nuclear forces and\n\n* using many-body methods like coupled-cluster theory or in-medium SRG\n\n## The infinite electron gas\n\nThe electron gas is perhaps the only realistic model of a \nsystem of many interacting particles that allows for an analytical solution\nof the Hartree-Fock equations. Furthermore, to first order in the interaction, one can also\nobtain an analytical expression for the total energy and several other properties of a many-particle systems. \nThe model gives a very good approximation to the properties of valence electrons in metals.\nThe assumptions are\n\n * System of electrons that is not influenced by external forces except by an attraction provided by a uniform background of ions. These ions give rise to a uniform background charge. The ions are stationary.\n\n * The system as a whole is neutral.\n\n * We assume we have $N_e$ electrons in a cubic box of length $L$ and volume $\\Omega=L^3$. This volume contains also a uniform distribution of positive charge with density $N_ee/\\Omega$. \n\nThe homogeneus electron gas is a system of electrons that is not\ninfluenced by external forces except by an attraction provided by a\nuniform background of ions. These ions give rise to a uniform\nbackground charge. The ions are stationary and the system as a whole\nis neutral.\nIrrespective of this simplicity, this system, in both two and\nthree-dimensions, has eluded a proper description of correlations in\nterms of various first principle methods, except perhaps for quantum\nMonte Carlo methods. In particular, the diffusion Monte Carlo\ncalculations of [Ceperley](http://journals.aps.org/prl/abstract/10.1103/PhysRevLett.45.566) \nand [Ceperley and Tanatar](http://journals.aps.org/prb/abstract/10.1103/PhysRevB.39.5005) \nare presently still considered as the\nbest possible benchmarks for the two- and three-dimensional electron\ngas. \n\n\n\nThe electron gas, in \ntwo or three dimensions is thus interesting as a test-bed for \nelectron-electron correlations. The three-dimensional \nelectron gas is particularly important as a cornerstone \nof the local-density approximation in density-functional \ntheory. In the physical world, systems \nsimilar to the three-dimensional electron gas can be \nfound in, for example, alkali metals and doped \nsemiconductors. Two-dimensional electron fluids are \nobserved on metal and liquid-helium surfaces, as well as \nat metal-oxide-semiconductor interfaces. However, the Coulomb \ninteraction has an infinite range, and therefore \nlong-range correlations play an essential role in the\nelectron gas. \n\n\n\n\nAt low densities, the electrons become \nlocalized and form a lattice. This so-called Wigner \ncrystallization is a direct consequence \nof the long-ranged repulsive interaction. At higher\ndensities, the electron gas is better described as a\nliquid.\nWhen using, for example, Monte Carlo methods the electron gas must be approximated \nby a finite system. The long-range Coulomb interaction \nin the electron gas causes additional finite-size effects that are not\npresent in other infinite systems like nuclear matter or neutron star matter.\nThis poses additional challenges to many-body methods when applied \nto the electron gas.\n\n\n\n\n\n## The infinite electron gas as a homogenous system\n\nThis is a homogeneous system and the one-particle wave functions are given by plane wave functions normalized to a volume $\\Omega$ \nfor a box with length $L$ (the limit $L\\rightarrow \\infty$ is to be taken after we have computed various expectation values)\n\n$$\n\\psi_{\\mathbf{k}\\sigma}(\\mathbf{r})= \\frac{1}{\\sqrt{\\Omega}}\\exp{(i\\mathbf{kr})}\\xi_{\\sigma}\n$$\n\nwhere $\\mathbf{k}$ is the wave number and $\\xi_{\\sigma}$ is a spin function for either spin up or down\n\n$$\n\\xi_{\\sigma=+1/2}=\\left(\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right) \\hspace{0.5cm}\n\\xi_{\\sigma=-1/2}=\\left(\\begin{array}{c} 0 \\\\ 1 \\end{array}\\right).\n$$\n\nWe assume that we have periodic boundary conditions which limit the allowed wave numbers to\n\n$$\nk_i=\\frac{2\\pi n_i}{L}\\hspace{0.5cm} i=x,y,z \\hspace{0.5cm} n_i=0,\\pm 1,\\pm 2, \\dots\n$$\n\nWe assume first that the electrons interact via a central, symmetric and translationally invariant\ninteraction $V(r_{12})$ with\n$r_{12}=|\\mathbf{r}_1-\\mathbf{r}_2|$. The interaction is spin independent.\n\nThe total Hamiltonian consists then of kinetic and potential energy\n\n$$\n\\hat{H} = \\hat{T}+\\hat{V}.\n$$\n\nThe operator for the kinetic energy can be written as\n\n$$\n\\hat{T}=\\sum_{\\mathbf{k}\\sigma}\\frac{\\hbar^2k^2}{2m}a_{\\mathbf{k}\\sigma}^{\\dagger}a_{\\mathbf{k}\\sigma}.\n$$\n\n## Defining the Hamiltonian operator\n\nThe Hamiltonian operator is given by\n\n$$\n\\hat{H}=\\hat{H}_{el}+\\hat{H}_{b}+\\hat{H}_{el-b},\n$$\n\nwith the electronic part\n\n$$\n\\hat{H}_{el}=\\sum_{i=1}^N\\frac{p_i^2}{2m}+\\frac{e^2}{2}\\sum_{i\\ne j}\\frac{e^{-\\mu |\\mathbf{r}_i-\\mathbf{r}_j|}}{|\\mathbf{r}_i-\\mathbf{r}_j|},\n$$\n\nwhere we have introduced an explicit convergence factor\n(the limit $\\mu\\rightarrow 0$ is performed after having calculated the various integrals).\nCorrespondingly, we have\n\n$$\n\\hat{H}_{b}=\\frac{e^2}{2}\\int\\int d\\mathbf{r}d\\mathbf{r}'\\frac{n(\\mathbf{r})n(\\mathbf{r}')e^{-\\mu |\\mathbf{r}-\\mathbf{r}'|}}{|\\mathbf{r}-\\mathbf{r}'|},\n$$\n\nwhich is the energy contribution from the positive background charge with density\n$n(\\mathbf{r})=N/\\Omega$. Finally,\n\n$$\n\\hat{H}_{el-b}=-\\frac{e^2}{2}\\sum_{i=1}^N\\int d\\mathbf{r}\\frac{n(\\mathbf{r})e^{-\\mu |\\mathbf{r}-\\mathbf{x}_i|}}{|\\mathbf{r}-\\mathbf{x}_i|},\n$$\n\nis the interaction between the electrons and the positive background.\n\n\n\n## Single-particle Hartree-Fock energy\n\nIn the first exercise below we show that the Hartree-Fock energy can be written as\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m_e}-\\frac{e^{2}}\n{\\Omega^{2}}\\sum_{k'\\leq\nk_{F}}\\int d\\mathbf{r}e^{i(\\mathbf{k}'-\\mathbf{k})\\mathbf{r}}\\int\nd\\mathbf{r'}\\frac{e^{i(\\mathbf{k}-\\mathbf{k}')\\mathbf{r}'}}\n{\\vert\\mathbf{r}-\\mathbf{r}'\\vert}\n$$\n\nresulting in\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m_e}-\\frac{e^{2}\nk_{F}}{2\\pi}\n\\left[\n2+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right]\n$$\n\nThe previous result can be rewritten in terms of the density\n\n$$\nn= \\frac{k_F^3}{3\\pi^2}=\\frac{3}{4\\pi r_s^3},\n$$\n\nwhere $n=N_e/\\Omega$, $N_e$ being the number of electrons, and $r_s$ is the radius of a sphere which represents the volum per conducting electron. \nIt can be convenient to use the Bohr radius $a_0=\\hbar^2/e^2m_e$.\nFor most metals we have a relation $r_s/a_0\\sim 2-6$. The quantity $r_s$ is dimensionless.\n\n\nIn the second exercise below we find that\nthe total energy\n$E_0/N_e=\\langle\\Phi_{0}|\\hat{H}|\\Phi_{0}\\rangle/N_e$ for\nfor this system to first order in the interaction is given as\n\n$$\nE_0/N_e=\\frac{e^2}{2a_0}\\left[\\frac{2.21}{r_s^2}-\\frac{0.916}{r_s}\\right].\n$$\n\n\n\n## Exercise 1: Hartree-Fock single-particle solution for the electron gas\n\nThe electron gas model allows closed form solutions for quantities like the \nsingle-particle Hartree-Fock energy. The latter quantity is given by the following expression\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}}\n{V^{2}}\\sum_{k'\\leq\nk_{F}}\\int d\\mathbf{r}e^{i(\\mathbf{k'}-\\mathbf{k})\\mathbf{r}}\\int\nd\\mathbf{r}'\\frac{e^{i(\\mathbf{k}-\\mathbf{k'})\\mathbf{r}'}}\n{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\n$$\n\n**a)**\nShow first that\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}\nk_{F}}{2\\pi}\n\\left[\n2+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right]\n$$\n\n\n\n**Hint.**\nHint: Introduce the convergence factor \n$e^{-\\mu\\vert\\mathbf{r}-\\mathbf{r}'\\vert}$\nin the potential and use $\\sum_{\\mathbf{k}}\\rightarrow\n\\frac{V}{(2\\pi)^{3}}\\int d\\mathbf{k}$\n\n\n\n\n\n**Solution.**\nWe want to show that, given the Hartree-Fock equation for the electron gas\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}}\n{V^{2}}\\sum_{p\\leq\nk_{F}}\\int d\\mathbf{r}\\exp{(i(\\mathbf{p}-\\mathbf{k})\\mathbf{r})}\\int\nd\\mathbf{r}'\\frac{\\exp{(i(\\mathbf{k}-\\mathbf{p})\\mathbf{r}'})}\n{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\n$$\n\nthe single-particle energy can be written as\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}\nk_{F}}{2\\pi}\n\\left[\n2+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right].\n$$\n\nWe introduce the convergence factor \n$e^{-\\mu\\vert\\mathbf{r}-\\mathbf{r}'\\vert}$\nin the potential and use $\\sum_{\\mathbf{k}}\\rightarrow\n\\frac{V}{(2\\pi)^{3}}\\int d\\mathbf{k}$. We can then rewrite the integral as\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{e^{2}}\n{V^{2}}\\sum_{k'\\leq\nk_{F}}\\int d\\mathbf{r}\\exp{(i(\\mathbf{k'}-\\mathbf{k})\\mathbf{r})}\\int\nd\\mathbf{r}'\\frac{\\exp{(i(\\mathbf{k}-\\mathbf{p})\\mathbf{r}'})}\n{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}= \n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n\\frac{e^{2}}{V (2\\pi)^3} \\int d\\mathbf{r}\\int\n\\frac{d\\mathbf{r}'}{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\\exp{(-i\\mathbf{k}(\\mathbf{r}-\\mathbf{r}'))}\\int d\\mathbf{p}\\exp{(i\\mathbf{p}(\\mathbf{r}-\\mathbf{r}'))},\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\nand introducing the abovementioned convergence factor we have\n\n\n
\n\n$$\n\\begin{equation}\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{V (2\\pi)^3} \\int d\\mathbf{r}\\int d\\mathbf{r}'\\frac{\\exp{(-\\mu\\vert\\mathbf{r}-\\mathbf{r}'\\vert})}{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\\int d\\mathbf{p}\\exp{(i(\\mathbf{p}-\\mathbf{k})(\\mathbf{r}-\\mathbf{r}'))}.\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\nWith a change variables to $\\mathbf{x} = \\mathbf{r}-\\mathbf{r}'$ and $\\mathbf{y}=\\mathbf{r}'$ we rewrite the last integral as\n\n$$\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{V (2\\pi)^3} \\int d\\mathbf{p}\\int d\\mathbf{y}\\int d\\mathbf{x}\\exp{(i(\\mathbf{p}-\\mathbf{k})\\mathbf{x})}\\frac{\\exp{(-\\mu\\vert\\mathbf{x}\\vert})}{\\vert\\mathbf{x}\\vert}.\n$$\n\nThe integration over $\\mathbf{x}$ can be performed using spherical coordinates, resulting in (with $x=\\vert \\mathbf{x}\\vert$)\n\n$$\n\\int d\\mathbf{x}\\exp{(i(\\mathbf{p}-\\mathbf{k})\\mathbf{x})}\\frac{\\exp{(-\\mu\\vert\\mathbf{x}\\vert})}{\\vert\\mathbf{x}\\vert}=\\int x^2 dx d\\phi d\\cos{(\\theta)}\\exp{(i(\\mathbf{p}-\\mathbf{k})x\\cos{(\\theta))}}\\frac{\\exp{(-\\mu x)}}{x}.\n$$\n\nWe obtain\n\n\n
\n\n$$\n\\begin{equation}\n4\\pi \\int dx \\frac{ \\sin{(\\vert \\mathbf{p}-\\mathbf{k}\\vert)x} }{\\vert \\mathbf{p}-\\mathbf{k}\\vert}{\\exp{(-\\mu x)}}= \\frac{4\\pi}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}.\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\nThis results gives us\n\n\n
\n\n$$\n\\begin{equation}\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{V (2\\pi)^3} \\int d\\mathbf{p}\\int d\\mathbf{y}\\frac{4\\pi}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}=\\lim_{\\mu \\to 0}\\frac{e^{2}}{ 2\\pi^2} \\int d\\mathbf{p}\\frac{1}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2},\n\\label{_auto5} \\tag{5}\n\\end{equation}\n$$\n\nwhere we have used that the integrand on the left-hand side does not depend on $\\mathbf{y}$ and that $\\int d\\mathbf{y}=V$.\n\nIntroducing spherical coordinates we can rewrite the integral as\n\n\n
\n\n$$\n\\begin{equation}\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{ 2\\pi^2} \\int d\\mathbf{p}\\frac{1}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}=\\frac{e^{2}}{ 2\\pi^2} \\int d\\mathbf{p}\\frac{1}{\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}= \n\\label{_auto6} \\tag{6}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n\\frac{e^{2}}{\\pi} \\int_0^{k_F} p^2dp\\int_0^{\\pi} d\\theta\\cos{(\\theta)}\\frac{1}{p^2+k^2-2pk\\cos{(\\theta)}},\n\\label{_auto7} \\tag{7}\n\\end{equation}\n$$\n\nand with the change of variables $\\cos{(\\theta)}=u$ we have\n\n$$\n\\frac{e^{2}}{\\pi} \\int_0^{k_F} p^2dp\\int_{0}^{\\pi} d\\theta\\cos{(\\theta)}\\frac{1}{p^2+k^2-2pk\\cos{(\\theta)}}=\\frac{e^{2}}{\\pi} \\int_0^{k_F} p^2dp\\int_{-1}^{1} du\\frac{1}{p^2+k^2-2pku},\n$$\n\nwhich gives\n\n$$\n\\frac{e^{2}}{k\\pi} \\int_0^{k_F} pdp\\left\\{ln(\\vert p+k\\vert)-ln(\\vert p-k\\vert)\\right\\}.\n$$\n\nIntroducing new variables $x=p+k$ and $y=p-k$, we obtain after some straightforward reordering of the integral\n\n$$\n\\frac{e^{2}}{k\\pi}\\left[\nkk_F+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right],\n$$\n\nwhich gives the abovementioned expression for the single-particle energy.\n\n\n\n**b)**\nRewrite the above result as a function of the density\n\n$$\nn= \\frac{k_F^3}{3\\pi^2}=\\frac{3}{4\\pi r_s^3},\n$$\n\nwhere $n=N/V$, $N$ being the number of particles, and $r_s$ is the radius of a sphere which represents the volum per conducting electron.\n\n\n\n**Solution.**\nIntroducing the dimensionless quantity $x=k/k_F$ and the function\n\n$$\nF(x) = \\frac{1}{2}+\\frac{1-x^2}{4x}\\ln{\\left\\vert \\frac{1+x}{1-x}\\right\\vert},\n$$\n\nwe can rewrite the single-particle Hartree-Fock energy as\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{2e^{2}\nk_{F}}{\\pi}F(k/k_F),\n$$\n\nand dividing by the non-interacting contribution at the Fermi level,\n\n$$\n\\varepsilon_{0}^{F}=\\frac{\\hbar^{2}k_F^{2}}{2m},\n$$\n\nwe have\n\n$$\n\\frac{\\varepsilon_{k}^{HF} }{\\varepsilon_{0}^{F}}=x^2-\\frac{e^2m}{\\hbar^2 k_F\\pi}F(x)=x^2-\\frac{4}{\\pi k_Fa_0}F(x),\n$$\n\nwhere $a_0=0.0529$ nm is the Bohr radius, setting thereby a natural length scale. \n\n\nBy introducing the radius $r_s$ of a sphere whose volume is the volume occupied by each electron, we can rewrite the previous equation in terms of $r_s$ using that the electron density $n=N/V$\n\n$$\nn=\\frac{k_F^3}{3\\pi^2} = \\frac{3}{4\\pi r_s^3},\n$$\n\nwe have (with $k_F=1.92/r_s$,\n\n$$\n\\frac{\\varepsilon_{k}^{HF} }{\\varepsilon_{0}^{F}}=x^2-\\frac{e^2m}{\\hbar^2 k_F\\pi}F(x)=x^2-\\frac{r_s}{a_0}0.663F(x),\n$$\n\nwith $r_s \\sim 2-6$ for most metals.\n\n\n\nIt can be convenient to use the Bohr radius $a_0=\\hbar^2/e^2m$.\nFor most metals we have a relation $r_s/a_0\\sim 2-6$.\n\n**c)**\nMake a plot of the free electron energy and the Hartree-Fock energy and discuss the behavior around the Fermi surface. Extract also the Hartree-Fock band width $\\Delta\\varepsilon^{HF}$ defined as\n\n$$\n\\Delta\\varepsilon^{HF}=\\varepsilon_{k_{F}}^{HF}-\n\\varepsilon_{0}^{HF}.\n$$\n\nCompare this results with the corresponding one for a free electron and comment your results. How large is the contribution due to the exchange term in the Hartree-Fock equation?\n\n\n\n**Solution.**\nWe can now define the so-called band gap, that is the scatter between the maximal and the minimal value of the electrons in the conductance band of a metal (up to the Fermi level). \nFor $x=1$ and $r_s/a_0=4$ we have\n\n$$\n\\frac{\\varepsilon_{k=k_F}^{HF} }{\\varepsilon_{0}^{F}} = -0.326,\n$$\n\nand for $x=0$ we have\n\n$$\n\\frac{\\varepsilon_{k=0}^{HF} }{\\varepsilon_{0}^{F}} = -2.652,\n$$\n\nwhich results in a gap at the Fermi level of\n\n$$\n\\Delta \\varepsilon^{HF} = \\frac{\\varepsilon_{k=k_F}^{HF} }{\\varepsilon_{0}^{F}}-\\frac{\\varepsilon_{k=0}^{HF} }{\\varepsilon_{0}^{F}} = 2.326.\n$$\n\nThis quantity measures the deviation from the $k=0$ single-particle energy and the energy at the Fermi level.\nThe general result is\n\n$$\n\\Delta \\varepsilon^{HF} = 1+\\frac{r_s}{a_0}0.663.\n$$\n\nThe following python code produces a plot of the electron energy for a free electron (only kinetic energy) and \nfor the Hartree-Fock solution. We have chosen here a ratio $r_s/a_0=4$ and the equations are plotted as funtions\nof $k/f_F$.\n\n\n```\n%matplotlib inline\n\nimport numpy as np\nfrom math import log\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':['Hartree-Fock energy']})\nfont = {'family' : 'serif',\n 'color' : 'darkred',\n 'weight' : 'normal',\n 'size' : 16,\n }\n\nN = 100\nx = np.linspace(0.0, 2.0,N)\nF = 0.5+np.log(abs((1.0+x)/(1.0-x)))*(1.0-x*x)*0.25/x\ny = x*x -4.0*0.663*F\n\nplt.plot(x, y, 'b-')\nplt.plot(x, x*x, 'r-')\nplt.title(r'{\\bf Hartree-Fock single-particle energy for electron gas}', fontsize=20) \nplt.text(3, -40, r'Parameters: $r_s/a_0=4$', fontdict=font)\nplt.xlabel(r'$k/k_F$',fontsize=20)\nplt.ylabel(r'$\\varepsilon_k^{HF}/\\varepsilon_0^F$',fontsize=20)\n# Tweak spacing to prevent clipping of ylabel\nplt.subplots_adjust(left=0.15)\nplt.savefig('hartreefockspelgas.pdf', format='pdf')\nplt.show()\n```\n\nFrom the plot we notice that the exchange term increases considerably the band gap\ncompared with the non-interacting gas of electrons.\n\n\nWe will now define a quantity called the effective mass.\nFor $\\vert\\mathbf{k}\\vert$ near $k_{F}$, we can Taylor expand the Hartree-Fock energy as\n\n$$\n\\varepsilon_{k}^{HF}=\\varepsilon_{k_{F}}^{HF}+\n\\left(\\frac{\\partial\\varepsilon_{k}^{HF}}{\\partial k}\\right)_{k_{F}}(k-k_{F})+\\dots\n$$\n\nIf we compare the latter with the corresponding expressiyon for the non-interacting system\n\n$$\n\\varepsilon_{k}^{(0)}=\\frac{\\hbar^{2}k^{2}_{F}}{2m}+\n\\frac{\\hbar^{2}k_{F}}{m}\\left(k-k_{F}\\right)+\\dots ,\n$$\n\nwe can define the so-called effective Hartree-Fock mass as\n\n$$\nm_{HF}^{*}\\equiv\\hbar^{2}k_{F}\\left(\n\\frac{\\partial\\varepsilon_{k}^{HF}}\n{\\partial k}\\right)_{k_{F}}^{-1}\n$$\n\n**d)**\nCompute $m_{HF}^{*}$ and comment your results.\n\n**e)**\nShow that the level density (the number of single-electron states per unit energy) can be written as\n\n$$\nn(\\varepsilon)=\\frac{Vk^{2}}{2\\pi^{2}}\\left(\n\\frac{\\partial\\varepsilon}{\\partial k}\\right)^{-1}\n$$\n\nCalculate $n(\\varepsilon_{F}^{HF})$ and comment the results.\n\n\n\n\n\n\n\n\n\n\n\n## Exercise 2: Hartree-Fock ground state energy for the electron gas in three dimensions\n\nWe consider a system of electrons in infinite matter, the so-called electron gas. This is a homogeneous system and the one-particle states are given by plane wave function normalized to a volume $\\Omega$ \nfor a box with length $L$ (the limit $L\\rightarrow \\infty$ is to be taken after we have computed various expectation values)\n\n$$\n\\psi_{\\mathbf{k}\\sigma}(\\mathbf{r})= \\frac{1}{\\sqrt{\\Omega}}\\exp{(i\\mathbf{kr})}\\xi_{\\sigma}\n$$\n\nwhere $\\mathbf{k}$ is the wave number and $\\xi_{\\sigma}$ is a spin function for either spin up or down\n\n$$\n\\xi_{\\sigma=+1/2}=\\left(\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right) \\hspace{0.5cm}\n\\xi_{\\sigma=-1/2}=\\left(\\begin{array}{c} 0 \\\\ 1 \\end{array}\\right).\n$$\n\nWe assume that we have periodic boundary conditions which limit the allowed wave numbers to\n\n$$\nk_i=\\frac{2\\pi n_i}{L}\\hspace{0.5cm} i=x,y,z \\hspace{0.5cm} n_i=0,\\pm 1,\\pm 2, \\dots\n$$\n\nWe assume first that the particles interact via a central, symmetric and translationally invariant\ninteraction $V(r_{12})$ with\n$r_{12}=|\\mathbf{r}_1-\\mathbf{r}_2|$. The interaction is spin independent.\n\nThe total Hamiltonian consists then of kinetic and potential energy\n\n$$\n\\hat{H} = \\hat{T}+\\hat{V}.\n$$\n\nThe operator for the kinetic energy is given by\n\n$$\n\\hat{T}=\\sum_{\\mathbf{k}\\sigma}\\frac{\\hbar^2k^2}{2m}a_{\\mathbf{k}\\sigma}^{\\dagger}a_{\\mathbf{k}\\sigma}.\n$$\n\n**a)**\nFind the expression for the interaction\n$\\hat{V}$ expressed with creation and annihilation operators. The expression for the interaction\nhas to be written in $k$ space, even though $V$ depends only on the relative distance. It means that you need to set up the Fourier transform $\\langle \\mathbf{k}_i\\mathbf{k}_j| V | \\mathbf{k}_m\\mathbf{k}_n\\rangle$.\n\n\n\n**Solution.**\nA general two-body interaction element is given by (not using anti-symmetrized matrix elements)\n\n$$\n\\hat{V} = \\frac{1}{2} \\sum_{pqrs} \\langle pq \\hat{v} \\vert rs\\rangle a_p^\\dagger a_q^\\dagger a_s a_r ,\n$$\n\nwhere $\\hat{v}$ is assumed to depend only on the relative distance between two interacting particles, that is\n$\\hat{v} = v(\\vec r_1, \\vec r_2) = v(|\\vec r_1 - \\vec r_2|) = v(r)$, with $r = |\\vec r_1 - \\vec r_2|$). \nIn our case we have, writing out explicitely the spin degrees of freedom as well\n\n\n
\n\n$$\n\\begin{equation}\n\\hat{V} = \\frac{1}{2} \\sum_{\\substack{\\sigma_p \\sigma_q \\\\ \\sigma_r \\sigma_s}}\n\\sum_{\\substack{\\mathbf{k}_p \\mathbf{k}_q \\\\ \\mathbf{k}_r \\mathbf{k}_s}}\n\\langle \\mathbf{k}_p \\sigma_p, \\mathbf{k}_q \\sigma_2\\vert v \\vert \\mathbf{k}_r \\sigma_3, \\mathbf{k}_s \\sigma_s\\rangle\na_{\\mathbf{k}_p \\sigma_p}^\\dagger a_{\\mathbf{k}_q \\sigma_q}^\\dagger a_{\\mathbf{k}_s \\sigma_s} a_{\\mathbf{k}_r \\sigma_r} .\n\\label{_auto8} \\tag{8}\n\\end{equation}\n$$\n\nInserting plane waves as eigenstates we can rewrite the matrix element as\n\n$$\n\\langle \\mathbf{k}_p \\sigma_p, \\mathbf{k}_q \\sigma_q\\vert \\hat{v} \\vert \\mathbf{k}_r \\sigma_r, \\mathbf{k}_s \\sigma_s\\rangle =\n\\frac{1}{\\Omega^2} \\delta_{\\sigma_p \\sigma_r} \\delta_{\\sigma_q \\sigma_s}\n\\int\\int \\exp{-i(\\mathbf{k}_p \\cdot \\mathbf{r}_p)} \\exp{-i( \\mathbf{k}_q \\cdot \\mathbf{r}_q)} \\hat{v}(r) \\exp{i(\\mathbf{k}_r \\cdot \\mathbf{r}_p)} \\exp{i( \\mathbf{k}_s \\cdot \\mathbf{r}_q)} d\\mathbf{r}_p d\\mathbf{r}_q ,\n$$\n\nwhere we have used the orthogonality properties of the spin functions. We change now the variables of integration\nby defining $\\mathbf{r} = \\mathbf{r}_p - \\mathbf{r}_q$, which gives $\\mathbf{r}_p = \\mathbf{r} + \\mathbf{r}_q$ and $d^3 \\mathbf{r} = d^3 \\mathbf{r}_p$. \nThe limits are not changed since they are from $-\\infty$ to $\\infty$ for all integrals. This results in\n\n$$\n\\begin{align*}\n\\langle \\mathbf{k}_p \\sigma_p, \\mathbf{k}_q \\sigma_q\\vert \\hat{v} \\vert \\mathbf{k}_r \\sigma_r, \\mathbf{k}_s \\sigma_s\\rangle\n&= \\frac{1}{\\Omega^2} \\delta_{\\sigma_p \\sigma_r} \\delta_{\\sigma_q \\sigma_s} \\int\\exp{i (\\mathbf{k}_s - \\mathbf{k}_q) \\cdot \\mathbf{r}_q} \\int v(r) \\exp{i(\\mathbf{k}_r - \\mathbf{k}_p) \\cdot ( \\mathbf{r} + \\mathbf{r}_q)} d\\mathbf{r} d\\mathbf{r}_q \\\\\n&= \\frac{1}{\\Omega^2} \\delta_{\\sigma_p \\sigma_r} \\delta_{\\sigma_q \\sigma_s} \\int v(r) \\exp{i\\left[(\\mathbf{k}_r - \\mathbf{k}_p) \\cdot \\mathbf{r}\\right]}\n\\int \\exp{i\\left[(\\mathbf{k}_s - \\mathbf{k}_q + \\mathbf{k}_r - \\mathbf{k}_p) \\cdot \\mathbf{r}_q\\right]} d\\mathbf{r}_q d\\mathbf{r} .\n\\end{align*}\n$$\n\nWe recognize the integral over $\\mathbf{r}_q$ as a $\\delta$-function, resulting in\n\n$$\n\\langle \\mathbf{k}_p \\sigma_p, \\mathbf{k}_q \\sigma_q\\vert \\hat{v} \\vert \\mathbf{k}_r \\sigma_r, \\mathbf{k}_s \\sigma_s\\rangle =\n\\frac{1}{\\Omega} \\delta_{\\sigma_p \\sigma_r} \\delta_{\\sigma_q \\sigma_s} \\delta_{(\\mathbf{k}_p + \\mathbf{k}_q),(\\mathbf{k}_r + \\mathbf{k}_s)} \\int v(r) \\exp{i\\left[(\\mathbf{k}_r - \\mathbf{k}_p) \\cdot \\mathbf{r}\\right]} d^3r .\n$$\n\nFor this equation to be different from zero, we must have conservation of momenta, we need to satisfy\n$\\mathbf{k}_p + \\mathbf{k}_q = \\mathbf{k}_r + \\mathbf{k}_s$. We can use the conservation of momenta to remove one of the summation variables resulting in\n\n$$\n\\hat{V} =\n\\frac{1}{2\\Omega} \\sum_{\\sigma \\sigma'} \\sum_{\\mathbf{k}_p \\mathbf{k}_q \\mathbf{k}_r} \\left[ \\int v(r) \\exp{i\\left[(\\mathbf{k}_r - \\mathbf{k}_p) \\cdot \\mathbf{r}\\right]} d^3r \\right]\na_{\\mathbf{k}_p \\sigma}^\\dagger a_{\\mathbf{k}_q \\sigma'}^\\dagger a_{\\mathbf{k}_p + \\mathbf{k}_q - \\mathbf{k}_r, \\sigma'} a_{\\mathbf{k}_r \\sigma},\n$$\n\nwhich can be rewritten as\n\n\n
\n\n$$\n\\begin{equation}\n\\hat{V} =\n\\frac{1}{2\\Omega} \\sum_{\\sigma \\sigma'} \\sum_{\\mathbf{k} \\mathbf{p} \\mathbf{q}} \\left[ \\int v(r) \\exp{-i( \\mathbf{q} \\cdot \\mathbf{r})} d\\mathbf{r} \\right]\na_{\\mathbf{k} + \\mathbf{q}, \\sigma}^\\dagger a_{\\mathbf{p} - \\mathbf{q}, \\sigma'}^\\dagger a_{\\mathbf{p} \\sigma'} a_{\\mathbf{k} \\sigma},\n\\label{eq:V} \\tag{9}\n\\end{equation}\n$$\n\nThis equation will be useful for our nuclear matter calculations as well. In the last equation we defined\nthe quantities\n$\\mathbf{p} = \\mathbf{k}_p + \\mathbf{k}_q - \\mathbf{k}_r$, $\\mathbf{k} = \\mathbf{k}_r$ og $\\mathbf{q} = \\mathbf{k}_p - \\mathbf{k}_r$.\n\n\n\n**b)**\nCalculate thereafter the reference energy for the infinite electron gas in three dimensions using the above expressions for the kinetic energy and the potential energy.\n\n\n\n**Solution.**\nLet us now compute the expectation value of the reference energy using the expressions for the kinetic energy operator and the interaction.\nWe need to compute $\\langle \\Phi_0\\vert \\hat{H} \\vert \\Phi_0\\rangle = \\langle \\Phi_0\\vert \\hat{T} \\vert \\Phi_0\\rangle + \\langle \\Phi_0\\vert \\hat{V} \\vert \\Phi_0\\rangle$, where $\\vert \\Phi_0\\rangle$ is our reference Slater determinant, constructed from filling all single-particle states up to the Fermi level.\nLet us start with the kinetic energy first\n\n$$\n\\langle \\Phi_0\\vert \\hat{T} \\vert \\Phi_0\\rangle \n= \\langle \\Phi_0\\vert \\left( \\sum_{\\mathbf{p} \\sigma} \\frac{\\hbar^2 p^2}{2m} a_{\\mathbf{p} \\sigma}^\\dagger a_{\\mathbf{p} \\sigma} \\right) \\vert \\Phi_0\\rangle \\\\\n= \\sum_{\\mathbf{p} \\sigma} \\frac{\\hbar^2 p^2}{2m} \\langle \\Phi_0\\vert a_{\\mathbf{p} \\sigma}^\\dagger a_{\\mathbf{p} \\sigma} \\vert \\Phi_0\\rangle .\n$$\n\nFrom the possible contractions using Wick's theorem, it is straightforward to convince oneself that the expression for the kinetic energy becomes\n\n$$\n\\langle \\Phi_0\\vert \\hat{T} \\vert \\Phi_0\\rangle = \\sum_{\\mathbf{i} \\leq F} \\frac{\\hbar^2 k_i^2}{m} = \\frac{\\Omega}{(2\\pi)^3} \\frac{\\hbar^2}{m} \\int_0^{k_F} k^2 d\\mathbf{k}.\n$$\n\nThe sum of the spin degrees of freedom results in a factor of two only if we deal with identical spin $1/2$ fermions. \nChanging to spherical coordinates, the integral over the momenta $k$ results in the final expression\n\n$$\n\\langle \\Phi_0\\vert \\hat{T} \\vert \\Phi_0\\rangle = \\frac{\\Omega}{(2\\pi)^3} \\left( 4\\pi \\int_0^{k_F} k^4 d\\mathbf{k} \\right) = \\frac{4\\pi\\Omega}{(2\\pi)^3} \\frac{1}{5} k_F^5 = \\frac{4\\pi\\Omega}{5(2\\pi)^3} k_F^5 = \\frac{\\hbar^2 \\Omega}{10\\pi^2 m} k_F^5 .\n$$\n\nThe density of states in momentum space is given by $2\\Omega/(2\\pi)^3$, where we have included the degeneracy due to the spin degrees of freedom.\nThe volume is given by $4\\pi k_F^3/3$, and the number of particles becomes\n\n$$\nN = \\frac{2\\Omega}{(2\\pi)^3} \\frac{4}{3} \\pi k_F^3 = \\frac{\\Omega}{3\\pi^2} k_F^3 \\quad \\Rightarrow \\quad\nk_F = \\left( \\frac{3\\pi^2 N}{\\Omega} \\right)^{1/3}.\n$$\n\nThis gives us\n\n\n
\n\n$$\n\\begin{equation}\n\\langle \\Phi_0\\vert \\hat{T} \\vert \\Phi_0\\rangle =\n\\frac{\\hbar^2 \\Omega}{10\\pi^2 m} \\left( \\frac{3\\pi^2 N}{\\Omega} \\right)^{5/3} =\n\\frac{\\hbar^2 (3\\pi^2)^{5/3} N}{10\\pi^2 m} \\rho^{2/3} ,\n\\label{eq:T_forventning} \\tag{10}\n\\end{equation}\n$$\n\nWe are now ready to calculate the expectation value of the potential energy\n\n$$\n\\begin{align*}\n\\langle \\Phi_0\\vert \\hat{V} \\vert \\Phi_0\\rangle \n&= \\langle \\Phi_0\\vert \\left( \\frac{1}{2\\Omega} \\sum_{\\sigma \\sigma'} \\sum_{\\mathbf{k} \\mathbf{p} \\mathbf{q} } \\left[ \\int v(r) \\exp{-i (\\mathbf{q} \\cdot \\mathbf{r})} d\\mathbf{r} \\right] a_{\\mathbf{k} + \\mathbf{q}, \\sigma}^\\dagger a_{\\mathbf{p} - \\mathbf{q}, \\sigma'}^\\dagger a_{\\mathbf{p} \\sigma'} a_{\\mathbf{k} \\sigma} \\right) \\vert \\Phi_0\\rangle \\\\\n&= \\frac{1}{2\\Omega} \\sum_{\\sigma \\sigma'} \\sum_{\\mathbf{k} \\mathbf{p} \\mathbf{q}} \\left[ \\int v(r) \\exp{-i (\\mathbf{q} \\cdot \\mathbf{r})} d\\mathbf{r} \\right]\\langle \\Phi_0\\vert a_{\\mathbf{k} + \\mathbf{q}, \\sigma}^\\dagger a_{\\mathbf{p} - \\mathbf{q}, \\sigma'}^\\dagger a_{\\mathbf{p} \\sigma'} a_{\\mathbf{k} \\sigma} \\vert \\Phi_0\\rangle .\n\\end{align*}\n$$\n\nThe only contractions which result in non-zero results are those that involve states below the Fermi level, that is \n$k \\leq k_F$, $p \\leq k_F$, $|\\mathbf{p} - \\mathbf{q}| < \\mathbf{k}_F$ and $|\\mathbf{k} + \\mathbf{q}| \\leq k_F$. Due to momentum conservation we must also have $\\mathbf{k} + \\mathbf{q} = \\mathbf{p}$, $\\mathbf{p} - \\mathbf{q} = \\mathbf{k}$ and $\\sigma = \\sigma'$ or $\\mathbf{k} + \\mathbf{q} = \\mathbf{k}$ and $\\mathbf{p} - \\mathbf{q} = \\mathbf{p}$. \nSummarizing, we must have\n\n$$\n\\mathbf{k} + \\mathbf{q} = \\mathbf{p} \\quad \\text{and} \\quad \\sigma = \\sigma', \\qquad\n\\text{or} \\qquad\n\\mathbf{q} = \\mathbf{0} .\n$$\n\nWe obtain then\n\n$$\n\\langle \\Phi_0\\vert \\hat{V} \\vert \\Phi_0\\rangle =\n\\frac{1}{2\\Omega} \\left( \\sum_{\\sigma \\sigma'} \\sum_{\\mathbf{q} \\mathbf{p} \\leq F} \\left[ \\int v(r) d\\mathbf{r} \\right] - \\sum_{\\sigma}\n\\sum_{\\mathbf{q} \\mathbf{p} \\leq F} \\left[ \\int v(r) \\exp{-i (\\mathbf{q} \\cdot \\mathbf{r})} d\\mathbf{r} \\right] \\right).\n$$\n\nThe first term is the so-called direct term while the second term is the exchange term. \nWe can rewrite this equation as (and this applies to any potential which depends only on the relative distance between particles)\n\n\n
\n\n$$\n\\begin{equation}\n\\langle \\Phi_0\\vert \\hat{V} \\vert \\Phi_0\\rangle =\n\\frac{1}{2\\Omega} \\left( N^2 \\left[ \\int v(r) d\\mathbf{r} \\right] - N \\sum_{\\mathbf{q}} \\left[ \\int v(r) \\exp{-i (\\mathbf{q}\\cdot \\mathbf{r})} d\\mathbf{r} \\right] \\right),\n\\label{eq:V_b} \\tag{11}\n\\end{equation}\n$$\n\nwhere we have used the fact that a sum like $\\sum_{\\sigma}\\sum_{\\mathbf{k}}$ equals the number of particles. Using the fact that the density is given by\n$\\rho = N/\\Omega$, with $\\Omega$ being our volume, we can rewrite the last equation as\n\n$$\n\\langle \\Phi_0\\vert \\hat{V} \\vert \\Phi_0\\rangle =\n\\frac{1}{2} \\left( \\rho N \\left[ \\int v(r) d\\mathbf{r} \\right] - \\rho\\sum_{\\mathbf{q}} \\left[ \\int v(r) \\exp{-i (\\mathbf{q}\\cdot \\mathbf{r})} d\\mathbf{r} \\right] \\right).\n$$\n\nFor the electron gas\nthe interaction part of the Hamiltonian operator is given by\n\n$$\n\\hat{H}_I=\\hat{H}_{el}+\\hat{H}_{b}+\\hat{H}_{el-b},\n$$\n\nwith the electronic part\n\n$$\n\\hat{H}_{el}=\\sum_{i=1}^N\\frac{p_i^2}{2m}+\\frac{e^2}{2}\\sum_{i\\ne j}\\frac{e^{-\\mu |\\mathbf{r}_i-\\mathbf{r}_j|}}{|\\mathbf{r}_i-\\mathbf{r}_j|},\n$$\n\nwhere we have introduced an explicit convergence factor\n(the limit $\\mu\\rightarrow 0$ is performed after having calculated the various integrals).\nCorrespondingly, we have\n\n$$\n\\hat{H}_{b}=\\frac{e^2}{2}\\int\\int d\\mathbf{r}d\\mathbf{r}'\\frac{n(\\mathbf{r})n(\\mathbf{r}')e^{-\\mu |\\mathbf{r}-\\mathbf{r}'|}}{|\\mathbf{r}-\\mathbf{r}'|},\n$$\n\nwhich is the energy contribution from the positive background charge with density\n$n(\\mathbf{r})=N/\\Omega$. Finally,\n\n$$\n\\hat{H}_{el-b}=-\\frac{e^2}{2}\\sum_{i=1}^N\\int d\\mathbf{r}\\frac{n(\\mathbf{r})e^{-\\mu |\\mathbf{r}-\\mathbf{x}_i|}}{|\\mathbf{r}-\\mathbf{x}_i|},\n$$\n\nis the interaction between the electrons and the positive background.\nWe can show that\n\n$$\n\\hat{H}_{b}=\\frac{e^2}{2}\\frac{N^2}{\\Omega}\\frac{4\\pi}{\\mu^2},\n$$\n\nand\n\n$$\n\\hat{H}_{el-b}=-e^2\\frac{N^2}{\\Omega}\\frac{4\\pi}{\\mu^2}.\n$$\n\nFor the electron gas and a Coulomb interaction, these two terms are cancelled (in the thermodynamic limit) by the contribution from the direct term arising\nfrom the repulsive electron-electron interaction. What remains then when computing the reference energy is only the kinetic energy contribution and the contribution from the exchange term. For other interactions, like nuclear forces with a short range part and no infinite range, we need to compute both the direct term and the exchange term.\n\n\n\n**c)**\nShow thereafter that the final Hamiltonian can be written as\n\n$$\nH=H_{0}+H_{I},\n$$\n\nwith\n\n$$\nH_{0}={\\displaystyle\\sum_{\\mathbf{k}\\sigma}}\n\\frac{\\hbar^{2}k^{2}}{2m}a_{\\mathbf{k}\\sigma}^{\\dagger}\na_{\\mathbf{k}\\sigma},\n$$\n\nand\n\n$$\nH_{I}=\\frac{e^{2}}{2\\Omega}{\\displaystyle\\sum_{\\sigma_{1}\\sigma_{2}}}{\\displaystyle\\sum_{\\mathbf{q}\\neq 0,\\mathbf{k},\\mathbf{p}}}\\frac{4\\pi}{q^{2}}\na_{\\mathbf{k}+\\mathbf{q},\\sigma_{1}}^{\\dagger}\na_{\\mathbf{p}-\\mathbf{q},\\sigma_{2}}^{\\dagger}\na_{\\mathbf{p}\\sigma_{2}}a_{\\mathbf{k}\\sigma_{1}}.\n$$\n\n**d)**\nCalculate $E_0/N=\\langle \\Phi_{0}\\vert H\\vert \\Phi_{0}\\rangle/N$ for for this system to first order in the interaction. Show that, by using\n\n$$\n\\rho= \\frac{k_F^3}{3\\pi^2}=\\frac{3}{4\\pi r_0^3},\n$$\n\nwith $\\rho=N/\\Omega$, $r_0$\nbeing the radius of a sphere representing the volume an electron occupies \nand the Bohr radius $a_0=\\hbar^2/e^2m$, \nthat the energy per electron can be written as\n\n$$\nE_0/N=\\frac{e^2}{2a_0}\\left[\\frac{2.21}{r_s^2}-\\frac{0.916}{r_s}\\right].\n$$\n\nHere we have defined\n$r_s=r_0/a_0$ to be a dimensionless quantity.\n\n**e)**\nPlot your results. Why is this system stable?\nCalculate thermodynamical quantities like the pressure, given by\n\n$$\nP=-\\left(\\frac{\\partial E}{\\partial \\Omega}\\right)_N,\n$$\n\nand the bulk modulus\n\n$$\nB=-\\Omega\\left(\\frac{\\partial P}{\\partial \\Omega}\\right)_N,\n$$\n\nand comment your results.\n\n\n\n\n\n\n\n\n## Preparing the ground for numerical calculations; kinetic energy and Ewald term\n\nThe kinetic energy operator is\n\n\n
\n\n$$\n\\begin{equation}\n \\hat{H}_{\\text{kin}} = -\\frac{\\hbar^{2}}{2m}\\sum_{i=1}^{N}\\nabla_{i}^{2},\n\\label{_auto9} \\tag{12}\n\\end{equation}\n$$\n\nwhere the sum is taken over all particles in the finite\nbox. The Ewald electron-electron interaction operator \ncan be written as\n\n\n
\n\n$$\n\\begin{equation}\n \\hat{H}_{ee} = \\sum_{i < j}^{N} v_{E}\\left( \\mathbf{r}_{i}-\\mathbf{r}_{j}\\right)\n + \\frac{1}{2}Nv_{0},\n\\label{_auto10} \\tag{13}\n\\end{equation}\n$$\n\nwhere $v_{E}(\\mathbf{r})$ is the effective two-body \ninteraction and $v_{0}$ is the self-interaction, defined \nas $v_{0} = \\lim_{\\mathbf{r} \\rightarrow 0} \\left\\{ v_{E}(\\mathbf{r}) - 1/r\\right\\} $. \n\nThe negative \nelectron charges are neutralized by a positive, homogeneous \nbackground charge. Fraser *et al.* explain how the\nelectron-background and background-background terms, \n$\\hat{H}_{eb}$ and $\\hat{H}_{bb}$, vanish\nwhen using Ewald's interaction for the three-dimensional\nelectron gas. Using the same arguments, one can show that\nthese terms are also zero in the corresponding \ntwo-dimensional system. \n\n\n\n\n## Ewald correction term\n\nIn the three-dimensional electron gas, the Ewald \ninteraction is\n\n$$\nv_{E}(\\mathbf{r}) = \\sum_{\\mathbf{k} \\neq \\mathbf{0}}\n \\frac{4\\pi }{L^{3}k^{2}}e^{i\\mathbf{k}\\cdot \\mathbf{r}}\n e^{-\\eta^{2}k^{2}/4} \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n + \\sum_{\\mathbf{R}}\\frac{1}{\\left| \\mathbf{r}\n -\\mathbf{R}\\right| } \\mathrm{erfc} \\left( \\frac{\\left| \n \\mathbf{r}-\\mathbf{R}\\right|}{\\eta }\\right)\n - \\frac{\\pi \\eta^{2}}{L^{3}},\n\\label{_auto11} \\tag{14}\n\\end{equation}\n$$\n\nwhere $L$ is the box side length, $\\mathrm{erfc}(x)$ is the \ncomplementary error function, and $\\eta $ is a free\nparameter that can take any value in the interval \n$(0, \\infty )$.\n\n\n\n## Interaction in momentum space\n\nThe translational vector\n\n\n
\n\n$$\n\\begin{equation}\n \\mathbf{R} = L\\left(n_{x}\\mathbf{u}_{x} + n_{y}\n \\mathbf{u}_{y} + n_{z}\\mathbf{u}_{z}\\right) ,\n\\label{_auto12} \\tag{15}\n\\end{equation}\n$$\n\nwhere $\\mathbf{u}_{i}$ is the unit vector for dimension $i$,\nis defined for all integers $n_{x}$, $n_{y}$, and \n$n_{z}$. These vectors are used to obtain all image\ncells in the entire real space. \nThe parameter $\\eta $ decides how \nthe Coulomb interaction is divided into a short-ranged\nand long-ranged part, and does not alter the total\nfunction. However, the number of operations needed\nto calculate the Ewald interaction with a desired \naccuracy depends on $\\eta $, and $\\eta $ is therefore \noften chosen to optimize the convergence as a function\nof the simulation-cell size. In\nour calculations, we choose $\\eta $ to be an infinitesimally\nsmall positive number, similarly as was done by [Shepherd *et al.*](https://journals.aps.org/prb/abstract/10.1103/PhysRevB.86.035111) and [Roggero *et al.*](https://journals.aps.org/prb/abstract/10.1103/PhysRevB.88.115138).\n\nThis gives an interaction that is evaluated only in\nFourier space. \n\nWhen studying the two-dimensional electron gas, we\nuse an Ewald interaction that is quasi two-dimensional.\nThe interaction is derived in three dimensions, with \nFourier discretization in only two dimensions. The Ewald effective\ninteraction has the form\n\n$$\nv_{E}(\\mathbf{r}) = \\sum_{\\mathbf{k} \\neq \\mathbf{0}} \n \\frac{\\pi }{L^{2}k}\\left\\{ e^{-kz} \\mathrm{erfc} \\left(\n \\frac{\\eta k}{2} - \\frac{z}{\\eta }\\right)+ \\right. \\nonumber\n$$\n\n$$\n\\left. e^{kz}\\mathrm{erfc} \\left( \\frac{\\eta k}{2} + \\frac{z}{\\eta }\n \\right) \\right\\} e^{i\\mathbf{k}\\cdot \\mathbf{r}_{xy}} \n \\nonumber\n$$\n\n$$\n+ \\sum_{\\mathbf{R}}\\frac{1}{\\left| \\mathbf{r}-\\mathbf{R}\n \\right| } \\mathrm{erfc} \\left( \\frac{\\left| \\mathbf{r}-\\mathbf{R}\n \\right|}{\\eta }\\right) \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n - \\frac{2\\pi}{L^{2}}\\left\\{ z\\mathrm{erf} \\left( \\frac{z}{\\eta }\n \\right) + \\frac{\\eta }{\\sqrt{\\pi }}e^{-z^{2}/\\eta^{2}}\\right\\},\n\\label{_auto13} \\tag{16}\n\\end{equation}\n$$\n\nwhere the Fourier vectors $\\mathbf{k}$ and the position vector\n$\\mathbf{r}_{xy}$ are defined in the $(x,y)$ plane. When\napplying the interaction $v_{E}(\\mathbf{r})$ to two-dimensional\nsystems, we set $z$ to zero. \n\n\nSimilarly as in the \nthree-dimensional case, also here we \nchoose $\\eta $ to approach zero from above. The resulting \nFourier-transformed interaction is\n\n\n
\n\n$$\n\\begin{equation}\n v_{E}^{\\eta = 0, z = 0}(\\mathbf{r}) = \\sum_{\\mathbf{k} \\neq \\mathbf{0}} \n \\frac{2\\pi }{L^{2}k}e^{i\\mathbf{k}\\cdot \\mathbf{r}_{xy}}. \n\\label{_auto14} \\tag{17}\n\\end{equation}\n$$\n\nThe self-interaction $v_{0}$ is a constant that can be \nincluded in the reference energy.\n\n\n\n\n## Antisymmetrized matrix elements in three dimensions\n\nIn the three-dimensional electron gas, the antisymmetrized\nmatrix elements are\n\n\n
\n\n$$\n\\label{eq:vmat_3dheg} \\tag{18}\n \\langle \\mathbf{k}_{p}m_{s_{p}}\\mathbf{k}_{q}m_{s_{q}}\n |\\tilde{v}|\\mathbf{k}_{r}m_{s_{r}}\\mathbf{k}_{s}m_{s_{s}}\\rangle_{AS} \n \\nonumber\n$$\n\n$$\n= \\frac{4\\pi }{L^{3}}\\delta_{\\mathbf{k}_{p}+\\mathbf{k}_{q},\n \\mathbf{k}_{r}+\\mathbf{k}_{s}}\\left\\{ \n \\delta_{m_{s_{p}}m_{s_{r}}}\\delta_{m_{s_{q}}m_{s_{s}}}\n \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{r}}\\right) \n \\frac{1}{|\\mathbf{k}_{r}-\\mathbf{k}_{p}|^{2}}\n \\right. \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n \\left. - \\delta_{m_{s_{p}}m_{s_{s}}}\\delta_{m_{s_{q}}m_{s_{r}}}\n \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{s}} \\right)\n \\frac{1}{|\\mathbf{k}_{s}-\\mathbf{k}_{p}|^{2}} \n \\right\\} ,\n\\label{_auto15} \\tag{19}\n\\end{equation}\n$$\n\nwhere the Kronecker delta functions \n$\\delta_{\\mathbf{k}_{p}\\mathbf{k}_{r}}$ and\n$\\delta_{\\mathbf{k}_{p}\\mathbf{k}_{s}}$ ensure that the \ncontribution with zero momentum transfer vanishes.\n\n\nSimilarly, the matrix elements for the two-dimensional\nelectron gas are\n\n\n
\n\n$$\n\\label{eq:vmat_2dheg} \\tag{20}\n \\langle \\mathbf{k}_{p}m_{s_{p}}\\mathbf{k}_{q}m_{s_{q}}\n |v|\\mathbf{k}_{r}m_{s_{r}}\\mathbf{k}_{s}m_{s_{s}}\\rangle_{AS} \n \\nonumber\n$$\n\n$$\n= \\frac{2\\pi }{L^{2}}\n \\delta_{\\mathbf{k}_{p}+\\mathbf{k}_{q},\\mathbf{k}_{r}+\\mathbf{k}_{s}}\n \\left\\{ \\delta_{m_{s_{p}}m_{s_{r}}}\\delta_{m_{s_{q}}m_{s_{s}}} \n \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{r}}\\right)\n \\frac{1}{\n |\\mathbf{k}_{r}-\\mathbf{k}_{p}|} \\right.\n \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n - \\left. \\delta_{m_{s_{p}}m_{s_{s}}}\\delta_{m_{s_{q}}m_{s_{r}}}\n \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{s}}\\right)\n \\frac{1}{ \n |\\mathbf{k}_{s}-\\mathbf{k}_{p}|}\n \\right\\} ,\n\\label{_auto16} \\tag{21}\n\\end{equation}\n$$\n\nwhere the single-particle momentum vectors $\\mathbf{k}_{p,q,r,s}$\nare now defined in two dimensions.\n\nIn actual calculations, the \nsingle-particle energies, defined by the operator $\\hat{f}$, are given by\n\n\n
\n\n$$\n\\begin{equation}\n \\langle \\mathbf{k}_{p}|f|\\mathbf{k}_{q} \\rangle\n = \\frac{\\hbar^{2}k_{p}^{2}}{2m}\\delta_{\\mathbf{k}_{p},\n \\mathbf{k}_{q}} + \\sum_{\\mathbf{k}_{i}}\\langle \n \\mathbf{k}_{p}\\mathbf{k}_{i}|v|\\mathbf{k}_{q}\n \\mathbf{k}_{i}\\rangle_{AS}.\n\\label{eq:fock_heg} \\tag{22}\n\\end{equation}\n$$\n\n## Periodic boundary conditions and single-particle states\n\nWhen using periodic boundary conditions, the \ndiscrete-momentum single-particle basis functions\n\n$$\n\\phi_{\\mathbf{k}}(\\mathbf{r}) =\ne^{i\\mathbf{k}\\cdot \\mathbf{r}}/L^{d/2}\n$$\n\nare associated with \nthe single-particle energy\n\n\n
\n\n$$\n\\begin{equation}\n \\varepsilon_{n_{x}, n_{y}} = \\frac{\\hbar^{2}}{2m} \\left( \\frac{2\\pi }{L}\\right)^{2}\\left( n_{x}^{2} + n_{y}^{2}\\right)\n\\label{_auto17} \\tag{23}\n\\end{equation}\n$$\n\nfor two-dimensional sytems and\n\n\n
\n\n$$\n\\begin{equation}\n \\varepsilon_{n_{x}, n_{y}, n_{z}} = \\frac{\\hbar^{2}}{2m}\n \\left( \\frac{2\\pi }{L}\\right)^{2}\n \\left( n_{x}^{2} + n_{y}^{2} + n_{z}^{2}\\right)\n\\label{_auto18} \\tag{24}\n\\end{equation}\n$$\n\nfor three-dimensional systems.\n\n\nWe choose the single-particle basis such that both the occupied and \nunoccupied single-particle spaces have a closed-shell \nstructure. This means that all single-particle states \ncorresponding to energies below a chosen cutoff are\nincluded in the basis. We study only the unpolarized spin\nphase, in which all orbitals are occupied with one spin-up \nand one spin-down electron. \n\n\nThe table illustrates how single-particle energies\n fill energy shells in a two-dimensional electron box.\n Here $n_{x}$ and $n_{y}$ are the momentum quantum numbers,\n $n_{x}^{2} + n_{y}^{2}$ determines the single-particle \n energy level, $N_{\\uparrow \\downarrow }$ represents the \n cumulated number of spin-orbitals in an unpolarized spin\n phase, and $N_{\\uparrow \\uparrow }$ stands for the\n cumulated number of spin-orbitals in a spin-polarized\n system.\n\n\n\n\n## Magic numbers for the two-dimensional electron gas\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_{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## Hartree-Fock energies\n\nFinally, a useful benchmark for our calculations is the expression for\nthe reference energy $E_0$ per particle.\nDefining the $T=0$ density $\\rho_0$, we can in turn determine in three\ndimensions the radius $r_0$ of a sphere representing the volume an\nelectron occupies (the classical electron radius) as\n\n$$\nr_0= \\left(\\frac{3}{4\\pi \\rho}\\right)^{1/3}.\n$$\n\nIn two dimensions the corresponding quantity is\n\n$$\nr_0= \\left(\\frac{1}{\\pi \\rho}\\right)^{1/2}.\n$$\n\nOne can then express the reference energy per electron in terms of the\ndimensionless quantity $r_s=r_0/a_0$, where we have introduced the\nBohr radius $a_0=\\hbar^2/e^2m$. The energy per electron computed with\nthe reference Slater determinant can then be written as\n(using hereafter only atomic units, meaning that $\\hbar = m = e = 1$)\n\n$$\ng\nE_0/N=\\frac{1}{2}\\left[\\frac{2.21}{r_s^2}-\\frac{0.916}{r_s}\\right],\n$$\n\nfor the three-dimensional electron gas. For the two-dimensional gas\nthe corresponding expression is (show this)\n\n$$\nE_0/N=\\frac{1}{r_s^2}-\\frac{8\\sqrt{2}}{3\\pi r_s}.a\n$$\n\nFor an infinite homogeneous system, there are some particular\nsimplications due to the conservation of the total momentum of the\nparticles. By symmetry considerations, the total momentum of the\nsystem has to be zero. Both the kinetic energy operator and the\ntotal Hamiltonian $\\hat{H}$ are assumed to be diagonal in the total\nmomentum $\\mathbf{K}$. Hence, both the reference state $\\Phi_{0}$ and\nthe correlated ground state $\\Psi$ must be eigenfunctions of the\noperator $\\mathbf{\\hat{K}}$ with the corresponding eigemnvalue\n$\\mathbf{K} = \\mathbf{0}$. This leads to important\nsimplications to our different many-body methods. In coupled cluster\ntheory for example, all\nterms that involve single particle-hole excitations vanish. \n\n\n\n\n\n## Exercise 3: Magic numbers for the three-dimensional electron gas and perturbation theory to second order\n\n\n**a)**\nSet up the possible magic numbers for the electron gas in three dimensions using periodic boundary conditions..\n\n\n\n**Hint.**\nFollow the example for the two-dimensional electron gas and add the third dimension via the quantum number $n_z$.\n\n\n\n\n\n**Solution.**\nUsing the same approach as made with the two-dimensional electron gas with the single-particle kinetic energy defined as\n\n$$\n\\frac{\\hbar^2}{2m}\\left(k_{n_x}^2+k_{n_y}^2k_{n_z}^2\\right),\n$$\n\nand\n\n$$\nk_{n_i}=\\frac{2\\pi n_i}{L} \\hspace{0.1cm} n_i = 0, \\pm 1, \\pm 2, \\dots,\n$$\n\nwe can set up a similar table and obtain (assuming identical particles one and including spin up and spin down solutions) for energies less than or equal to $n_{x}^{2}+n_{y}^{2}+n_{z}^{2}\\le 3$\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_{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
\nContinuing in this way we get for $n_{x}^{2}+n_{y}^{2}+n_{z}^{2}=4$ a total of 22 additional states, resulting in $76$ as a new magic number. For the lowest six energy values the degeneracy in energy gives us $2$, $14$, $38$, $54$, $76$ and $114$ as magic numbers. These numbers will then define our Fermi level when we compute the energy in a Cartesian basis. When performing calculations based on many-body perturbation theory, Coupled cluster theory or other many-body methods, we need then to add states above the Fermi level in order to sum over single-particle states which are not occupied. \n\nIf we wish to study infinite nuclear matter with both protons and neutrons, the above magic numbers become $4, 28, 76, 108, 132, 228, \\dots$.\n\n\n\n**b)**\nEvery number of particles for filled shells defines also the number of particles to be used in a given calculation. Use the number of particles to define the density of the system\n\n$$\n\\rho = g \\frac{k_F^3}{6\\pi^2},\n$$\n\nwhere you need to define $k_F$ and the degeneracy $g$, which is two for one type of spin-$1/2$ particles and four for symmetric nuclear matter.\n\n**c)**\nUse the density to find the length $L$ of the box used with periodic boundary contributions, that is use the relation\n\n$$\nV= L^3= \\frac{A}{\\rho}.\n$$\n\nYou can use $L$ to define the spacing to set up the spacing between varipus $k$-values, that is\n\n$$\n\\Delta k = \\frac{2\\pi}{L}.\n$$\n\nHere, $A$ can be the number of nucleons. If we deal with the electron gas only, this needs to be replaced by the number of electrons $N$.\n\n\n\n\n\n\n\n\n## Exercise 4: Quantum numbers for the electron gas in 3d\n\n\n**a)**\nSet up the quantum numbers for 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 =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\n\n**b)**\nCompute now the contribution to the correlation energy for the electron gas at the level of second-order perturbation theory using a given number of electrons $N$ and a given (defined by you) number of single-particle states above the Fermi level.\nThe following Python code shows an implementation for the electron gas in three dimensions for second perturbation theory using the Coulomb interaction. Here we have hard-coded a case which computes the energy for $N=14$ and a total of $5$ major shells.\n\n\n\n**Solution.**\n\n\n```\nfrom numpy import *\n\nclass electronbasis():\n def __init__(self, N, rs, Nparticles):\n ############################################################\n ##\n ## Initialize basis: \n ## N = number of shells\n ## rs = parameter for volume \n ## Nparticles = Number of holes (conflicting naming, sorry)\n ##\n ###########################################################\n \n self.rs = rs\n self.states = []\n self.nstates = 0\n self.nparticles = Nparticles\n self.nshells = N - 1\n self.Nm = N + 1\n \n self.k_step = 2*(self.Nm + 1)\n Nm = N\n n = 0 #current shell\n ene_integer = 0\n while n <= self.nshells:\n is_shell = False\n for x in range(-Nm, Nm+1):\n for y in range(-Nm, Nm+1):\n for z in range(-Nm,Nm+1):\n e = x*x + y*y + z*z\n if e == ene_integer:\n is_shell = True\n self.nstates += 2\n self.states.append([e, x,y,z,1])\n self.states.append([e, x,y,z, -1])\n \n if is_shell:\n n += 1\n ene_integer += 1\n self.L3 = (4*pi*self.nparticles*self.rs**3)/3.0\n self.L2 = self.L3**(2/3.0)\n self.L = pow(self.L3, 1/3.0)\n \n for i in range(self.nstates):\n self.states[i][0] *= 2*(pi**2)/self.L**2 #Multiplying in the missing factors in the single particle energy\n self.states = array(self.states) #converting to array to utilize vectorized calculations \n \n def hfenergy(self, nParticles):\n #Calculate the HF-energy (reference energy) for nParticles particles\n e0 = 0.0\n if nParticles<=self.nstates:\n for i in range(nParticles):\n e0 += self.h(i,i)\n for j in range(nParticles):\n if j != i:\n e0 += .5*self.v(i,j,i,j)\n else:\n #Safety for cases where nParticles exceeds size of basis\n print(\"Not enough basis states.\")\n \n return e0\n \n def h(self, p,q):\n #Return single particle energy\n return self.states[p,0]*(p==q)\n\n \n def v(self,p,q,r,s):\n #Two body interaction for electron gas\n val = 0\n terms = 0.0\n term1 = 0.0\n term2 = 0.0\n kdpl = self.kdplus(p,q,r,s)\n if kdpl != 0:\n val = 1.0/self.L3\n if self.kdspin(p,r)*self.kdspin(q,s)==1:\n if self.kdwave(p,r) != 1.0:\n term1 = self.L2/(pi*self.absdiff2(r,p))\n if self.kdspin(p,s)*self.kdspin(q,r)==1:\n if self.kdwave(p,s) != 1.0:\n term2 = self.L2/(pi*self.absdiff2(s,p))\n return val*(term1-term2)\n\n \n #The following is a series of kroenecker deltas used in the two-body interactions. \n #Just ignore these lines unless you suspect an error here\n def kdi(self,a,b):\n #Kroenecker delta integer\n return 1.0*(a==b)\n def kda(self,a,b):\n #Kroenecker delta array\n d = 1.0\n for i in range(len(a)):\n d*=(a[i]==b[i])\n return d\n def kdfullplus(self,p,q,r,s):\n #Kroenecker delta wavenumber p+q,r+s\n return self.kda(self.states[p][1:5]+self.states[q][1:5],self.states[r][1:5]+self.states[s][1:5])\n def kdplus(self,p,q,r,s):\n #Kroenecker delta wavenumber p+q,r+s\n return self.kda(self.states[p][1:4]+self.states[q][1:4],self.states[r][1:4]+self.states[s][1:4])\n def kdspin(self,p,q):\n #Kroenecker delta spin\n return self.kdi(self.states[p][4], self.states[q][4])\n def kdwave(self,p,q):\n #Kroenecker delta wavenumber\n return self.kda(self.states[p][1:4],self.states[q][1:4])\n def absdiff2(self,p,q):\n val = 0.0\n for i in range(1,4):\n val += (self.states[p][i]-self.states[q][i])*(self.states[p][i]-self.states[q][i])\n return val\n\n \ndef MBPT2(bs):\n #2. order MBPT Energy \n Nh = bs.nparticles\n Np = bs.nstates-bs.nparticles #Note the conflicting notation here. bs.nparticles is number of hole states \n vhhpp = zeros((Nh**2, Np**2))\n vpphh = zeros((Np**2, Nh**2))\n #manual MBPT(2) energy (Should be -0.525588309385 for 66 states, shells = 5, in this code)\n psum2 = 0\n for i in range(Nh):\n for j in range(Nh):\n for a in range(Np):\n for b in range(Np):\n #val1 = bs.v(i,j,a+Nh,b+Nh)\n #val2 = bs.v(a+Nh,b+Nh,i,j)\n vhhpp[i + j*Nh, a+b*Np] = bs.v(i,j,a+Nh,b+Nh)\n vpphh[a+b*Np,i + j*Nh] = bs.v(a+Nh,b+Nh,i,j)/(bs.states[i,0] + bs.states[j,0] - bs.states[a + Nh, 0] - bs.states[b+Nh,0])\n psum = .25*sum(dot(vhhpp,vpphh).diagonal())\n return psum\n \ndef MBPT2_fast(bs):\n #2. order MBPT Energy \n Nh = bs.nparticles\n Np = bs.nstates-bs.nparticles #Note the conflicting notation here. bs.nparticles is number of hole states \n vhhpp = zeros((Nh**2, Np**2))\n vpphh = zeros((Np**2, Nh**2))\n #manual MBPT(2) energy (Should be -0.525588309385 for 66 states, shells = 5, in this code)\n psum2 = 0\n for i in range(Nh):\n for j in range(i):\n for a in range(Np):\n for b in range(a):\n val = bs.v(i,j,a+Nh,b+Nh)\n eps = val/(bs.states[i,0] + bs.states[j,0] - bs.states[a + Nh, 0] - bs.states[b+Nh,0])\n vhhpp[i + j*Nh, a+b*Np] = val \n vhhpp[j + i*Nh, a+b*Np] = -val \n vhhpp[i + j*Nh, b+a*Np] = -val\n vhhpp[j + i*Nh, b+a*Np] = val \n \n \n vpphh[a+b*Np,i + j*Nh] = eps\n vpphh[a+b*Np,j + i*Nh] = -eps\n vpphh[b+a*Np,i + j*Nh] = -eps\n vpphh[b+a*Np,j + i*Nh] = eps\n \n \n psum = .25*sum(dot(vhhpp,vpphh).diagonal())\n return psum\n\n\n#user input here\nnumber_of_shells = 5\nnumber_of_holes = 14 #(particles)\n\n\n#initialize basis \nbs = electronbasis(number_of_shells,1.0,number_of_holes) #shells, r_s = 1.0, holes\n\n#Print some info to screen\nprint (\"Number of shells:\", number_of_shells)\nprint (\"Number of states:\", bs.nstates)\nprint (\"Number of holes :\", bs.nparticles)\nprint (\"Reference Energy:\", bs.hfenergy(number_of_holes), \"hartrees \")\nprint (\" :\", 2*bs.hfenergy(number_of_holes), \"rydbergs \")\n\nprint (\"Ref.E. per hole :\", bs.hfenergy(number_of_holes)/number_of_holes, \"hartrees \")\nprint (\" :\", 2*bs.hfenergy(number_of_holes)/number_of_holes, \"rydbergs \")\n\n\n\n#calculate MBPT2 energy\nprint (\"MBPT2 energy :\", MBPT2_fast(bs), \" hartrees\")\n```\n\nAs we will see later, for the infinite electron gas, second-order perturbation theory diverges in the thermodynamical limit, a feature which can easily be noted if one lets the number of single-particle states above the Fermi level to increase. The resulting expression in a Cartesian basis will not converge.\n\n\n\n\n\n\n\n\n\n## Infinite nuclear matter and neutron star matter\n\nStudies of dense baryonic matter are of central importance to our basic understanding \nof the stability of nuclear matter, spanning from matter at high densities and temperatures\nto matter as found within dense astronomical objects like neutron stars. \n\nNeutron star matter\nat densities of 0.1 fm$^{-3}$ and greater, is often assumed to \nbe made of mainly neutrons, protons, electrons and \nmuons in beta equilibrium. However, other baryons like various hyperons may exist, as well as possible mesonic condensates and transitions to quark degrees of freedom at higher densities. \nHere we focus on specific definitions of various phases and focus \non distinct phases of matter such as pure baryonic\nmatter and/or quark matter.\nThe composition of matter is then \ndetermined by the requirements of chemical and electrical equilibrium.\nFurthermore, we will also consider matter at temperatures much lower\nthan the typical Fermi energies.\nThe equilibrium conditions are governed by the weak processes \n(normally referred to as the processes\nfor $\\beta$-equilibrium)\n\n\n
\n\n$$\n\\begin{equation} \n b_1 \\rightarrow b_2 + l +\\bar{\\nu}_l \\hspace{1cm} b_2 +l \\rightarrow b_1 \n+\\nu_l,\n\\label{eq:betadecay} \\tag{25}\n\\end{equation}\n$$\n\nwhere $b_1$ and $b_2$ refer to e.g.\\ the baryons being a neutron and a proton, \nrespectively, \n$l$ is either an electron or a muon and $\\bar{\\nu}_l $\nand $\\nu_l$ their respective anti-neutrinos and neutrinos. Muons typically \nappear at\na density close to nuclear matter saturation density, the latter being\n\n$$\nn_0 \\approx 0.16 \\pm 0.02 \\hspace{1cm} \\mathrm{fm}^{-3},\n$$\n\nwith a corresponding binding energy ${\\cal E}_0$ \nfor symmetric nuclear matter (SNM) at saturation density of\n\n$$\n{\\cal E}_0 = B/A=-15.6\\pm 0.2 \\hspace{1cm} \\mathrm{MeV}.\n$$\n\nIn this work the energy per baryon ${\\cal E}$ will always be in units of MeV, \nwhile\nthe energy density $\\varepsilon$ will \nbe in units of MeVfm$^{-3}$ and the number density\\footnote{We will often \nloosely just use density in our discussions.}\n$n$ in units of fm$^{-3}$. The pressure $P$ is \ndefined through the relation\n\n\n
\n\n$$\n\\begin{equation}\n P=n^2\\frac{\\partial {\\cal E}}{\\partial n}=\n n\\frac{\\partial \\varepsilon}{\\partial n}-\\varepsilon,\n\\label{_auto19} \\tag{26}\n\\end{equation}\n$$\n\nwith \ndimension MeVfm$^{-3}$. \nSimilarly, the chemical potential for particle species $i$\nis given by\n\n\n
\n\n$$\n\\begin{equation}\n \\mu_i = \\left(\\frac{\\partial \\varepsilon}{\\partial n_i}\\right),\n\\label{eq:chemicalpotdef} \\tag{27}\n\\end{equation}\n$$\n\nwith dimension MeV.\nIn calculations of properties of neutron star matter in $\\beta$-equilibrium,\nwe will need to calculate the energy per baryon ${\\cal E}$ for e.g. several \nproton fractions $x_p$, which corresponds to\nthe ratio of protons as\ncompared to the total nucleon number ($Z/A$), \n defined as\n\n\n
\n\n$$\n\\begin{equation}\n x_p = \\frac{n_p}{n},\n\\label{_auto20} \\tag{28}\n\\end{equation}\n$$\n\nwhere $n=n_p+n_n$, the total baryonic density if neutrons and\nprotons are the only baryons present. In that case,\nthe total Fermi momentum $k_F$ and the Fermi momenta $k_{Fp}$,\n$k_{Fn}$ for protons and neutrons are related to the total nucleon density\n$n$ by\n\n$$\nn = \\frac{2}{3\\pi^2} k_F^3 \\nonumber\n$$\n\n$$\n= x_p n + (1-x_p) n \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n = \\frac{1}{3\\pi^2} k_{Fp}^3 + \\frac{1}{3\\pi^2} k_{Fn}^3.\n\\label{eq:densi} \\tag{29}\n\\end{equation}\n$$\n\nThe energy per baryon will thus be\nlabelled as ${\\cal E}(n,x_p)$.\n${\\cal E}(n,0)$ will then refer to the energy per baryon for pure neutron\nmatter (PNM) while ${\\cal E}(n,\\frac{1}{2})$ is the corresponding value for \nSNM. Furthermore, in this work, subscripts $n,p,e,\\mu$\nwill always refer to neutrons, protons, electrons and muons, respectively.\n\n\nSince the mean free path of a neutrino in a neutron star is bigger\nthan the typical radius of such a star ($\\sim 10$ km), \nwe will throughout assume that neutrinos escape freely from the neutron star,\nsee for example the work of Prakash et al.\nfor a discussion\non trapped neutrinos. Eq. ([eq:betadecay](#eq:betadecay)) yields then the following\nconditions for matter in $\\beta$ equilibrium with for example nucleonic degrees \nfreedom only\n\n\n
\n\n$$\n\\begin{equation}\n \\mu_n=\\mu_p+\\mu_e,\n\\label{eq:npebetaequilibrium} \\tag{30}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\n n_p = n_e,\n\\label{eq:chargeconserv} \\tag{31}\n\\end{equation}\n$$\n\nwhere $\\mu_i$ and $n_i$ refer to the chemical potential and number density\nin fm$^{-3}$ of particle species $i$. \nIf muons are present as well, we need to modify the equation for \ncharge conservation, Eq. ([eq:chargeconserv](#eq:chargeconserv)), to read\n\n$$\nn_p = n_e+n_{\\mu},\n$$\n\nand require that $\\mu_e = \\mu_{\\mu}$.\nWith more particles present, the equations read\n\n\n
\n\n$$\n\\begin{equation}\n \\sum_i\\left(n_{b_i}^+ +n_{l_i}^+\\right) = \n \\sum_i\\left(n_{b_i}^- +n_{l_i}^-\\right),\n\\label{eq:generalcharge} \\tag{32}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation} \n \\mu_n=b_i\\mu_i+q_i\\mu_l,\n\\label{eq:generalbeta} \\tag{33}\n\\end{equation}\n$$\n\nwhere $b_i$ is the baryon number, $q_i$ the lepton charge and the superscripts \n$(\\pm)$ on \nnumber densities $n$ represent particles with positive or negative charge.\nTo give an example, it is possible to have baryonic matter with hyperons like\n$\\Lambda$ \nand $\\Sigma^{-,0,+}$ and isobars $\\Delta^{-,0,+,++}$ as well in addition\nto the nucleonic degrees of freedom.\nIn this case the chemical equilibrium condition of Eq. ([eq:generalbeta](#eq:generalbeta)) \nbecomes,\nexcluding muons,\n\n$$\n\\mu_{\\Sigma^-} = \\mu_{\\Delta^-} = \\mu_n + \\mu_e , \\nonumber\n$$\n\n$$\n\\mu_{\\Lambda} = \\mu_{\\Sigma^0} = \\mu_{\\Delta^0} = \\mu_n , \\nonumber\n$$\n\n$$\n\\mu_{\\Sigma^+} = \\mu_{\\Delta^+} = \\mu_p = \\mu_n - \\mu_e ,\\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n \\mu_{\\Delta^{++}} = \\mu_n - 2 \\mu_e .\n\\label{eq:beta_baryonicmatter} \\tag{34}\n\\end{equation}\n$$\n\nA transition from hadronic to quark matter is expected at high densities. \nThe high-density quark matter phase\nin the interior of neutron stars is also described by\nrequiring the system to be locally neutral\n\n\n
\n\n$$\n\\begin{equation} \n\\label{eq:quarkneut} \\tag{35}\n (2/3)n_u -(1/3)n_d - (1/3)n_s - n_e = 0,\n\\end{equation}\n$$\n\nwhere $n_{u,d,s,e}$ \nare the densities of the $u$, $d$ and $s$ quarks and of the\nelectrons (eventually muons as well), respectively. \nMorover, the system must be in $\\beta$-equilibrium, i.e.\\ \nthe chemical potentials have to satisfy the following equations:\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:ud} \\tag{36}\n \\mu_d=\\mu_u+\\mu_e,\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:us} \\tag{37}\n \\mu_s=\\mu_u+\\mu_e .\n\\end{equation}\n$$\n\nEquations ([eq:quarkneut](#eq:quarkneut))-([eq:us](#eq:us)) have to be solved \nself-consistently together with the field equations for quarks \nat a fixed density $n=n_u+n_d+n_s$.\n\nAn important ingredient in the discussion of the EoS and the criteria for\nmatter in $\\beta$-equilibrium is the so-called symmetry energy ${\\cal S} (n)$, \ndefined as\nthe difference in energy for symmetric nuclear matter\nand pure neutron matter\n\n\n
\n\n$$\n\\begin{equation}\n {\\cal S} (n) = {\\cal E} (n,x_p=0) - {\\cal E} (n,x_p=1/2 ).\n\\label{eq:symenergy} \\tag{38}\n\\end{equation}\n$$\n\nIf we expand the energy per baryon in the case of nucleonic degrees of freedom \nonly\nin the proton concentration $x_p$ about the value of the energy \nfor SNM ($x_p=\\frac{1}{2}$), we obtain,\n\n\n
\n\n$$\n\\begin{equation}\n {\\cal E} (n,x_p)={\\cal E} (n,x_p=\\frac{1}{2})+\n \\frac{1}{2}\\frac{d^2 {\\cal E}}{dx_p^2} (n)\\left(x_p-1/2\\right)^2+\\dots ,\n\\label{eq:energyexpansion} \\tag{39}\n\\end{equation}\n$$\n\nwhere the term $d^2 {\\cal E}/dx_p^2$ \nis to be associated with the symmetry energy ${\\cal S} (n)$ in the empirical\nmass formula. If\nwe assume that higher order derivatives in the above expansion are small\n(we will see examples of this in the next subsection), then through the \nconditions\nfor $\\beta$-equilbrium of Eqs. ([eq:npebetaequilibrium](#eq:npebetaequilibrium)) and \n([eq:chargeconserv](#eq:chargeconserv))\nand Eq. ([eq:chemicalpotdef](#eq:chemicalpotdef)) we can define the proton\nfraction by the symmetry energy as\n\n\n
\n\n$$\n\\begin{equation} \n \\hbar c\\left(3\\pi^2nx_p\\right)^{1/3} = 4{\\cal S} (n)\\left(1-2x_p\\right),\n\\label{eq:crudeprotonfraction} \\tag{40}\n\\end{equation}\n$$\n\nwhere the electron chemical potential is given\nby $\\mu_e = \\hbar c k_F$, i.e.\\ ultrarelativistic electrons are assumed.\nThus, the symmetry energy is of paramount importance for studies \nof neutron star matter in $\\beta$-equilibrium.\nOne can extract information about the value of the symmetry energy at saturation \ndensity\n$n_0$ from systematic studies of the masses of atomic nuclei. However, these \nresults\nare limited to densities around $n_0$ and for proton fractions close to \n$\\frac{1}{2}$.\nTypical values for ${\\cal S} (n)$ at $n_0$ are in the range $27-38$ MeV.\nFor densities greater than $n_0$ it is more difficult to get a reliable \ninformation on the symmetry energy, and thereby the related proton fraction.\nWe will shed more light on this topic in the next subsection.\n\n\nFinally, another property of interest in the discussion of the various \nequations of state \nis the incompressibility modulus $K$ at non-zero pressure\n\n\n
\n\n$$\n\\begin{equation}\n K=9\\frac{\\partial P}{\\partial n}.\n\\label{eq:incompressibility} \\tag{41}\n\\end{equation}\n$$\n\nThe sound speed $v_s$ depends as well on the density\nof the nuclear medium through the relation\n\n\n
\n\n$$\n\\begin{equation}\n \\left(\\frac{v_s}{c}\\right)^2=\\frac{dP}{d\\varepsilon}=\n \\frac{dP}{dn}\\frac{dn}{d\\varepsilon}=\n \\left(\\frac{K}{9(m_nc^2+{\\cal E}+P/n)}\\right).\n\\label{eq:speedofsound} \\tag{42}\n\\end{equation}\n$$\n\nIt is important to keep track of the dependence on density of $v_s$\nsince a superluminal behavior can occur at higher densities for most\nnon-relativistic EoS.\nSuperluminal behavior would\nnot occur with a fully relativistic theory, and it is necessary to\ngauge the magnitude of the effect it introduces at the higher densities.\nThis will be discussed at the end of this section.\nThe adiabatic constant $\\Gamma$ can also be extracted from the EoS\nby\n\n\n
\n\n$$\n\\begin{equation}\n \\Gamma = \\frac{n}{P}\\frac{\\partial P}{\\partial n}.\n\\label{eq:adiabaticconstant} \\tag{43}\n\\end{equation}\n$$\n\n## Brueckner-Hartree-Fock theory\n\n\nThe Brueckner $G$-matrix has historically been an important ingredient\nin many-body calculations of nuclear systems. In this section, we will\nbriefly survey the philosophy behind the $G$-matrix.\n\nHistorically, the $G$-matrix was developed in microscopic nuclear\nmatter calculations using realistic nucleon-nucleon (NN) interactions.\nIt is an ingenuous as well as an interesting method to overcome the\ndifficulties caused by the strong, short-range repulsive core contained\nin all modern models for the NN interaction. The $G$-matrix method was\noriginally developed by Brueckner, and further\ndeveloped by Goldstone and Bethe, Brandow and Petschek. \nIn the literature it is generally referred to as the\nBrueckner theory or the Brueckner-Bethe-Goldstone theory.\n\nSuppose we want to calculate the nuclear matter ground-state\nenergy $E_0$ using the non-relativistic Schr\\\"{o}dinger equation\n\n\n
\n\n$$\n\\begin{equation}\n H\\Psi_0(A)=E_0(A)\\Psi_0(A),\n\\label{_auto21} \\tag{44}\n\\end{equation}\n$$\n\nwith $H=T+V$ where $A$ denotes the number of particles, $T$\nis the kinetic energy and $V$ is\nthe nucleon-nucleon\n(NN) potential. Models for the NN interaction are discussed in the chapter on nuclear forces.\nThe corresponding unperturbed\nproblem is\n\n\n
\n\n$$\n\\begin{equation}\n H_0\\psi_0(A)=W_0(A)\\psi_0(A).\n\\label{_auto22} \\tag{45}\n\\end{equation}\n$$\n\nHere $H_0$ is just kinetic energy $T$ and $\\psi_0$ is a Slater\ndeterminant representing the Fermi sea, where all orbits through the\nFermi momentum $k_F$ are filled. We write\n\n\n
\n\n$$\n\\begin{equation}\n E_0=W_0+\\Delta E_0,\n\\label{_auto23} \\tag{46}\n\\end{equation}\n$$\n\nwhere $\\Delta E_0$ is the ground-state energy shift or correlation energy as it was defined in many-body perturbation theory.\nIf we know how to calculate $\\Delta E_0$, then we know $E_0$, since\n$W_0$ is easily obtained. In the limit $A\\rightarrow \\infty$,\nthe quantities $E_0$ and $\\Delta E_0$ themselves are not well\ndefined, but the ratios $E_0/A$ and $\\Delta E_0/A$ are. The\nnuclear-matter binding energy per nucleon is commonly denoted\nby $BE/A$, which is just $-E_0/A$. In passing, we note that\nthe empirical value for symmetric nuclear matter (proton number\n$Z$=neutron number $N$) is $\\approx 16$ MeV.\nThere exists a formal theory for the calculation of $\\Delta E_0$.\nAccording to the well-known Goldstone linked-diagram theory, the energy shift $\\Delta E_0$ is given exactly by the\ndiagrammatic expansion shown in Fig. [fig:goldstone](#fig:goldstone). This theory,\nis a linked-cluster perturbation expansion for the ground state\nenergy of a many-body system, and applies equally well to both\nnuclear matter and closed-shell nuclei such as the doubly magic\nnucleus $^{40}$Ca. \nWe will not discuss the Goldstone expansion, but rather discuss\nbriefly how it is used in calculations.\n\n\n
\n\n

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\n

The 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\n

Single 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\n

Bayesian 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\n# Unic Cell Determination and Stereographic Projection\n\n[Download](https://raw.githubusercontent.com/gduscher/MSE672-Introduction-to-TEM//main/Diffraction/CH2_09-Unit_Cell.ipynb)\n \n[](\n https://colab.research.google.com/github/gduscher/MSE672-Introduction-to-TEM/blob/main/Diffraction/CH2_09-Unit_Cell.ipynb)\n\n\n\npart of \n\n **[MSE672: Introduction to Transmission Electron Microscopy](../_MSE672_Intro_TEM.ipynb)**\n\nby Gerd Duscher, Spring 2021\n\nMicroscopy Facilities
\nJoint Institute of Advanced Materials
\nMaterials Science & Engineering
\nThe University of Tennessee, Knoxville\n\nBackground and methods to analysis and quantification of data acquired with transmission electron microscopes\n\n\n## Load relevant python packages\n### Check Installed Packages\n\n\n```python\nimport sys\nfrom pkg_resources import get_distribution, DistributionNotFound\n\ndef test_package(package_name):\n \"\"\"Test if package exists and returns version or -1\"\"\"\n try:\n version = get_distribution(package_name).version\n except (DistributionNotFound, ImportError) as err:\n version = '-1'\n return version\n\n# Colab setup ------------------\nif 'google.colab' in sys.modules:\n !pip install pyTEMlib -q\n# pyTEMlib setup ------------------\nelse:\n if test_package('pyTEMlib') < '0.2021.3.17':\n print('installing pyTEMlib')\n !{sys.executable} -m pip install --upgrade pyTEMlib -q\n# ------------------------------\nprint('done')\n```\n\n installing pyTEMlib\n done\n\n\n WARNING: You are using pip version 21.0; however, version 21.0.1 is available.\n You should consider upgrading via the 'C:\\Users\\nosle\\anaconda3\\python.exe -m pip install --upgrade pip' command.\n\n\n## Import numerical and plotting python packages\nImport the python packages that we will use:\n\nBeside the basic numerical (numpy) and plotting (pylab of matplotlib) libraries,\n\nand some libraries from the book\n* kinematic scattering library.\n\n\n```python\n# import matplotlib and numpy\n# use \"inline\" instead of \"notebook\" for non-interactive plots\nimport sys\nif 'google.colab' in sys.modules:\n %pylab --no-import-all inline\nelse:\n %pylab --no-import-all notebook\n \n# additional package \nimport itertools \nfrom matplotlib import patches\n\n# Import libraries from the book\n\n# Import libraries from pyTEMlib\nimport pyTEMlib\nimport pyTEMlib.KinsCat as ks # Kinematic sCattering Library\n # Atomic form factors from Kirklands book\n\n__notebook_version__ = '2021.02.17'\nprint('pyTEM version: ', pyTEMlib.__version__)\nprint('notebook version: ', __notebook_version__)\n```\n\n Populating the interactive namespace from numpy and matplotlib\n Using KinsCat library version 0.5 by G.Duscher\n spglib not installed; Symmetry functions of spglib disabled\n pyTEM version: 0.2021.02.17\n notebook version: 2021.02.17\n\n\n C:\\Users\\nosle\\anaconda3\\lib\\site-packages\\pyUSID\\viz\\__init__.py:16: FutureWarning: Please use sidpy.viz.plot_utils instead of pyUSID.viz.plot_utils. pyUSID.plot_utils will be removed in a future release of pyUSID\n warn('Please use sidpy.viz.plot_utils instead of pyUSID.viz.plot_utils. '\n\n\n## Unit Cell Determination\n\n- The HOLZ rings will give the lattice repeat vector (reciprocal vector parallel to the zone axis).\n- So tilting in [001] zone axis, the ZOLZ pattern will give you the [100] and [010] distance \n- and the HOLZ ring radius the [001] distance.\n\n> **This is the determination of the lattice parameter of a unit cell.**\n>\n>Thus, we see that one can determine 3D information from a single two dimensional pattern. \n>\n>It might be necessary to use other low order zone axes.\n\n### Measurements\n\n- Record HOLZ and ZOLZ patterns, if possible in one picture (use double illumination with different exposure times to enhance dynamic range), but with different convergence angles.\n- If the angle of the ring is too large then your measurements may suffer from lens distortions.\n- If the HOLZ ring is split measure the inner one.\n\n### Z-Component of Unit Cell\n\nIf $H$ is the distance between the reciprocal-lattice planes parallel to the beam and $G_n$ is the projected radius of the HOLZ ring, then \n\\begin{eqnarray}\nG_1&=& \\left( \\frac{2H}{\\lambda}\\right)^{1/2} = \\sqrt{\\frac{2H}{\\lambda}}\\\\\nG_2&=& 2\\left( \\frac{H}{\\lambda}\\right)^{1/2} = 2 \\sqrt{\\frac{H}{\\lambda}}\n\\end{eqnarray}\nfor FOLZ and SOLZ. \n\nSimilar expressions can be developed for higher order HOLZ rings.\n\nIn real space you get for example for FOLZ:\n\\begin{equation}\n\\frac{1}{H}=\\frac{2}{\\lambda G_1^2} = \\frac{2}{\\lambda} \\left(\\frac{\\lambda L}{r}\\right)^{2}\n\\end{equation}\n\nIf you did use a zone axis which is not ${100}$, then you have to compare your result to calculated values.\n\nAssuming you are looking down $[UVW]$ then we know:\n\\begin{equation}\n\\frac{1}{H}= |[UVW]|\n\\end{equation}\n\nNow we have to calculate this $|[UVW]|$ for different structures:\\\\\n#### for fcc:\n\\begin{equation}\n\\frac{1}{H}= \\frac{a_0}{p(U^2+V^2+W^2)}\n\\end{equation}\nwith $a_0$ is the lattice parameter and $p=1$ for $U+V+W$ is odd; $p=2$ for $U+V+W$ is even.\n\n\n#### for bcc:\nthe same relationship as for fcc is true for bcc but $p$ is different: $p=2$ for $U$, $V$, and $W$ all odd; $p=1$ otherwise.\n\n\nLook up other crystal systems.\n\nIf a ring is forbidden: you have to multiply your measurement $1/H_m$ with an integer $n$ to obtain the distance of the crystal.\n\n\n## Lattice Centering\n\nWe are going to look at cubic structures to \n- fcc\n- bcc \n- a-face\n- b-face\n- primitive or simple cubic\n\nThe maximal excitation error is chosen so that ZOLZ and FOLZ overlap and we can see the different centering \n\n\n```python\ndef plot_spots(tags, ax):\n \"\"\"Simple plotting for spot pattern\"\"\"\n \n points = tags['allowed']['g']\n ix = np.argsort((points**2).sum(axis=1))\n p = points[ix]\n Laue_zones = np.unique(p[:,2]) \n ZOLZ = np.where(p[:,2] == Laue_zones[0])\n FOLZ = np.where(p[:,2] == Laue_zones[1])\n SOLZ = np.where(p[:,2] == Laue_zones[2])\n\n ax.scatter(p[ZOLZ,0], p[ZOLZ,1], color='red')\n ax.scatter(p[FOLZ,0], p[FOLZ,1], color='blue', alpha = 0.3)\n ax.scatter(p[SOLZ,0], p[SOLZ,1], color='green', alpha = 0.3)\n\n ax.set_aspect('equal')\n ax.set_title(tags['crystal_name'])\n ax.set_xlim(-40,40)\n ax.set_ylim(-40,40)\n \n# load structure\ntags = ks.structure_by_name('FCC Fe')\n\n# add necessary parameters for kinematic scattering calculation\ntags['acceleration_voltage_V'] = 200000\ntags['convergence_angle_mrad'] = 0\ntags['zone_hkl'] = [0, 0, 1] # incident neares zone axis: defines Laue Zones!!!!\ntags['mistilt'] = np.array([0,0,0]) # mistilt in degrees\n\ntags['Sg_max'] = 2.5 # 1/nm maximum allowed excitation error ; This parameter is related to the thickness\ntags['hkl_max'] = 15 # Highest evaluated Miller indices\n# calulcuate kinematic scattering data\nks.kinematic_scattering(tags, False)\n\nfig, ax = plt.subplots(nrows=2, ncols=3, figsize=(10,6))\n\n\n# plot diffraction pattern\nplot_spots(tags, ax[0, 0])\ntags['crystal_name'] = 'FCC or I'\nplot_spots(tags, ax[1, 2])\n\n\ntags.update(ks.structure_by_name('BCC Fe'))\nks.kinematic_scattering(tags, False)\n\n# plot diffraction pattern\nplot_spots(tags, ax[1, 0])\n\ntags['crystal_name'] = 'a-face'\ntags['base'] = np.array([[0. , 0. , 0. ], [0, 1/2, 1/2]])\nks.kinematic_scattering(tags, False)\nplot_spots(tags, ax[0, 1])\n\ntags['crystal_name'] = 'b-face'\ntags['base'] = np.array([[0. , 0. , 0. ], [1/2, 0, 1/2]])\nks.kinematic_scattering(tags, False)\nplot_spots(tags, ax[1, 1])\n\ntags['crystal_name'] = 'simple cubic'\ntags['base'] = np.array([[0. , 0. , 0. ]])\ntags['elements'] = ['Fe']\nks.kinematic_scattering(tags, False)\nplot_spots(tags, ax[0, 2])\n\n\n```\n\n\n \n\n\n\n\n\n\nTo analyse an experimental pattern: \n\n- Extend the pattern for the ZOLZ into the HOLZ ring and look for discrepancies. \n\n## Laue Circle\n\nThe mistilt (angles in degrees) leads to a circular pattern in the ZOLZ.\n\nAny mistilt will cause the Ewald sphere to cut through the projection plane in a circle:\nthe Laue circle. The maximal excitation error $S_{g_{max}}$ has to be rather small for this effect to appear.\n\nThe nearest zone axis will always be in the middle of the Laue circle.\n\nIf you encounter such a Laue circle try to minimize the circle by tilting towards the center.\nYou can try this out below in rhe\n\n\n```python\n# -----Input ----------\ntags['mistilt'] = np.array([0., -2 , 0])\ntags['Sg_max'] = .05 # 1/nm maximum allowed excitation error ; This parameter is related to the thickness\n# ---------------------\n\n# add necessary parameters for kinematic scattering calculation\ntags['acceleration_voltage_V'] = 200000\ntags['convergence_angle_mrad'] = 0\ntags['zone_hkl'] = [0, 0, 1] # incident neares zone axis: defines Laue Zones!!!!\n \ntags['crystal_name'] = f\"FCC with mistilt {tags['mistilt']}\"\nks.kinematic_scattering(tags, False)\nks.plotSAED(tags)\n```\n\n\n \n\n\n\n
\n\n\nThe next graph shows a cross section through the reciprocal space (with Ewald sphere).\n\nThe tilt out of zone axis (blue) leaves some spots in the middle with an high excitation error $s_g$ larger than the maximum allowed one. These spots (in the figure from 2 1/nm to 8 1/nm) are invisible in such a case. Because the Ewald sphere is a 3D object the cut of a sphere with a plane will give a circle. \n\n\n\n```python\nfrom pyTEMlib import animation \nplt.figure()\nanimation.deficient_holz_line(exact_bragg=False, laue_zone=0, color='black')\nanimation.deficient_holz_line(exact_bragg=True, laue_zone=0, color='blue')\n```\n\n\n \n\n\n\n
\n\n\n## Stereographic Projection\nThere are a lot of problems in materials science you can solve with diffraction patterns in the TEM.\n\n For instance the orientation relationship two crystals have to each other. What is the grain boundary plane and so on.\n\nThe method to visualize such orientation relationships is the stereographic projection.\n\n\n### Construction \n\nThe Schematic below shows the construction of **Stereographic Projection** for cubic systems.\n\nDraw the crystal in the middle of a sphere. Draw a line from the center of the sphere through the middle of each plane (must be normal to the plane). Mark where this line intersects the sphere (it is named P in figure above). From this point draw a line to the south or north pole so that you intersect the equatorial plane. If you have to go to the south pole, mark the intersection of this line with equatorial plane with a dot;\nif you go to the north pole mark this intersection with a circle.We construct the point P'. This point represents uniquely one plane. The relevant area of the equatorial plane is a disk. \n\nNow we can also project circumference of a circle. Note that all the planes perpendicular to a low order zone axis lay on such a circle. These circles show up as lines or as ovals in the stereographic projection .\n\nChange the Miller indices to see the change \n\n\n```python\n# ------Input ----------\nreflection = np.array([1,0, 1])\n# -----------------------\nif reflection[1] != 0:\n print('we only use a cross section so y is set to 0')\n reflection[1] = 0\n\nR = 90 # 90 degrees projection sphere\nx,y,z =reflection/np.linalg.norm(reflection)*R # Coordinates on sphere surface\nx_projeted = (x*R/(R+z)) # x coordinate on stereographic projection plane\nprint(f'projected x-coordinate is {x_projeted:.2f} degree')\n\nplt.figure()\nplt.title(f'Cross Section of Stereographic Projection of {reflection} ')\nsphere = plt.Circle(( 0. , 0. ), R , fill=False, linewidth=2) \nplt.gca().set_aspect( 'equal') \nplt.gca().add_artist(sphere) \n\nplt.plot([-R*1.1,R*1.1], [0,0])\nplt.text(0.04, 0, 'O', horizontalalignment='center', verticalalignment='bottom')\nplt.text(-50, 0, 'projection plane', horizontalalignment='center', verticalalignment='bottom')\nplt.ylim(-R*1.1,R*1.1)\nplt.scatter(0,-R)\nplt.text(0,-R*1.02, 'S', horizontalalignment='center', verticalalignment='top')\nplt.scatter(0,0)\n\nplt.plot([0, x], [0, z], label='diffracted wave vector') \nplt.scatter(x, z)\nplt.text(x*1.04, z, 'P', horizontalalignment='center', verticalalignment='bottom')\n\nplt.plot([x, 0], [z, -R], label='connection to south pole') \nplt.scatter(x_projeted, 0)\nplt.text(x_projeted, -0.4, 'P\\'', horizontalalignment='left', verticalalignment='top', )\nplt.legend(loc='upper left');\n```\n\n projected x-coordinate is 37.28 degree\n\n\n\n \n\n\n\n
\n\n\n**Some features of the stereographic projection:**\n \n- We can represent plane normals and directions in the same projection.\n- The can read off the angles between the directions, because the angles are preserved in this projection. Possibly the most important feature of this projection.\n- The zone axis is always 90$^{\\rm o} $ away from any plane normal to its zone.\n- All the planes normal to a particular zone will lay on a great circle (oval). The zone of the centrale pole is on the circumference of the whole projection.\n- The angle between two planes is the angle between their normals measured with the Wulff net.\n- We can add the symmetry elements of any particular crystal system. \n\n### Wulff Plot\n\nThe result of the stereographic Projection of the holeprojeciton sphere is shown below. It is convenient to show the ** circles of the sphere** as a grid the Wulff Plot. \n\nBut first we define some helper functions.\n\n\n```python\n## ## Some helper functions first\ndef circumcenter(a,b,c):\n ax, ay = a\n bx, by = b\n cx, cy = c\n d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))\n ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d\n uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d\n return (ux, uy)\n\ndef wulff_net(ax, density=10):\n \n outer_ring = plt.Circle(( 0. , 0. ), 90 , fill=False, linewidth=2) \n\n ax.set_aspect( 'equal') \n ax.add_artist( outer_ring ) \n ax.spines['left'].set_position(('data', 0))\n ax.spines['bottom'].set_position(('data', 0))\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n \n ax.set_xlim(-94,94)\n ax.set_ylim(-94,94)\n \n for phi in range(density,90,density):\n phi_r = np.radians(phi)\n x,y = 90*np.sin(phi_r), 90*np.cos(phi_r)\n u,v = circumcenter([x,y],[-x,y],[0,90-phi])\n theta = np.degrees(np.arctan2( y-v, x-u))\n ax.add_patch(patches.Arc((0. , v), (v-90+phi)*2, (v-90+phi)*2, fill=False, edgecolor = 'gray', linewidth=.5, theta1=180-theta , theta2=theta))\n ax.add_patch(patches.Arc((0. , -v), (v-90+phi)*2, (v-90+phi)*2, fill=False, edgecolor = 'gray', linewidth=.5, theta1=-theta , theta2=180+theta))\n u,v = circumcenter([0,90],[0,-90],[phi,0])\n theta = np.degrees(np.arctan2(u, phi))\n radius = np.sqrt(u**2+ 90**2)\n \n theta = np.degrees(np.arctan2( 90, u))\n radius = np.abs(u-phi)\n ax.add_patch(patches.Arc((u, 0), radius*2, radius*2, fill=False, edgecolor = 'gray', linewidth=.5, theta1=180+theta , theta2=-180-theta))\n ax.add_patch(patches.Arc((-u, 0), radius*2, radius*2, fill=False, edgecolor = 'gray', linewidth=.5, theta1=theta , theta2=-theta))\n\n \ndef add_main_circles(ax):\n phi = 45\n phi_r = np.radians(phi)\n x,y = 90*np.sin(phi_r), 90*np.cos(phi_r)\n\n ax.plot([x,-x], [y,-y], color='blue')\n ax.plot([x,-x], [-y,y], color='blue')\n\n phi_r = np.radians(phi)\n x,y = 90*np.sin(phi_r), 90*np.cos(phi_r)\n u,v = circumcenter([x,y],[-x,y],[0,90-phi])\n theta = np.degrees(np.arctan2( y-v, x-u))\n ax.add_patch(patches.Arc((0., 90), np.sqrt(2)*180, np.sqrt(2)*180, fill=False, edgecolor = 'blue', linewidth=1, theta1=180+45 , theta2=-45))\n ax.add_patch(patches.Arc((0., -90), np.sqrt(2)*180, np.sqrt(2)*180, fill=False, edgecolor = 'blue', linewidth=1, theta1=45, theta2=180-45))\n ax.add_patch(patches.Arc((90., 0), np.sqrt(2)*180, np.sqrt(2)*180, fill=False, edgecolor = 'blue', linewidth=1, theta1=180-45, theta2=180+45))\n ax.add_patch(patches.Arc((-90., 0), np.sqrt(2)*180, np.sqrt(2)*180, fill=False, edgecolor = 'blue', linewidth=1, theta1=-45 , theta2=45))\n\n\n\n```\n\nAgain change the Miller indices around to see where the reflections *lands*.\n\n\n```python\n# ------Input ----------\nreflection = np.array([3, 1, 1])\n# -----------------------\nR = 90 # 90 degrees Ewald sphere\nprojected =(reflection/np.linalg.norm(reflection)*R) # Coordinates on ewals sphere surface\n\nprojected = projected*R/(R+projected[2]) # x coordinate on stereographic projection plane\nif projected[2]>=0:\n print(f'Projected coordinates: {projected[:2]}')\nelse:\n print('negative l Miller index is not supported')\nplt.figure()\nplt.title(f'Stereographic Projection of {reflection}')\nwulff_net(plt.gca(), density=10)\nadd_main_circles(plt.gca())\nif projected[2]>=0:\n plt.scatter(projected[0], projected[1], color='red')\n```\n\n Projected coordinates: [62.54886934 20.84962311]\n\n\n\n \n\n\n\n
\n\n\n### Cubic Crystal Reflections \n\nchange the maximum Miller index around to see what happens\n\n\n```python\n# ------Input ----------\nhkl_max = 7\n# -----------------------\nh = np.linspace(-hkl_max,hkl_max,2*hkl_max+1) # all evaluated single Miller Indices\nhkl = np.array(list(itertools.product(h,h,h)), dtype=int) # all evaluated Miller indices\nzero = np.where(np.linalg.norm(hkl)==0)\nR = 90 # 90 degrees projection sphere\n\nprojected = []\nreflections = []\nfor reflection in hkl:\n if reflection[2]>=0:\n if np.linalg.norm(reflection) >0:\n p = reflection/np.linalg.norm(reflection)*R# Coordinates on sphere surface\n projected.append(p*R/(R+p[2])) # x coordinate on stereographic projection plane\n reflections.append(reflection)\nprojected = np.array(projected)\nreflections = np.array(reflections, dtype=int)\n\nplt.figure()\nplt.title(f'Stereographic Projection of hkl up to [{hkl_max}{hkl_max}{hkl_max}]' )\nwulff_net(plt.gca(), density=10)\nadd_main_circles(plt.gca())\ncolor=['orange', 'green', 'red'] + ['blue']*200\nfor index, spot in enumerate(projected):\n color_index = int(np.abs(reflections[index]).sum()-1)\n plt.scatter(spot[0], spot[1], color=color[color_index])\n if color_index<3:\n plt.text(spot[0], spot[1], f'{reflections[index]}', horizontalalignment='left', verticalalignment='top')\n\n```\n\n\n \n\n\n\n
\n\n\n### Stereographic Projections for Any Symmertry and Any Orientation \n\nWe did already all the work in the earlier notebooks and now we can just plot those the projections of the allowed $\\vec{g}$ vectors.\n\nThe stereographic projection is after all only a projection of allowed reflections.\n\nUse a high ``hkl_max`` parameter (about 15) and you start seeing the Kikuchi bands (next [notebook](CH2-10-Kikuchi.ipynb)) \n\nAlso see whether you can detect the 3-fold symmetry in [111] zone axis.\n\n\n```python\n# ---Input ---------\nhkl_max = 8\nzone_axis = [0,0,1]\n# ------------------\n\n#Initialize the dictionary of the input\ntags = {}\n### Define Crystal\ntags = ks.structure_by_name('silicon')\n\n### Define experimental parameters:\ntags['acceleration_voltage_V'] = 200.0 *1000.0 #V\ntags['new_figure'] = False\ntags['plot FOV'] = 30\ntags['convergence_angle_mrad'] = 0\ntags['zone_hkl'] = np.array(zone_axis) # incident neares zone axis: defines Laue Zones!!!!\ntags['mistilt'] = np.array([0,0,0]) # mistilt in degrees\ntags['Sg_max'] = 20 # 1/nm maximum allowed excitation error ; This parameter is related to the thickness\ntags['hkl_max'] = hkl_max # Highest evaluated Miller indices\n\n######################################\n# Diffraction Simulation of Crystal #\n######################################\n\n \nks.kinematic_scattering(tags, verbose = True)\n\nhkl = tags['allowed']['g'][tags['allowed']['g'][:,2]>=0]\n\nprojected = []\nreflections = []\nfor reflection in hkl:\n p = reflection/np.linalg.norm(reflection)*R# Coordinates on sphere surface\n projected.append(p*R/(R+p[2])) # x coordinate on stereographic projection plane\n reflections.append(reflection)\nprojected = np.array(projected)\nreflections = np.array(reflections, dtype=int)\n\nplt.figure()\nplt.title(f'Stereographic Projection of hkl up to [{hkl_max}{hkl_max}{hkl_max}]' )\nwulff_net(plt.gca(), density=10)\n# add_main_circles(plt.gca())\ncolor=['orange', 'green', 'red'] + ['blue']*100\nalpha = [1, 1, 1] + [0.2]*100\nfor index, spot in enumerate(projected):\n color_index = int(np.abs(reflections[index]).sum()-1)\n plt.scatter(spot[0], spot[1], color=color[color_index], alpha = alpha[color_index])\n if color_index<3:\n plt.text(spot[0], spot[1], f'{reflections[index]}', horizontalalignment='left', verticalalignment='top')\n\n\n```\n\n reciprocal_unit_cell\n [[1.764 0. 0. ]\n [0. 1.764 0. ]\n [0. 0. 1.764]]\n The inner potential is 84619.583kV\n Magnitude of incident wave vector in material 392.0 1/nm and vacuum 398.7 1/nm\n The convergence angle of 0mrad = 0.00 1/nm\n Rotation angles are 0.0 deg and 90.0 deg\n Center of Ewald sphere [ 0. 0. 391.99390809]\n Of the 4912 tested reciprocal_unit_cell points, 4912 have an excitation error less than 20.00 1/nm\n Of the 4912 possible reflection 876 are allowed.\n There are 40 allowed reflections in the zero order Laue Zone\n There are 128 allowed reflections in the first order Laue Zone\n There are 80 allowed reflections in the second order Laue Zone\n There are 628 allowed reflections in the other higher order Laue Zones\n Length of zone axis vector in real space 0.567 nm\n There are 0 forbidden but dynamical activated diffraction spots:\n KinsCat's \"Kinematic_Scattering\" finished\n\n\n\n \n\n\n\n
\n\n\n### Just a Pretty Plot\n\n\n```python\ndef add_main_planes(ax):\n ax.scatter(0, 0, color='blue', s=50)\n ax.text(0, 0, '[001]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(-90, 0, color='blue', s=50)\n ax.text(-90, 0, r'[0$\\bar{1}$0]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(90, 0, color='blue', s=50)\n ax.text(90, 0, '[010]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(0, 90, color='blue', s=50)\n ax.text(0, 90, r'[$\\bar{1}$00]', horizontalalignment='left', verticalalignment='top')\n ax.scatter(0, -90, color='blue', s=50)\n ax.text(0, -90, '[100]', horizontalalignment='left', verticalalignment='top')\n \n phi_r = np.radians(45)\n r = 46.6# 1/np.tan(phi_r/2)*20\n x,y = r*sin(phi_r), r*cos(phi_r)\n ax.scatter(x,-y, color='red', s=50)\n ax.text(x,-y, '[111]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(x,y, color='red', s=50)\n ax.text(x,y, r'[$\\bar{1}$11]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(-x,y, color='red', s=50)\n ax.text(-x,y, r'[$\\bar{1}\\bar{1}$1]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(-x,-y, color='red', s=50)\n ax.text(-x,-y, r'[1,$\\bar{1}$,1]', horizontalalignment='left',verticalalignment='top')\n\n ax.scatter(37.2, 0, color='green', s=50)\n ax.text(37.2, 0, '[011]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(-37.2, 0, color='green', s=50)\n ax.text(-37.2, 0, r'[0$\\bar{1}$1]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(0, -37.2, color='green', s=50)\n ax.text(0, -37.2, r'[101]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(0, 37.2, color='green', s=50)\n ax.text(0,37.2 , r'[$\\bar{1}$01]', horizontalalignment='left',verticalalignment='top')\n \n phi = 45\n phi_r = np.radians(phi)\n x,y = 90*sin(phi_r), 90*cos(phi_r)\n\n ax.scatter(-x, -y, color='green', s=50)\n ax.text(-x, -y, '[110]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(x,-y, color='green', s=50)\n ax.text(x,-y, r'[1$\\bar{1}$0]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(x,y, color='green', s=50)\n ax.text(x,y, r'[$\\bar{1}$10]', horizontalalignment='left',verticalalignment='top')\n ax.scatter(-x,y, color='green', s=50)\n ax.text(-x,y, r'[$\\bar{1}\\bar{1}$0]', horizontalalignment='left',verticalalignment='top')\n\nplt.figure(figsize=(5, 5))\n\nwulff_net(plt.gca(), density=10)\nadd_main_planes(plt.gca())\nadd_main_circles(plt.gca())\n```\n\n## Summary\n\nLot's of information can be gained with basic crystallogrpahy tools and trigonometry.\n\n\n## Navigation\n\n- **Back: [Spot Diffraction Pattern](CH2_8-Spot_Diffraction_Pattern)** \n- **Next: [Kikuchi Lines](CH2_10-Kikuchi_Lines.ipynb)** \n- **Chapter 2: [Diffraction](CH2_00-Diffraction.ipynb)** \n- **List of Content: [Front](../_MSE672_Intro_TEM.ipynb)** \n\n\n```python\n\n```\n", "meta": {"hexsha": "8111ee2b4230c04ba9ed008e8b35e2dad9d07731", "size": 618244, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Diffraction/.ipynb_checkpoints/CH2_09-Unit_Cell-checkpoint.ipynb", "max_stars_repo_name": "mthompson360/MSE672-Introduction-to-TEM", "max_stars_repo_head_hexsha": "36001614aed8526b92e77ed61afbf2d29d027871", "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": "Diffraction/.ipynb_checkpoints/CH2_09-Unit_Cell-checkpoint.ipynb", "max_issues_repo_name": "mthompson360/MSE672-Introduction-to-TEM", "max_issues_repo_head_hexsha": "36001614aed8526b92e77ed61afbf2d29d027871", "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": "Diffraction/.ipynb_checkpoints/CH2_09-Unit_Cell-checkpoint.ipynb", "max_forks_repo_name": "mthompson360/MSE672-Introduction-to-TEM", "max_forks_repo_head_hexsha": "36001614aed8526b92e77ed61afbf2d29d027871", "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": 72.7345882353, "max_line_length": 243800, "alphanum_fraction": 0.6678738492, "converted": true, "num_tokens": 7392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.17106118322669, "lm_q1q2_score": 0.08219125118207082}} {"text": "```python\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"\"))\n```\n\n\n\n\n\n# Naive image anomaly detection on Fashion MNIST with Euclidean and Riemannian means, distances, and norms\n\nThe goal of this notebook is to evaluate to possibility to achieve anomaly detection in image databases with naive distances to centroids and norms using Euclidean and Riemannian representations. The methods considered being rudimentary, only simple AD setups where the objective is to discriminate between two classes of the Fashion MNIST dataset will be considered. A general approach to embed images into the space of covariance matrices is introduced.\n\n\n**Table of contents:**\n\n---\n\n[1. Introduction and motivation](#intro)\n\n[1.1. Experiments hyperparameters](#intro1)\n\n---\n\n[2. Analysis/Experiment](#analysis)\n\n[2.1. Dataset loading](#analysis1)\n\n[2.2. Dataset description and preprocessing into covariance matrices](#analysis2)\n\n[2.3. AD with Riemannian distance to Fréchet mean](#analysis3)\n\n[2.4. AD with norm of negated geodesic PCA](#analysis4)\n\n[2.5. AD with norm of negated geodesic PCA with Giotto-TDA preprocessing](#analysis5)\n\n[2.6. Role of Geomstats/Giotto-TDA in the analysis](#analysis6)\n\n---\n\n[3. Benchmark](#benchmark)\n\n[3.1. Euclidean baseline: distance to Euclidean mean](#benchmark1)\n\n[3.2. Euclidean baseline: distance to Euclidean mean after PCA](#benchmark2)\n\n[3.3. Euclidean baseline: Mahalanobis distance to Euclidean mean](#benchmark3)\n\n[3.4. Euclidean baseline: Mahalanobis distance to Euclidean mean after PCA](#benchmark4)\n\n[3.5. Euclidean baseline: norm negated PCA](#benchmark5)\n\n[3.6. Results comparison](#benchmark6)\n\n---\n\n[4. Limitations and perspectives](#limitations)\n\n---\n\n[5. References](#references)\n\n---\n\n\n```python\n# tensorflow not amongst Geomstats’ and Giotto-tda’s requirements.txt\nimport sys\n!{sys.executable} -m pip install tensorflow\n!{sys.executable} -m pip install giotto-tda-nightly\n```\n\n Requirement already satisfied: tensorflow in /home/blupon/anaconda3/lib/python3.7/site-packages (2.2.0)\n Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (0.35.1)\n Requirement already satisfied: wrapt>=1.11.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (1.11.2)\n Requirement already satisfied: protobuf>=3.8.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (3.14.0)\n Requirement already satisfied: numpy<2.0,>=1.16.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (1.19.2)\n Requirement already satisfied: astunparse==1.6.3 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (1.6.3)\n Requirement already satisfied: google-pasta>=0.1.8 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (0.2.0)\n Requirement already satisfied: grpcio>=1.8.6 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (1.31.0)\n \u001b[33mWARNING: Keyring is skipped due to an exception: Failed to unlock the collection!\u001b[0m\n Collecting scipy==1.4.1; python_version >= \"3\"\n Using cached scipy-1.4.1-cp37-cp37m-manylinux1_x86_64.whl (26.1 MB)\n Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (2.10.0)\n Requirement already satisfied: absl-py>=0.7.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (0.11.0)\n Requirement already satisfied: opt-einsum>=2.3.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (3.1.0)\n Requirement already satisfied: keras-preprocessing>=1.1.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (1.1.2)\n Requirement already satisfied: six>=1.12.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (1.15.0)\n Requirement already satisfied: tensorboard<2.3.0,>=2.2.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (2.2.2)\n Requirement already satisfied: tensorflow-estimator<2.3.0,>=2.2.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (2.2.0)\n Requirement already satisfied: termcolor>=1.1.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (1.1.0)\n Requirement already satisfied: gast==0.3.3 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorflow) (0.3.3)\n Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.2)\n Requirement already satisfied: setuptools>=41.0.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (50.3.1.post20201107)\n Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.6.0)\n Requirement already satisfied: google-auth<2,>=1.6.3 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.27.0)\n Requirement already satisfied: requests<3,>=2.21.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (2.24.0)\n Requirement already satisfied: werkzeug>=0.11.15 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.0.1)\n Requirement already satisfied: markdown>=2.6.8 in /home/blupon/anaconda3/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (3.3.3)\n Requirement already satisfied: requests-oauthlib>=0.7.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.3.0)\n Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3.6\" in /home/blupon/anaconda3/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.7)\n Requirement already satisfied: pyasn1-modules>=0.2.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.2.8)\n Requirement already satisfied: cachetools<5.0,>=2.0.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.2.1)\n Requirement already satisfied: chardet<4,>=3.0.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.0.4)\n Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.25.11)\n Requirement already satisfied: idna<3,>=2.5 in /home/blupon/anaconda3/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2.10)\n Requirement already satisfied: certifi>=2017.4.17 in /home/blupon/anaconda3/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2020.12.5)\n Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /home/blupon/anaconda3/lib/python3.7/site-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (2.0.0)\n Requirement already satisfied: oauthlib>=3.0.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)\n Requirement already satisfied: pyasn1>=0.1.3 in /home/blupon/anaconda3/lib/python3.7/site-packages (from rsa<5,>=3.1.4; python_version >= \"3.6\"->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.8)\n Requirement already satisfied: zipp>=0.5 in /home/blupon/anaconda3/lib/python3.7/site-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.4.0)\n Installing collected packages: scipy\n Attempting uninstall: scipy\n Found existing installation: scipy 1.6.3\n Uninstalling scipy-1.6.3:\n Successfully uninstalled scipy-1.6.3\n \u001b[31mERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts.\n \n We recommend you use --use-feature=2020-resolver to test your packages with the new resolver before it becomes the default.\n \n giotto-tda 0.4.0 requires scipy>=1.5.0, but you'll have scipy 1.4.1 which is incompatible.\n giotto-tda-nightly 20210113.12 requires scipy>=1.5.0, but you'll have scipy 1.4.1 which is incompatible.\n geomstats 2.2.2 requires joblib==0.14.1, but you'll have joblib 1.0.1 which is incompatible.\u001b[0m\n Successfully installed scipy-1.4.1\n Requirement already satisfied: giotto-tda-nightly in /home/blupon/anaconda3/lib/python3.7/site-packages (20210113.12)\n Requirement already satisfied: joblib>=0.16.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from giotto-tda-nightly) (1.0.1)\n Requirement already satisfied: plotly>=4.8.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from giotto-tda-nightly) (4.14.3)\n Requirement already satisfied: pyflagser>=0.4.3 in /home/blupon/anaconda3/lib/python3.7/site-packages (from giotto-tda-nightly) (0.4.4)\n Requirement already satisfied: python-igraph>=0.8.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from giotto-tda-nightly) (0.9.1)\n Requirement already satisfied: ipywidgets>=7.5.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from giotto-tda-nightly) (7.5.1)\n \u001b[33mWARNING: Keyring is skipped due to an exception: Failed to unlock the collection!\u001b[0m\n Collecting scipy>=1.5.0\n Using cached scipy-1.6.3-cp37-cp37m-manylinux1_x86_64.whl (27.4 MB)\n Requirement already satisfied: numpy>=1.19.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from giotto-tda-nightly) (1.19.2)\n Requirement already satisfied: scikit-learn>=0.23.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from giotto-tda-nightly) (0.23.2)\n Requirement already satisfied: retrying>=1.3.3 in /home/blupon/anaconda3/lib/python3.7/site-packages (from plotly>=4.8.2->giotto-tda-nightly) (1.3.3)\n Requirement already satisfied: six in /home/blupon/anaconda3/lib/python3.7/site-packages (from plotly>=4.8.2->giotto-tda-nightly) (1.15.0)\n Requirement already satisfied: texttable>=1.6.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from python-igraph>=0.8.2->giotto-tda-nightly) (1.6.3)\n Requirement already satisfied: traitlets>=4.3.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipywidgets>=7.5.1->giotto-tda-nightly) (5.0.5)\n Requirement already satisfied: ipython>=4.0.0; python_version >= \"3.3\" in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipywidgets>=7.5.1->giotto-tda-nightly) (7.19.0)\n Requirement already satisfied: widgetsnbextension~=3.5.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipywidgets>=7.5.1->giotto-tda-nightly) (3.5.1)\n Requirement already satisfied: nbformat>=4.2.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipywidgets>=7.5.1->giotto-tda-nightly) (5.0.8)\n Requirement already satisfied: ipykernel>=4.5.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipywidgets>=7.5.1->giotto-tda-nightly) (5.3.4)\n Requirement already satisfied: threadpoolctl>=2.0.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from scikit-learn>=0.23.1->giotto-tda-nightly) (2.1.0)\n Requirement already satisfied: ipython-genutils in /home/blupon/anaconda3/lib/python3.7/site-packages (from traitlets>=4.3.1->ipywidgets>=7.5.1->giotto-tda-nightly) (0.2.0)\n Requirement already satisfied: pexpect>4.3; sys_platform != \"win32\" in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (4.8.0)\n Requirement already satisfied: backcall in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (0.2.0)\n Requirement already satisfied: pickleshare in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (0.7.5)\n Requirement already satisfied: setuptools>=18.5 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (50.3.1.post20201107)\n Requirement already satisfied: pygments in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (2.7.2)\n Requirement already satisfied: decorator in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (4.4.2)\n Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (3.0.8)\n Requirement already satisfied: jedi>=0.10 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (0.17.1)\n Requirement already satisfied: notebook>=4.4.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (6.1.4)\n Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbformat>=4.2.0->ipywidgets>=7.5.1->giotto-tda-nightly) (3.2.0)\n Requirement already satisfied: jupyter-core in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbformat>=4.2.0->ipywidgets>=7.5.1->giotto-tda-nightly) (4.6.3)\n Requirement already satisfied: jupyter-client in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipykernel>=4.5.1->ipywidgets>=7.5.1->giotto-tda-nightly) (6.1.7)\n Requirement already satisfied: tornado>=4.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from ipykernel>=4.5.1->ipywidgets>=7.5.1->giotto-tda-nightly) (6.0.4)\n Requirement already satisfied: ptyprocess>=0.5 in /home/blupon/anaconda3/lib/python3.7/site-packages (from pexpect>4.3; sys_platform != \"win32\"->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (0.6.0)\n Requirement already satisfied: wcwidth in /home/blupon/anaconda3/lib/python3.7/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (0.2.5)\n Requirement already satisfied: parso<0.8.0,>=0.7.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.5.1->giotto-tda-nightly) (0.7.0)\n Requirement already satisfied: Send2Trash in /home/blupon/anaconda3/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (1.5.0)\n Requirement already satisfied: pyzmq>=17 in /home/blupon/anaconda3/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (19.0.2)\n Requirement already satisfied: terminado>=0.8.3 in /home/blupon/anaconda3/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.9.1)\n Requirement already satisfied: prometheus-client in /home/blupon/anaconda3/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.8.0)\n Requirement already satisfied: argon2-cffi in /home/blupon/anaconda3/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (20.1.0)\n Requirement already satisfied: nbconvert in /home/blupon/anaconda3/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (6.0.7)\n Requirement already satisfied: jinja2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (2.11.2)\n Requirement already satisfied: attrs>=17.4.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.5.1->giotto-tda-nightly) (20.3.0)\n Requirement already satisfied: pyrsistent>=0.14.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.17.3)\n Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /home/blupon/anaconda3/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.5.1->giotto-tda-nightly) (2.0.0)\n Requirement already satisfied: python-dateutil>=2.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets>=7.5.1->giotto-tda-nightly) (2.8.1)\n Requirement already satisfied: cffi>=1.0.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from argon2-cffi->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (1.14.0)\n Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.5.1)\n Requirement already satisfied: bleach in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (3.2.1)\n Requirement already satisfied: pandocfilters>=1.4.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (1.4.3)\n Requirement already satisfied: defusedxml in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.6.0)\n Requirement already satisfied: entrypoints>=0.2.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.3)\n Requirement already satisfied: mistune<2,>=0.8.1 in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.8.4)\n Requirement already satisfied: jupyterlab-pygments in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.1.2)\n Requirement already satisfied: testpath in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.4.4)\n Requirement already satisfied: MarkupSafe>=0.23 in /home/blupon/anaconda3/lib/python3.7/site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (1.1.1)\n Requirement already satisfied: zipp>=0.5 in /home/blupon/anaconda3/lib/python3.7/site-packages (from importlib-metadata; python_version < \"3.8\"->jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.5.1->giotto-tda-nightly) (3.4.0)\n Requirement already satisfied: pycparser in /home/blupon/anaconda3/lib/python3.7/site-packages (from cffi>=1.0.0->argon2-cffi->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (2.20)\n Requirement already satisfied: async-generator in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (1.10)\n Requirement already satisfied: nest-asyncio in /home/blupon/anaconda3/lib/python3.7/site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (1.4.2)\n Requirement already satisfied: webencodings in /home/blupon/anaconda3/lib/python3.7/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (0.5.1)\n Requirement already satisfied: packaging in /home/blupon/anaconda3/lib/python3.7/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (20.4)\n Requirement already satisfied: pyparsing>=2.0.2 in /home/blupon/anaconda3/lib/python3.7/site-packages (from packaging->bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.5.1->giotto-tda-nightly) (2.4.7)\n Installing collected packages: scipy\n Attempting uninstall: scipy\n Found existing installation: scipy 1.4.1\n Uninstalling scipy-1.4.1:\n Successfully uninstalled scipy-1.4.1\n \u001b[31mERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts.\n \n We recommend you use --use-feature=2020-resolver to test your packages with the new resolver before it becomes the default.\n \n tensorflow 2.2.0 requires scipy==1.4.1; python_version >= \"3\", but you'll have scipy 1.6.3 which is incompatible.\n geomstats 2.2.2 requires joblib==0.14.1, but you'll have joblib 1.0.1 which is incompatible.\u001b[0m\n Successfully installed scipy-1.6.3\n\n\n\n```python\nimport geomstats.backend as gs\nfrom geomstats.learning.kmeans import RiemannianKMeans\nimport geomstats.geometry.spd_matrices as spd\nfrom geomstats.learning.kmeans import FrechetMean\nfrom geomstats.learning.pca import TangentPCA\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.covariance import EmpiricalCovariance\nfrom sklearn.decomposition import PCA\n\nfrom gtda.images import RadialFiltration\nfrom gtda.images import DilationFiltration\nfrom gtda.images import ErosionFiltration\nfrom gtda.images import DensityFiltration\nfrom gtda.images import Binarizer\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# make sure tensorflow doesn't use GPU to avoid problem of insufficient GPU memory to handle batch size\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n```\n\n INFO: Using numpy backend\n\n\n#
1. Introduction and motivation\n\n
\nAnomaly detection (AD) in images is a useful tool in a large variety of applications. One can detect anomalies on images to raise an alarm in video surveillance, or to identify flaws for quality control. This AD problem is an active research subject in the machine learning and data processing community. The main difference between AD and classification lies in the supervision and the information available during training. Whereas classification requires representative training data for each mode, AD gathers a single or a set of classes in a unique normal mode and separates the latter from any different data. In order to do this, so-called unsupervised AD only uses normal samples during training to characterize the normality latent distribution, whereas semi-supervised AD additionally takes into account a minority of labelled anomalies to learn the latent boundary. AD remains a difficult task when normality is complex, e.g. multimodal, or when the data provided that defines the latent distribution of normality is not representative, which could lead to a latent boundary easily excluding normal samples in the test phase. Other typical difficulties include potentially infinite diversity when it comes to anomalies and excessive similarity between some normal samples and some anomalies. The following image illustrates what a generic AD setup looks like.\n
\n\n\n```python\n# show image with python to avoid github error when displaying notebook in browser without jupyter\nplt.figure(figsize=(14,9))\nplt.imshow(mpimg.imread('multimodal_AD.png'))\n```\n\n
\nIn this notebook, we explore the performances of naive AD methods with simple distances and norms directly in representation space or after a PCA dimensionality reduction. The objective is to check where naive approaches stand with respect to the very simple AD task of separating two modes of data, i.e. normality is not multimodal and abnormality is not infinitely diverse. This amounts to discriminating between two classes with training data available only for one of the two. The dataset chosen for this experiment is Fashion MNIST. This choice is motivated by the will to practice on a simple enough dataset, avoiding the complexity of CIFAR10 and the lack of multiscale structure in MNIST.\n
\n\n
\n\n
\nWorking on distance to centroids and norms asks the question of the representation space on which to compute those features. Following recent research putting forward the relevance of SPD matrices representations, the images will first be transformed into covariance matrices. This enables us to compare the performances of means and distances either defined in an Euclidean setting or a Riemannian setting, the Riemannian setting being provided by the SPD manifold. The Riemannian tools carry the hope that a well chosen manifold makes the distances between samples more relevant with respect to the AD task considered. This translates into the idea that a well chosen manifold is a manifold more adapted to the data distribution.\n
\n\n
\n\n
\nThe next figure represents the AD pipelines considered in this notebook, with each notebook subsection implementing the corresponding method indicated on the left.\n
\n\n\n```python\n# show image with python to avoid github error when displaying notebook in browser without jupyter\nplt.figure(figsize=(20,13))\nplt.imshow(mpimg.imread('ICLR2021_geomstatsChallenge_pipelines.png'))\n```\n\n## 1.1. Experiments hyperparameters \n\n\n```python\nresults_dic = {}\n```\n\nChoice of the Fashion MNIST classes we will separate, we choose 0 (T-shirt) and 2 (Pullover) to obtain a difficult separation problem, since these two classes are quite similar:\n\n\n```python\nclass1 = 0\nclass2 = 2\n```\n\nChoice of the number of samples available to compute the mean, defining the normality centroid or reference point:\n\n\n```python\nnsamples = 1000\n```\n\nChoice of the covariance matrix type:\n\n\n```python\ncov_type = 'siegel2'\n```\n\nChoice of the image axis along which the covariance matrix will be computed:\n\n\n```python\naxis_to_cov = 2\n```\n\nChoice of the Giotto-TDA preprocessing filter, and of the binarization threshold for the binarization preceding the filter:\n\n\n```python\n# gfiltertype = 'density'\n# gfiltertype = 'dilation'\n# gfiltertype = 'erosion'\ngfiltertype = 'radial'\n\nbinarize_threshold = 0.4\n```\n\nChoice of the number of components for PCA:\n\n\n```python\nn_components_PCA = 20\n```\n\n# 2. Analysis/Experiment\n\n## 2.1. Dataset loading \n\nThe so-called normal class seen during training in the unsupersived AD setup is class1, defined in the hyperparameters. The other class, which we try to separate from class1 will only be seen in test.\n\n\n```python\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()\n\nx_train = x_train/255.\nx_test = x_test/255.\n\nfilter_class = y_train==class1\n\nx_train1 = x_train[filter_class,:,:]\ny_train1 = y_train[filter_class]\nx_train1 = x_train1[0:nsamples,:,:]\nx_train1 = np.expand_dims(x_train1,axis=-1)\n\nfilter_class = y_test==class1\nx_test1 = x_test[filter_class]\nx_test1 = np.expand_dims(x_test1,axis=-1)\n\nfilter_class = y_test==class2\nx_test2 = x_test[filter_class]\nx_test2 = np.expand_dims(x_test2,axis=-1)\n```\n\n## 2.2. Dataset description and preprocessing into covariance matrices \n\nTo obtain a relevant SPD matrix to describe an image, transformations of the image will be accumulated, the resulting tensor will be reshaped according to the chosen covariance matrix axis in the hyperparameters, and finally the covariance matrix will be computed. To make this SPD as much relevant as possible, the append mean approach is considered, in order to associate the two first orders representations in the SPD matrix. It can be interpreted as the Riemannian space of non-centered multivariate Gaussian distributions, which has a geometry described by the Siegel metric [[1]](#[1]).\n\n\n```python\ndef compute_transformation(x_train):\n x_train=x_train+(np.random.random(x_train.shape)/100)\n xout=[]\n xout.append(x_train)\n for i in range(-3,4,2):\n xtemp=tf.roll(x_train,i,axis=1)\n for j in range(-3,4,2):\n xout.append(tf.roll(xtemp,j,axis=2))\n xout.append(tf.image.flip_left_right(x_train))\n xout.append(tf.image.flip_up_down(x_train))\n xout.append(tf.image.rot90(x_train))\n xout.append(tf.image.rot90(x_train,k=2))\n xout.append(tf.image.rot90(x_train,k=3))\n xout=np.stack(xout,axis=-1)\n return xout\n```\n\n\n```python\ndef reshape_byaxis(xout,axis=1):\n xout=np.swapaxes(xout,axis,-1)\n return np.reshape(xout,[xout.shape[0],xout.shape[1]*xout.shape[2]*xout.shape[3],xout.shape[4]])\n```\n\nIn the following function, three possible SPD representations can be computed: a covariance matrix, or two append mean SPD representations combining first and second order moments. As indicated in the code comments, these two append mean approaches stem from the literature [[1]](#[1]) [[2]](#[2]).\n\n
\n\nAppend mean approach SPD representation with \"siegel\" option for **compute_cov()** (cf. next notebook cell):\n\n
\n\n\\begin{equation}\n\\begin{pmatrix}\n\\Sigma+ \\beta^2 \\mu \\mu^T & \\beta \\mu \\\\\n\\beta \\mu^T & 1\n\\end{pmatrix}\n\\end{equation}\n\n
\n\nAppend mean approach SPD representation with \"siegel2\" option for **compute_cov()** (cf. next notebook cell):\n\n
\n\n\\begin{equation}\n\\begin{pmatrix}\n\\Sigma+ \\beta \\mu \\mu^T & \\beta \\mu \\\\\n\\beta \\mu^T & \\beta\n\\end{pmatrix}\n\\end{equation}\n\n
\n\nIn the previous equations, beta is a constant, sigma the covariance matrix, and mu the mean vector.\n\n\n```python\ndef compute_cov(xout,option='simple'):\n resC=[]\n if option=='simple':\n for i in range(xout.shape[0]):\n C=np.cov(xout[i,:,:].T)\n resC.append(C)\n elif option=='siegel': # append mean from equation 2 here https://arxiv.org/pdf/1703.06817.pdf\n beta=.3 # Constant recommended in https://arxiv.org/pdf/1703.06817.pdf\n for i in range(xout.shape[0]):\n C=np.cov(xout[i,:,:].T)\n m=np.expand_dims(np.mean(xout[i,:,:],axis=0),axis=-1)\n resC.append(np.concatenate([np.concatenate([C+(beta**2)*(m*m.T),beta*m],axis=1),np.concatenate([beta*m,np.ones([1,1])],axis=0).T]))\n elif option=='siegel2': # append mean from lemma 3.1 here https://core.ac.uk/download/pdf/82584625.pdf\n beta=.3 #Constant recommended in https://arxiv.org/pdf/1703.06817.pdf\n for i in range(xout.shape[0]):\n C=np.cov(xout[i,:,:].T)\n m=np.expand_dims(np.mean(xout[i,:,:],axis=0),axis=-1)\n resC.append(np.concatenate([np.concatenate([C+beta*(m*m.T),beta*m],axis=1),np.concatenate([beta*m,beta*np.ones([1,1])],axis=0).T]))\n return np.array(resC)\n```\n\n\n```python\nx_train1_transformations = compute_transformation(x_train1)\nx_test1_transformations = compute_transformation(x_test1)\nx_test2_transformations = compute_transformation(x_test2)\n\nfig, ax = plt.subplots(2,11,figsize=(20,5))\nfor transf_index1 in range(2):\n for transf_index2 in range(11):\n ax[transf_index1,transf_index2].imshow(x_train1_transformations[0,:,:,0,transf_index2+11*(transf_index1==1)])\nax[0,5].set_title('Image transformations accumulated in order to compute \\na covariance matrix along the horizontal or vertical axis\\n', fontsize=20)\n```\n\n\n```python\nx_train1_transformations = reshape_byaxis(x_train1_transformations, axis=axis_to_cov)\nx_test1_transformations = reshape_byaxis(x_test1_transformations, axis=axis_to_cov)\nx_test2_transformations = reshape_byaxis(x_test2_transformations, axis=axis_to_cov)\n\nSPD_train1 = compute_cov(x_train1_transformations, option=cov_type)\nSPD_test1 = compute_cov(x_test1_transformations, option=cov_type)\nSPD_test2 = compute_cov(x_test2_transformations, option=cov_type)\n```\n\n\n```python\nfig, ax = plt.subplots(1,2,figsize=(20,8))\nax[0].imshow(x_train1[3])\nax[0].set_title('Untransformed input image', fontsize=20)\nax[1].imshow(SPD_train1[3])\nax[1].set_title('SPD representation of the image \\n(notice the append mean approach illuminating the last column & row)', fontsize=20)\n\nfig, ax = plt.subplots(1,2,figsize=(20,8))\nax[0].imshow(x_test2[7])\nax[0].set_title('Untransformed input image', fontsize=20)\nax[1].imshow(SPD_test2[7])\nax[1].set_title('SPD representation of the image \\n(notice the append mean approach illuminating the last column & row)', fontsize=20)\n```\n\n## 2.3. AD with Riemannian distance to Fréchet mean \n\nA Riemannian metric must be chosen among those available in Geomstats, in order to compute the Fréchet mean and the distance to this mean\n\n\n```python\ndim = SPD_train1[0].shape[1]\n# riem_metric = spd.SPDMetricAffine(dim)\nriem_metric = spd.SPDMetricLogEuclidean(dim)\n```\n\nCompute Fréchet SPD matrices mean according to previously chosen SPD metric:\n\n\n```python\nFM = FrechetMean(riem_metric).fit(SPD_train1)\n\nplt.imshow(FM.estimate_)\nplt.title('Fréchet mean of our normal class training samples')\nplt.show()\n```\n\nCompute distances of test samples to Fréchet mean:\n\n\n```python\nriemdist_test1 = riem_metric.dist(FM.estimate_,np.array(SPD_test1))\nplt.hist(riemdist_test1, alpha=0.2, color='r', bins=100)\n\nriemdist_test2 = riem_metric.dist(FM.estimate_,np.array(SPD_test2))\nplt.hist(riemdist_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for the two classes')\nplt.show()\n```\n\nROC AUC achieved:\n\n\n```python\nprint(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([riemdist_test1, riemdist_test2])))\n```\n\n 0.7279720000000001\n\n\n\n```python\nresults_dic['dist_frechet_mean'] = roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([riemdist_test1, riemdist_test2]))\n```\n\n## 2.4. AD with norm of negated geodesic PCA \n\nUse norm of negated geodesic PCA as detector [[3]](#[3]), with the previously computed Riemannian mean as PCA base point:\n\n\n```python\ntpca = TangentPCA(metric=riem_metric, n_components=n_components_PCA)\ntpca = tpca.fit(SPD_train1, base_point=FM.estimate_)\n\ntangent_projected_data_test1 = tpca.transform(SPD_test1)\ntangent_projected_data_test2 = tpca.transform(SPD_test2)\n```\n\n\n```python\nscores = []\nfor var in range(0,19):\n scores.append(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([np.sum(tangent_projected_data_test1[:,var:]**2,axis=1),np.sum(tangent_projected_data_test2[:,var:]**2,axis=1)])))\n\nprint(\"Best ROC AUC is: {} for norm of {} last PCA dimensions\".format(max(scores), 20-scores.index(max(scores))))\n```\n\n Best ROC AUC is: 0.8808370000000001 for norm of 14 last PCA dimensions\n\n\n\n```python\nnegPCAscore_test1 = np.sum(tangent_projected_data_test1[:,scores.index(max(scores)):]**2,axis=1)\nplt.hist(negPCAscore_test1, alpha=0.2, color='r', bins=100)\n\nnegPCAscore_test2 = np.sum(tangent_projected_data_test2[:,scores.index(max(scores)):]**2,axis=1)\nplt.hist(negPCAscore_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for the two classes')\nplt.show()\n```\n\n\n```python\nresults_dic['negated geodesic PCA'] = max(scores)\n```\n\n## 2.5. AD with norm of negated geodesic PCA with Giotto-TDA preprocessing \n\n\n```python\nclass giotto_preprocessing():\n def __init__(self, x_train, filter_name):\n self.filter_name = filter_name\n if self.filter_name == 'dilation':\n self.filter = DilationFiltration()\n elif self.filter_name == 'erosion':\n self.filter = ErosionFiltration()\n elif self.filter_name == 'density':\n self.filter = DensityFiltration()\n elif self.filter_name == 'radial':\n self.filter = RadialFiltration()\n else: \n raise NoValidGiottoFilterError\n self.filter.fit(x_train)\n \n def transform(self, x):\n return self.filter.transform(x)\n```\n\nBinarize data to be able to apply Giotto-TDA filter:\n\n\n```python\nbinarizer = Binarizer(threshold=binarize_threshold) \nx_train1 = binarizer.fit_transform(x_train1)\n\nx_test1 = binarizer.transform(x_test1)\nx_test2 = binarizer.transform(x_test2)\n```\n\nDefine Giotto-TDA filter:\n\n\n```python\ngfilter = giotto_preprocessing(x_train1, gfiltertype)\n```\n\nTransform train and test data with Giotto-TDA filter and compute new SPD representations:\n\n\n```python\nx_train1_filtered = gfilter.transform(x_train1)\n\nx_test1_filtered = gfilter.transform(x_test1)\nx_test2_filtered = gfilter.transform(x_test2)\n```\n\n\n```python\nx_train1_transformations_filtered = compute_transformation(x_train1_filtered)\nx_test1_transformations_filtered = compute_transformation(x_test1_filtered)\nx_test2_transformations_filtered = compute_transformation(x_test2_filtered)\n\nx_train1_transformations_filtered = reshape_byaxis(x_train1_transformations_filtered, axis=axis_to_cov)\nx_test1_transformations_filtered = reshape_byaxis(x_test1_transformations_filtered, axis=axis_to_cov)\nx_test2_transformations_filtered = reshape_byaxis(x_test2_transformations_filtered, axis=axis_to_cov)\n\nSPD_train1_filtered = compute_cov(x_train1_transformations_filtered, option=cov_type)\nSPD_test1_filtered = compute_cov(x_test1_transformations_filtered, option=cov_type)\nSPD_test2_filtered = compute_cov(x_test2_transformations_filtered, option=cov_type)\n```\n\n\n```python\nfig, ax = plt.subplots(1,2,figsize=(20,8))\nax[0].imshow(x_train1_filtered[3])\nax[0].set_title('Filtered input image', fontsize=20)\nax[1].imshow(SPD_train1_filtered[3])\nax[1].set_title('SPD representation of the filtered image', fontsize=20)\n\nfig, ax = plt.subplots(1,2,figsize=(20,8))\nax[0].imshow(x_test2_filtered[7])\nax[0].set_title('Filtered input image', fontsize=20)\nax[1].imshow(SPD_test2_filtered[7])\nax[1].set_title('SPD representation of the filtered image', fontsize=20)\n```\n\nA new Riemannian mean needs to be computed in order to compute the PCA base point:\n\n\n```python\ndim = SPD_train1_filtered[0].shape[1]\n# riem_metric = spd.SPDMetricAffine(dim)\nriem_metric = spd.SPDMetricLogEuclidean(dim)\n```\n\n\n```python\nFM = FrechetMean(riem_metric).fit(SPD_train1_filtered)\nFM.estimate_\n\nplt.imshow(FM.estimate_)\nplt.title('Fréchet mean of our normal class filtered training samples')\nplt.show()\n```\n\n\n```python\ntpca = TangentPCA(metric=riem_metric, n_components=n_components_PCA)\ntpca = tpca.fit(SPD_train1_filtered, base_point=FM.estimate_)\n\ntangent_projected_fdata_test1 = tpca.transform(SPD_test1_filtered)\ntangent_projected_fdata_test2 = tpca.transform(SPD_test2_filtered)\n```\n\n\n```python\nscores = []\nfor var in range(0,19):\n scores.append(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1_filtered)),np.ones(len(SPD_test1_filtered))]),np.concatenate([np.sum(tangent_projected_fdata_test1[:,var:]**2,axis=1),np.sum(tangent_projected_fdata_test2[:,var:]**2,axis=1)])))\n\nprint(\"Best ROC AUC is: {} for norm of {} last PCA dimensions\".format(max(scores), 20-scores.index(max(scores))))\n```\n\n Best ROC AUC is: 0.887529 for norm of 13 last PCA dimensions\n\n\n\n```python\nnegPCAscore_test1 = np.sum(tangent_projected_fdata_test1[:,scores.index(max(scores)):]**2,axis=1)\nplt.hist(negPCAscore_test1, alpha=0.2, color='r', bins=100)\n\nnegPCAscore_test2 = np.sum(tangent_projected_fdata_test2[:,scores.index(max(scores)):]**2,axis=1)\nplt.hist(negPCAscore_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for the two classes')\nplt.show()\n```\n\n\n```python\nresults_dic['negated geodesic PCA with preprocessing filter'] = max(scores)\n```\n\n## 2.6. Role of Geomstats/Giotto-TDA in the analysis \n\n
\nThe package geomstats allows the AD naive approach, i.e. the distance to the normality reference centroid, to be tested on the SPD manifold on which the data points are projected. The library realizes the most important computations in our experiments, which are the computations of a Riemannian mean and of a Riemannian distance. It also allows us to consider another AD naive approach, i.e. the one where the norm of the last PCA components constitutes an AD score, with its TangentPCA() function, which takes into account the manifold constraint. Finally, Giotto-TDA provides us with a useful preprocessing filter which leads to an improvement in the AD performances.\n
\n\n# 3. Benchmark \n\n\n```python\nclass EuclideanMetric():\n \n def __init__(self, withMahalanobis=False, train_data=None, pca_reduce=False, n_components=20):\n self.withMahalanobis = withMahalanobis\n self.n_components = n_components\n self.pca_reduce = pca_reduce\n if self.pca_reduce:\n self.pca = PCA(n_components=self.n_components)\n if train_data is None:\n raise NoTrainDataError\n else:\n if self.pca_reduce:\n self.pca = self.pca.fit(train_data.reshape(train_data.shape[0], -1))\n self.centroid = self.init_centroid(train_data)\n if self.withMahalanobis:\n self.empiCov = self.init_Mahalanobis(train_data)\n self.cov = self.empiCov.covariance_\n \n def init_centroid(self, x):\n x = x.reshape(x.shape[0], -1)\n if self.pca_reduce:\n x = self.pca.transform(x)\n return np.sum(x, axis=0)/x.shape[0]\n \n def init_Mahalanobis(self, x):\n x = x.reshape(x.shape[0], -1)\n if self.pca_reduce:\n x = self.pca.transform(x)\n \n empiCov = EmpiricalCovariance()\n empiCov.fit(x)\n plt.imshow(empiCov.covariance_)\n plt.title('Mahalanobis Covariance Matrix')\n plt.show()\n return empiCov\n\n def dist_to_centroid(self, test_data):\n if self.withMahalanobis:\n return self.Mahalanobis(test_data)\n else:\n return self.Frobenius(test_data)\n \n def Frobenius(self, x):\n x = x.reshape(x.shape[0], -1)\n if self.pca_reduce:\n x = self.pca.transform(x)\n return np.sqrt(np.sum((np.subtract(x, self.centroid))**2, axis=1))\n \n def Mahalanobis(self, x):\n x = x.reshape(x.shape[0], -1)\n if self.pca_reduce:\n x = self.pca.transform(x)\n batch_scores = self.empiCov.mahalanobis(x)\n return np.sqrt(batch_scores)\n```\n\n## 3.1. Euclidean baseline: distance to Euclidean mean \n\n\n```python\nbaseline_metric = EuclideanMetric(withMahalanobis=False, train_data=SPD_train1, pca_reduce=False)\n```\n\n\n```python\nplt.imshow(baseline_metric.centroid.reshape(29,29))\nplt.title('Euclidean mean of our normal class training samples')\nplt.show()\n```\n\n\n```python\neucldist_test1 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test1))\nplt.hist(eucldist_test1, alpha=0.2, color='r', bins=100)\n\neucldist_test2 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test2))\nplt.hist(eucldist_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for two classes')\nplt.show()\n```\n\n\n```python\nprint(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2])))\n```\n\n 0.664795\n\n\n\n```python\nresults_dic['distance to Euclidean mean'] = roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2]))\n```\n\n## 3.2. Euclidean baseline: distance to Euclidean mean after PCA \n\n\n```python\nbaseline_metric = EuclideanMetric(withMahalanobis=False, train_data=SPD_train1, pca_reduce=True, n_components=n_components_PCA)\n```\n\n\n```python\neucldist_test1 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test1))\nplt.hist(eucldist_test1, alpha=0.2, color='r', bins=100)\n\neucldist_test2 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test2))\nplt.hist(eucldist_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for two classes')\nplt.show()\n```\n\n\n```python\nprint(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2])))\n```\n\n 0.659112\n\n\n\n```python\nresults_dic['distance to Euclidean mean after PCA'] = roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2]))\n```\n\n## 3.3. Euclidean baseline: Mahalanobis distance to Euclidean mean \n\n\n```python\nbaseline_metric = EuclideanMetric(withMahalanobis=True, train_data=SPD_train1, pca_reduce=False, n_components=n_components_PCA)\n```\n\n\n```python\neucldist_test1 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test1))\nplt.hist(eucldist_test1, alpha=0.2, color='r', bins=100)\n\neucldist_test2 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test2))\nplt.hist(eucldist_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for two classes')\nplt.show()\n```\n\n\n```python\nprint(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2])))\n```\n\n 0.863534\n\n\n\n```python\nresults_dic['Mahalanobis distance to Euclidean mean'] = roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2]))\n```\n\n## 3.4. Euclidean baseline: Mahalanobis distance to Euclidean mean after PCA \n\n\n```python\nbaseline_metric = EuclideanMetric(withMahalanobis=True, train_data=SPD_train1, pca_reduce=True, n_components=n_components_PCA)\n```\n\n\n```python\neucldist_test1 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test1))\nplt.hist(eucldist_test1, alpha=0.2, color='r', bins=100)\n\neucldist_test2 = baseline_metric.dist_to_centroid(test_data=np.array(SPD_test2))\nplt.hist(eucldist_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for two classes')\nplt.show()\n```\n\n\n```python\nprint(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2])))\n```\n\n 0.8198350000000001\n\n\n\n```python\nresults_dic['Mahalanobis distance to Euclidean mean after PCA'] = roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([eucldist_test1, eucldist_test2]))\n```\n\n## 3.5. Euclidean baseline: norm negated PCA \n\n\n```python\nbaseline_metric = EuclideanMetric(withMahalanobis=False, train_data=SPD_train1, pca_reduce=True, n_components=n_components_PCA)\n```\n\n\n```python\ntangent_projected_data_test1 = baseline_metric.pca.transform(SPD_test1.reshape(SPD_test1.shape[0], -1))\ntangent_projected_data_test2 = baseline_metric.pca.transform(SPD_test2.reshape(SPD_test2.shape[0], -1))\n```\n\n\n```python\nscores = []\nfor var in range(0,19):\n scores.append(roc_auc_score(np.concatenate([np.zeros(len(SPD_test1)),np.ones(len(SPD_test2))]),np.concatenate([np.sum(tangent_projected_data_test1[:,var:]**2,axis=1),np.sum(tangent_projected_data_test2[:,var:]**2,axis=1)])))\n\nprint(\"Best ROC AUC is: {} for norm of {} last PCA dimensions\".format(max(scores), 20-scores.index(max(scores))))\n```\n\n Best ROC AUC is: 0.8371390000000001 for norm of 4 last PCA dimensions\n\n\n\n```python\nnegPCAscore_test1 = np.sum(tangent_projected_data_test1[:,scores.index(max(scores)):]**2,axis=1)\nplt.hist(negPCAscore_test1, alpha=0.2, color='r', bins=100)\n\nnegPCAscore_test2 = np.sum(tangent_projected_data_test2[:,scores.index(max(scores)):]**2,axis=1)\nplt.hist(negPCAscore_test2, alpha=0.2, color='g', bins=100)\n\nplt.title('Outlier Score for the two classes')\nplt.show()\n```\n\n\n```python\nresults_dic['norm of negated PCA'] = max(scores)\n```\n\n## 3.6. Results comparison \n\n\n```python\nprint('ROC AUCs of the method considered:')\nfor key in results_dic:\n print(results_dic[key], '---->', key)\n```\n\n ROC AUCs of the method considered:\n 0.7279720000000001 ----> dist_frechet_mean\n 0.8808370000000001 ----> negated geodesic PCA\n 0.887529 ----> negated geodesic PCA with preprocessing filter\n 0.664795 ----> distance to Euclidean mean\n 0.659112 ----> distance to Euclidean mean after PCA\n 0.863534 ----> Mahalanobis distance to Euclidean mean\n 0.8198350000000001 ----> Mahalanobis distance to Euclidean mean after PCA\n 0.8371390000000001 ----> norm of negated PCA\n\n\nNegated geodesic PCA led to the best ROC AUC performance for the AD task considered. Giotto-TDA preprocessing filter led to a slight performances increase. We also notice the relatively good performances of the Mahalanobis distances in the Euclidean setup.\n\n# 4. Limitations and perspectives \n\n# Limitations of this analysis\n\n
\nIn this analysis, we projected data on the SPD manifold hoping for a better understanding of the data latent distribution on this mathematical structure. Good performances were obtained with the naive AD method harnessing the SPD representation, but a final conclusion regarding the absolute relevance of the specific manifold choice can not be reached. In order to reach such a conclusion, one would need to compare the projection of the same problem on a wide variety of manifolds. On the one hand, this camparison would allow to detect the best manifold available if any, on the other hand it would help understand the actual contribution of the manifold chosen here.\n
\n\n
\n\n
\nAdditionally, the AD problem considered, as well as the competing methods implemented, remain naive in its complexity. Although naive, the methods provide in this specific case relatively interesting performances. A study progressively complexifying the AD problem solved would allow to better understand the limits of such naive methods, and the point after which machine learning with, for example, deep neural networks, is actually needed.\n
\n\n# Limitation of Geomstats and Giotto-TDA\n\n\n\nTrainable SPD representations transformations would have allowed to go further in the Euclidean versus Riemannian comparison, enabling the comparison of more complex models.\n\n# Proposed features for Geomstats and Giotto-TDA\n\n\n\n
\nPreprocessing dedicated to SPD matrices, or generating a useful SPD representation for various data types would be an interesting contribution to the machine learning on manifolds toolbox. An implementation of a SPD neural network, or so-called second order neural networks, with the Riemannian gradient and much attention given to the efficiency of the gradient computation, would be welcomed since a widely accepted reference code for this promising model has yet to appear. Moreover, such an implementation would enable more subtle comparisons between AD tasks on a variety of manifolds, to take a step back with respect to the Euclidean methods widely used.\n
\n\n# 5. References \n\n[1] \"A Distance between Multivariate Normal Distributions Based in an Embedding into the Siegel Group\" Miquel Calvo and Josep M. Oller\n\nhttps://core.ac.uk/download/pdf/82584625.pdf\n\n[2] \"Second-order Convolutional Neural Networks\" Kaicheng Yu and Mathieu Salzmann \n\nhttps://arxiv.org/pdf/1703.06817.pdf\n\n[3] \"Modeling the Distribution of Normal Data in Pre-Trained Deep Features for Anomaly Detection\" Oliver Rippel, Patrick Mertens and Dorit Merhof \n\nhttps://arxiv.org/pdf/2005.14140.pdf\n\n\n```python\n\n```\n", "meta": {"hexsha": "e69838c44cb79bed10588e978b15dc82de8ca70c", "size": 855651, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Blupblupblup/submission_geomstatsICLR2021challenge_NaiveImageAD_Euclidean_vs_Riemannian.ipynb", "max_stars_repo_name": "s-shailja/challenge-iclr-2021", "max_stars_repo_head_hexsha": "28ad9d126597166bc41715f77c8cf366b8fba975", "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": "Blupblupblup/submission_geomstatsICLR2021challenge_NaiveImageAD_Euclidean_vs_Riemannian.ipynb", "max_issues_repo_name": "s-shailja/challenge-iclr-2021", "max_issues_repo_head_hexsha": "28ad9d126597166bc41715f77c8cf366b8fba975", "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": "Blupblupblup/submission_geomstatsICLR2021challenge_NaiveImageAD_Euclidean_vs_Riemannian.ipynb", "max_forks_repo_name": "s-shailja/challenge-iclr-2021", "max_forks_repo_head_hexsha": "28ad9d126597166bc41715f77c8cf366b8fba975", "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": 447.0485893417, "max_line_length": 274816, "alphanum_fraction": 0.9358336518, "converted": true, "num_tokens": 15331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.21733752611649484, "lm_q1q2_score": 0.08205375496495587}} {"text": "# Molecular Dynamics: Lab 2\n\nIn part based on [Fortran code from Furio Ercolessi](http://www.fisica.uniud.it/~ercolessi/md/f90/) and the [CHEM126 course of Kalju Khan](http://web.chem.ucsb.edu/~kalju/chem126).\n\n\n```\nfrom IPython.core.display import HTML\ncss_file = '../ipython_notebook_styles/ngcmstyle.css'\nHTML(open(css_file, \"r\").read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Energy minimization\n\nIn lab 1 we worked with the Lennard-Jones potential. Other simple potentials include the **harmonic** potential\n\n$$\n\\begin{equation}\n V = \\frac{1}{2} k \\left( r - r_{\\text{eq}} \\right)^2\n\\end{equation}\n$$\n\nwith harmonic constant $k$ and equilibrium position $r_{\\text{eq}}$, the **Kratzer** potential\n\n$$\n\\begin{equation}\n V = D_0 \\left( \\frac{r-r_{\\text{eq}}}{r} \\right)^2\n\\end{equation}\n$$\n\nwith dissociation energy $D_0$, and the **Morse** potential\n\n$$\n\\begin{equation}\n V = D_0 \\left[ 1 - e^{-\\alpha (r - r_{\\text{eq}})} \\right]^2\n\\end{equation}\n$$\n\nwhere $\\alpha$ is the Morse parameter.\n\n### Carbon Monoxide\n\nFor example, carbon monoxide (CO) consists of one carbon atom (atomic weight 12.011) and one oxygen atom (atomic weight 15.999) separated by 1.1283 Angstroms. This can be modelled by \n\n1. a harmonic potential with $k = 2743.0$ and $r_{\\text{eq}} = 1.1283$ Angstroms, or\n2. a Kratzer potential with $D_0 = 258.9$ kcal/mol and the same equilibrium distance, or\n3. a Morse potential with $\\alpha = 2.302$ Angstroms${}^{-1}$, and the same dissociation energy and equilibrium distance.\n\nUsing standard minimization algorithms (e.g. `scipy.optimize.minimize`) show that, for suitable initial guesses, all of the above potentials have minima at the expected location. \n\nBy plotting the potentials, understand why the success of the algorithms changes. \n\nBriefly test how changing the potential changes the number of steps required by the algorithm. \n\nAlso compute the force $\\frac{dV}{dr}$ at the minimum point for each potential to check that it vanishes as expected.\n\n\n```\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'serif'\nrcParams['font.size'] = 16\nrcParams['figure.figsize'] = (12,6)\nfrom scipy.optimize import minimize\n```\n\n\n```\n\n```\n\n### Evolution\n\nUsing your velocity-Verlet integrator from lab 1, evolve the CO molecule using the Morse potential. Note that, unlike lab 1, the two particles now have different mass. It is perhaps easiest to scale it so that the carbon particle has mass $1$ and the oxygen mass $1.332029$. Do *not* use periodic boundaries! Try using $\\Delta t = 0.001$ up to $t=1$. Start from the equilibrium position and show that it does not evolve. The move the location of the oxygen atom slightly and see how it evolves.\n\n\n```\n\n```\n\n## Water\n\nThe paper of [Praprotnik, Janezic, and Mavri](http://dx.doi.org/10.1021/jp046158d) suggests a potential for a single water molecule (one oxygen atom and two hydrogen with atomic weights $1.008$) of\n\n$$\n\\begin{equation}\n V = \\sum_{l = 1}^2 D_0 \\left[ 1 - e^{\\alpha \\Delta r_{OH_l}} \\right]^2 + \\frac{1}{2} k_{\\theta} \\Delta r_{HH}^2 + k_{r \\theta} \\Delta r_{HH} \\left( \\Delta r_{OH_1} + \\Delta r_{OH_2} \\right) + k_{rr} \\Delta r_{OH_1} \\Delta r_{OH_2}.\n\\end{equation}\n$$\n\nThe first term is the Morse potential again, and the other terms are the intra-molecule bond potentials. $\\Delta r_{OH_l} = r_{OH_l} - r_{OH_{\\text{eq}}}$ is the stretch in the distance between the oxygen atom and the $l^{\\text{th}}$ hydrogen atom $r_{OH_l}$ and its equilibrium value, and $\\Delta r_{HH} = r_{HH_l} - r_{HH_{\\text{eq}}}$ is the stretch in the distance between the hydrogen atoms. The parameter values are\n\n1. $D_0 = 101.9188$ kcal/mol.\n2. $\\alpha = 2.567$ Angstrom${}^{-1}$\n3. $k_{\\theta} = 328.645606$ kcal/mol/Angstrom${}^2$\n4. $k_{r \\theta} = -211.4672$ kcal/mol/Angstrom${}^2$\n5. $k_{rr} = 111.70765$ kcal/mol/Angstrom${}^2$\n6. $r_{OH_{\\text{eq}}} = 1$ Angstrom\n7. $r_{HH_{\\text{eq}}} = 1.633$ Angstrom\n\n\nFix the oxygen atom at the origin and start the hydrogen atoms at $(\\pm 0.8, 0.6, 0)$. Use the minimization techniques to find the equilibrium position of the atoms, [comparing against the known structure of water](http://en.wikipedia.org/wiki/Water_model).\n\n**NOTE**: if using `scipy`'s minimization routine, you may have to increase the tolerance as high as $10^{-4}$ to make it converge.\n\n\n```\n\n```\n\nUsing your integrator, evolve the molecule and see how it behaves.\n\n\n```\n\n```\n", "meta": {"hexsha": "0026e32a1835f4350ea47a2153d550cdc9a0af7b", "size": 13549, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FEEG6016 Simulation and Modelling/2014/Molecular Dynamics Lab 2.ipynb", "max_stars_repo_name": "ngcm/training-public", "max_stars_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-06-23T05:50:49.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-22T10:29:53.000Z", "max_issues_repo_path": "FEEG6016 Simulation and Modelling/2014/Molecular Dynamics Lab 2.ipynb", "max_issues_repo_name": "Jhongesell/training-public", "max_issues_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-11-28T08:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-28T08:29:55.000Z", "max_forks_repo_path": "FEEG6016 Simulation and Modelling/2014/Molecular Dynamics Lab 2.ipynb", "max_forks_repo_name": "Jhongesell/training-public", "max_forks_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-04-18T21:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T17:35:58.000Z", "avg_line_length": 35.3759791123, "max_line_length": 503, "alphanum_fraction": 0.4954609196, "converted": true, "num_tokens": 2291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.1732882144682526, "lm_q1q2_score": 0.08191047567220082}} {"text": "```python\n\"\"\"Tutorial: CEPA0 and CCD\"\"\"\n\n__author__ = \"Adam S. Abbott\"\n__credit__ = [\"Adam S. Abbott\", \"Justin M. Turney\"]\n\n__copyright__ = \"(c) 2014-2017, The Psi4NumPy Developers\"\n__license__ = \"BSD-3-Clause\"\n__date__ = \"2017-05-23\"\n```\n\n# Introduction\nIn this tutorial, we will implement the coupled-electron pair approximation (CEPA0) and coupled-cluster doubles (CCD) methods using our spin orbital framework covered in the [previous tutorial](8a_Intro_to_spin_orbital_postHF.ipynb).\n\n\n### I. Coupled Cluster Theory\n\nIn single reference coupled cluster theory, dynamic correlation is acquired by operating an exponential operator on some reference determinant, such as a Hartree-Fock wavefunction, to obtain the coupled cluster wavefunction given by:\n\n\\begin{equation}\n\\mid \\mathrm{\\Psi_{CC}} \\rangle = \\exp(\\hat{T}) \\mid \\mathrm{\\Phi} \\rangle \n\\end{equation}\n\nwhere $\\hat{T} = T_1 + T_2 + ... + T_n$ is the sum of \"cluster operators\" which act on our reference wavefunction to excite electrons from occupied ($i, j, k$...) to virtual ($a, b, c$...) orbitals. In second quantization, these cluster operators are expressed as:\n\n\\begin{equation}\nT_k = \\left(\\frac{1}{k!}\\right)^2 \\sum_{\\substack{i_1 \\ldots i_k \\\\ a_1 \\ldots a_k }} t_{i_1 \\ldots i_k}^{a_1 \\ldots a_k} a_{a_1}^{\\dagger} \\ldots a_{a_k}^{\\dagger} a_{i_k} \\ldots a_{i_1}\n\\end{equation}\n\nwhere $t$ is the $t$-amplitude, and $a^{\\dagger}$ and $a$ are creation and annihilation operators.\n\n### II. Coupled Cluster Doubles\nFor CCD, we only include the doubles cluster operator:\n\n\\begin{equation}\n\\mid \\mathrm{\\Psi_{CCD}} \\rangle = \\exp(T_2) \\mid \\mathrm{\\Phi} \\rangle\n\\end{equation}\n\nThe CCD Schrödinger equation is\n\n\\begin{equation}\n\\hat{H} \\mid \\mathrm{\\Psi_{CCD}} \\rangle = E \\mid \\mathrm{\\Psi_{CCD}}\\rangle\n\\end{equation}\n\nThe details will not be covered here, but if we project the CCD Schrödinger equation on the left by our Hartree-Fock reference determinant $ \\langle \\mathrm{\\Phi}\\mid $, assuming intermediate normalization $\\langle \\Phi \\mid \\mathrm{\\Psi_{CCD}} \\rangle = 1$, we obtain:\n\n\\begin{equation}\n \\langle \\Phi \\mid \\hat{H} \\space \\exp(T_2) \\mid \\Phi \\rangle = E\n\\end{equation}\n\nwhich is most easily evaluated with a diagrammatic application of Wick's theorem. Assuming Brillouin's theorem applies (that is, our reference is a Hartree-Fock wavefunction) we obtain:\n\n\\begin{equation}\nE_{\\mathrm{CCD}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}\n\\end{equation}\n\nA somewhat more involved derivation is that of the $t$-amplitudes. These are obtained in a similar fashion to the energy expression, this time projecting the CCD Schrödinger equation on the left by a doubly-excited reference determinant $ \\langle\\Phi_{ij}^{ab}\\mid $:\n\n\\begin{equation}\n\\langle\\Phi_{ij}^{ab}\\mid \\hat{H} \\space \\exp(T_2) \\mid \\Phi \\rangle\n\\end{equation}\n\nI will spare you the details of solving this expectation value as well. But, if one evaluates the diagrams via Wick's theorem and simplifies, the $t$-amplitudes are given by:\n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} - \\tfrac{1}{2}\\hat{P}_{(a \\space / \\space b)} \\bar{g}_{kl}^{cd} t_{ac}^{ij} t_{bd}^{kl} - \\tfrac{1}{2} \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ab}^{ik} t_{cd}^{jl} + \\tfrac{1}{4} \\bar{g}_{kl}^{cd} t_{cd}^{ij} t_{ab}^{kl} + \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ac}^{ik} t_{bd}^{jl} \\right)\n\\end{equation}\n\nwhere $(\\mathcal{E}_{ab}^{ij})^{-1}$ is the orbital energy denominator, more familiarly known as\n\n\\begin{equation}\n(\\mathcal{E}_{ab}^{ij})^{-1} = \\frac{1}{\\epsilon_i + \\epsilon_j - \\epsilon_a - \\epsilon_b}\n\\end{equation}\n\nand $\\bar{g}_{pq}^{rs}$ is the antisymmetrized two-electron integral in physicist's notation $\\langle pq \\mid\\mid rs \\rangle$. $\\hat{P}$ is the *antisymmetric permutation operator*. This operator acts on a term to produce the sum of the permutations of the indicated indices, with an appropriate sign factor. Its effect is best illustrated by an example. Consider the fourth term, which is really four terms in one. \n\n$\\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk}$ produces: \n\n1. The original: $ \\quad \\bar{g}_{ak}^{ic} t_{bc}^{jk} \\\\ $\n\n2. Permuation of $a$ and $b$: $ \\quad \\textrm{-} \\bar{g}_{bk}^{ic} t_{ac}^{jk} \\\\ $\n\n3. Permuation of $i$ and $j$: $ \\quad \\, \\, \\textrm{-} \\bar{g}_{ak}^{jc} t_{bc}^{ik} \\\\ $\n\n4. Permuation of $a$ and $b$, $i$ and $j$: $ \\quad \\bar{g}_{bk}^{jc} t_{ac}^{ik} \\\\ $\n\n\nNote that each permutation adds a sign change. This shorthand notation keeps the equation in a more manageable form. \n\nSince the $t$-amplitudes and the energy depend on $t$-amplitudes, we must iteratively solve these equations until they reach self consistency, and the energy converges to some threshold.\n\n### III. Retrieving MP2 and CEPA0 from the CCD equations\nIt is interesting to note that if we only consider the first term of the expression for the doubles amplitude $t_{ab}^{ij}$ and plug it into the energy expression, we obtain the MP2 energy expression:\n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\bar{g}_{ab}^{ij} \n\\end{equation}\n\n\\begin{equation}\nE_{\\mathrm{MP2}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} \\bar{g}_{ab}^{ij} (\\mathcal{E}_{ab}^{ij})^{-1}\n\\end{equation}\n\nFurthermore, if we leave out the quadratic terms in the CCD amplitude equation (terms containing two $t$-amplitudes), we obtain the coupled electron-pair approximation (CEPA0):\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} \\right)\n\\end{equation}\n\nThe CEPA0 energy expression is identical:\n\n\\begin{equation}\nE_{\\mathrm{CEPA0}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}\n\\end{equation}\n\nUsing our spin orbital setup for the MO coefficients, orbital energies, and two-electron integrals used in the [previous tutorial](8a_Intro_to_spin_orbital_postHF.ipynb), we are equipped to program the expressions for the CEPA0 and CCD correlation energy.\n\n### Implementation: CEPA0 and CCD\nAs usual, we import Psi4 and NumPy, and set the appropriate options. \n\n\n```python\n# ==> Import statements & Global Options <==\nimport psi4\nimport numpy as np\n\npsi4.set_memory(int(2e9))\nnumpy_memory = 2\npsi4.core.set_output_file('output.dat', False)\n```\n\n\n```python\n# ==> Molecule & Psi4 Options Definitions <==\nmol = psi4.geometry(\"\"\"\n0 1\nO\nH 1 1.1\nH 1 1.1 2 104\nsymmetry c1\n\"\"\")\n\n\n\npsi4.set_options({'basis': '6-31g',\n 'scf_type': 'pk',\n 'reference': 'rhf',\n 'mp2_type': 'conv',\n 'e_convergence': 1e-8,\n 'd_convergence': 1e-8})\n```\n\nNote that since we are using a spin orbital setup, we are free to use any Hartree-Fock reference we want. Here we choose RHF. For convenience, we let Psi4 take care of the Hartree-Fock procedure, and return the wavefunction object.\n\n\n```python\n# Get the SCF wavefunction & energies\nscf_e, scf_wfn = psi4.energy('scf', return_wfn=True)\n```\n\nLoad in information about the basis set and orbitals using MintsHelper and the wavefunction:\n\n\n```python\nmints = psi4.core.MintsHelper(scf_wfn.basisset())\nnbf = mints.nbf() # number of basis functions\nnso = 2 * nbf # number of spin orbitals\nnalpha = scf_wfn.nalpha() # number of alpha electrons\nnbeta = scf_wfn.nbeta() # number of beta electrons\nnocc = nalpha + nbeta # number of occupied orbitals\nnvirt = 2 * nbf - nocc # number of virtual orbitals\n```\n\nSpin-block our MO coefficients and two-electron integrals, just like in the spin orbital MP2 code:\n\n\n```python\nCa = np.asarray(scf_wfn.Ca())\nCb = np.asarray(scf_wfn.Cb())\nC = np.block([\n [ Ca , np.zeros_like(Cb) ],\n [np.zeros_like(Ca) , Cb ]\n ])\n\n# Result: | Ca 0 |\n# | 0 Cb|\n\n```\n\n\n```python\n# Get the two electron integrals using MintsHelper\nI = np.asarray(mints.ao_eri())\n\ndef spin_block_tei(I):\n \"\"\" \n Function that spin blocks two-electron integrals\n Using np.kron, we project I into the space of the 2x2 identity, tranpose the result\n and project into the space of the 2x2 identity again. This doubles the size of each axis.\n The result is our two electron integral tensor in the spin orbital form.\n \"\"\"\n identity = np.eye(2)\n I = np.kron(identity, I)\n return np.kron(identity, I.T)\n\n# Spin-block the two electron integral array\nI_spinblock = spin_block_tei(I)\n\n```\n\nConvert two-electron integrals to antisymmetrized physicist's notation:\n\n\n```python\n# Converts chemist's notation to physicist's notation, and antisymmetrize\n# (pq | rs) ---> \n# Physicist's notation\ntmp = I_spinblock.transpose(0, 2, 1, 3)\n# Antisymmetrize:\n# = - \ngao = tmp - tmp.transpose(0, 1, 3, 2)\n\n```\n\nObtain the orbital energies, append them, and sort the columns of our MO coefficient matrix according to the increasing order of orbital energies. \n\n\n```python\n# Get orbital energies \neps_a = np.asarray(scf_wfn.epsilon_a())\neps_b = np.asarray(scf_wfn.epsilon_b())\neps = np.append(eps_a, eps_b)\n\n# Before sorting the orbital energies, we can use their current arrangement to sort the columns\n# of C. Currently, each element i of eps corresponds to the column i of C, but we want both\n# eps and columns of C to be in increasing order of orbital energies\n\n# Sort the columns of C according to the order of increasing orbital energies \nC = C[:, eps.argsort()] \n\n# Sort orbital energies in increasing order\neps = np.sort(eps) \n\n```\n\nFinally, we transform our two-electron integrals to the MO basis. Here, we denote the integrals as `gmo` to differentiate from the chemist's notation integrals `I_mo`.\n\n\n```python\n# Transform gao, which is the spin-blocked 4d array of physicist's notation, \n# antisymmetric two-electron integrals, into the MO basis using MO coefficients \ngmo = np.einsum('pQRS, pP -> PQRS',\n np.einsum('pqRS, qQ -> pQRS',\n np.einsum('pqrS, rR -> pqRS',\n np.einsum('pqrs, sS -> pqrS', gao, C), C), C), C)\n\n```\n\nConstruct the 4-dimensional array of orbital energy denominators:\n\n\n```python\n# Define slices, create 4 dimensional orbital energy denominator tensor\nn = np.newaxis\no = slice(None, nocc)\nv = slice(nocc, None)\ne_abij = 1 / (-eps[v, n, n, n] - eps[n, v, n, n] + eps[n, n, o, n] + eps[n, n, n, o])\n```\n\nWe now have everything we need to construct our $t$-amplitudes and iteratively solve for our CEPA0 and CCD energy. To build the $t$-amplitudes, we first construct an empty 4-dimensional array to store them. \n\n\n```python\n# Create space to store t amplitudes\nt_amp = np.zeros((nvirt, nvirt, nocc, nocc))\n\n```\n\n# Implementation: CEPA0\nFirst we will program CEPA0. Recall the expression for the $t$-amplitudes:\n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} \\right)\n\\end{equation}\n\nThese terms translate naturally into code using NumPy's `einsum` function. To access only the occupied and virtual indices of `gmo` we use our slices defined above. The permutation operator terms can be easily obtained by transposing the original result accordingly. To construct each iteration's $t$-amplitude: \n\n~~~python\nmp2 = gmo[v, v, o, o]\ncepa1 = (1 / 2) * np.einsum('abcd, cdij -> abij', gmo[v, v, v, v], t_amp)\ncepa2 = (1 / 2) * np.einsum('klij, abkl -> abij', gmo[o, o, o, o], t_amp)\ncepa3a = np.einsum('akic, bcjk -> abij', gmo[v, o, o, v], t_amp)\ncepa3b = -cepa3a.transpose(1, 0, 2, 3)\ncepa3c = -cepa3a.transpose(0, 1, 3, 2)\ncepa3d = cepa3a.transpose(1, 0, 3, 2)\ncepa3 = cepa3a + cepa3b + cepa3c + cepa3d\n\nt_amp_new = e_abij * (mp2 + cepa1 + cepa2 + cepa3)\n~~~\n\nTo evaluate the energy, $E_{\\mathrm{CEPA0}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}$,\n\n~~~python\nE_CEPA0 = (1 / 4) * np.einsum('ijab, abij ->', gmo[o, o, v, v], t_amp_new)\n~~~\n\nPutting it all together, we initialize the energy, set the max iterations, and iterate the energy until it converges to our convergence criterion:\n\n\n```python\n# Initialize energy\nE_CEPA0 = 0.0\n\nMAXITER = 50\n\nfor cc_iter in range(MAXITER + 1):\n E_old = E_CEPA0\n \n # Collect terms\n mp2 = gmo[v, v, o, o]\n cepa1 = (1 / 2) * np.einsum('abcd, cdij -> abij', gmo[v, v, v, v], t_amp)\n cepa2 = (1 / 2) * np.einsum('klij, abkl -> abij', gmo[o, o, o, o], t_amp)\n cepa3a = np.einsum('akic, bcjk -> abij', gmo[v, o, o, v], t_amp)\n cepa3b = -cepa3a.transpose(1, 0, 2, 3)\n cepa3c = -cepa3a.transpose(0, 1, 3, 2)\n cepa3d = cepa3a.transpose(1, 0, 3, 2)\n cepa3 = cepa3a + cepa3b + cepa3c + cepa3d\n\n # Update t amplitude\n t_amp_new = e_abij * (mp2 + cepa1 + cepa2 + cepa3)\n\n # Evaluate Energy\n E_CEPA0 = (1 / 4) * np.einsum('ijab, abij ->', gmo[o, o, v, v], t_amp_new)\n t_amp = t_amp_new\n dE = E_CEPA0 - E_old\n print('CEPA0 Iteration %3d: Energy = %4.12f dE = %1.5E' % (cc_iter, E_CEPA0, dE))\n\n if abs(dE) < 1.e-8:\n print(\"\\nCEPA0 Iterations have converged!\")\n break\n\n if (cc_iter == MAXITER):\n psi4.core.clean()\n raise Exception(\"\\nMaximum number of iterations exceeded.\")\n\nprint('\\nCEPA0 Correlation Energy: %5.15f' % (E_CEPA0))\nprint('CEPA0 Total Energy: %5.15f' % (E_CEPA0 + scf_e))\n```\n\n CEPA0 Iteration 0: Energy = -0.142119840297 dE = -1.42120E-01\n CEPA0 Iteration 1: Energy = -0.142244391285 dE = -1.24551E-04\n CEPA0 Iteration 2: Energy = -0.146403555998 dE = -4.15916E-03\n CEPA0 Iteration 3: Energy = -0.147737944877 dE = -1.33439E-03\n CEPA0 Iteration 4: Energy = -0.148357998670 dE = -6.20054E-04\n CEPA0 Iteration 5: Energy = -0.148640319451 dE = -2.82321E-04\n CEPA0 Iteration 6: Energy = -0.148774677657 dE = -1.34358E-04\n CEPA0 Iteration 7: Energy = -0.148840007370 dE = -6.53297E-05\n CEPA0 Iteration 8: Energy = -0.148872388063 dE = -3.23807E-05\n CEPA0 Iteration 9: Energy = -0.148888687541 dE = -1.62995E-05\n CEPA0 Iteration 10: Energy = -0.148897003541 dE = -8.31600E-06\n CEPA0 Iteration 11: Energy = -0.148901297946 dE = -4.29440E-06\n CEPA0 Iteration 12: Energy = -0.148903540421 dE = -2.24248E-06\n CEPA0 Iteration 13: Energy = -0.148904723684 dE = -1.18326E-06\n CEPA0 Iteration 14: Energy = -0.148905354221 dE = -6.30537E-07\n CEPA0 Iteration 15: Energy = -0.148905693366 dE = -3.39145E-07\n CEPA0 Iteration 16: Energy = -0.148905877390 dE = -1.84023E-07\n CEPA0 Iteration 17: Energy = -0.148905978068 dE = -1.00678E-07\n CEPA0 Iteration 18: Energy = -0.148906033572 dE = -5.55039E-08\n CEPA0 Iteration 19: Energy = -0.148906064388 dE = -3.08158E-08\n CEPA0 Iteration 20: Energy = -0.148906081607 dE = -1.72194E-08\n CEPA0 Iteration 21: Energy = -0.148906091285 dE = -9.67815E-09\n \n CEPA0 Iterations have converged!\n \n CEPA0 Correlation Energy: -0.148906091285338\n CEPA0 Total Energy: -76.101435136027135\n\n\nSince `t_amp` is initialized to zero, the very first iteration should be the MP2 correlation energy. We can check the final CEPA0 energy with Psi4. The method is called `lccd`, or linear CCD, since CEPA0 omits the terms with two cluster amplitudes.\n\n\n```python\npsi4.driver.p4util.compare_values(psi4.energy('lccd'), E_CEPA0 + scf_e, 6, 'CEPA0 Energy')\n```\n\n \tCEPA0 Energy......................................................PASSED\n\n\n\n\n\n True\n\n\n\n# Implementation: CCD\n\nTo code CCD, we only have to add in the last four terms in our expression for the $t$-amplitudes: \n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} - \\underline{\\tfrac{1}{2}\\hat{P}_{(a \\space / \\space b)} \\bar{g}_{kl}^{cd} t_{ac}^{ij} t_{bd}^{kl} - \\tfrac{1}{2} \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ab}^{ik} t_{cd}^{jl} + \\tfrac{1}{4} \\bar{g}_{kl}^{cd} t_{cd}^{ij} t_{ab}^{kl} + \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ac}^{ik} t_{bd}^{jl}} \\right)\n\\end{equation}\n\nwhich we readily translate into `einsum`'s:\n\n~~~python\nccd1a = np.einsum('klcd, acij, bdkl -> abij', gmo[o, o, v, v], t_amp, t_amp)\nccd1b = -ccd1a.transpose(1, 0, 2, 3)\nccd1 = -(1 / 2) * (ccd1a + ccd1b)\n\nccd2a = np.einsum('klcd, abik, cdjl -> abij', gmo[o, o, v, v], t_amp, t_amp)\nccd2b = -ccd2a.transpose(0, 1, 3, 2)\nccd2 = -(1 / 2) * (ccd2a + ccd2b)\n\nccd3 = (1 / 4) * np.einsum('klcd, cdij, abkl -> abij', gmo[o, o, v, v], t_amp, t_amp)\n\nccd4a = np.einsum('klcd, acik, bdjl -> abij', gmo[o, o, v, v], t_amp, t_amp)\nccd4b = -ccd4a.transpose(0, 1, 3, 2)\nccd4 = (ccd4a + ccd4b)\n~~~\n\nand the energy expression is identical to CEPA0:\n\\begin{equation}\nE_{CCD } = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}\n\\end{equation}\n\nAdding the above terms to our CEPA0 code will compute the CCD correlation energy (may take a minute or two to run):\n\n\n```python\n# Create space to store t amplitudes\nt_amp = np.zeros((nvirt, nvirt, nocc, nocc))\n\n# Initialize energy\nE_CCD = 0.0\n\nfor cc_iter in range(1, MAXITER + 1):\n E_old = E_CCD\n\n # Collect terms\n mp2 = gmo[v, v, o, o]\n cepa1 = (1 / 2) * np.einsum('abcd, cdij -> abij', gmo[v, v, v, v], t_amp)\n cepa2 = (1 / 2) * np.einsum('klij, abkl -> abij', gmo[o, o, o, o], t_amp)\n cepa3a = np.einsum('akic, bcjk -> abij', gmo[v, o, o, v], t_amp)\n cepa3b = -cepa3a.transpose(1, 0, 2, 3)\n cepa3c = -cepa3a.transpose(0, 1, 3, 2)\n cepa3d = cepa3a.transpose(1, 0, 3, 2)\n cepa3 = cepa3a + cepa3b + cepa3c + cepa3d\n\n ccd1a = np.einsum('klcd, acij, bdkl -> abij', gmo[o, o, v, v], t_amp, t_amp)\n ccd1b = -ccd1a.transpose(1, 0, 2, 3)\n ccd1 = -(1 / 2) * (ccd1a + ccd1b)\n\n ccd2a = np.einsum('klcd, abik, cdjl -> abij', gmo[o, o, v, v], t_amp, t_amp)\n ccd2b = -ccd2a.transpose(0, 1, 3, 2)\n ccd2 = -(1 / 2) * (ccd2a + ccd2b)\n\n ccd3 = (1 / 4) * np.einsum('klcd, cdij, abkl -> abij', gmo[o, o, v, v], t_amp, t_amp)\n\n ccd4a = np.einsum('klcd, acik, bdjl -> abij', gmo[o, o, v, v], t_amp, t_amp)\n ccd4b = -ccd4a.transpose(0, 1, 3, 2)\n ccd4 = (ccd4a + ccd4b)\n\n # Update Amplitude\n t_amp_new = e_abij * (mp2 + cepa1 + cepa2 + cepa3 + ccd1 + ccd2 + ccd3 + ccd4)\n\n # Evaluate Energy\n E_CCD = (1 / 4) * np.einsum('ijab, abij ->', gmo[o, o, v, v], t_amp_new)\n t_amp = t_amp_new\n dE = E_CCD - E_old\n print('CCD Iteration %3d: Energy = %4.12f dE = %1.5E' % (cc_iter, E_CCD, dE))\n\n if abs(dE) < 1.e-8:\n print(\"\\nCCD Iterations have converged!\")\n break\n\n if (cc_iter == MAXITER):\n psi4.core.clean()\n raise Exception(\"\\nMaximum number of iterations exceeded.\")\n\nprint('\\nCCD Correlation Energy: %5.15f' % (E_CCD))\nprint('CCD Total Energy: %5.15f' % (E_CCD + scf_e))\n\n```\n\nUnfortunately, Psi4 does not have a CCD code to compare this to. However, Psi4 does have Bruekner CCD, an orbital-optimized variant of CCD. We can qualitatively compare our energies to this energy. The Bruekner-CCD energy should be a little lower than our CCD energy due to the orbital optimization procedure.\n\n\n```python\npsi4_bccd = psi4.energy('bccd', ref_wfn = scf_wfn)\nprint('\\nPsi4 BCCD Correlation Energy: ', psi4_bccd - scf_e)\nprint('Psi4 BCCD Total Energy: ', psi4_bccd)\n```\n\n \n Psi4 BCCD Correlation Energy: -0.1492076631396344\n Psi4 BCCD Total Energy: -76.10173670788143\n\n\n## References\n\n1. Modern review of coupled-cluster theory, included diagrammatic derivations of the CCD equations:\n\t> [[Bartlett and Musial:2007](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.79.291)] Rodney J. Bartlett and Monika Musial, \"Coupled-cluster theory in quantum chemistry\" *Rev. Mod. Phys.* **79**, 291 (2007)\n \n2. Background on CEPA:\n >Kutzelnigg, Werner 1977 *Methods of Electronic Structure Theory* ed. H. F. Schaefer III (Plenum, New York), p 129\n\n3. More CEPA:\n > [Koch and Kutzelnigg:1981](https://link.springer.com/article/10.1007/BF00553396) S. Koch and W. Kutzelnigg, *Theor. Chim. Acta* **59**, 387 (1981). \n\n4. Original CCD Paper:\n > [Čížek:1996](http://aip.scitation.org/doi/abs/10.1063/1.1727484) Jiří Čížek, \"On the Correlation Problem in Atomic and Molecular Systems. Calculation of Wavefunction Components in Ursell‐Type Expansion Using Quantum‐Field Theoretical Methods\" *J. Chem. Phys* **45**, 4256 (1966) \n\n5. Useful notes on diagrams applied to post-HF methods:\n > A. V. Copan, \"Diagram notation\" accessed with https://github.com/CCQC/chem-8950/tree/master/2017\n\n", "meta": {"hexsha": "06a24c74d83d395bf50f231ed84616eebf495395", "size": 30730, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorials/08_CEPA0_and_CCD/8b_CEPA0_and_CCD.ipynb", "max_stars_repo_name": "loriab/psi4numpy", "max_stars_repo_head_hexsha": "01e5adec766549aeaf9a1c71bbe4129b3b3515d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tutorials/08_CEPA0_and_CCD/8b_CEPA0_and_CCD.ipynb", "max_issues_repo_name": "loriab/psi4numpy", "max_issues_repo_head_hexsha": "01e5adec766549aeaf9a1c71bbe4129b3b3515d0", "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": "Tutorials/08_CEPA0_and_CCD/8b_CEPA0_and_CCD.ipynb", "max_forks_repo_name": "loriab/psi4numpy", "max_forks_repo_head_hexsha": "01e5adec766549aeaf9a1c71bbe4129b3b3515d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0280373832, "max_line_length": 995, "alphanum_fraction": 0.5572079401, "converted": true, "num_tokens": 7560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771175, "lm_q2_score": 0.17328819952513227, "lm_q1q2_score": 0.0819104711833229}} {"text": "Probabilistic Programming and Bayesian Methods for Hackers \n========\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n#### Looking for a printed version of Bayesian Methods for Hackers?\n\n_Bayesian Methods for Hackers_ is now a published book by Addison-Wesley, available on [Amazon](http://www.amazon.com/Bayesian-Methods-Hackers-Probabilistic-Addison-Wesley/dp/0133902838)! \n\n\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assumes that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json, matplotlib\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials) / 2, 2, k + 1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials) - 1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2 * p / (1 + p), color=\"#348ABD\", lw=3)\n# plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2 * (0.2) / 1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Is my code bug-free?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1. / 3, 2. / 3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.ylim(0,1)\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n#### Expected Value\nExpected value (EV) is one of the most important concepts in probability. The EV for a given probability distribution can be described as \"the mean value in the long run for many repeated samples from that distribution.\" To borrow a metaphor from physics, a distribution's EV as like its \"center of mass.\" Imagine repeating the same experiment many times over, and taking the average over each outcome. The more you repeat the experiment, the closer this average will become to the distributions EV. (side note: as the number of repeated experiments goes to infinity, the difference between the average outcome and the EV becomes arbitrarily small.)\n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1. / l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0, 1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```python\nimport pymc as pm\n\nalpha = 1.0 / count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = pm.Exponential(\"lambda_1\", alpha)\nlambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\ntau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```python\nprint(\"Random output:\", tau.random(), tau.random(), tau.random())\n```\n\n Random output: 21 31 29\n\n\n\n```python\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. Deterministic functions will be covered in Chapter 2. \n\n\n```python\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n# Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n [-----------------100%-----------------] 40000 of 40000 complete in 5.8 sec\n\n\n```python\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```python\nfigsize(12.5, 10)\n# histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data) - 20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n# type your code here.\n\nlambda_1_samples.mean()\n```\n\n\n\n\n 17.759989917035039\n\n\n\n\n```python\nlambda_2_samples.mean()\n```\n\n\n\n\n 22.738906564964601\n\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n# type your code here.\n\nnp.mean(lambda_1_samples/lambda_2_samples)\n```\n\n\n\n\n 0.78225828246937623\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n# type your code here.\nnp.mean(lambda_1_samples[tau_samples[tau_samples<45]])\n```\n\n\n\n\n 16.821068474609294\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "89575b34452ae111ba6657cc832075b11777c7c3", "size": 464370, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2-JH.ipynb", "max_stars_repo_name": "jonhilgart22/probabilistic-programming-and-bayesian-methods", "max_stars_repo_head_hexsha": "0c906be64a1c2a53d85fdc1213f24c64c15bba9c", "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": "Chapter1_Introduction/Ch1_Introduction_PyMC2-JH.ipynb", "max_issues_repo_name": "jonhilgart22/probabilistic-programming-and-bayesian-methods", "max_issues_repo_head_hexsha": "0c906be64a1c2a53d85fdc1213f24c64c15bba9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2-JH.ipynb", "max_forks_repo_name": "jonhilgart22/probabilistic-programming-and-bayesian-methods", "max_forks_repo_head_hexsha": "0c906be64a1c2a53d85fdc1213f24c64c15bba9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-30T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-24T00:06:37.000Z", "avg_line_length": 388.2692307692, "max_line_length": 146420, "alphanum_fraction": 0.9115295992, "converted": true, "num_tokens": 11749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.21469141911224196, "lm_q1q2_score": 0.0818445666542794}} {"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols, exp\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n\n```python\nu, u1, u2, t, a, b, c = symbols('u u1 u2 t a b c')\n```\n\n# Differential equations\n# Exponential eAt of a matrix\n\n## Differential equations (ordinary only)\n\n* A differential equation moves on from the previous lecture's difference equation which had finite steps to continuously changing systems (here in the time parameter *t*)\n* A differential equation included a function and its derivative(s)\n* It has and order based on the highest derivative that appears\n* Here we are only concerned with differential equation with constant coefficients\n* The simplest differential equation is the following\n$$ \\frac{dy}{dt}={a}{y}\\left(t\\right) $$\n* It is simply solved in the following manner (which gives us some insight into the general solution for these equations)\n$$ \\frac { dy }{ dt } =ay\\\\ \\frac { 1 }{ y } dy=adt\\\\ \\int { \\frac { 1 }{ y } } dy=a\\int { } dt\\\\ \\ln { \\left| y \\right| } =a\\left( t+{ c }_{ 1 } \\right) \\\\ { e }^{ \\ln { \\left| y \\right| } }={ e }^{ at+a{ c }_{ 1 } }\\\\ y={ e }^{ at }{ e }^{ a{ c }_{ 1 } }\\\\ y=c{ e }^{ at } $$\n* We can solve for the constant(s) if we have values for the initial condition (usually *t*=0) for *y*(t) and all its derivatives (called *initial value problems*)\n* We can write a system of differential equations in matrix form\n$$ { y }_{ 1 }^{ ' }=3{ y }_{ 1 }\\\\ { y }_{ 2 }^{ ' }=-2{ y }_{ 2 }\\\\ { y }_{ 3 }^{ ' }=6{ y }_{ 3 }\\\\ \\therefore \\quad \\begin{bmatrix} { y }_{ 1 }^{ ' } \\\\ { y }_{ 2 }^{ ' } \\\\ { y }_{ 3 }^{ ' } \\end{bmatrix}=\\begin{bmatrix} 3 & 0 & 0 \\\\ 0 & -2 & 0 \\\\ 0 & 0 & 6 \\end{bmatrix}\\begin{bmatrix} { y }_{ 1 } \\\\ { y }_{ 2 } \\\\ { y }_{ 3 } \\end{bmatrix} $$\n\n* Rewriting the above, we consider the following differential equations in this lecture\n$$ \\frac { d\\underline { u } }{ dt } =A\\underline { u } $$\n\n* So suppose we have these two differential equations\n$$ \\frac{{d}\\underline{u}_{1}}{{d}{t}} = -\\underline{u}_{1}+2\\underline{u}_{2} \\\\ \\frac{{d}\\underline{u}_{2}}{{d}{t}} = \\underline{u}_{1}-2\\underline{u}_{2} $$\n* The intial consitions are given by the following\n$$ \\underline{u}\\left({0}\\right)=\\begin{bmatrix}1\\\\0\\end{bmatrix} $$\n\n* We can write it as A**u**\n\n\n```python\nA = Matrix([[-1, 2], [1, -2]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 2\\\\1 & -2\\end{matrix}\\right]$$\n\n\n\n\n```python\nu_vect = Matrix([u1, u2]) # u is now a sympy mathematical symbol\n# Have to use another variable name, i.e. u_vect\nu_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}u_{1}\\\\u_{2}\\end{matrix}\\right]$$\n\n\n\n* Multiplying this A**u** brings you back to the two linear equations\n\n\n```python\nA * u_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}- u_{1} + 2 u_{2}\\\\u_{1} - 2 u_{2}\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}-3 : 1, & 0 : 1\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects() # The results give the two eigenvectors in the following format\n# (eigenvalue, no of eigenvectors, eigenvector)\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}-3, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}0, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}2\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\nS, D = A.diagonalize() # For interest sake we get the matrix of eigenvectors and the diagonal matrix\nS, D\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}-1 & 2\\\\1 & 1\\end{matrix}\\right], & \\left[\\begin{matrix}-3 & 0\\\\0 & 0\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* To complete the solution now, we note that there are two eigenvalues, which will give us the following\n * Two constants\n * Two exponent to the power eigenvalue times *t*\n * Two eigenvectors\n* It is written like this, with **x**i denoting an eigenvector\n$$ \\underline { u } \\left( t \\right) ={ c }_{ 1 }{ e }^{ { \\lambda }_{ 1 }t }{ \\underline { x } }_{ 1 }+{ c }_{ 2 }{ e }^{ { \\lambda }_{ 2 }t }{ \\underline { x } }_{ 2 } $$\n* This makes our solution as follows\n$$ \\underline { u } \\left( t \\right) ={ c }_{ 1 }{ e }^{ -3t }\\begin{bmatrix} -1 \\\\ 1 \\end{bmatrix}+{ c }_{ 2 }{ e }^{ \\left( 0 \\right) t }\\begin{bmatrix} 2 \\\\ 1 \\end{bmatrix}\\\\ \\underline { u } \\left( t \\right) ={ c }_{ 1 }{ e }^{ -3t }\\begin{bmatrix} -1 \\\\ 1 \\end{bmatrix}+{ c }_{ 2 }\\begin{bmatrix} 2 \\\\ 1 \\end{bmatrix} $$\n* There is clearly a constant term and a term that approaches zero at *t* approaches infinity\n\n* Writing this as two separate equations we have the following\n$$ { u }_{ 1 }\\left( t \\right) =-{ c }_{ 1 }{ e }^{ -3t }+2{ c }_{ 2 }\\\\ { u }_{ 2 }\\left( t \\right) ={ c }_{ 1 }{ e }^{ -3t }+{ c }_{ 2 } $$\n\n* Using the initial conditions we can solve for *c*i\n$$ { u }_{ 1 }\\left( 0 \\right) =-{ c }_{ 1 }{ e }^{ -3\\left( 0 \\right) }+2{ c }_{ 2 }=1\\\\ { u }_{ 2 }\\left( 0 \\right) ={ c }_{ 1 }{ e }^{ -3\\left( 0 \\right) }+{ c }_{ 2 }=0\\\\ -{ c }_{ 1 }+2{ c }_{ 2 }=1\\\\ { c }_{ 1 }+{ c }_{ 2 }=0 $$\n\n* Let's use an augmented matrix and Gauss-Jordan elimination to solve for the two constants (or at least the python™ equivalent)\n\n\n```python\nC = Matrix([[-1, 2, 1], [1, 1, 0]])\nC.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & - \\frac{1}{3}\\\\0 & 1 & \\frac{1}{3}\\end{matrix}\\right], & \\begin{bmatrix}0, & 1\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* Which gives us the final solution\n$$ { u }_{ 1 }\\left( t \\right) =\\frac { 1 }{ 3 } { e }^{ -3t }+\\frac { 2 }{ 3 } \\\\ { u }_{ 2 }\\left( t \\right) =\\frac { -1 }{ 3 } { e }^{ -3t }+\\frac { 1 }{ 3 } $$\n\n* Just to remind ourselves about the previous lecture where we had difference equations and had something like the following\n$$ \\underline{u}={c}_{1}{\\lambda}_{1}^{k}{\\underline{x}}_{1}+{c}_{2}{\\lambda}_{2}^{k}{\\underline{x}}_{2} $$\n* Which is for finite steps, i.e. stepping by one\n$$ \\underline{u}_{k+1}={A}\\underline{u}_{k} $$\n\n## What can the eigenvalues tell us about these equations as *t* approaches ∞\n\n* If both eigenvalues (real parts) are negative, the equation **t**(t) approaches **0** (called *stability*)\n* If one eigenvalue (real part) is zero and the others (real parts) are less than one, the equations reach is specific value (called a *steady state*)\n* If any eigenvalue (real parts) is larger than zero, the equations approach ±∞\n\n## What can the matrix A2×2 tell us about the eigenvalues (and then what happens when *t* approaches ∞)\n\n* The trace is equal to the sum of the eigenvalues\n* The determinant is the product of the eigenvalues\n\n* If the trace is negative **and** the determinant positive, we will have stability\n\n## Using diagonalization\n\n* Consider the following derivation\n$$ \\frac { d\\underline { u } }{ dt } =A\\underline { u } \\\\ \\because \\quad A\\underline { u } =S\\underline { v } \\\\ S\\frac { d\\underline { v } }{ dt } =S\\underline { v } \\\\ \\frac { d\\underline { v } }{ dt } =S\\underline { v } { S }^{ -1 }=\\Lambda \\underline { v } $$\n\n* From this we have the following\n$$ \\underline { v } \\left( t \\right) ={ e }^{ \\Lambda t }\\underline { v } \\left( 0 \\right) \\\\ \\underline { u } \\left( t \\right) =S{ e }^{ \\Lambda t }{ S }^{ -1 }\\underline { u } \\left( 0 \\right) \\\\ {e}^{At}={S}{e}^{\\Lambda{t}}{S}^{-1} $$\n\n## Matrix exponential *e*At\n\n* How do we calculate a matrix as a power? \n* Consider Taylor series expansion\n$$ {e}^{At}={I}+{At} + \\frac{{\\left(At\\right)}^{2}}{2!}+\\frac{{\\left(At\\right)}^{3}}{3!}+\\dots+\\frac{{\\left(At\\right)}^{n}}{n!} $$\n* This comes from the following\n$$ { e }^{ x }=\\sum _{ n=0 }^{ \\infty }{ \\frac { { x }^{ n } }{ n! } } $$\n* As the denominator increases the *n*th term approaches 0\n* Remember also this (geometric) series (just for fun)\n$$ \\frac { 1 }{ 1-x } =\\sum _{ 0 }^{ \\infty }{ { x }^{ n } } \\\\ { \\left( I-At \\right) }^{ -1 }=I+At+{ \\left( At \\right) }^{ 2 }+\\dots { \\left( At \\right) }^{ n } $$\n* This will blow up unless then eigenvalues of A are less than 1\n\n* Now, let calculate *e*At, remembering the following\n$$ {A}^{k}={S}{\\Lambda}^{k}{S}^{-1} $$\n$$ { e }^{ At }=\\sum _{ n=0 }^{ \\infty }{ \\frac { \\left( S{ \\Lambda }^{ n }{ S }^{ -1 } \\right) ^{ n }{ t }^{ n } }{ n! } } $$\n\n* We thus have the following\n$$ {e}^{At}={S}{e}^{\\Lambda{t}}{S}^{-1} $$\n* This is with the assumption that A can be diagonalized (otherwise we will have to use the infinite series (above)\n$$ {e}^{At}={I}+{At} + \\frac{{\\left(At\\right)}^{2}}{2!}+\\frac{{\\left(At\\right)}^{3}}{3!}+\\dots+\\frac{{\\left(At\\right)}^{n}}{n!} $$\n\n* Remember that Λ is a diagonal matrix and therefor we would have the following\n$$ { e }^{ \\Lambda t }=\\begin{bmatrix} { e }^{ { \\lambda }_{ 1 }t } & 0 & 0 & 0 \\\\ 0 & { e }^{ { \\lambda }_{ 2 }t } & 0 & 0 \\\\ \\vdots & \\vdots & \\dots & \\vdots \\\\ 0 & 0 & 0 & { e }^{ { \\lambda }_{ n }t } \\end{bmatrix} $$\n\n* The S and S-1 matrices are stable, it is therefor the Λ matrix that provides an approach to zero as *t* approaches ∞\n* This is achieved by every λi having a real part less than zero\n\n* The powers of A go to zero if the absolute value of the real part of all the λi-values is less than 1\n\n+ Let's consider this example\n\n$$ \\underline { y } ''+b\\underline { y } '+{k}\\underline{y}=\\underline { 0 } $$\n\n* We have to create a system of two first-order equations\n$$ \\underline{u}=\\begin{bmatrix} y' \\\\ y \\end{bmatrix} \\\\ \\underline{u}'=\\begin{bmatrix}{y}''\\\\{y}'\\end{bmatrix}=\\begin{bmatrix} -{b} & -{k} \\\\ 1 & 0 \\end{bmatrix}\\begin{bmatrix} {y}' \\\\ {y} \\end{bmatrix}$$\n\n## Example problems\n\n### Example problem 1\n\n* Find the general solutions, the matrix A, and the first column of *e*At of the following third-order, ordinary, homogeneous differential equation with constant coefficients\n$$ \\frac { { d }^{ 3 }y }{ d{ t }^{ 3 } } +2\\frac { { d }^{ 2 }y }{ d{ t }^{ 2 } } -\\frac { dy }{ dt } -2y=0 $$\n\n#### Solution\n\n* Since the differential equation is third order, we need to create three first-order differential equations\n$$ \\frac { { d }^{ 3 }y }{ d{ t }^{ 3 } } +2\\frac { { d }^{ 2 }y }{ d{ t }^{ 2 } } -\\frac { dy }{ dt } -2y=0\\\\ \\therefore \\quad y'''=-2y''+y'+2\\\\ \\underline { u } =\\begin{bmatrix} y'' \\\\ y' \\\\ y \\end{bmatrix}\\\\ \\underline { u } '=\\begin{bmatrix} y''' \\\\ y'' \\\\ y' \\end{bmatrix}\\\\ \\underline { u } '=A\\underline { u } =\\begin{bmatrix} -2 & 1 & 2 \\\\ 1 & 0 & 0 \\\\ 0 & 1 & 0 \\end{bmatrix}\\begin{bmatrix} y'' \\\\ y' \\\\ y \\end{bmatrix} $$\n\n* Notice that when we do the last matrix multiplication, we get exactly what we need\n$$ \\underline { u } '=\\begin{bmatrix} y''' \\\\ y'' \\\\ y' \\end{bmatrix}=\\begin{bmatrix} -2y''+y'+2y \\\\ y'' \\\\ y' \\end{bmatrix} $$\n\n* We now have the matrix A and we can calculate *e*At if A is diagonalizable\n\n\n```python\nA = Matrix([[-2, 1, 2], [1, 0, 0], [0, 1, 0]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}-2 & 1 & 2\\\\1 & 0 & 0\\\\0 & 1 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\nS, D = A.diagonalize()\nS, D\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}4 & 1 & 1\\\\-2 & -1 & 1\\\\1 & 1 & 1\\end{matrix}\\right], & \\left[\\begin{matrix}-2 & 0 & 0\\\\0 & -1 & 0\\\\0 & 0 & 1\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* We can calculate *e*At from the following\n$$ {e}^{At}={S}{e}^{\\Lambda{t}}{S}^{-1} $$\n\n* Remember that Λ is a diagonal matrix and therefor we would have the following\n$$ { e }^{ \\Lambda t }=\\begin{bmatrix} { e }^{ { \\lambda }_{ 1 }t } & 0 & 0 & 0 \\\\ 0 & { e }^{ { \\lambda }_{ 2 }t } & 0 & 0 \\\\ \\vdots & \\vdots & \\dots & \\vdots \\\\ 0 & 0 & 0 & { e }^{ { \\lambda }_{ n }t } \\end{bmatrix} $$\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}-2 : 1, & -1 : 1, & 1 : 1\\end{Bmatrix}$$\n\n\n\n* This gives us the three eigenvalues from which we can create the diagonal matrix *e*Λt\n\n\n```python\ne_Lamda_t = Matrix([[exp(-2 * t), 0, 0], [0, exp(-t), 0], [0, 0, exp(t)]])\ne_Lamda_t\n```\n\n\n\n\n$$\\left[\\begin{matrix}e^{- 2 t} & 0 & 0\\\\0 & e^{- t} & 0\\\\0 & 0 & e^{t}\\end{matrix}\\right]$$\n\n\n\n* We have to multiply the following three matrices (with which python is not comfortable, so I'll do it in two steps)\n\n\n```python\nS, e_Lamda_t, S.inv()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}4 & 1 & 1\\\\-2 & -1 & 1\\\\1 & 1 & 1\\end{matrix}\\right], & \\left[\\begin{matrix}e^{- 2 t} & 0 & 0\\\\0 & e^{- t} & 0\\\\0 & 0 & e^{t}\\end{matrix}\\right], & \\left[\\begin{matrix}\\frac{1}{3} & 0 & - \\frac{1}{3}\\\\- \\frac{1}{2} & - \\frac{1}{2} & 1\\\\\\frac{1}{6} & \\frac{1}{2} & \\frac{1}{3}\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n\n```python\nfirst_part = S * e_Lamda_t\nfirst_part\n```\n\n\n\n\n$$\\left[\\begin{matrix}4 e^{- 2 t} & e^{- t} & e^{t}\\\\- 2 e^{- 2 t} & - e^{- t} & e^{t}\\\\e^{- 2 t} & e^{- t} & e^{t}\\end{matrix}\\right]$$\n\n\n\n\n```python\nfirst_part * S.inv()\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{e^{t}}{6} - \\frac{e^{- t}}{2} + \\frac{4}{3} e^{- 2 t} & \\frac{e^{t}}{2} - \\frac{e^{- t}}{2} & \\frac{e^{t}}{3} + e^{- t} - \\frac{4}{3} e^{- 2 t}\\\\\\frac{e^{t}}{6} + \\frac{e^{- t}}{2} - \\frac{2}{3} e^{- 2 t} & \\frac{e^{t}}{2} + \\frac{e^{- t}}{2} & \\frac{e^{t}}{3} - e^{- t} + \\frac{2}{3} e^{- 2 t}\\\\\\frac{e^{t}}{6} - \\frac{e^{- t}}{2} + \\frac{1}{3} e^{- 2 t} & \\frac{e^{t}}{2} - \\frac{e^{- t}}{2} & \\frac{e^{t}}{3} + e^{- t} - \\frac{1}{3} e^{- 2 t}\\end{matrix}\\right]$$\n\n\n\n* We still need to write our general solution\n$$ \\underline { u } \\left( t \\right) ={ c }_{ 1 }{ e }^{ { \\lambda }_{ 1 }t }{ \\underline { x } }_{ 1 }+{ c }_{ 2 }{ e }^{ { \\lambda }_{ 2 }t }{ \\underline { x } }_{ 2 }+{ c }_{ 3 }{ e }^{ { \\lambda }_{ 3 }t }{ \\underline { x } }_{ 3 } $$\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}-2, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}4\\\\-2\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}-1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\-1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* With these eigenvalues and eigenvectors we get\n$$ \\underline { u } \\left( t \\right) =\\begin{bmatrix} { y }'' \\\\ y' \\\\ y \\end{bmatrix}={ c }_{ 1 }{ e }^{ -2t }\\begin{bmatrix} 4 \\\\ -2 \\\\ 1 \\end{bmatrix}+{ c }_{ s }{ e }^{ -t }\\begin{bmatrix} 1 \\\\ -1 \\\\ 1 \\end{bmatrix}+{ c }_{ 3 }{ e }^{ t }\\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\end{bmatrix}\\\\ \\therefore \\quad y\\left( t \\right) ={ c }_{ 1 }{ e }^{ -2t }+{ c }_{ 2 }{ e }^{ -t }+{ c }_{ 3 }{ e }^{ t } $$\n\n### Example problem 2\n\n* Solve the following second-order ordinary differential equation\n$$ y''-y'-6y=0 $$\n\n#### Solution\n\n* We need to create two first-order equations \n$$ \\therefore \\quad y''=y'+6y\\\\ \\because \\quad \\underline { u } \\left( t \\right) =\\begin{bmatrix} y' \\\\ y \\end{bmatrix}\\\\ \\underline { u } '\\left( t \\right) =\\begin{bmatrix} y'' \\\\ y' \\end{bmatrix}\\\\ \\therefore \\quad \\underline { u } '\\left( t \\right) =\\begin{bmatrix} 1 & 6 \\\\ 1 & 0 \\end{bmatrix}\\underline { u } \\left( t \\right) $$\n\n\n```python\nA = Matrix([[1, 6], [1, 0]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 6\\\\1 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}-2, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-2\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}3, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}3\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* The solution is thus as follows\n$$ {y}\\left({t}\\right)={c}_{1}{e}^{-2t}+{c}_{2}{e}^{3t} $$\n\n\n```python\n\n```\n", "meta": {"hexsha": "9609f91dde40cf7a9fb7fcd6cdb8ad59f5f237de", "size": 33413, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_23_Differential_equations_Exponential_of_a_matrix.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_23_Differential_equations_Exponential_of_a_matrix.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_23_Differential_equations_Exponential_of_a_matrix.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": 32.004789272, "max_line_length": 532, "alphanum_fraction": 0.446173645, "converted": true, "num_tokens": 6568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.19682619657611936, "lm_q1q2_score": 0.08166296178199986}} {"text": "```python\n# %load ../../preconfig.py\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.rcParams['axes.grid'] = False\n\nimport numpy as np\nimport pandas as pd\n#import itertools\n\nimport networkx as nx\n\nimport string\n\nimport logging\nlogger = logging.getLogger()\n```\n\n10 Mining Social-Network Graphs\n=================\n1. how to identify \"communities\"? \n communities: strong connections, usually overlap.\n \n2. explore efficient algorithms for discovering other properities of graphs.\n\n### 10.1 Social Networks as Graphs\n#### 10.1.1 What is a Social Network?\nThe essential characteristics of a social network are:\n\n1. There is a collection of entities that participate in the network.\n\n2. There is at least one relationship between entities of the network.\n\n + all-or-nothing: friends of Facebook.\n \n + discrete degree: friends, family as in Google plus.\n \n + real number: the times of talking.\n \n3. There is an assumption of nonrandomness or locality. \n If A is related to both B and C, then there is a higher probability than average that B and C are related.\n\n#### 10.1.2 Social Networks as Graphs\nsocial graph: The entities are the nodes, and an edge connects two nodes if the nodes are realted by the relationship that characterizes the network.\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_1.png'))\n```\n\nIs Fig 10.1 typical of a social network, in the sense that it exhibits locality of relationships?\n\nSuppose X, Y and Z are nodes of Fig 10.1, with edges between X and Y and also between X and Z.\n\n1. What would we *expect* the probability of an edge between Y and Z to be? \n The graph has 9 edges out of the $C_7^2 = 21$ pairs of nodes. \n \n Since we already have (X,Y) and (X,Z), the probability of an edge (Y,Z) is $(9-2)/(21-2) = 0.368$. If the graph were large enough, that probability would be very close to the fraction of the pairs of nodes that have edges between them, i.e., $9/21 = 0.429$.\n \n2. Then, we must compute the probability that $(Y,Z)$ exists in Fig 10.1, given that edges $(X,Y)$ and $(Y,Z)$ exist. \n We count the pairs of nodes that could be $Y$ and $Z$, without worrying about which node is $Y$ and which is $Z$.\n \n If $X$ is $A$, $(B,C)$ contributes one positive example. All details are in the table following. In all, the fraction of times the third edge exists in thus $9 / 16 = 0.563 > 0.368$. \n \n| node | pos | neg |\n|------|-----|-----|\n| A | 1 | 0|\n| C | 1 | 0|\n| E | 1 | 0|\n| G | 1 | 0|\n| F | 2 | 1|\n| B | 1 | 2|\n| D | 2 | 4|\n|sum| 9 | 7| 16 |\n\n\n#### 10.1.3 Varieties of Social Networks\n1. Telephone Networks\n\n2. Email Networks\n\n3. Collaboration Networks \n + Wikipedia: articles and editors. \n + published research papers and authors. \n \n4. Other example \n + information networks (patents) \n + infrastruture networks (roads) \n + biological networks (genes) \n + product co-purchasing networks (Groupon) \n\n### 10.1.4 Graphs with Several Node Types\nThere are other social phenomena that involve entities of different types. The natural way to represent such information is as a $K$-partite graph for some $k > 1$. In general, a $k$-partite graph consists of $k$ disjoint sets of nodes, with no edges between nodes of the same set.\n\nEg: \ndeli.cio.cu: there are three different kinds of entites: users, tags and pages.\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_2.png'))\n```\n\n`#exercise`\n\n### 10.2 Clustering of Social-Network Graphs\nclustering of the graph as a way to identify communities.\n\n\n#### 10.2.1 Distance Measures for Social-Network Graphs\ndistance measure:\n\\begin{align}\n d(x,y) = \n \\begin{cases}\n 0 \\text{ or } 1 \\text{ or } 1 & \\text{if edge} (x,y) {exists} \\\\\n 1 \\text{ or } \\infty \\text{ or } 1.5 & \\text{otherwise}\n \\end{cases}\n\\end{align}\n\n\n#### 10.2.2 Applying Standard Clustering Methods\nThey are generally unsuitable for the problem of clustering social-network graphs.\n\n\n#### 10.2.3 Betweenness: define\n*betweenness* of an edge $(a,b)$: \nthe number of pairs of nodes $x$ and $y$ such that $(a,b)$ lies on the shortest path between $x$ and $y$. And it's credicted with the fraction of all shortest paths between $x$ and $y$ if existed.\n\nA high score indicates that $(a,b)$ runs between two different communities, namely, $a$ and $b$ do no belong to the same community.\n\n\n#### 10.2.4 The Girvan-Newman Algorithm: calculate betweenness\nThe algorithm is aimed to calculate the number of shortest paths going through each eage.\n\n1) Starting at a node $X$, perform a breadth-first search (BFS) of the graph to label levels of each node. \n + DAG edges: edges between levels.\n \n + If there is a DAG edge $(Y,Z)$, where $Y$ is at the level about $Z$, then we shall call $Y$ a *parent* of $Z$ and $Z$ a *child* of $Y$.\n \n2) to label each node by the number of shortest paths that reach it from the root. \n + Start by labeling the root 1. \n + Then, from the top down, label each node $Y$ by the sum of the labes of its parents.\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_4.png'))\n```\n\n3) to calculate for each edge $e$ the sum over all nodes $Y$ of the fraction of shortest paths from the root $X$ to $Y$ that go through $e$. \n + from the bottom up.\n \n 1. Each leaf in the DAG gets a credit of 1.\n \n 2. Each node that is not a leaf gets a credit = 1 + the sum of the credits of the DAG edges from that node to its child nodes.\n \n 3. credit for $(Y_i, Z)$ is: \n $$\\text{credit}(Y_i, Z) = \\text{credit}(Z) \\frac{p_i}{\\sum_{j=1}^k p_i}$$\n where $Y_1, Y_2, \\dotsc, Y_k$ are the parents of $Z$, and $p_i$ is the number of the shorest paths from the root to $Y_i$, namely, the labels in Step 2).\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_6.png'))\n```\n\n4) After performing the credit calculation with *each node* as the root, \n 1. we sum the credits for each edge. \n \n 2. And then divive the credit for each edge by 2, as each shortest path will have been discovered twice.\n \n 3. Then we get the the true betweenness.\n\n#### 10.2.5 Using Betweenness to Find Communities\nIt's a process of edge removal:\n\n1. Start with the graph and all its edges;\n\n2. then remove edges with the highest betweenness, until the graph has broken into a suitable number of connected components.\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_7.png'))\nplt.figure()\nplt.imshow(plt.imread('./res/fig10_8.png'))\n```\n\nSpeeding up the Betweenness Calculation: \nIf the large is large, we can pick a subset of the nodes at random and use these as the root of breadth-first searches, we can get an approximation to the betweenness of each edge that will serve in most applications.\n\n**cons**: \nIt is not possible to place an individual in two different communities, and everyone is assigned to a community.\n\n\n```python\n# Exercises for Section 10.2\n```\n\n### 10.3 Direct Discovery of Communities\n#### 10.3.1 Finding Cliques\nNP-complete: finding a large *clique* (a sef of nodes with edges between any two of them).\n\n#### 10.3.2 Complete Bipartite Graphs\nA *complete bipartite graph* $K_{s,t}$ consists of $s$ nodes on one side and $t$ nodes on the other side, with all $st$ possible edges between the nodes of one side and the other present.\n\n**Idea**: \n\n1. While it is not possible to guarantee that a graph with many edges necessarily has a large clique, it is possible to guarantee that a bipartite graph with many edges has a large complete bipartite subgraph.\n\n2. We can regard a complete bipartite subgraph as the nucleus of a community, and add to it nodes with many edges to existing members of the community.\n\n + If its nodes is consisted of two or more types, construct bipartite graphs directly.\n \n + If all nodes have the same type, divide the node into two equal groups at random.\n\n#### 10.3.3 Finding Complete Bipartite Subgraphs\nIt's possible to view the problem of finding instance of $K_{s,t}$ within $G$ as one of finding frequent itemsets.\n\n1. \"items\" - left side. \n\n2. \"baskets\" - right side. \n The members of the basket for node $v$ are the nodes of the left side to which $v$ is connected.\n\n3. Let the support threshold be $s$, the number of nodes that the instance of $K_{s,t}$ has on the right side.\n\nthe problem of find $K_{s,t}$ $\\to$ finding frequent itemsets $F$ of size $t$.\n\n#### 10.3.4 Why Complete Bipartite Graphs Must Exist\nAssume:\n\n1. the graph $G$ has $n$ nodes on the left and another $n$ nodes on the right.\n\n2. let $d$ be the average degree of all nodes.\n\n3. the degree of the $i$th node on the right is $d_i$.\n\nProof:\n\n1. The total contribution of the $n$ nodes on the right is $\\sum_i \\binom{d_i}{t} \\geq n \\binom{d}{t}$ .\n\n2. The number of itemsets of size $t$ is $\\binom{n}{t}$.\n\n3. Thus, the average count of an itemset of size $t$ is $n \\binom{d}{t} / \\binom{n}{t}$ ???\n\n\\begin{align}\n n \\binom{d}{t} / \\binom{n}{t} &= n \\frac{d!}{(d-t)! t!} \\frac{t! (n-t)!}{n!} \\\\\n &= n \\frac{d (d-1) \\dotso (d-t+1)}{n (n-1) \\dotso (n-t+1)} \\\\\n &\\approx n \\frac{d^t}{n^t} \\quad \\text{when } n >> d >> t\n\\end{align}\n\nThat is, if there is a community with $n$ nodes on each side, the average degree of the nodes is $d$, and $n(d/n)^t \\geq s$, then this community is guaranteed to have a complete bipartite subgraph $K_{s,t}$.\n\n\n```python\n# Exercises for Section 10.3\n```\n\n### 10.4 Partitioning of Graphs\ntools from matrix theory $\\to$ minimizing the \"cut\" size.\n\n#### 10.4.1 What Makes a Good Partition?\n1. divide the nodes into two sets so that the *cut* (sets of edges between two groups) is minimized.\n\n2. two sets are approximately equal in size.\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_11.png'))\n```\n\n#### 10.4.2 Normalized Cuts\nA proper definition of a \"good\" cut must belance the size of the cut itself against the difference in the sizes of the sets that the cut creates.\n\nThe *normalized cut* value for $S$ and $T$ is\n\\begin{equation}\n \\frac{\\operatorname{Cut}(S,T)}{\\operatorname{Vol}(S)} + \\frac{\\operatorname{Cut}(S,T)}{\\operatorname{Vol}(T)}\n\\end{equation}\nwhere $\\operatorname{Vol}(S)$ is the number of edges with at least one end in $S$, and $\\operatorname{Cut}(S,T)$ is the number of edges connected between $S$ and $T$.\n\n#### 10.4.3 Some Matrices That Describe Graphs\n1. adjacent matrix:\n \\begin{equation}\n A_{i,j} = \\begin{cases}\n 1, & \\text{if node $i$ and $j$ is connected} \\\\\n 0, & \\text{otherwise}\n \\end{cases}\n \\end{equation}\n \n2. degree matrix:\n $D_{i,i}$ is the degree of the $i$th node.\n \n3. Laplacian matrix:\n $L = D - A$\n Notice that each row and column sums to zero.\n\n#### 10.4.4 Eigenvalues of the Laplacian Matrix\nThe smallest eignevalues and their eigenvectors reveal the information we desire.\n\n1. The smallest eignevalues for every Laplacian matrix is 0, and its corresponding eigenvectors is $\\mathbf{1}$ ones matrix.\n\n2. the second-smallest eigenvalues of $L$ is the minimum of $x^T L x$, and the minimum is taken under the constraints:\n + $\\displaystyle \\sum_{i=1}^n x_i^2 = 1$\n + $x$ is orthogonal to the eigenvector associated with the smallest eigenvalue.\n $$x^T \\mathbf{1} = \\displaystyle \\sum_{i=1}^n x_i = 0$$\n \nIn all:\n$x^T L x = \\sum_{i,j} (x_i - x_j)^2$\n \nAs a consequence, $x$ must have some positive and some negative components $\\to$ two sets/groups.\n\n#### 10.4.5 Alternative Partitioning Methods\n1. We could set the threshold at some point other than zero.\n\n2. We may also want to a partition into more than two components:\n + split repeatedly as far as desired.\n + use several of the eigenvectors to partition the graph.\n \nAttention: \nwhile each eigenvector tries to produce a minimum-sized cut, the fact that successive eigenvectors have to satisfy more and more constraints generally causes the cuts they describe to be progressively worse.\n\n\n```python\n# Exercises for Section 10.4\n## Ex 10.4.1 \n### (a)\n\nedges = [\n ('A', 'B'), ('A', 'C'), ('B', 'C'), \n ('B', 'H'), ('C', 'D'), ('H', 'I'),\n ('H', 'G'), ('D', 'E'), ('D', 'F'),\n ('I', 'G'), ('G', 'E'), ('E', 'F')\n]\n\nG = nx.Graph()\nG.add_edges_from(edges)\n```\n\n\n```python\nnx.draw(G)\n```\n\n\n```python\nA = nx.adjacency_matrix(G).todense()\nA\n```\n\n\n\n\n matrix([[0, 0, 0, 0, 0, 0, 0, 1, 1],\n [0, 0, 1, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 1, 0, 0],\n [0, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 1, 1, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 1, 1, 0, 0, 1, 0],\n [1, 0, 0, 0, 0, 0, 1, 0, 1],\n [1, 0, 0, 0, 0, 1, 0, 1, 0]], dtype=int64)\n\n\n\n\n```python\nD = np.diag(np.ravel(A.sum(axis=1)))\nD\n```\n\n\n\n\n array([[2, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 2, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 3, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 3, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 2, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 3, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 3, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 3, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 3]], dtype=int64)\n\n\n\n\n```python\nL = D - A\nL\n```\n\n\n\n\n matrix([[ 2, 0, 0, 0, 0, 0, 0, -1, -1],\n [ 0, 2, -1, 0, 0, -1, 0, 0, 0],\n [ 0, -1, 3, -1, 0, -1, 0, 0, 0],\n [ 0, 0, -1, 3, -1, 0, -1, 0, 0],\n [ 0, 0, 0, -1, 2, 0, -1, 0, 0],\n [ 0, -1, -1, 0, 0, 3, 0, 0, -1],\n [ 0, 0, 0, -1, -1, 0, 3, -1, 0],\n [-1, 0, 0, 0, 0, 0, -1, 3, -1],\n [-1, 0, 0, 0, 0, -1, 0, -1, 3]], dtype=int64)\n\n\n\n\n```python\n### Ex 10.4.2 \nw, v = np.linalg.eig(L)\n```\n\n\n```python\neig_min = np.argmin(w)\nw = np.delete(w, eig_min)\nv =np.delete(v, eig_min, axis=0)\n\neig_2nd_min = np.argmin(w)\neigv_2nd_min = np.ravel(v[eig_2nd_min])\n```\n\n\n```python\nsetA = set([n for v, n in zip(eigv_2nd_min, G.nodes()) if v >= 0])\nsetB = set(G.nodes()) - setA\nprint(setA, setB)\n```\n\n {'B', 'F', 'D', 'C', 'A', 'E'} {'I', 'H', 'G'}\n\n\n### 10.5 Finding Overlapping Communities\nCommunities are in practice rarely disjoint.\n\nAssume: \nthe probability that two individuals are connected by an edge increases as they become members of more communities in common.\n\n#### 10.5.1 The Nature of Communities\nWe expect edges to be dense with any community, but we expect edges to be even denser in the intersection of two communities, three communities, and so on.\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_19.png'))\n```\n\n#### 10.5.2 Maximum-Likelihood Estimation\nWe assume that the value of the parameters that gives the largest value of the likelihood is the correct model for the observed artifact.\n$$\\operatorname{argmax}_{\\theta} P[f(\\theta)]) $$\n\nprior probabilities:\n$$\\operatorname{argmax}_{\\theta} P[f(\\theta)]) = \\operatorname{argmax}_{\\theta} P[f(\\theta) | \\theta] \\, P[\\theta] $$\n\n#### 10.5.3 The Affiliation-Graph Model\naffiliation-graph model: generate social graphs from communities.\n\ncommunity-affiliation graphs:\n\n+ Given: $C$ communities, $N$ nodes(individuals).\n\n+ Question: $n_i \\in C_k$ ?\n\n+ Model:\n - Parameter: the memberships in the communities, $C_k = {n_i}$. \n - Parameter: $P_{ck}$ is the probability that two members of community $C_k$ are connected by an edge, $P_{ck} = P[(u,v) \\in E \\, | \\, u \\in C_k, v \\in C_k]$.\n \n \nwe compute the likelihood that a given graph with the proper number of nodes is generated by this mechanism.\n\n##### membership: Y/N\n1. Parameter: membership\n define membership: $n_i \\in C_k$. \n 0 / 1, Yes / No, decrete variable $\\to$ brute search\n\n2. Parameter: $P_{ck}$ \n\\begin{align}\n &P_{u,v} = 1 - \\displaystyle \\prod_{C_k in M} (1 - P_{ck}) \\quad \\text{where } M = {C_i: u \\in C_i, v \\in C_i}\\\\\n &P[f(P_{ck}, C_k, E)] = \\displaystyle \\prod_{(u,v) \\in E} P_{u,v} \\, \\prod_{(u,v) \\notin E} (1 - P_{u,v}) \n\\end{align}\n\n3. Goal:\n find $\\operatorname{argmax}_{C_k} P[f(P_{ck}, C_k, E)]$. \n \n##### membership: \"strength\"\navoiding the use of discrete membership changes. This improvement allows us to use standard methods.\n\n\"strenght of membership\": \nthe stronger the membership of two individuals in the same community, the more likely it is that this community will cause them to have an edge between them.\n\nIn the improved model,\n\n1. Parameter: membership\n define membership: strength, $F_{xC} \\in \\mathbb{R}_{\\ge 0}$\n \n2. Parameter: $P_{ck}$\n $$P_C(u,v) = 1 - e^{- F_{u,C} F_{v,C}}$$\n\n\n```python\n# exercise\n```\n\n### 10.6 Simrank\nThe purpose of simrank is to measure the similarity between nodes of the same type, and it does so by seeing where random walkers on the graph wind up when starting at a particular node $\\to$ limited in the size of graphs.\n\n#### 10.6.1 Random Walkers on a Social Graph\nRandom walkers:\n\nA walker at a node $N$ of an undirected graph will move with equal probability to any of the *neighbors* of $N$.\n\n#### 10.6.2 Random Walks with Restart\nLet $M$ be the *transition matrix* of the graph $G$: the entry in row $i$ and column $j$ of $M$ is $1/k$ if node $j$ of $G$ has degree $k$, and one of the adjacent nodes is $i$.\n\n$\\beta$ is the probability that the walker continues at random, so $1 - \\beta$ is the probability the walker will teleport to the initial node $N$. \n\n$v'$ is the probability the walker is at each of the nodes at the next round:\n$$v' = \\beta M v + (1 - \\beta) e_N$$\n\n\n```python\nplt.imshow(plt.imread('./res/fig10_22.png'))\n```\n\n\n```python\nedges = [\n ('Picture 1', 'Sky'),\n ('Picture 1', 'Tree'),\n ('Picture 2', 'Sky'),\n ('Picture 3', 'Sky'),\n ('Picture 3', 'Tree')\n]\n\nG=nx.Graph()\nG.add_edges_from(edges)\nnx.draw(G)\n```\n\n\n```python\nnodelist = ['Picture 1', 'Picture 2', 'Picture 3', 'Sky', 'Tree']\nadj = nx.adjacency_matrix(G, nodelist=nodelist).todense()\n```\n\n\n```python\nadj = pd.DataFrame(adj, index=nodelist, columns=nodelist)\nadj\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
Picture 1Picture 2Picture 3SkyTree
Picture 100011
Picture 200010
Picture 300011
Sky11100
Tree10100
\n
\n\n\n\n\n```python\nM = adj.apply(lambda x: x / sum(x), axis=0)\nM\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
Picture 1Picture 2Picture 3SkyTree
Picture 10.000.00.3333330.5
Picture 20.000.00.3333330.0
Picture 30.000.00.3333330.5
Sky0.510.50.0000000.0
Tree0.500.50.0000000.0
\n
\n\n\n\n\n```python\nbeta = 0.8\ne_0 = np.identity(M.shape[0])[0]\ne_0 = pd.DataFrame({'e_0': e_0}, index=nodelist)\ne_0\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
e_0
Picture 11
Picture 20
Picture 30
Sky0
Tree0
\n
\n\n\n\n\n```python\ndef random_walk(v: pd.DataFrame, beta: float, M: pd.DataFrame, e_n: pd.DataFrame) -> pd.DataFrame:\n return beta * (M.dot(v)) + (1 - beta) * e_n\n```\n\n\n```python\nv = [e_0]\niter_time = 50\n\nv_ = v[0]\nfor k in range(iter_time):\n v_ = random_walk(v_, beta, M, e_0)\n v.append(v_) \n\nindex = list(range(iter_time+1))\npd.concat(v, axis=1).T.reset_index(drop=True).T\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 \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 \n \n \n \n \n \n \n \n
0123456789...41424344454647484950
Picture 110.20.4666670.2533330.4183110.2863290.3913080.3073250.3744460.320749...0.3445910.3446250.3445980.3446200.3446030.3446160.3446050.3446140.3446070.344613
Picture 200.00.1066670.0213330.1009780.0372620.0894480.0476990.0812280.054405...0.0663260.0663430.0663290.0663400.0663310.0663380.0663330.0663370.0663330.066336
Picture 300.00.2666670.0533330.2183110.0863290.1913080.1073250.1744460.120749...0.1445910.1446250.1445980.1446200.1446030.1446160.1446050.1446140.1446070.144613
Sky00.40.0800000.3786670.1397330.3354310.1788730.3046050.2040190.284540...0.2487850.2487340.2487740.2487420.2487680.2487470.2487640.2487500.2487610.248752
Tree00.40.0800000.2933330.1226670.2546490.1490630.2330460.1658600.219557...0.1957070.1956730.1957000.1956790.1956960.1956820.1956930.1956840.1956910.195686
\n

5 rows × 51 columns

\n
\n\n\n\n1. If we wanted to know what node were most similar to another node, we would have to start the analsis over for that node.\n\n2. notice that convergence takes time, since there is an initial oscillation.\n\n\n```python\n# Exercise\n```\n\n### 10.7 Counting Triangles\n#### 10.7.1 Why Count Triangles?\n1. to measure the extent to which a graph looks like a social network.\n\n If we start with $n$ nodes and add $m$ edges to a graph at random:\n + sets of three nodes: $\\binom{n}{3}$.\n + The probability of an edge between any two given nodes being added is $m / \\binom{n}{2} \\approx 2 m / n^2$.\n + The probability that any set of three nodes has edges between each pair (independently chosen) is $(2m / n^2)^3 = 8 m^3 / n^6$.\n + expected number of triangles of random graph is $(8 m^3 / n^6) (n^3 / 6) = \\frac{4}{3} (m / n)^3$.\n \n We expect the number of triangles to be much greater than the value for a random graph.\n \n2. It has been demonstrated that the age of a community is related to the density of triangles.\n\n#### 10.7.2 An Algorithm for Finding Triangles\nSuppose we have a graph of $n$ nodes and $m \\geq n$ edges.\n\nnouns:\n+ heavy hitter: the node whose degree is at least $\\sqrt{m}$.\n note, the number of heavy-hitter nodes is nore more than $2\\sqrt{m}$, since otherwise the sum of degree of nodes would be more than $2m$.\n \n+ heavy-hitter triangle: the triangle all three of whose nodes are heavy hitter.\n\nAssuming the graph is represented by its edges, we preprocess the graph as follows:\n\n1. Compute the degree of each node. $O(m)$\n\n2. Create an index on edges, with the pair of nodes at its ends as the key. constructed in $O(m)$. Query the existence of an edge $O(1)$.\n\n3. Create another index of edges, this one with key equal to a single node. to retrieve the nodes adjacent to given node. $O(\\sqrt{m})$\n\n\norder the nodes: `nodes.sort_values(by=['degree', 'id'])`\n\n\n##### Finding triangles:\n1. Heavy-Hitter Triangles:\n Find in all heavy-hitter nodes which is only $O(\\sqrt{m})$.\n time: $O(\\sqrt{m}^3) = O(m^{3/2})$\n \n2. Other Triangles:\n Consider each edge $(v_1, v_2)$:\n + if both $v_1$ and $v_2$ are heavy hitters, ignore the dege. (use $v_3$ since the computation is less).\n \n + if $v_1 < v_2$, query whether $(v_1.\\text{adjacent nodes}), v_2)$ exits. $O(\\sqrt{m} * m) = O(m^{3/2})$.\n \nThe total time of the algorithm is $O(m^{3/2})$.\n\n#### 10.7.3 Optimality of the Triangle-Finding Algorithm\nIt turns out the algorithm described above is, to within an order of magnitude the best possible.\n\nFor a complete graph on $n$ nodes, it has $m = \\binom{n}{2}$ edges and the number of triangles is $\\binom{n}{3}$. Since we cannot enumerate triangles in less time than the number of those triangles $O(n^3) = O((\\sqrt{m})^3) = O(m^{3/2})$.\n\nFor sparse graphs, we can add to the complete graph a chain of nodes with any length up to $n^2$ to convert.\n\n#### 10.7.4 Finding Triangles Using MapReduce\nmultiway join technique:\n$E(X, Y) \\bowtie E(X, Z) \\bowtie E(Y, Z)$\n\nif we hash nodes to $b$ buckets, then there will be $b^3$ reducers, since $(h(u), h(v), z)$, $(h(u), y, h(v))$ and $(x, h(u), h(v)$ are mapped. \n$\\to$ The total communication required is thus $3b$ key-value pairs for each of the $m$ tuples of the edge relation $E$, namely $O(mb)$ if we use $b^3$ Reduce tasks. \n$\\to$ each Reduce task receives $O(mb) / b^3 = O(m / b^2)$ edges. \n$\\to$ If we use the algorithm of Section 10.7.2, the computation cost of each Reduce is $O((m / b^2)^{3/2})$. Thus, the total computation cost of $b^3$ Reduce is $O((m / b^2)^{3/2} * b^3) = O(m^{3/2})$.\n\n#### 10.7.5 Using Fewer Reduce Tasks\nBy a judicious ordering of the nodes, we can lower the number of reduce tasks by approximately a factor of 6.\n\nOrder by \"name\", $(h(i), i)$. The Reduce task corresponding to list of bucket $(i, j, k)$ will be needed only if $i \\leq j \\leq k$.\n\n#### 10.7.6 Exercises for Section 10.7\n\n### 10.8 Neighborhood Properties of Graphs\n#### 10.8.1 Directed Graphs and Neighborhoods\nall undirected graphs can be represented by directed graphs.\n\n**path**: a sequence of nodes in a directed graph. Its *length* is the number of arcs, instead of nodes, along the path.\n\nThe *neighborhood of radius* $d$ for $v$ is: $\\{u : \\operatorname{len}(u, v) \\leq d\\}$, denote this neighborhood by $N(v, d)$.\n\nThe *neighborhood profile* of a node $v$ is the sequence of sizes of its neighborhoods $|N(v, 1)|, |N(v, 2)|, \\dotso$.\n\n#### 10.8.2 The Diameter of a Graph\nThe *diameter* $d$ of a directed graph: $\\max (\\operatorname{len}(u, v)): u \\in G, v \\in G$.\n\nfor each node $v$, we can find the smallest $d$ such that $|N(v, d)| = |N(v, d+1)|$, and call it $d(v)$. $\\to$ the $d$ of $G$ is: $\\max_{v} d(v)$.\n\nA graph is *strongly connected* if there is a paht from any node to any other node. If $G$ is strongly connected, the $d = \\max_{v} d(v)$.\n\n\"six degrees of separation\": the diameter of social graph is six. Unfortunately, not all important graphs exhibit such tight connections.\n\n#### 10.8.3 Transitive Closure and Reachability\nThe *transitive closure* of a graph is: $\\{(u, v) : \\operatorname{len of Path}(u, v) \\geq 0 \\}$. denoted $\\operatorname{Path}(u, v)$.\n\n*reachability*: we say node $u$ reaches node $v$ if $\\operatorname{Path}(u, v)$.\n\n$\\operatorname{Path}(u, v)$ is true if and only if $v$ is in $N(u, \\infty) = \\cup_{i \\geq 0} N(u, i)$.\n\nThe two problems - transtive closure and reachability - are related, but there are many examples of graphs where reachability is feasible and transitive closure is not.\n\n#### 10.8.4 Transitive Closure Via MapReduce\ntransitive closure is actually more readily parallelizable than is reachability.\n\n##### calculate reachability\n$\\operatorname{Arc}(X, Y) = \\{(x, y) \\text{ where } x \\to y\\}$.\n\n```\nSELECT DISTINCT Arc.Y\nFROM Reach, Arc\nWHERE Arc.X = Reach.X\n```\n\nhow many rounds this process requires depends on how far from $v$ is the furthest node that $v$ can reach.\n\n\n##### calculate transitive closure\nrecursive-doubling method\n\n```\nSELECT DISTINCT p1.X, p2.Y\nFROM Path p1, Path p2\nWHERE p1.Y = p2.X\n```\n\n#### 10.8.5 Smart Transitive Closure\nThe above recursive-doubling method does a lot of redundant work, since there may exist many paths between two nodes.\n\n_smart_ transitive closure: \nEvery path of length greater than 1 can be broken into a _head_ whose length is a power of 2, followed by a _tail_ whose length is no greater than the length of the head.\n\n$Q(X, Y)$ holds all pairs of nodes $(x, y)$ such that the shortest path from $x$ to $y$ is of length exactly $2^i$ after the $i$th round.\n\nIntitally, set both $Q$ and _Path_ to be copies of the relation _Arc_.\n\nOn the $(i + 1)$st round, we do the following:\n\n1. Compute a new value for $Q$ by joining it with itself: \n ```\n SELECT DISTINCT q1.X, q2.Y\n FROM Q q1, Q q2\n WHERE q1.Y = q2.X\n ```\n \n2. Subtract _Path_ from the relation _Q_ computed in step 1.\n\n3. Join _Path_ with the nw value of _Q_ computed in 2: \n ```\n SELECT DISTINCT Q.X, Path.Y\n FROM Q, Path\n WHERE Q.Y = Path.X\n ```\n \n4. Set the new value of _Path_ to be the union of the relation computed in step 3, the new value of _Q_ computed in step 1, and the old value of _Path_.\n\n#### 10.8.6 Transitive Closure by Graph Reduction\ncollapse an SCC (Stronly connected components) to a single node when computing the transitive closure.\n\nto find most of the SCC's in a graph by some random node selections followed by two breadth-first searches.\n\nLet $G$ be the graph to be reduced, and let $G'$ be $G$ with all the arcs reversed.\n\n1. Pick a node $v$ from $G$ at random.\n\n2. Find $N_G(v, \\infty)$, the set of nodes reachable from $v$ in $G$.\n\n3. Find $N_{G'} (v, \\infty)$, the set of nodes that $v$ reaches in the graph $G'$ that has the arcs of $G$ reversed.\n\n4. Construct the SCC S containing $v$, which is $N_G(v, \\infty) \\cap N_{G'}(v, \\infty)$.\n\n5. Replace SCC S by a single node $s$ in $G$.\n\n#### 10.8.7 Approximating the Sizes of Neighborhoods\napproximation:\n\n1. apply hash function $h$ to nodes $\\{v\\}$, find the longest \"tail length\" $R$.\n\n2. estimate the size of the set is $2^R$.\n\n\n```python\n# Exercise 10.8.8\n```\n", "meta": {"hexsha": "ff189d6d8766169cf6467c618efe691e764d9acf", "size": 584611, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mining_of_Massive_Datasets/Mining_Social_Network_Graphs/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "Mining_of_Massive_Datasets/Mining_Social_Network_Graphs/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "Mining_of_Massive_Datasets/Mining_Social_Network_Graphs/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 324.6035535813, "max_line_length": 73708, "alphanum_fraction": 0.9084912874, "converted": true, "num_tokens": 10795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.16238003058646674, "lm_q1q2_score": 0.08119001529323337}} {"text": "```\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"./styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n###### Content provided under a Creative Commons Attribution license, CC-BY 4.0; code under MIT License. (c)2014 [David I. Ketcheson](http://davidketcheson.info)\n\n##### version 0.1 - April 2014\n\n# Fluid dynamics\n\nIn this lesson we will look at the system of hyperbolic PDEs that governs the motions of fluids in the absence of viscosity. These consist of conservation laws for **mass, momentum**, and **energy**. Together, they are referred to as the **compressible Euler equations**, or simply the Euler equations.\n\n## Mass conservation\n\nWe will use $\\rho(x,t)$ to denote the fluid density and $u(x,t)$ for its velocity. Then the equation for conservation of mass is just the **continuity equation** we discussed in [Lesson 1](Lesson_01_Advection.ipynb):\n\n$$\\rho_t + (\\rho u)_x = 0.$$\n\n## Momentum conservation\n\nThe momentum is given by the product of density and velocity, i.e. $\\rho u$. The momentum flux has two components. First, the momentum is transported in the same way that the density is; this flux is given by the momentum times the density; i.e. $\\rho u^2$.\n\nTo understand the second term in the momentum flux, we must realize that a fluid is made up of many tiny molecules. The density and velocity we are modeling are average values over some small region of space. The individual molecules in that region are not all moving with exactly velocity $u$; that's just their average. Each molecule also has some additional random velocity component. These random velocities are what accounts for the **pressure** of the fluid, which we'll denote by $p$. These velocity components also lead to a net flux of momentum. Thus the momentum conservation equation is\n\n$$(\\rho u)_t + (\\rho u^2 + p)_x = 0.$$\n\n## Energy conservation\n\nThe energy has two components: internal energy $\\rho e$ and kinetic energy $\\rho u^2/2$:\n\n$$E = \\rho e + \\frac{1}{2}\\rho u^2.$$\n\nLike the momentum flux, the energy flux involves both bulk transport ($Eu$) and transport due to pressure ($pu$):\n\n$$E_t + (u(E+p)) = 0.$$\n\n## Equation of state\n\nYou may have noticed that we have 4 unknowns (density, momentum, energy, and pressure) but only 3 conservation laws. We need one more relation to close the system. That relation, known as the equation of state, expresses how the pressure is related to the other quantities. We'll focus on the case of an ideal gas, for which\n\n$$p = \\rho e (\\gamma-1).$$\n\nHere $\\gamma$ is the ratio of specific heats, which for air is approximately 1.4.\n\n## The Euler equations\n\nWe can write the three conservation laws as a single system $q_t + f(q)_x = 0$ by defining\n\\begin{align}\nq & = \\begin{pmatrix} \\rho \\\\ \\rho u \\\\ E\\end{pmatrix}, & \nf(q) & = \\begin{pmatrix} \\rho u \\\\ \\rho u^2 + p \\\\ u(E+p)\\end{pmatrix}.\n\\end{align}\n\nIn three dimensions, the equations are similar. We have two additional velocity components $v, w$, and their corresponding fluxes. Additionally, we have to account for fluxes in the $y$ and $z$ directions. We can write the full system as\n\n$$ q_t + f(q)_x + g(q)_y + h(q)_z = 0$$\n\nwith\n\n\\begin{align}\nq & = \\begin{pmatrix} \\rho \\\\ \\rho u \\\\ \\rho v \\\\ \\rho w \\\\ E\\end{pmatrix}, &\nf(q) & = \\begin{pmatrix} \\rho u \\\\ \\rho u^2 + p \\\\ \\rho u v \\\\ \\rho u w \\\\ u(E+p)\\end{pmatrix} &\ng(q) & = \\begin{pmatrix} \\rho v \\\\ \\rho uv \\\\ \\rho v^2 + p \\\\ \\rho v w \\\\ v(E+p)\\end{pmatrix} &\nh(q) & = \\begin{pmatrix} \\rho w \\\\ \\rho uw \\\\ \\rho vw \\\\ \\rho w^2 + p \\\\ w(E+p)\\end{pmatrix}.\n\\end{align}\n\n## Solving the Euler equations\n\nThese equations can be solved in a manner similar to what we used for advection and traffic flow. As you might guess, computing the flux gets significantly more complicated since we now have 3 (or 5) equations and more complicated flux expressions.\n\n## PyClaw\n\nImplementing a solver for the Euler equations from scratch would be a lot of fun, but to save some time we'll use a package called [PyClaw](http://clawpack.github.io/doc/pyclaw/), which is part of the [Clawpack](http://clawpack.github.io/) software (Clawpack stands for Conservation LAWs PACKage). PyClaw allows us to quickly and easily set up and solve problems modeled by hyperbolic PDEs.\n\nNow let's get started. First, import the parts of Clawpack that we'll use:\n\n\n```\nfrom clawpack import pyclaw\nfrom clawpack import riemann\n```\n\n### Setting up a problem\nTo solve a problem, we'll need to create the following:\n\n- A **domain** over which to solve the problem\n- A **solution**, where we will provide the initial data. After running, the solution will contain -- you guessed it! -- the solution.\n- A **solver**, which is responsible for actually evolving the solution in time. Here we'll need to specify the equations to be solved and the boundary conditions.\n- A **controller**, which handles the running, output, and can be used for plotting\n\nThis might sound complicated at first, but stick with me.\n\nLet's start by creating a controller and specifying the simulation end time:\n\n\n```\nclaw = pyclaw.Controller()\nclaw.tfinal = 0.1 # Simulation end time\n\nclaw.keep_copy = True # Keep solution data in memory for plotting\nclaw.output_format = None # Don't write solution data to file\nclaw.num_output_times = 50 # Write 50 output frames\n```\n\n### Riemann solvers\n\nThe method used to compute the flux between each pair of cells is referred to as a *Riemann solver*. By specifying a Riemann solver, we will specify the system of PDEs that we want to solve. So far we have only used very simple approximate Riemann solvers. Clawpack includes much more sophisticated Riemann solvers for many hyperbolic systems.\n\nPlace your cursor at the end of the line in the box below and hit 'Tab' (for autocompletion). You'll see a dropdown list of all the Riemann solvers currently available in PyClaw. The ones with 'py' at the end of the name are written in pure Python; the others are written in Fortran and wrapped with f2py.\n\n\n```\nriemann.\n```\n\nWe'll start with a simple 1D problem, using the Riemann solver `riemann.euler_with_efix_1D`:\n\n\n```\nriemann_solver = riemann.euler_with_efix_1D\nclaw.solver = pyclaw.ClawSolver1D(riemann_solver)\n```\n\nWe also need to specify boundary conditions. We'll use extrapolation boundary conditions, so that waves simply pass out of the domain:\n\n\n```\nclaw.solver.all_bcs = pyclaw.BC.extrap\n```\n\n### The problem domain\nNext we need to specify the domain and the grid. We'll solve on the unit line $[0,1]$ using 100 grid cells. Note that each argument to the Domain constructor must be a tuple:\n\n\n```\ndomain = pyclaw.Domain( (0.,), (1.,), (100,))\n```\n\n### The initial solution\nNext we create a solution object that belongs to the controller and extends over the domain we specified:\n\n\n```\nclaw.solution = pyclaw.Solution(claw.solver.num_eqn,domain)\n```\n\nThe initial data is specified in an array named `solution.q`. The density is contained in `q[0,:]`, the momentum in `q[1,:]`, and the energy in `q[2,:]`.\n\n\n```\nx=domain.grid.x.centers # grid cell centers\ngam = 1.4 # ratio of specific heats\n\nrho_left = 1.0; rho_right = 0.125\np_left = 1.0; p_right = 0.1\n\nclaw.solution.q[0,:] = (x<0.5)*rho_left + (x>=0.5)*rho_right\nclaw.solution.q[1,:] = 0.\nclaw.solution.q[2,:] = ((x<0.5)*p_left + (x>=0.5)*p_right)/(gam-1.0)\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.plot(x, claw.solution.q[0,:],'-o')\n```\n\nThis problem is known as the **Sod shock-tube**. It amounts to setting up a tube with a thin separator between a high-pressure, high-density region and a low-pressure, low-density region, then suddenly removing the separator.\n\nNext we need to specify the value of $\\gamma$, the ratio of specific heats.\n\n\n```\nproblem_data = claw.solution.problem_data\nproblem_data['gamma'] = 1.4\nproblem_data['gamma1'] = 0.4\n```\n\nFinally, let's run the simulation.\n\n\n```\nclaw.run()\n```\n\n### Plotting\nNow we'll plot the results, which are contained in a list called `claw.frames`. It's simple to plot a single frame with matplotlib:\n\n\n```\nfrom matplotlib import animation\nimport matplotlib.pyplot as plt\nfrom clawpack.visclaw.JSAnimation import IPython_display\nimport numpy as np\n\nfig = plt.figure()\nax = plt.axes(xlim=(0, 1), ylim=(-0.2, 1.2))\n\nframe = claw.frames[0]\npressure = frame.q[0,:]\nline, = ax.plot([], [], 'o-', lw=2)\n\ndef fplot(frame_number):\n frame = claw.frames[frame_number]\n pressure = frame.q[0,:]\n line.set_data(x,pressure)\n return line,\n\nanimation.FuncAnimation(fig, fplot, frames=len(claw.frames), interval=30)\n```\n\n### Waves\n\nIn the solution, 3 waves are visible:\n1. A **shock wave** moving rapidly to the right as the low-density fluid is compressed.\n2. A **rarefaction** wave moving to the left as the high-density fluid expands.\n3. A **contact discontinuity** moving more slowly to the right. This discontinuity in the density separates the region containing fluid that started in the high-pressure region and fluid that started in the low-pressure region.\n\nIn fact, the solution of any Riemann problem consists of some combination of these three types of waves. In the Euler equations, one of the waves is always a contact discontinuity, but each of the other two waves may be a shock or a rarefaction, depending on the left and right states.\n\n### Putting it all together\n\nFor convenience, all of the code from the cells above to set up and run the shocktube problem is pasted together below. Play around with the code. You might:\n- Increase the number of grid points to see what the solution converges to. Notice that the code still runs pretty fast even for larger grids. This is because the bottom layer of code in PyClaw is compiled Fortran, not Python.\n- Change the initial left and right states, or set up a completely different initial condition. See if you can generate a solution with two shock waves, or two rarefaction waves (some physical intuition is helpful here).\n- Change the ratio of specific heats\n- Make the boundaries periodic, so that there is a second shock wave moving left from $x=1$.\n\n\n```\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom clawpack import pyclaw\nfrom clawpack import riemann\n\nclaw = pyclaw.Controller()\nclaw.tfinal = 0.1\n\nclaw.keep_copy = True # Keep solution data in memory for plotting\nclaw.output_format = None # Don't write solution data to file\nclaw.num_output_times = 50 # Write 50 output frames\n\nriemann_solver = riemann.euler_with_efix_1D\nclaw.solver = pyclaw.ClawSolver1D(riemann_solver)\n\nclaw.solver.all_bcs = pyclaw.BC.extrap\n\ndomain = pyclaw.Domain( (0.,), (1.,), (100,))\nx=domain.grid.x.centers # grid cell centers\n\nclaw.solution = pyclaw.Solution(claw.solver.num_eqn,domain)\n\ngam = 1.4 # ratio of specific heats\nclaw.solution.problem_data['gamma'] = gam\nclaw.solution.problem_data['gamma1'] = gam-1.0\n\nrho_left = 1.0; rho_right = 0.125\np_left = 1.0; p_right = 0.1\n\nclaw.solution.q[0,:] = (x<0.5)*rho_left + (x>=0.5)*rho_right\nclaw.solution.q[1,:] = 0.\nclaw.solution.q[2,:] = ((x<0.5)*p_left + (x>=0.5)*p_right)/(gam-1.0)\n\nstatus = claw.run()\n```\n", "meta": {"hexsha": "05869994621a369d1625204ecddd8846d4647937", "size": 22990, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lesson_04_Fluid_dynamics.ipynb", "max_stars_repo_name": "IanHawke/HyperPython", "max_stars_repo_head_hexsha": "6a9c151de269d93e00aaafc370ff06682c7c666a", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-07T00:12:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T00:12:13.000Z", "max_issues_repo_path": "Lesson_04_Fluid_dynamics.ipynb", "max_issues_repo_name": "IanHawke/HyperPython", "max_issues_repo_head_hexsha": "6a9c151de269d93e00aaafc370ff06682c7c666a", "max_issues_repo_licenses": ["CC-BY-4.0", "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_Fluid_dynamics.ipynb", "max_forks_repo_name": "IanHawke/HyperPython", "max_forks_repo_head_hexsha": "6a9c151de269d93e00aaafc370ff06682c7c666a", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8586156112, "max_line_length": 614, "alphanum_fraction": 0.5324488908, "converted": true, "num_tokens": 3801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.2658804847339313, "lm_q1q2_score": 0.08083874791942201}} {"text": "# Getting Started With Python\n\n## Installation\n\nThere are various ways to install Python. Assuming the reader is not (yet) well versed in programming, I suggest to download the Anaconda distribution, which works for all major operating systems (Mac OS X, Windows, Linux) and provides a fully fledged Python installation including necessary libraries and Jupyter notebooks. \n\n* Go to https://www.continuum.io/downloads\n* Download latest version corresponding to your OS\n* Run .exe/.pkg file. \n - Make sure to set flag \"Add Anaconda to my PATH environment variable\" and \n - \"Register Anaconda as my default Python 3.6\"\n\nBe sure to download the latest Python 3.x version (not 2.x; backward compability is not always given!). \n\nThe installation should not cause any problems. If you wisch a step-by-step guide (incl. some further insights) see [Cyrille Rossants excellent notebook](http://nbviewer.jupyter.org/github/ipython-books/minibook-2nd-code/blob/master/chapter1/12-installation.ipynb) on the topic.\n\n## IPyton / Jupyter Notebooks\n\nWhat you see here is a so called Jupyter notebook. It makes it possible to interactively combine code with output (results, graphics), markdown text and LaTeX (for mathematical expressions). All codes discussed in this course will be provided through such notebooks and you soon will understand and appreciate the functionality they provide.\n\n* The basic markdown commands are well summarized [here](http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html). \n* LaTeX is a typesetting language with extensive capabilities to typeset math. For a basic introductin to math in LaTeX see sections 3.3 - 3.4 (p. 22 - 33) of *More Math into LaTeX* by Grätzer (2007), [available as pdf here](http://www.latexstudio.net/wp-content/uploads/2014/09/math.into_.Latex_.4ed.pdf)\n\n\nIf you are keen on learning more about IPython/Jupyter, consider [this notebook](http://nbviewer.jupyter.org/github/ipython-books/minibook-2nd-code/blob/master/chapter1/13-nbui.ipynb) - a well written introduction by Cyrille Rossant.\n\n## Data Types in Python\n\n### Building Blocks\n\nTo analyze data in Python, it has to be stored as some kind of data type. These data types form the structure of the data and make data easily accessible. Python's basic building blocks are:\n* Numbers (integer, floating point, and complex)\n* Booleans (true/false)\n* Strings\n* Lists\n* Dictionaries\n* Tuples\n\nWe will discuss the first four data types above as these are relevant for us.\n\nPython is a dynamic typing language meaning that - unlike in static languages such as VBA, C, Java etc. - you do not explicitly need to assign a data type to a variable. Python will do that for you. A few examples will explain this best: \n\n\n```python\na = 42 # In VBA you would first have to define data type, only then the value: Dim a as integer; a = 42\nb = 10.3 # VBA: Dim b as Double; b = 10.3\nc = 'hello' # VBA: Dim c as String; c = \"hello\"\nd = True # VBA: Dim d as Boolean; d = True\n\nprint('a: ', type(a))\nprint('b: ', type(b))\nprint('c: ', type(c))\nprint('d: ', type(d))\n```\n\n a: \n b: \n c: \n d: \n\n\n### Simple Arithmetics\nSimple arithmetic operations are straight forward:\n\n\n```python\na = 2 + 4 - 8 # Addition & Subtraction\nb = 6 * 7 / 3 - 2 # Multiplication & Division\nc = 2**(1/2) # Exponents & Square root\nd = 10 % 3 # Modulus\ne = 10 // 3 # Floor division\n\nprint(' a =', a, '\\n',\n 'b =', b, '\\n',\n 'c =', c, '\\n',\n 'd =', d, '\\n',\n 'e =', e)\n```\n\n a = -2 \n b = 12.0 \n c = 1.4142135623730951 \n d = 1 \n e = 3\n\n\nWe can even use arithmetic operators to concatenate strings:\n\n\n```python\na = 'Hello'\nb = 'World!'\nprint(a + ' ' + b)\n\nprint(a * 3)\n```\n\n Hello World!\n HelloHelloHello\n\n\n### Lists\nNow let's look at lists. Lists are capable of combining multiple data types.\n\n\n```python\ne = ['Calynn', '10.3', b, d]\nprint('e: ', type(e))\nprint([type(item) for item in e])\n```\n\n e: \n [, , , ]\n\n\nNote that the second element in list `e` is set in quotation marks and thus Python interprets this as string.\n\n## NumPy Arrays\n\n### NumPy Arrays from Lists\n\nFor as useful list appear, its flexibility comes at a high cost. Because each element contains not only the value itself but also information about the data type, storing data in list consumes a lot of memory. For this reason the Python community introduced NumPy (short for Numerical Python). Among other things, this package provides **fixed-type arrays** which are more efficient to store and operate on dense data than simple lists. \n\nFixed-type arrays are dense arrays of uniform type. We start by importing the NumPy package and creating some simple NumPy arrays form Python lists.\n\n\n```python\nimport numpy as np\n\n# Integer array\nnp.array([3, 18, 12])\n```\n\n\n\n\n array([ 3, 18, 12])\n\n\n\n\n```python\n# Floating point array\nnp.array([3., 18, 12])\n```\n\n\n\n\n array([ 3., 18., 12.])\n\n\n\nSimilarly, we can explicitly set the data type:\n\n\n```python\nnp.array([3, 18, 12], dtype='float32') \n```\n\n\n\n\n array([ 3., 18., 12.], dtype=float32)\n\n\n\n\n```python\n# Multidimensional arrays\nnp.array([range(i, i + 3) for i in [1, 2, 3]])\n```\n\n\n\n\n array([[1, 2, 3],\n [2, 3, 4],\n [3, 4, 5]])\n\n\n\nWe've seen above that we can define the data type for NumPy arrays. A list of available data types can be found in the [NumPy documentation](https://docs.scipy.org/doc/numpy/user/basics.types.html).\n\n\n### NumPy Arrays from Scratch\nSometimes it is helpful to create arrays from scratch. Here are some examples:\n\n\n```python\n# Integer array with 8 zeros \nnp.zeros(shape=8, dtype='int')\n```\n\n\n\n\n array([0, 0, 0, 0, 0, 0, 0, 0])\n\n\n\n\n```python\n# 2x3 floating-point array filled with 1s\nnp.ones((2, 3), 'float32')\n```\n\n\n\n\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n\n\n\nNote that I do not need to use `np.ones(shape=(2, 3), dtype='float32')` to define the shape. It's ok to go with the short version as long as the order is correct, Python will understand. However, going with the explicit version helps to make your code more readable and I encourage students to follow this advice.\n\n\n```python\n# 3x2 array filled with 2.71\nnp.full(shape=(3, 2), fill_value=2.71)\n```\n\n\n\n\n array([[ 2.71, 2.71],\n [ 2.71, 2.71],\n [ 2.71, 2.71]])\n\n\n\n\n```python\n# 3x3 boolean array filled with 'True'\nnp.full((2, 2), 1, bool)\n```\n\n\n\n\n array([[ True, True],\n [ True, True]], dtype=bool)\n\n\n\n\n```python\n# Array filled with linear sequence\nnp.arange(start = 0, stop = 1, step = 0.1) # or simply np.arrange(0, 1, 0.1)\n```\n\n\n\n\n array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])\n\n\n\n\n```python\n# Array of evenly spaced values\nnp.linspace(start = 0, stop = 1, num = 4)\n```\n\n\n\n\n array([ 0. , 0.33333333, 0.66666667, 1. ])\n\n\n\nArrays with random variables are easily created. Below three examples. See the [numpy.random documentation page](https://docs.scipy.org/doc/numpy/reference/routines.random.html) for details on how to generate other rv arrays.\n\n\n```python\n# 4x4 array of uniformly distributed random variables\nnp.random.random((4, 4))\n```\n\n\n\n\n array([[ 0.54009291, 0.63963002, 0.63434996, 0.23271539],\n [ 0.93474271, 0.24525379, 0.04107161, 0.01701793],\n [ 0.17410066, 0.42886507, 0.14338677, 0.142046 ],\n [ 0.54005321, 0.03878921, 0.8827711 , 0.55105743]])\n\n\n\n\n```python\n# 3x3 array of normally distributed rv (with mean = 4, sd = 6)\nnp.random.normal(loc = 4, scale = 6, size = (3, 3))\n```\n\n\n\n\n array([[ -8.06536073, 7.31049404, 4.55116972],\n [ 16.79746137, 9.28275757, 11.03506686],\n [ 11.10279939, 4.99549227, 9.11912977]])\n\n\n\n\n```python\n# 3x3 array of random integers in interval [0, 15)\nnp.random.randint(low = 0, high = 15, size = (3, 3))\n```\n\n\n\n\n array([[ 0, 3, 7],\n [10, 7, 8],\n [10, 7, 10]])\n\n\n\n\n```python\n# 4x4 identity matrix\nnp.eye(4)\n```\n\n\n\n\n array([[ 1., 0., 0., 0.],\n [ 0., 1., 0., 0.],\n [ 0., 0., 1., 0.],\n [ 0., 0., 0., 1.]])\n\n\n\n### NumPy Array Attributes\nEach NumPy array has certain attributes.\n\nHere are some attributes we can call:\n\n| Attribute | Description |\n|-----------|------------------------|\n| `ndim` | No. of dimensions |\n| `shape` | Size of each dimension |\n| `size` | Total size of array |\n| `dtype` | Data type of array |\n| `itemsize` | Size (in bytes) |\n| `nbytes` | Total size (in bytes) |\n\nTo show how one can access them we'll define three arrays.\n\n\n```python\nnp.random.seed(1234) # Set seed for reproducibility\n\nx = np.random.randint(10, size = 6) # 1-dimensional array (vector)\ny = np.random.randint(10, size = (3, 4)) # 2-dimensional array (matrix)\nz = np.random.randint(10, size = (3, 4, 5)) # 3-dimensional array\n```\n\nAnd here's how we call for these properties:\n\n\n```python\nprint('ndim: ', z.ndim)\nprint('shape: ', z.shape)\nprint('size: ', z.size)\nprint('data type: ', z.dtype)\nprint('itemsize: ', z.itemsize)\nprint('nbytes: ', z.nbytes)\n```\n\n ndim: 3\n shape: (3, 4, 5)\n size: 60\n data type: int32\n itemsize: 4\n nbytes: 240\n\n\n### Index: How to Access Elements\nWhat might be a bit counterintuitive at the beginning is that **Python's indexing starts at 0**. Other than that, accessing the $i$'th element (starting at 0) of a list or a array is straight forward. \n\n\n```python\nprint(e, '\\n') # List from above\nprint(x, '\\n') # One dimensional np array from above\nprint(y, '\\n') # Two dimensional np array from above\n```\n\n ['Calynn', '10.3', 'World!', 1] \n \n [3 6 5 4 8 9] \n \n [[1 7 9 6]\n [8 0 5 0]\n [9 6 2 0]] \n \n\n\n\n```python\ne[1]\n```\n\n\n\n\n '10.3'\n\n\n\n\n```python\nx[5]\n```\n\n\n\n\n 9\n\n\n\n\n```python\ny[2, 0] # Note again that [m, n] starts counting for both rows (m) as well as columns (n) from 0\n```\n\n\n\n\n 9\n\n\n\nTo access the end of an array, you can also use negative indices:\n\n\n```python\ne[-1]\n```\n\n\n\n\n 1\n\n\n\n\n```python\ny[-2, 2]\n```\n\n\n\n\n 5\n\n\n\nArrays are also possible as inputs:\n\n\n```python\nind = [3, 5, -4]\nx[ind]\n```\n\n\n\n\n array([4, 9, 5])\n\n\n\n\n```python\nx = np.arange(12).reshape((3, 4))\nprint(x)\nrow = np.array([1, 2])\ncol = np.array([0, 3])\nx[row, col]\n```\n\n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\n\n\n\n\n array([ 4, 11])\n\n\n\nKnowing the index we can also replace elements of an array:\n\n\n```python\nx[0] = 99\nx\n```\n\n\n\n\n array([[99, 99, 99, 99],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n\n\n\n**IMPORTANT NOTE: **\n\n**NumPy arrays have a fixed type. This means that e.g. if you insert a floating-point value to an integer array, the value will be truncated!**\n\n\n\n```python\nx[0] = 3.14159; x\n```\n\n\n\n\n array([[ 3, 3, 3, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n\n\n\n### Array Slicing\nWe can also use square brackets to access a subset of the data. The syntax is:\n\n`x[start:stop:step]`\n\nThe default values are: `start=0`, `stop='size of dimension'`, `step=1` \n\n\n```python\nx = np.arange(10)\nx\n```\n\n\n\n\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n\n\n\n```python\nx[:3] # First three elements\n```\n\n\n\n\n array([0, 1, 2])\n\n\n\n\n```python\nx[7:] # Elements AFTER index 7\n```\n\n\n\n\n array([7, 8, 9])\n\n\n\n\n```python\nx[4:8] # Element 5, 6, 7 and 8\n```\n\n\n\n\n array([4, 5, 6, 7])\n\n\n\n\n```python\nx[::2] # Even elements\n```\n\n\n\n\n array([0, 2, 4, 6, 8])\n\n\n\n\n```python\nx[1::2] # Odd elements\n```\n\n\n\n\n array([1, 3, 5, 7, 9])\n\n\n\n\n```python\nx[::-1] # All elements reversed\n```\n\n\n\n\n array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])\n\n\n\n\n```python\nx[::-2] # Odd elements reversed\n```\n\n\n\n\n array([9, 7, 5, 3, 1])\n\n\n\nArray slicing works the same for multidimensional arrays.\n\n\n```python\ny # from above\n```\n\n\n\n\n array([[1, 7, 9, 6],\n [8, 0, 5, 0],\n [9, 6, 2, 0]])\n\n\n\n\n```python\ny[:2, :3] # Rows 0 and 1, columns 0, 1, 2\n```\n\n\n\n\n array([[1, 7, 9],\n [8, 0, 5]])\n\n\n\n\n```python\ny[:, 2] # Third column\n```\n\n\n\n\n array([9, 5, 2])\n\n\n\n\n```python\ny[0, :] # First row\n```\n\n\n\n\n array([1, 7, 9, 6])\n\n\n\n**IMPORTANT NOTE:**\n\n**When slicing and assigning part of an existing array to a new variable, the new variable will only hold a \"view\" but not a copy. This means, that if you change a value in the new array, the original array will also be changed. The idea behind this is to save memory. But fear not: with the \".copy()\" method, you still can get a true copy.**\n\nHere a few corresponding examples for better understanding:\n\n\n```python\nySub = y[:2, :2]\nprint(ySub)\n```\n\n [[1 7]\n [8 0]]\n\n\n\n```python\nySub[0, 0] = 99\nprint(ySub, '\\n')\nprint(y)\n```\n\n [[99 7]\n [ 8 0]] \n \n [[99 7 9 6]\n [ 8 0 5 0]\n [ 9 6 2 0]]\n\n\n\n```python\nySubCopy = y[:2, :2].copy()\nySubCopy[0, 0] = 33\nprint(ySubCopy, '\\n')\nprint(y)\n```\n\n [[33 7]\n [ 8 0]] \n \n [[99 7 9 6]\n [ 8 0 5 0]\n [ 9 6 2 0]]\n\n\n### Concatenating, Stacking and Splitting\nOften it is useful to combine multiple arrays into one or to split a single array into multiple arrays. To accomplish this, we can use NumPy's `concatenate` and `vstack`/`hstack` function.\n\n\n```python\nx = np.array([1, 2, 3])\ny = np.array([11, 12, 13])\nz = np.array([21, 22, 23])\nnp.concatenate([x, y, z])\n```\n\n\n\n\n array([ 1, 2, 3, 11, 12, 13, 21, 22, 23])\n\n\n\n\n```python\n# Stack two vectors horizontally\nnp.hstack([x, y])\n```\n\n\n\n\n array([ 1, 2, 3, 11, 12, 13])\n\n\n\n\n```python\n# Stack two vectors vertically\nnp.vstack([x, y])\n```\n\n\n\n\n array([[ 1, 2, 3],\n [11, 12, 13]])\n\n\n\n\n```python\n# Stack matrix with column vector\nm = np.arange(0, 9, 1).reshape((3, 3))\nnp.vstack([m, z])\n```\n\n\n\n\n array([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n [21, 22, 23]])\n\n\n\n\n```python\n# Stack matrix with row vector\nnp.hstack([m, z.reshape(3, 1)])\n```\n\n\n\n\n array([[ 0, 1, 2, 21],\n [ 3, 4, 5, 22],\n [ 6, 7, 8, 23]])\n\n\n\nThe opposite of concatenating is splitting. Numpy has `np.split`, `np.hsplit` and `np.vsplit` functions. Each of these takes a list of indices, giving the split points, as input.\n\n\n```python\nx = np.arange(8.0)\na, b, c = np.split(x, [3, 5])\nprint(a, b, c)\n```\n\n [ 0. 1. 2.] [ 3. 4.] [ 5. 6. 7.]\n\n\n\n```python\nx = np.arange(16).reshape(4, 4)\nupper, lower = np.vsplit(x, [3])\nprint(upper, '\\n\\n', lower)\n```\n\n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]] \n \n [[12 13 14 15]]\n\n\n\n```python\nleft, right = np.hsplit(x, [2])\nprint(left, '\\n\\n', right)\n```\n\n [[ 0 1]\n [ 4 5]\n [ 8 9]\n [12 13]] \n \n [[ 2 3]\n [ 6 7]\n [10 11]\n [14 15]]\n\n\n## Conditions\n\n### Boolean Operators\n\nBoolean operators check an input and return either `True` (equals 1 as value) or `False` (equals 0). This is often very helpful if one wants to check for conditions or sort out part of a data set which meet a certain condition. Here are the common comparison operators:\n\n| **Operator** | **Description** |\n|:------------:|----------------------------|\n| == | equal ($=$) |\n| != | not equal ($\\neq$) |\n| < | less than ($<$) |\n| <= | less or equal ($\\leq$) |\n| > | greater ($>$) |\n| >= | greater or equal ($\\geq$) |\n| & | Mathematical AND ($\\land$) |\n| | | Mathematical OR ($\\lor$) |\n| `in` | element of ($\\in$) |\n\nThe following sections give a glimpse of how these operators can be used.\n\n\n```python\nx = np.arange(start=0, stop=8, step=1)\nprint(x)\nprint(x == 2)\nprint(x != 3)\nprint((x < 2) | (x > 6))\n```\n\n [0 1 2 3 4 5 6 7]\n [False False True False False False False False]\n [ True True True False True True True True]\n [ True True False False False False False True]\n\n\n\n```python\n# Notice the difference\nprint(x[x <= 4])\nprint(x <= 4)\n```\n\n [0 1 2 3 4]\n [ True True True True True False False False]\n\n\n#### If ... else statements\n\nThese statements check a given condition and depending on the result (`True`, `False`) execute a subsequent code. As usual, an example will do. Notice that indentation is necessary for Python to correctly compile the code. \n\n\n```python\nx = 3\n\nif x%2 == 0:\n print(x, 'is an even number')\nelse:\n print(x, 'is an odd number')\n \n```\n\n 3 is an odd number\n\n\nIt is also possible to have more than one condition as the next example shows.\n\n\n```python\nx = 20\n\nif x > 0:\n print(x, 'is positive')\nelif x < 0:\n print(x, 'is negative')\nelse:\n print(x, 'is neither strictly positive nor strictly negative')\n```\n\n 20 is positive\n\n\nCombining these two statements would make for a nested if ... else statement.\n\n\n```python\nx = -3\nif x > 0:\n if (x%2) == 0:\n print(x, 'is positive and even')\n else:\n print(x, 'is positive and odd')\nelif x < 0:\n if (x%2) == 0:\n print(x, 'is negative and even')\n else:\n print(x, 'is negative and odd')\nelse:\n print(x, 'is 0')\n```\n\n -3 is negative and odd\n\n\n### Loops\n\n#### \"For\" Loops\n\n\"For\" loops iterate over a given sequence. They are very easy to implement as the following example shows. We start with an example and give some explanations afterwards. \n\nFor our example, let's assume you ought to sum up the integer values of a sequence from 10 to 1 with a loop. There are obviously more efficient ways of doing this but this serves well as an introductory example. From primary school we know the result is easily calculated as\n\n$$\n\\begin{equation}\n \\sum_{i=1}^n x_i = \\dfrac{n (n+1)}{2} \\qquad -> \\qquad \\dfrac{10 \\cdot 11}{2} = 55\n\\end{equation}\n$$\n\n\n```python\nseq = np.arange(start=10, stop=0, step=-1)\nseqSum = 0\nfor value in seq:\n seqSum = seqSum + value\n\nseqSum\n```\n\n\n\n\n 55\n\n\n\nA few imprtant notes:\n* Indentation is not just here for better readability of the code but it is actually necessary for Python to correctly interpret the code.\n* Though it is not necessary, we initiate `seqSum = 0` here. Otherwise, if we run the code repeatedly we add to the previous total!\n* `value` takes on every value in array `seq`. In the first loop `value=10`, second loop `value=9`, etc. \n\nLoops can be nested, too. Here's an example.\n\n\n```python\nseq = seq.reshape(2, 5)\nseqSum = 0\nrow, col = seq.shape\n\nfor rowIndex in range(0, row):\n for colIndex in range(0, col):\n seqSum = seqSum + seq[rowIndex, colIndex]\n \nseqSum\n```\n\n\n\n\n 55\n\n\n\n#### \"While\" Loops\n\n\"While\" loops execute as long as a certain boolean condition is met. Picking up the above example we can formulate the following loop:\n\n\n```python\nseqSum = 0\ni = 10\nwhile i >= 1:\n seqSum = seqSum + i\n i = i - 1 # Also: i -= 1\n \nprint(seqSum)\n```\n\n 55\n\n\n### Functions\n\nFunctions come into play when either a task needs to be performed more than once or when it helps reduce the complexity of a code. \n\nFollowing up on our play examples from above, let us assume we're tasked to write a function which sums up all even and all odd integers of a vector. \n\n\n```python\ndef sumOddEven(vector):\n \"\"\"Calculates sum of odd and even numbers in array.\n \n Args:\n vector: NumPy array of length n\n \n Returns:\n odd: Sum of odd numbers\n even: Sum of even numbers\n \"\"\"\n \n # Initiate values\n odd = 0\n even = 0\n \n # Loop through values of array; check for each\n # value whether it is odd or even and add to \n # previous total.\n for value in vector:\n if (value % 2) == 0:\n even = even + value\n else:\n odd = odd + value\n \n return odd, even\n\n# Initiate array [1, 2, ..., 99, 100]\nseq = np.arange(1, 101, 1)\n\n# Apply function and print results\nodd, even = sumOddEven(seq)\nprint('Odd: ', odd, ', ', 'Even: ', even) \n```\n\n Odd: 2500 , Even: 2550\n\n\n## Commenting\n\nAbove code snippet not only shows how functions are set up but also displays the importance of comments. Comments are preceeded by a hash sign (#), such that the interpreter will not parse what follows the hash. When programming, you should always comment your code to notate your work. This details your steps/thoughts/ideas not only for other developers but also for you when you pick up your code some time after writing it. Good programmers make heavy use of commenting and I strongly encourage the reader to follow this standard. \n\n## Slowness of Loops\n\nIt is at this point important to note that loops should only be used as a last resort. Below we show why. The first code runs our previously defined function. The second code uses NumPy's built-in function. \n\n\n```python\n%%timeit\nseq = np.arange(1,10001, 1)\nsumOddEven(seq)\n```\n\n 4.47 ms ± 415 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n\n\n```python\n%%timeit\nseq[(seq % 2) == 0].sum()\nseq[(seq % 2) == 1].sum()\n```\n\n 10.5 µs ± 924 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\nAbove timing results show what was hinted before: In 9'999 out of a 10'000 cases it is significantly faster using already built in functions compared to loops. The simple reason is that modules such as NumPy or Pandas use (at their core) optimized compile code to calculate the results and this is most certainly faster than a loop. \n\nSo in summary: Above examples helped introduce if statements, loops and functions. In real life, however, you should check if Python does not already offer a built-in function for your task. If yes, make sure to use it.\n\n## Broadcasting\n\n### Computations on Arrays\n\nIn closing this chapter we briefly introduce NumPy's broadcasting functionality. Rules for matrix arithmetic apply to NumPy arrays as one would expect and it is left to the reader to explore it. Broadcasting, however, goes one step further in that it allows for element-by-element operations on arrays (and matrices) of different dimensions - which under normal rules would not be compatible. An example shows this best.\n\n\n```python\nM = np.ones(shape=(3, 3))\nv = np.array([1, 2, 3])\nM + v\n```\n\n\n\n\n array([[ 2., 3., 4.],\n [ 2., 3., 4.],\n [ 2., 3., 4.]])\n\n\n\n\n```python\n# Notice the difference\nvecAdd = v + v\nbroadAdd = v.reshape((3, 1)) + v\n\nprint(vecAdd, '\\n')\nprint(broadAdd)\n```\n\n [2 4 6] \n \n [[2 3 4]\n [3 4 5]\n [4 5 6]]\n\n\n## Further Resources\n\nThe following ressources, which were consulted to write this notebook, are recommended to better acquaint yourself with Python and NumPy:\n\n* Vanderplas, Jake, 2016, *Python Data Science Handbook* (O'Reilly Media, Sebastopol, CA).\n* Sheppard, Kevin, 2017, Introduction to Python for Econometrics, Statistics and Data Analysis from Website https://www.kevinsheppard.com/images/b/b3/Python_introduction-2016.pdf, 07/07/2017.\n* Paarsch, Harry J., and Golyaev, Konstantin, 2016, *A Gentle Introduction to Effective Computing in Quantitative Research: What Every Research Assistant Should Know*, MIT Press, Cambridge, MA.\n", "meta": {"hexsha": "da4cfc9010de2f2c4ced17e8178bea177058c84d", "size": 46591, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0101_GettingStartedWithPython.ipynb", "max_stars_repo_name": "mauriciocpereira/ML_in_Finance_UZH", "max_stars_repo_head_hexsha": "d99fa0f56b92f4f81f9bbe024de317a7949f0d38", "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": "0101_GettingStartedWithPython.ipynb", "max_issues_repo_name": "mauriciocpereira/ML_in_Finance_UZH", "max_issues_repo_head_hexsha": "d99fa0f56b92f4f81f9bbe024de317a7949f0d38", "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": "0101_GettingStartedWithPython.ipynb", "max_forks_repo_name": "mauriciocpereira/ML_in_Finance_UZH", "max_forks_repo_head_hexsha": "d99fa0f56b92f4f81f9bbe024de317a7949f0d38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4597180262, "max_line_length": 542, "alphanum_fraction": 0.4889785581, "converted": true, "num_tokens": 7260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.18952109132967757, "lm_q1q2_score": 0.08079693071424443}} {"text": "### Static Equilibrium\n\nIn this notebook, we will derive, interpret, and simulate the static equilibrium of the model.\n\nLast edited: Wed. 1/23/19, by Arnav Sood\n\n\n```julia\n# For equation numbering\nmacro javascript_str(s) display(\"text/javascript\", s); end\n \njavascript\"\"\"\nMathJax.Hub.Queue(\n [\"resetEquationNumbers\", MathJax.InputJax.TeX],\n [\"PreProcess\", MathJax.Hub],\n [\"Reprocess\", MathJax.Hub]\n);\n\"\"\"\n```\n\n\n\n### Market's Problem\n\nBegin with the formula for the Inflow Prior $\\lambda^I$\n\n\\begin{equation} \n\\lambda^I = \\frac{e_H \\lambda}{e_H \\lambda + e_L (1 - \\lambda}\n\\end{equation}\n\nRecall the formula for the final signal-dependent prior, $\\lambda^o(h; m)$, in terms of the above:\n\n\\begin{equation} \n\\lambda^o(h; m) = \\frac{\\lambda^I}{\\lambda^I + (1-\\lambda^I)\\phi}\n\\end{equation}\n\nThis can be rearranged to express $\\lambda^o(h; m)$ (hereafter $\\lambda^o(h)$, for convenience), in terms of model primitives:\n\n\\begin{equation} \n\\lambda^o(h) = \\frac{e_H \\lambda}{e_H \\lambda + \\phi e_L (1 - \\lambda)}\n\\end{equation}\n\nThis passes a sanity check, since it says that the final prior is the share of high types, out of all those who get the high signal (high types + $\\phi$ times low types)\n\n### Firms' Problem\n\nFirms here are mechanistic, acting according to:\n\n\\begin{equation}\nV_i = \\max_{\\text{entry}, \\text{no entry}}\\{\\omega_i, \\phi_i R - p\\}\n\\end{equation}\n\nin the constraint region.\n\nAssuming an interior solution (that is, one where $e_H, e_L \\in (0, 1)$ strictly), we have:\n\n\\begin{align}\ne_H &= F_H(R - p) \\\\ \ne_L &= F_L(\\phi R - p)\n\\end{align}\n\nNote that $e_H, e_L$ are but **fractions** of firms of each type that enter the market, and need to be multiplied by their respective (prior) masses, $\\lambda, 1 - \\lambda$, to have meaning.\n\nWe assumed earlier that the constraint is not violated. Or:\n\n\\begin{align}\n\\lambda^o(h) &\\geq \\underline{\\lambda} \\\\ \n\\frac{e_H \\lambda}{e_H \\lambda + \\phi e_L (1 - \\lambda)} &\\geq \\underline{\\lambda} \\\\ \ne_H \\lambda (1 - \\underline{\\lambda}) &\\geq \\underline{\\lambda} \\phi e_L (1 - \\lambda) \\\\ \n\\phi &\\leq \\frac{e_H \\lambda (1 - \\underline{\\lambda})}{e_L \\underline{\\lambda} (1 - \\lambda)}\n\\end{align}\n\nThis will be our chief constraint. For ease of reference, we can call this the **market credulity constraint.**\n\n### Rater's Problem\n\nA forward-looking credit rater, who (for convenience) shares a common prior with the market about the type-distribution of firms, is then seeking to solve the following problem:\n\n\n\\begin{align}\n\\max_{\\phi \\in [0, 1], p \\geq 0} p \\left\\{ F_H(R - p) \\lambda + F_L(\\phi R - p)(1 - \\lambda) \\right\\}\n\\end{align}\n\nsubject to: \n\n\\begin{equation}\n\\phi \\leq \\frac{e_H \\lambda (1 - \\underline{\\lambda})}{e_L \\underline{\\lambda} (1 - \\lambda)}\n\\end{equation}\n\nWe can write the following Lagrangian (assuming the problem is suitable, which we will have to show later): \n\n\\begin{equation}\nL = p \\left\\{ F_H(R - p) \\lambda + F_L(\\phi R - p)(1 - \\lambda) \\right\\} - \\mu (\\log \\phi + \\log F_L(\\phi R - p) - \\log F_H(R - p) - \\log \\tau)\n\\end{equation}\n\nWhere \n\n\\begin{equation}\n\\tau \\equiv \\frac{\\lambda(1 - \\underline{\\lambda})}{\\underline{\\lambda}(1-\\lambda)}\n\\end{equation}\n\nWe can derive first-order conditions:\n\n#### FOC $\\phi$\n\n\\begin{equation}\np R (1 - \\lambda) f_L(\\phi R - p) = \\mu \\left(\\frac{1}{\\phi} + \\frac{R f_L(\\phi R - p)}{F_L(\\phi R - p)}\\right)\n\\end{equation}\n\n#### FOC $p$\n\n\\begin{equation}\nF_H(R - p)\\lambda + F_L(\\phi R - p)(1 - \\lambda) - p[f_H(R - p)\\lambda + f_L(\\phi R - p)(1 - \\lambda)] + \\mu \\left(\\frac{f_L(\\phi R - p)}{F_L(\\phi R - p)} - \\frac{f_H(R - p)}{F_H(R - p)} \\right) = 0\n\\end{equation}\n\n#### Complementary Slackness\n\n\\begin{equation}\n\\mu (\\log \\phi + \\log F_L (\\phi R - p) - \\log F_H (R - p) - \\log \\tau) = 0\n\\end{equation}\n\n#### Model Solution\n\nRewriting (15), we can derive an expression for the Lagrange/KKT multiplier:\n\n\\begin{equation}\n\\mu = \\frac{\\phi (1 - \\lambda)F_L(\\phi R - p)R \\cdot f_L(\\phi R - p)}{F_L(\\phi R - p) + \\phi R f_L(\\phi R - p)}\n\\end{equation}\n\nWe can make some observations here. \n\n1. The term to the left of the $\\cdot$ is total payoff earned on the public market by low-type firms.\n\n2. The multiplier is nonzero iff (1) the $\\phi$ parameter is nonzero, (2) the market reward is nonzero, (3) the price is nonzero, (4) $\\lambda$ is not 1 (i.e., rater and market must believe $\\exists$ some low-type firms), and (5) **both** $f_L$ and $F_L$ are nonzero (i.e., there has been some entry, and the density function is not locally flat, so a small perturbation yields rewards).\n\nAssuming the above parameter restrictions hold, we know the complementary slackness condition can be divided through by $\\mu$, to yield a binding constraint.\n\n### Interpretation\n\n### Implementation and Comparative Statics\n\nIn general, we have a system of 3 equations (15, 16, 17) in 3 unknowns ($\\phi$, $p$, $\\mu$). We can feed this to a nonlinear solver.\n\nFirst, define a holder for model primitives.\n\n#### Setup and Introduction\n\n\n```julia\nusing Parameters, Distributions\n```\n\n\n```julia\nModel = @with_kw (λ = 0.5, # share of good firms\n R = 2, # market payoff\n λ_bar = 0.74, # market credulity threshold\n ω_H = Uniform(1.5, 2.5), # High-type distribution of outside options\n ω_L = Uniform(1.01, 2.01), # Low-type distribution of outside options\n f_L = x -> pdf(ω_L, x),\n f_H = x -> pdf(ω_H, x),\n F_L = x -> cdf(ω_L, x),\n F_H = x -> cdf(ω_H, x)\n )\n```\n\n\n\n\n #3 (generic function with 2 methods)\n\n\n\nBefore proceeding, it's worh examining how this object we created works.\n\nIf we call it without arguments, it will the default values we supplied.\n\n\n```julia\nm = Model();\n@show m.λ, m.R, # defaults\n```\n\n (m.λ, m.R) = (0.5, 2)\n\n\n\n\n\n (0.5, 2)\n\n\n\nBut we can also supply specific arguments.\n\n\n```julia\nm = Model(λ = 0.3, R = 20, ω_H = Uniform(1., 21.));\n@show m.λ, m.R\n```\n\n (m.λ, m.R) = (0.3, 20)\n\n\n\n\n\n (0.3, 20)\n\n\n\nIt is preferred to use these things instead of a struct (i.e., the code below) for two reasons. \n\n1. Simplicity. Compare the code above to:\n\n```\nstruct Model{TF <: AbstractFloat, TI <: Integer, ...}\nλ::TF \nR::TI\n...\n```\n\n2. Correctness. If you are writing a `struct` by hand, then to get equal performance to a named tuple (the kind of thing we generate with a `Model()` call), we need to get the type parameterization (i.e., the `TF, TI`, etc.) exactly right. This is complicated by the fact that we use objects that are themselves parametrically typed (such as `Uniform{Float64}(a = 1.01, b = 2.01)`, for the distributions).\n\n#### Computational Solution\n\nDefine a baseline model.\n\n\n```julia\nm = Model(R = 1.5);\n```\n\nWrite code to take guesses for $\\phi, p, \\mu$, and a model $m$, and calculate the residuals for the three equations.\n\n\n```julia\nfunction residuals(vals; model = m)\n # unpack inputs\n @unpack λ, R, λ_bar, ω_H, ω_L, f_L, f_H, F_L, F_H = model\n ϕ, p, μ = vals # so vals is some vector [ϕ, p, μ]\n # define τ\n τ = λ*(1 - λ_bar)/(λ_bar * (1 - λ))\n # calculate residuals\n ϕ_residual = ϕ > 0 && F_L(ϕ*R - p) > 0 ? p*R*(1-λ)*f_L(ϕ*R - p) - μ*(1/ϕ + R*f_L(ϕ*R - p)/F_L(ϕ*R -p)) : 100 # (15) (return 100 for invalid residual expressions)\n p_residual = F_L(ϕ*R - p) > 0 && F_H(R - p) > 0 ? F_H(R - p)*λ + F_L(ϕ*R - p)*(1 - λ) - p*(f_H(R - p) + f_L(ϕ*R - p)) + μ*(f_L(ϕ*R - p)/F_L(ϕ*R - p) - f_H(R - p)/F_H(R - p)) : 100 # (16)\n μ_residual =sol ϕ > 0 && τ > 0 && F_L(ϕ*R - p) > 0 && F_H(R - p) > 0 ? μ*(log(ϕ) + log(F_L(ϕ*R - p)) - log(F_H(R - p)) - log(τ)) : 100 # (17)\n # return \n residuals = [ϕ_residual, p_residual, μ_residual]\nend\n```\n\nPass this to the solver.\n\n\n```julia\nusing NLsolve # https://github.com/JuliaNLSolvers/NLsolve.jl, one of the main Julia solvers\n```\n\n\n```julia\n@time result = nlsolve(residuals, [0.001, 0.001, 0.], inplace = false, store_trace = true, iterations = 10^6)\n```\n", "meta": {"hexsha": "1ce099ac79a9bd1ba7285aba246dcdba3391e4b3", "size": 13497, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "graveyard/static-equilibrium.ipynb", "max_stars_repo_name": "arnavs/credit-pricing", "max_stars_repo_head_hexsha": "72a593719c4a0ebac726fb4b91ae846bc65d301d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graveyard/static-equilibrium.ipynb", "max_issues_repo_name": "arnavs/credit-pricing", "max_issues_repo_head_hexsha": "72a593719c4a0ebac726fb4b91ae846bc65d301d", "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": "graveyard/static-equilibrium.ipynb", "max_forks_repo_name": "arnavs/credit-pricing", "max_forks_repo_head_hexsha": "72a593719c4a0ebac726fb4b91ae846bc65d301d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-04T10:47:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T10:47:24.000Z", "avg_line_length": 30.3303370787, "max_line_length": 411, "alphanum_fraction": 0.5092983626, "converted": true, "num_tokens": 2604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.08057242646470159}} {"text": "# [ATM 623: Climate Modeling](../index.ipynb)\n[Brian E. J. Rose](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany\n# Lecture 1: Climate models, the global energy budget and Fun with Python\n\n## Warning: content out of date and not maintained\n\nYou really should be looking at [The Climate Laboratory book](https://brian-rose.github.io/ClimateLaboratoryBook) by Brian Rose, where all the same content (and more!) is kept up to date.\n\n***Here you are likely to find broken links and broken code.***\n\n### About these notes:\n\nThis document uses the interactive [`Jupyter notebook`](https://jupyter.org) format. The notes can be accessed in several different ways:\n\n- The interactive notebooks are hosted on `github` at https://github.com/brian-rose/ClimateModeling_courseware\n- The latest versions can be viewed as static web pages [rendered on nbviewer](http://nbviewer.ipython.org/github/brian-rose/ClimateModeling_courseware/blob/master/index.ipynb)\n- A complete snapshot of the notes as of May 2017 (end of spring semester) are [available on Brian's website](http://www.atmos.albany.edu/facstaff/brose/classes/ATM623_Spring2017/Notes/index.html).\n\n[Also here is a legacy version from 2015](http://www.atmos.albany.edu/facstaff/brose/classes/ATM623_Spring2015/Notes/index.html).\n\nMany of these notes make use of the `climlab` package, available at https://github.com/brian-rose/climlab\n\n## Contents\n\n1. [What is a Climate Model?](#section1)\n2. [The observed global energy budget](#section2)\n3. [Quantifying the planetary energy budget](#section3)\n4. [Using Python to compute emission to space](#section4)\n\n____________\n\n\n## 1. What is a Climate Model?\n____________\n\nFirst, some thoughts on modeling from [xkcd](https://xkcd.com)\n\n\n\nLet's be a little pedantic and decompose that question:\n\n- what is Climate?\n- what is a Model?\n\n**Climate** is\n\n- statistics of weather, e.g. space and time averages of temperature and precip.\n- (statistics might also mean higher-order stats: variability etc)\n\nA **model** is\n\n - not easy to define!\n\nWikipedia: http://en.wikipedia.org/wiki/Conceptual_model\n\n> In the most general sense, a model is anything used in any way to represent anything else. Some models are physical objects, for instance, a toy model which may be assembled, and may even be made to work like the object it represents. Whereas, a conceptual model is a model made of the composition of concepts, that thus exists only in the mind. Conceptual models are used to help us know, understand, or simulate the subject matter they represent.\n\nGeorge E. P. Box (statistician):\n> Essentially, all models are wrong, but some are useful.”\n\nFrom the Climate Modelling Primer, 4th ed (McGuffie and Henderson-Sellers):\n\n> In the broadest sense, models are for learning about the world (in our case, the climate) and the learning takes place in the contruction and the manipulation of the model, as anyone who has watched a child build idealised houses or spaceships with Lego, or built with it themselves, will know. Climate models are, likewise, idealised representations of a complicated and complex reality through which our understanding of the climate has significantly expanded. All models involve some ignoring, distoring and approximating, but gradually they allow us to build understanding of the system being modelled. A child's Lego construction typically contains the essential elements of the real objects, improves with attention to detail, helps them understand the real world, but is never confused with the real thing.\n\n### A minimal definition of a climate model\n\n*A representation of the exchange of energy between the Earth system and space, and its effects on average surface temperature.*\n\n(what average?) \n\nNote the focus on **planetary energy budget**. That’s the key to all climate modeling.\n\n____________\n\n\n## 2. The observed global energy budget\n____________\n\nThe figure below shows current best estimates of the *global, annual mean* energy fluxes through the climate system.\n\nWe will look at many of these processes in detail throughout the course.\n\n\n\n## Things to note:\n\n### On the shortwave side\n\n- global mean albedo is 101.9 W m$^{-2}$ / 341.3 W m$^{-2}$ = 0.299\n- Reflection off clouds = 79 W m$^{-2}$\n- Off surface = 23 W m$^{-2}$\n - 3 times as much reflection off clouds as off surface\n \nWhy?? Think about both areas of ice and snow, and the fact that sunlight has to travel through cloudy atmosphere to get to the ice and snow. Also there is some absorption of shortwave by the atmosphere.\n\n- Atmospheric absorption = 78 W m$^{-2}$\n(so about the same as reflected by clouds)\n\nQUESTION: Which gases contribute to shortwave absorption?\n\n- O$_3$ and H$_2$O mostly.\n- We will look at this later.\n\n### On the longwave side\n\n- Observed emission from the SURFACE is 396 W m$^{-2}$\n- very close to the blackbody emission $\\sigma T^4$ at $T = 288$ K (the global mean surface temperature).\n- BUT emission to space is much smaller = 239 W m$^{-2}$\n\nQUESTION: What do we call this? (greenhouse effect)\n\n### Look at net numbers…\n\n- Net absorbed = 0.9 W m$^{-2}$\n- Why?\n- Where is that heat going?\n\nNote, the exchanges of energy between the surface and the atmosphere are complicated, involve a number of different processes. We will look at these more carefully later.\n\n### Additional points:\n\n- Notice that this is a budget of energy, not temperature.\n- We will need to discuss the connection between the two\n- **Clouds** affect both longwave and shortwave sides of the budget.\n- **WATER** is involved in many of the terms: \n\n - evaporation\n - latent heating (equal and opposite in the global mean)\n - clouds\n - greenhouse effect\n - atmospheric SW absorption\n - surface reflectivity (ice and snow)\n\n### Discussion point\n\nHow might we expect some of the terms in the global energy budget to vary under anthropogenic climate change?\n\n____________\n\n\n## 3. Quantifying the planetary energy budget\n____________\n\nA budget for the **energy content of the global atmosphere-ocean system**:\n\n\\begin{align} \n\\frac{dE}{dt} &= \\text{net energy flux in to system} \\\\\n &= \\text{flux in – flux out}\n\\end{align}\n\nwhere $E$ is the **enthalpy** or **heat content** of the total system.\n\nWe will express the budget **per unit surface area**, so each term above has units W m$^{-2}$\n\nNote: any **internal exchanges** of energy between different reservoirs (e.g. between ocean, land, ice, atmosphere) do not appear in this budget – because $E$ is the **sum of all reservoirs**.\n\n### Assumption:\n\n**The only quantitatively important energy sources to the whole system are radiative fluxes to and from space.**\n\nLet’s model those TOA (top-of-atmosphere) fluxes.\n\nFlux in is **incoming solar radiation**\nThe solar constant is\n\n$$ S_0 = 1365.2 \\text{ W m}^{-2} $$\n\n(all values will be consistent with Trenberth and Fasullo figure unless noted otherwise)\n\nThis is the flux of energy from the sun incident on a unit area perpendicular to the beam direction.\n\nThe area-weighted global mean incoming solar flux is\n\n$$ Q = S_0 \\frac{A_{cross-section}}{A_{surface}} $$\n\n[ draw sketch of sphere and illuminated disk ] \n\nwhere \n\n- $A_{cross-section}$ = area of the illuminated disk = $\\pi a^2$\n- $A_{surface}$ = surface area of sphere = $4 \\pi a^2$\n- $a$ = radius of Earth\n\nSo flux in is $Q = S_0 / 4 = 341.3$ W m$^{-2}$\n\nFlux out has two parts:\n\n- Reflected solar radiation\n- Emitted terrestrial (longwave) radiation\n\nIntroduce terminology / notation:\n\n**OLR = outgoing longwave radiation = terrestrial emissions to space**\n\nDefine the **planetary albedo**:\n\n- $\\alpha$ = reflected solar flux / incoming solar flux\n- Or reflected flux = $\\alpha Q$ = 101.9 W m$^{-2}$ from data\n- So from data, $\\alpha \\approx 0.3$\n\nDefine **ASR = absorbed solar radiation**\n\\begin{align}\nASR &= \\text{ incoming flux – reflected flux} \\\\\n &= Q - \\alpha Q \\\\\n &= (1-\\alpha) Q \n\\end{align}\n\nOur energy budget then says\n\n$$ \\frac{dE}{dt} = (1-\\alpha) Q - OLR $$\n\nNote: **This is a generically true statement.** We have just defined some terms, and made the [very good] assumption that the only significant energy sources are radiative exchanges with space.\n\n**This equation is the starting point for EVERY CLIMATE MODEL.**\n\nBut so far, we don’t actually have a MODEL. We just have a statement of a budget. To use this budget to make a model, we need to relate terms in the budget to state variables of the atmosphere-ocean system.\n\nFor now, the state variable we are most interested in is **temperature** – because it is directly connected to the physics of each term above.\n\n\n____________\n\n\n## 4. Using Python to compute emission to space\n____________\n\n*Most of what follows is intended as a \"fill in the blanks\" exercise. We will practice writing some Python code while discussing the physical process of longwave emission to space.*\n\nSuppose the Earth behaves like a **blackbody radiator** with effective global mean **emission temperature $T_e$**.\n\nThen\n\n$$ OLR = \\sigma T_e^4 $$\n\nwhere OLR = \"Outgoing Longwave Radiation\", and $\\sigma = 5.67 \\times 10{-8}$ W m$^{-2}$ K$^{-4}$ the Stefan-Boltzmann constant\n\n**We can just take this as a definition of the emission temperature.**\n\nLooking back at the observations, the global, annual mean value for OLR is 238.5 W m$^{-2}$.\n\n### Calculate the emission temperature $T_e$\n\nRerranging the Stefan-Boltzmann law we get\n\n$$ T_e = \\left(\\frac{\\text{OLR}}{\\sigma} \\right)^{\\frac{1}{4}} $$\n\nFirst just use Python like a hand calculator to calculate $T_e$ iteractively:\n\n\n```python\nOLR=238.5 # W/m23K4\nsigma=5.67e-8 # W/m2K4 \nTe=(OLR/sigma)**(1/4)\nprint('%.2f K' % Te)\n```\n\n 254.67 K\n\n\nTry typing a few different ways, with and without whitespace.\n\n\n```python\n\n```\n\n#### Python fact 1\n\nextra spaces are ignored! \n\nBut typing numbers interactively is tedious and error prone. Let's define a variable called `sigma`\n\n\n```python\n\n```\n\n#### Python fact 2\n\nWe can define new variables interactively. Variables let us give names to things. Names make our code easy to understand.\n\n### Thoughts on emission temperature\n\nWhat value did we find for the emission temperature $T_e$? How does it compare to the actual global mean surface temperature?\n\n*Is the blackbody radiator a good model for the Earth's emission to space?*\n\n### A simple greenhouse model\n\nThe emission to space is lower because of the greenhouse effect, which we will study in detail later. \n\nFor now, just introduce a basic concept:\n\n*Only a fraction of the surface emission makes it out to space.* \n\nWe will model the OLR as\n\n$$ \\text{OLR} = \\tau \\sigma T_s^4 $$\n\nwhere $\\tau$ is a number we will call the **transmissivity** of the atmosphere.\n\n\nLet's fit this model to observations:\n\n$$ \\tau = \\frac{\\text{OLR}}{\\sigma T_s^4} $$\n\n\n```python\ntau = 238.5 / sigma / 288**4\n```\n\nTry calculating OLR for a warmer Earth at 292 K:\n\n\n```python\nOLR = 238.5 # W/m2\nsigma = 5.67e-8 # W/m2K4 \nTs = 288 # K\ntau = OLR / sigma / Ts**4 # transmissivity (dimensionless)\n\n#Te=(OLR/sigma)**(1/4)\n#print('%.2f K' % Te)\n\nprint('tau= %.2f' % tau)\n\nTs = 292 # K\n\ndef OLR(Ts):\n OLR = tau * sigma * Ts**4\n #print ('for Ts = %.2f K: OLR = %.02f W/m²' % (Ts,OLR))\n #return print ('for Ts = %.2f K: OLR = %.02f W/m²' % (Ts,OLR))\n return OLR\n \n \n\n\n```\n\n tau= 0.61\n\n\nNaturally the emission to space is higher. By how much has it increased for this 4 degree warming?\n\n\n```python\nOLR(288)\nOLR(292)\n\n```\n\n\n\n\n 252.02860648282106\n\n\n\nAnswer: 13.5 W m$^{-2}$. Okay but this is tedious and prone to error.\nWhat we really want to do is **define a reusable function**\n\n\n```python\n\n```\n\nNote a few things:\n\n-\tThe colon at the end of the first line indicates that there is more coming.\n-\tThe interpreter automatically indents the code for us (after the colon)\n-\tThe interpreter automatically colors certain key words\n-\tWe need to hit return one more time at the end to finish our function\n\n\n#### Python fact 3\n\n**Indentations are not ignored! They serve to group together several lines of code.**\n\nwe will see plenty of examples of this – in this case, the indentation lets the interpreter know that the code is all part of the function definition.\n\n#### Python fact 4: \n\n`def` is a keyword that defines a function. \n\nJust like a mathematical function, a Python function takes one or more input arguments, performs some operations on those inputs, and gives back some resulting value. \n\n##### Python fact 5: \n\n`return` is a keyword that defines what value will be returned by the function.\n\nOnce a function is defined, we can call it interactively:\n\n\n```python\nprint(OLR(288), OLR(292), OLR(292)-OLR(288))\n```\n\n 238.5 252.02860648282106 13.528606482821061\n\n\n#### Python fact 6\n\n** The `#` symbol is used for comments in Python code. **\n\nThe interpreter will ignore anything that follows `#` on a line of code.\n\n#### Python fact 7:\n\n`print` is a function that causes the value of an expression (or a list of expressions) to be printed to the screen.\n\n(Don’t always need it, because by default the interpreter prints the output of the last statement to the screen, as we have seen).\n\n\nNote also that we defined variables named sigma and epsilon inside our OLR function. \n\nWhat happens if you try to `print(epsilon)`? \n\n\n```python\nprint(epsilon)\n```\n\n#### Python fact 8: \n\n**Variables defined in functions do not exist outside of that function.**\n\nTry declaring `sigma = 2`, then `print(sigma)`. And try computing `OLR(288)` again. Did anything change?\n\n\n```python\nsigma=2\nprint(sigma)\nOLR(288)\n```\n\n 2\n\n\n\n\n\n 8412698412.698413\n\n\n\nNote that we didn’t really **need** to define those variables inside the function. We could have written the function in one line.\n\nBut sometimes using named variables *makes our code much easier to read and understand!*\n\n### Arrays with `numpy`\n\nNow let’s try some array calculations:\n\n\n```python\nimport numpy as np\nT = np.linspace(230, 300, 10)\nprint(T[2])\n\n\n```\n\n 245.55555555555554\n\n\n- We have just created an array object. \n- The `linspace` function creates an array of numbers evenly spaced between the start and end points. \n- The third argument tells Python how many elements we want.\n\nWe will use the `numpy` package all the time. It is the basic workhorse of scientific computing with Python. We can't do much with arrays of numbers.\n\nDoes our `OLR` function work on an array of temperature values?\n\n\n```python\nOLR = 238.5 # W/m2\nsigma = 5.67e-8 # W/m2K4 \nTs = 288 # K\ntau = OLR / sigma / Ts**4 # transmissivity (dimensionless)\n\ndef OLR(Ts):\n OLR = tau * sigma * Ts**4\n #print ('for Ts = %.2f K: OLR = %.02f W/m²' % (Ts,OLR))\n return print ('for Ts = %.2f K: OLR = %.02f W/m²' % (Ts,OLR))\n #return OLR\n```\n\nNow let’s assign these values to a new variable.\n\n\n```python\nT = np.linspace(230, 300, 10)\nfor i in T:\n OLR(T[i])\n \n```\n\nNow try again to compute `OLR(288)`\n\nWhat do you get?\n\n\n```python\nsize(T)\n```\n\n#### Python fact 9: Assigning a value to a named variable overwrites whatever was already assigned to that name. \n\nPython is also case sensitive. If we had used `olr` to store the array, there would be no conflict.\n\nNow let’s re-enter our function. Start typing `def` and then hit the “up arrow” key. What happens?\n\n\n```python\nOLR = 238.5 # W/m2\nsigma = 5.67e-8 # W/m2K4 \nTs = 288 # K\ntau = OLR / sigma / Ts**4 # transmissivity (dimensionless)\n\n#Te=(OLR/sigma)**(1/4)\n#print('%.2f K' % Te)\n\nprint('tau= %.2f' % tau)\n\nTs = 292 # K\n\ndef OLR(Ts):\n OLR = tau * sigma * Ts**4\n #print ('for Ts = %.2f K: OLR = %.02f W/m²' % (Ts,OLR))\n #return print ('for Ts = %.2f K: OLR = %.02f W/m²' % (Ts,OLR))\n return OLR\n```\n\nThe editor gives us lots of useful keyboard shortcuts. \n\nHere it’s looking up the last expression we entered that began with `def`. Saves a lot of time and typing!\n\nRe-enter the function.\n\n\n```python\ndef\n```\n\nWhat happens if you use the `up arrow` without typing anything first?\n\n\n```python\n\n```\n\nAlso, try typing `history`\n\n\n```python\n\n```\n\nThis is very handy. The Python console is taking notes for you! \n\n\n```python\n\n```\n\n
\n[Back to ATM 623 notebook home](../index.ipynb)\n
\n\n____________\n## Version information\n____________\n\n\n\n```python\n%load_ext version_information\n%version_information\n```\n\n____________\n\n## Credits\n\nThe author of this notebook is [Brian E. J. Rose](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany.\n\nIt was developed in support of [ATM 623: Climate Modeling](http://www.atmos.albany.edu/facstaff/brose/classes/ATM623_Spring2015/), a graduate-level course in the [Department of Atmospheric and Envionmental Sciences](http://www.albany.edu/atmos/index.php)\n\nDevelopment of these notes and the [climlab software](https://github.com/brian-rose/climlab) is partially supported by the National Science Foundation under award AGS-1455071 to Brian Rose. Any opinions, findings, conclusions or recommendations expressed here are mine and do not necessarily reflect the views of the National Science Foundation.\n____________\n\n\n```python\n\n```\n", "meta": {"hexsha": "7761fcaadd57c6a1c0d00ea1b3a56eaa7b825af9", "size": 42830, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures/Lecture01 -- Planetary energy budget.ipynb", "max_stars_repo_name": "kboonma/ClimateModeling_courseware", "max_stars_repo_head_hexsha": "2e16806320cca66c117a7816ba0f3ae6106840a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-26T07:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T07:28:25.000Z", "max_issues_repo_path": "Lectures/Lecture01 -- Planetary energy budget.ipynb", "max_issues_repo_name": "kboonma/ClimateModeling_courseware", "max_issues_repo_head_hexsha": "2e16806320cca66c117a7816ba0f3ae6106840a0", "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": "Lectures/Lecture01 -- Planetary energy budget.ipynb", "max_forks_repo_name": "kboonma/ClimateModeling_courseware", "max_forks_repo_head_hexsha": "2e16806320cca66c117a7816ba0f3ae6106840a0", "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": 33.7244094488, "max_line_length": 1532, "alphanum_fraction": 0.5892131683, "converted": true, "num_tokens": 4475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.24798743179802785, "lm_q1q2_score": 0.08040630389129529}} {"text": "# Let's start!\nOPEN the jupyter notebook **Tutorial1-Part1** downloaded from the **indico timetable: https://indico.cern.ch/event/1088622/timetable/#20220111** to work locally or from the following link: **https://github.com/fusterma/JUAS2022** to work online.\n\n\n# Tutorials summary\n\nThe goal of these workshops is to do numerical exercices using MAD-X to visualize transverse dynamics concepts from a different point of view.\n\n**Friday 14th of January**\n- **Tutorial 1 - Part 1**: Introduction to the tools, small numerical exercises (all together).\n- **Tutorial 1 - Part 2**: My first circular accelerator: FODO cell – optics and first matching (groups of 3/4 students).\n- **Tutorial 1 - Part 3**: Adding dipoles to the FODO cell – MAD-X matching block (groups of 3/4 students).\n\n$\\color{red}{\\text{WEEKEND: homework exercice}}$\n\n**Monday 17th of January**\n- **Tutorial 2 - Part 1**: Natural chromaticity – MAD-X tracking module (groups of 3/4 students).\n- **Tutorial 2 - Part 2**: Chromaticity correction – impact of non-linearities (groups of 3/4 students).\n- **Tutorial 2 - Part 3**: Design of a transfer line - optics and matching (groups of 3/4 students).\n\n$\\color{red}{\\text{Homework + Tutorial 1 and Tutorial 2 jupyter-notebooks (to be delivered as late on Wednesday 19th to nuria.fuster@ific.uv.es)}}$. This will be considered as a BONUS to pass the accelerator design workshop oral exam. \n\n$\\color{red}{\\text{VERY IMPORTANT}}$: Save your jupyter-notebooks and download them to your computer after finishing the tutorials!! Otherwise your work will be lost!\n\n\n- The tutorials solutions will be uploaded on the indico timetable on Wednesday 19th.\n\n$\\color{blue}{\\text{Notes}}$: \n\n- For most of the tutorials we will split in groups of 3/4 students. These groups will be kept also for the accelerator design workshops on the third and fourth weeks of the JUAS course. \n\n\n- The timing of the tutorials (except Tutorial 1 - Part 1) will be:\n - 5 minutes for the introduction to the problem.\n - 25 minutes to work within your team and with your tutor on the problem.\n - 15 minutes for going through the solutions and discussion.\n\n\n- Tutors (Axel, Guido, Tessa, Davide and Nuria) will go around to help you and answer questions!\n\n\n- You can work as a team in the groups or by yourself but when you need help please ask your team mates or the tutor and use the screen share option.\n\n
\n\n
\n\n- The problems are long with many questions, we don't expect you to solve all of them. Some BONUS questions are there for discussion or homework.\n\n\n- We encourage you to use the Slack MAD-X channel during the workshops for the discussion part, during the weekend and all JUAS to post questions.\n\n# Tutorial 1: Part 1\n\nObjectives:\n\n- [Get familiar with the jupyter-notebooks.](#introjupyter)\n\n- [Get familiar with the basic python commands that we will use during the tutorials.](#intropython)\n\n- [How do we compute the optics of a lattice?](#firstexercice)\n\n- [Get familiar with python commands to send the information to the MAD-X code and review the main MAD-X blocks for optics calculations.](#intromadx)\n\n \n\n# Jupyter notebook \n\n- **OPEN** a jupyter notebook go to **FILE -> OPEN**.\n\n\n- **EDIT/INSERT/DELATE** a cell.\n\n\n- **RUN** (press bottom on the top command line or press CAPS+ENTER).\n\n\n- If working online **SAVE and DOWNLOAD**: after we finish one tutorial you need to SAVE and DOWNLOAD the jupyter-notebook into your PC. Otherwise your progres will be lost! \n\n\n- **SAVE TO BROWSER STORAGE** using the \"cloud\" icon (for those working on BINDER).\n\n# Basic python commands \n\nThe python universe has a huge number of libraries that extend the capabilities of python. \nNearly all of these are open source. For this workshop we will use the following:\n\n\n```python\n############################\n# Import special libraries #\n############################\n#For plotting\nfrom matplotlib import pyplot as plt \n# For numerical calulations (np.max(), np.min(), np.mean()...)\nimport numpy as np \n# For symbolic computation (solving algebra problems)\nimport sympy as sp\n# For structuring the data, visualization of tables and data manipultion\nimport pandas as pd \n# Library that allows us to use the MAD-X models \nfrom cpymad.madx import Madx \n# Plot display\n%matplotlib notebook\n```\n\nIf you want to learn more about **python**: \n\nhttps://www.youtube.com/watch?v=kqtD5dpn9C8 \n\nhttps://www.kaggle.com/learn/python\n\nMore about the **cpymad** library: http://hibtc.github.io/cpymad/getting-started\n\n# Scalars, arrays and matrices in Python\n\n\n```python\n# Scalar\na=20\nb=30\n```\n\n\n```python\n# Arrays and matrices\nsp.Matrix([1,2,3,4]) # 1D array\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1\\\\2\\\\3\\\\4\\end{matrix}\\right]$\n\n\n\n\n```python\nsp.Matrix([[1,2],[3,4]]) # 2x2 matrix\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]$\n\n\n\n\n```python\nA=sp.Matrix([[1,2],[3,4]])\nB=sp.Matrix([[1,2],[3,4]])\nA+B\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 & 4\\\\6 & 8\\end{matrix}\\right]$\n\n\n\n\n```python\nA*B\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}7 & 10\\\\15 & 22\\end{matrix}\\right]$\n\n\n\n# Plots in Python\n\n\n```python\n# Plot\n%matplotlib notebook\nx=[0,1,2,3,4,5,6,7,8,9,10]\ny=[0,1,2,3,4,5,6,7,8,9,10]\nplt.plot(x,y,'.-b',label='test')\nplt.legend()\nplt.grid()\nplt.xlabel('s [m]')\nplt.ylabel('x[m]') \n```\n\n\n \n\n\n\n\n\n\n\n\n\n Text(0, 0.5, 'x[m]')\n\n\n\n# How do we compute the optics of a lattice? \n\n \n- Here we want to motivate the use of optics codes such as MAD-X and at the same time illustrate the basic numerical approach behind some of the methods.\n \n\n- The TWISS method is based on matrix multiplications where first and second order transport matrices are used to get the optics of the machine.\n\n\n# FODO cell\n- Compute the linear optics functions of a FODO cell, which is the simplier combination of quadrupoles required to focuse the beam in both, vertical and horizontal planes.\n\n\n\n# Thin lens approximation (f >> $l_q$)\n\n- To do some first estimations analytically one uses the thin lens approximation.\n\n
\n\n
\n\n\n\n```python\n# Symbolic computation\n\n# Symbols defintion\nK = sp.Symbol(\"K\", positive = True)\nLq = sp.Symbol(\"Lq\", positive = True)\nLd = sp.Symbol(\"Ld\", positive = True)\n```\n\n\n```python\n#Matrices definition: A=sp.Matrix([[1,2],[3,4]])\n\n#Mfoc=??\n\n#Mdefoc=??\n\n#Mdrift=??\n```\n\n\n```python\n#################################################\n# Transport matrix of a focusing quadrupole #\n#################################################\nMfoc\n```\n\n\n```python\n################################################\n# Transport matrix of defocusing quadrupole #\n################################################\nMdefoc\n```\n\n\n```python\n##############################################\n# Transport matrix of a drift #\n##############################################\nMdrift\n```\n\n\n```python\n#Matrix multiplication and you can use the sp.simplify(M) command to simplify the elements of the matrix.\n\n```\n\n\n```python\n# Matrix elements computation\n# f=200 m, lq=1 m, ld= 30 m\nM_thin = M.subs(K, 1/(200*1)).subs(Lq, 1).subs(Ld,30) # units K in m-2, Lq and Ld in m\nM_thin\n```\n\n\n```python\n#And for 3 FODO cells?\n```\n\n# What can we do with the transfer matrix?\nThis matrix describes the optical properties of the lattice and defines the beam parameters.\n\n - We can propagate the phase space coordinates of a particle with a given set of initial coordinates.\n\n\n```python\n# Try with a paralel particle going through the center of the first quadrupole or with a certain amplitude\n\n```\n\n\n```python\n# Try with paralel particle going through the center of the first quadrupole or with a certain amplitude\nx=sp.Matrix([[1],[0]])\nx\n```\n\n\n```python\nx2=M*x\nx2\n```\n\n- We can compute the periodic solution TWISS functions.\n\n\n```python\n# Transfer matrix\nR11, R12, R21, R22 = sp.symbols('R11,R12,R21,R22')\n\nMt=sp.Matrix([[R11,R12],[R21,R22]])\n\nMt\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}R_{11} & R_{12}\\\\R_{21} & R_{22}\\end{matrix}\\right]$\n\n\n\n\n```python\n# In case of periodic conditions in the accelerator there is another way to describe the particles trjectories.\n# Periodic solution one-turn-transfer matrix in terms of twiss functions:\n\na, b, g, m = sp.symbols(r'\\alpha,\\beta, \\gamma,\\mu')\n\nM=sp.Matrix([[sp.cos(m)+a*sp.sin(m),b*sp.sin(m)],[-g*sp.sin(m),sp.cos(m)-a*sp.sin(m)]])\n\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\alpha \\sin{\\left(\\mu \\right)} + \\cos{\\left(\\mu \\right)} & \\beta \\sin{\\left(\\mu \\right)}\\\\- \\gamma \\sin{\\left(\\mu \\right)} & - \\alpha \\sin{\\left(\\mu \\right)} + \\cos{\\left(\\mu \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n#For the phase advance we use the comparison of the trace of the matrix\nsp.Eq(sp.cos(m),(R11+R22)/2)\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(\\mu \\right)} = \\frac{R_{11}}{2} + \\frac{R_{22}}{2}$\n\n\n\n\n```python\n#For the beta function we use the R12 matrix element\nsp.Eq(b,R12/sp.sin(m))\n```\n\n\n\n\n$\\displaystyle \\beta = \\frac{R_{12}}{\\sin{\\left(\\mu \\right)}}$\n\n\n\n\n```python\n#For the alfa function we use the trace of the matrix also\nsp.Eq(a,(R11-R22)/(2*sp.sin(m)))\n```\n\n\n\n\n$\\displaystyle \\alpha = \\frac{R_{11} - R_{22}}{2 \\sin{\\left(\\mu \\right)}}$\n\n\n\n\n```python\n#For the gamma we use the R21 element\nsp.Eq(g,-(R21/sp.sin(m)))\n```\n\n\n\n\n$\\displaystyle \\gamma = - \\frac{R_{21}}{\\sin{\\left(\\mu \\right)}}$\n\n\n\nOnce you have computed the periodic TWISS functions you can propagate them to any point in the machine using the transfer matrix of the TWISS functions from Transverse dynamics course.\n\n\n```python\nsp.Matrix([[R11**2, -2*R12*R11, R12**2],[-R11*R21,R12*R21+R22*R11, -R12*R22],[R21**2,-2*R22*R21, R22**2]])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}R_{11}^{2} & - 2 R_{11} R_{12} & R_{12}^{2}\\\\- R_{11} R_{21} & R_{11} R_{22} + R_{12} R_{21} & - R_{12} R_{22}\\\\R_{21}^{2} & - 2 R_{21} R_{22} & R_{22}^{2}\\end{matrix}\\right]$\n\n\n\n**Using the periodic one-turn-matrix one can define some interesting relations between the TWISS parameters and the magnetic properties of the lattice.**\n\n# Figure 1: Relation between $\\Delta \\mu$, K, $L_{cell}$, $L_q$\n\n\n```python\n# NOTE: here we consider that both quadrupoles hve the same strength\n# Relation between the phase advance of the cell and K, Lcell, Lq (from periodic solution an stbility condition)\na, b, g, m, d, Lq, Lc, K, pi = sp.symbols(r'\\alpha,\\beta, \\gamma,\\mu, \\Delta, L_{q}, L_{cell} K \\pi')\nsp.Eq(d*m/pi,2*sp.asin(K*Lq*Lc/4))\n```\n\n\n```python\n#Parametric plots\n%matplotlib notebook\nplt.rcParams['savefig.dpi'] = 90\nplt.rcParams['figure.dpi'] = 90\n\nx=np.arange(0,6,0.01)\ny=2*np.arcsin(x/4)/np.pi\nfig, ax1 = plt.subplots()\nax1.plot(x,y,'-')\nax1.set_ylabel(\"$\\Delta \\mu / \\pi [rad]$\", fontsize=16)\nax1.set_xlabel(\"$K*L_{quad}*L_{cell}$ [-]\", fontsize=16)\nax1.grid()\nax1.tick_params(axis='both', labelsize=16)\nplt.tight_layout() \n```\n\n :7: RuntimeWarning: invalid value encountered in arcsin\n y=2*np.arcsin(x/4)/np.pi\n\n\n\n \n\n\n\n\n\n\n# Exercice:\n- What is the quadrupole strenght to match a FODO cell phase advance of 45$^\\circ$ if the $L_{quad}$=5 m and $L_{cell}$=100 m?\n\n- And for a FODO cell phase advance of 90$^\\circ$?\n\n- What is the maximum phase advance in a FODO cell?\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n# Figure 2: Relation between $\\beta_{max}$ and $\\beta_{min}$ with K, $L_{cell}$, $L_q$\n\n\n```python\n# Relation between the beta of the cell and K, Lcell, Lq\na, bmin, bmax, g, m, d, Lq, Lc, K, pi = sp.symbols(r'\\alpha,\\beta_{min}, \\beta_{max}, \\gamma,\\mu, \\Delta, L_{q}, L_{cell} K \\pi')\nsp.Eq(bmin/Lc,(1-(K*Lq*Lc/4))/(sp.sin(2*sp.asin(K*Lq*Lc/4))))\n```\n\n\n\n\n$\\displaystyle \\frac{\\beta_{min}}{L_{cell}} = \\frac{- \\frac{K L_{cell} L_{q}}{4} + 1}{\\sin{\\left(2 \\operatorname{asin}{\\left(\\frac{K L_{cell} L_{q}}{4} \\right)} \\right)}}$\n\n\n\n\n```python\nsp.Eq(bmax/Lc,(1+(K*Lq*Lc/4))/(sp.sin(2*sp.asin(K*Lq*Lc/4))))\n```\n\n\n\n\n$\\displaystyle \\frac{\\beta_{max}}{L_{cell}} = \\frac{\\frac{K L_{cell} L_{q}}{4} + 1}{\\sin{\\left(2 \\operatorname{asin}{\\left(\\frac{K L_{cell} L_{q}}{4} \\right)} \\right)}}$\n\n\n\n\n```python\n%matplotlib notebook\nplt.rcParams['savefig.dpi'] = 90\nplt.rcParams['figure.dpi'] = 90\n\nx=np.arange(0.4,3.90,0.01)\nbetamax=(1+(x/4))/(np.sin(2*np.arcsin(x/4)))\nbetamin=(1-(x/4))/(np.sin(2*np.arcsin(x/4)))\nfig, ax1 = plt.subplots()\nax1.plot(x,betamax,'-',label=r\"$\\beta_{max}/L_{cell}$\")\nax1.plot(x,betamin,'-',label=r\"$\\beta_{min}/L_{cell}$\")\nax1.set_ylabel(\"[-]\", fontsize=16)\nax1.set_xlabel(\"$K*L_{quad}*L_{cell}$ [-]\", fontsize=16)\nplt.grid()\nplt.legend()\nplt.tick_params(axis='both', labelsize=16)\nplt.tight_layout() \n```\n\n\n \n\n\n\n\n\n\n# Exercice:\n- What is K and $L_{cell}$ to match a FODO cell with a phase advance of 90$^\\circ$ and a $\\beta_{max}$ of 200 m? The $L_{quad}$=2 m.\n\nHINT: You may need to combine the data from both plots.\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\nAt the end, the exact solution of the particle motion has to be calculated in full detail but using some approximations we can make the first steps easier and estimate the order of magnitud of some magnetic properties of our lattice.\n\n# Thick lens computation\n\n\n```python\nK = sp.Symbol(\"K\")\nLq = sp.Symbol(\"Lq\")\nLd= sp.Symbol(\"Ld\")\n\nMfoc=sp.Matrix([[sp.cos(sp.sqrt(K)*Lq),1/(sp.sqrt(K))*sp.sin(sp.sqrt(K)*Lq)],[-(sp.sqrt(K))*sp.sin(sp.sqrt(K)*Lq),sp.cos(sp.sqrt(K)*Lq)]])\n\nMdefoc=sp.Matrix([[sp.cosh(sp.sqrt(K)*Lq),1/(sp.sqrt(K))*sp.sinh(sp.sqrt(K)*Lq)],[(sp.sqrt(K))*sp.sinh(sp.sqrt(K)*Lq),sp.cosh(sp.sqrt(K)*Lq)]])\n\nMdrift=sp.Matrix([[1,Ld],[0,1]])\n```\n\n\n```python\n#################################################\n# Transport matrix of a focusing quadrupople #\n#################################################\nMfoc\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\cos{\\left(\\sqrt{K} Lq \\right)} & \\frac{\\sin{\\left(\\sqrt{K} Lq \\right)}}{\\sqrt{K}}\\\\- \\sqrt{K} \\sin{\\left(\\sqrt{K} Lq \\right)} & \\cos{\\left(\\sqrt{K} Lq \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n################################################\n# Transport matrix of a defocusing quadrupople #\n################################################\nMdefoc\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\cosh{\\left(\\sqrt{K} Lq \\right)} & \\frac{\\sinh{\\left(\\sqrt{K} Lq \\right)}}{\\sqrt{K}}\\\\\\sqrt{K} \\sinh{\\left(\\sqrt{K} Lq \\right)} & \\cosh{\\left(\\sqrt{K} Lq \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n##############################################\n# Transport matrix of a dipole #\n##############################################\nMdrift\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & Ld\\\\0 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nM=Mdrift*Mdefoc*Mdrift*Mfoc\nM=sp.simplify(M)\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\cos{\\left(\\sqrt{K} Lq \\right)} - \\left(2 \\sqrt{K} Ld \\cosh{\\left(\\sqrt{K} Lq \\right)} + K Ld^{2} \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\sinh{\\left(\\sqrt{K} Lq \\right)}\\right) \\sin{\\left(\\sqrt{K} Lq \\right)} & \\frac{\\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\sin{\\left(\\sqrt{K} Lq \\right)} + \\left(2 \\sqrt{K} Ld \\cosh{\\left(\\sqrt{K} Lq \\right)} + K Ld^{2} \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\sinh{\\left(\\sqrt{K} Lq \\right)}\\right) \\cos{\\left(\\sqrt{K} Lq \\right)}}{\\sqrt{K}}\\\\- \\sqrt{K} \\left(\\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\sin{\\left(\\sqrt{K} Lq \\right)} - \\cos{\\left(\\sqrt{K} Lq \\right)} \\sinh{\\left(\\sqrt{K} Lq \\right)}\\right) & \\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\cos{\\left(\\sqrt{K} Lq \\right)} + \\sin{\\left(\\sqrt{K} Lq \\right)} \\sinh{\\left(\\sqrt{K} Lq \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\nM_thick = M.subs(K, 1/(200*1)).subs(Lq, 1).subs(Ld,30) # units K in m-2, Lq and Ld in m\nM_thick\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0.821745966061752 & 66.6422445425746\\\\-0.000766666456349212 & 1.15474570697446\\end{matrix}\\right]$\n\n\n\n\n```python\nM_thin\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0.8275 & 64.5\\\\-0.00075 & 1.15\\end{matrix}\\right]$\n\n\n\n\n```python\n#And for 3 FODO cells?\n```\n\nIn real world applications, lattices (including FODO) are not designed by hand but\ndedicated software is used to do the design and simulation as for example MAD-X.\n\nThe TWISS in MADX it is based in matrix multiplications similar to what has been shown here. \n\n# Wha is next?\n\n- Now we are going to do optics calculations using MAD-X TWISS command (handle thousands of elements).\n\n\n- We will use the MATCHING MAD-X tool to compute the required magnetic properties for a desired TWISS functions.\n\n\n- We will use MAD-X to visulize the impact of some properties of the lattice on the TWISS and on the single particle DYNAMICS.\n\n# An introduction to MAD-X using the python interface
\n\nIn this first part we are going to get familiar with MAD-X syntax.\n\nFor more information please refer to the [MAD-X online manual](http://cern.ch/madx/releases/last-rel/madxuguide.pdf).\n\n**Basic steps:**\n\n - Load the cpymad library.\n - Instantiate the MADX class (we create an object of the class).\n - Access the methods in the class.\n - From the methods available we will be mainly using the method \"input\" to send to MAD-X the commands.\n\n\n```python\n#Load the cpymad library\nfrom cpymad.madx import Madx \n```\n\n\n```python\n#Launching MAD-X\nmyMad = Madx(stdout=True)\n```\n\n\n```python\n#String that will be interpreted by MAD-X\nmyString='''\nstop;\n'''\n```\n\n\n```python\n#Using the \"input\" method to send the commandas to the MAD-X class\nmyMad.input(myString);\n```\n\nWith the 'stop;' instruction we exit from MAD-X, so, as done in the following cell we need to re-instantiate our MAD-X object with the \n**myMad = Madx()** instruction.\n\n---\nIt is a good practice to make header, please use '!' to comment the single line.\n\n\n```python\n# Define and print a value\nmyMad = Madx(stdout=True)\nmyString='''\n\n!***************************************\n! It is a good practice to make a header\n!*************************************** \n\na= 20;\nvalue a;\n\n'''\nmyMad.input(myString);\n```\n\n--- \nUse the **help** keyword (very rudimental help)\n\n\n```python\n# To get information about the MAD-X methods (twiss, beam,match... ) use the commnd \"help\"\nmyString='''\nhelp, twiss;\n'''\nmyMad.input(myString);\n```\n\n\n```python\nmyString='''\nhelp, drift;\n'''\nmyMad.input(myString);\n```\n\n# Let's define the main ingredients to get some results from MAD-X!\n\n-Definition of machine parameters\n\n-Magnets definition\n\n-Sequence definition\n\n-Beam definition\n\n-Activate the sequence\n\n-Actions\n\n\n\n```python\nmyString='''\n! *********************************************************************\n! Definition of some parameters\n! ********************************************************************* \n\nl_cell=60;\nquadrupoleLenght=1;\nmyK:=0.005;// m^-2\n\n! *********************************************************************\n! Definition of magnets\n! ********************************************************************* \nQF: quadrupole, L=quadrupoleLenght, K1:=myK;\nQD: quadrupole, L=quadrupoleLenght, K1:=-myK;\n\n! *********************************************************************\n! Definition of sequence\n! *********************************************************************\nmyCell:sequence, refer=entry, L=L_CELL;\nquadrupole1: QF, at=0;\nmarker1: marker, at=15;\nquadrupole2: QD, at=30;\nendsequence;\n\n! *********************************************************************\n! Definition of beam\n! *********************************************************************\nbeam, particle=proton, energy=1;\n\n! *********************************************************************\n! Use of the sequence\n! *********************************************************************\nuse, sequence=myCell;\n\n! *********************************************************************\n! TWISS\n! *********************************************************************\n\nselect, flag=TWISS, column=keyword, name, s, betx, bety,alfx, alfy, x, y, dx, dy;\ntwiss, file=Test.madx;\n!plot, haxis=s, vaxis=betx,bety,dx,colour=100,file=Test;\n\n'''\nmyMad.input(myString);\n```\n\nThe OUTPUT generated by MADX can be found by accessing the jupyter-notebook files-view.\n- For accessing: CLIC on the jupyter-logo on the top of the page using the right buttom of your mouse and use the option \"Open Link in a New Tab\".\n\n**Output:**\n\n- SUMM table\n\n- TWISS table\n\n- TWISS .txt file\n\n- TWISS .ps plot\n\n# Accessing the data\n\n- Open the files generated by MAD-X.\n\n- Use python and output the required data on the jupyter-notebook.\n\n - Using MAD-X commands and the **input()** method.\n \n - Using **cpymad** methods:\n - **myMad.table.twiss.dframe()**\n - **myMad.table.summ.dframe()**\n\n\n```python\n#######################\n#Using MAD-X commands #\n#######################\nmyString='''\nvalue, table(SUMM,Q1);\nvalue, table(SUMM,betxmax);\n'''\nmyMad.input(myString);\n```\n\nAnd for the vertical plane?\n\n\n```python\n#######################\n#Using MAD-X commands #\n#######################\nmyString='''\nvalue, table(SUMM,Q2);\nvalue, table(SUMM,betymax);\n'''\nmyMad.input(myString);\n```\n\n\n```python\nmyString='''\nvalue, table(TWISS,MYCELL$END,betx);\nvalue, table(TWISS,MYCELL$END,bety);\n'''\nmyMad.input(myString);\n```\n\n# Using python pandas library\n\nPandas dataframe are very convenient, have a look in https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf.\n\n\n```python\n# Using another method from cpymad \"table.twiss.dframe()\"\nmyDF=myMad.table.twiss.dframe()\n```\n\n\n```python\nmyDF\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 \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 \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 \n \n \n \n \n \n \n
namekeywordsbetxalfxmuxbetyalfymuyx...sig54sig55sig56sig61sig62sig63sig64sig65sig66n1
#smycell$start:1marker0.0463.623288-1.1561090.000000369.7791620.9293160.0000000.0...0.00.00.00.00.00.00.00.00.00.0
quadrupole1quadrupole1:1quadrupole5.0463.6232881.1561090.001709369.779162-0.9293160.0021610.0...0.00.00.00.00.00.00.00.00.00.0
drift_0[0]drift_0:0drift25.0419.3948671.0553120.008930408.967742-1.0301130.0103500.0...0.00.00.00.00.00.00.00.00.00.0
marker1marker1:1marker25.0419.3948671.0553120.008930408.967742-1.0301130.0103500.0...0.00.00.00.00.00.00.00.00.00.0
drift_1[0]drift_1:0drift50.0369.7791620.9293160.019041463.623288-1.1561090.0194930.0...0.00.00.00.00.00.00.00.00.00.0
quadrupole2quadrupole2:1quadrupole55.0369.779162-0.9293160.021202463.6232881.1561090.0212020.0...0.00.00.00.00.00.00.00.00.00.0
drift_2[0]drift_2:0drift100.0463.623288-1.1561090.038533369.7791620.9293160.0385330.0...0.00.00.00.00.00.00.00.00.00.0
#emycell$end:1marker100.0463.623288-1.1561090.038533369.7791620.9293160.0385330.0...0.00.00.00.00.00.00.00.00.00.0
\n

8 rows × 256 columns

\n
\n\n\n\n\n```python\nmyDF[['name','s','betx','bety','alfx','alfy']]\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
namesbetxbetyalfxalfy
#smycell$start:10.0463.623288369.779162-1.1561090.929316
quadrupole1quadrupole1:15.0463.623288369.7791621.156109-0.929316
drift_0[0]drift_0:025.0419.394867408.9677421.055312-1.030113
marker1marker1:125.0419.394867408.9677421.055312-1.030113
drift_1[0]drift_1:050.0369.779162463.6232880.929316-1.156109
quadrupole2quadrupole2:155.0369.779162463.623288-0.9293161.156109
drift_2[0]drift_2:0100.0463.623288369.779162-1.1561090.929316
#emycell$end:1100.0463.623288369.779162-1.1561090.929316
\n
\n\n\n\n\n```python\nmyDF[\"s\"]\n```\n\n\n\n\n #s 0.0\n quadrupole1 5.0\n drift_0[0] 25.0\n marker1 25.0\n drift_1[0] 50.0\n quadrupole2 55.0\n drift_2[0] 100.0\n #e 100.0\n Name: s, dtype: float64\n\n\n\n\n```python\nmyDF[\"betx\"]\n```\n\n\n\n\n #s 463.623288\n quadrupole1 463.623288\n drift_0[0] 419.394867\n marker1 419.394867\n drift_1[0] 369.779162\n quadrupole2 369.779162\n drift_2[0] 463.623288\n #e 463.623288\n Name: betx, dtype: float64\n\n\n\n\n```python\nmyDF2=myMad.table.summ.dframe()\n```\n\n\n```python\nmyDF2\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
lengthorbit5alfagammatrq1dq1betxmaxdxmaxdxrmsxcomax...ycormsdeltapsynch_1synch_2synch_3synch_4synch_5synch_6synch_8nflips
#e100.0-0.00.00.00.038533-0.043847463.6232880.00.00.0...0.00.00.00.00.00.00.00.00.00.0
\n

1 rows × 27 columns

\n
\n\n\n\n\n```python\nmyDF2[\"q1\"]\n```\n\n\n\n\n #e 0.038533\n Name: q1, dtype: float64\n\n\n\n# Basic plot\n\n\n```python\n#Plot\nplt.plot(myDF['s'],myDF['betx'],'.-b',label='$\\\\beta_x$')\nplt.plot(myDF['s'],myDF['bety'],'.-r',label='$\\\\beta_y$')\n#Labels of the plot\nplt.xlabel('s [m]')\nplt.ylabel('[m]')\n#Legend and grid\nplt.legend(loc='best')\nplt.grid()\n```\n\n# For reference...\n\n---\nThis is an example to get familiar with the use of the physical constants and the formatting of the output. Have a look on the difference.\n\n\n```python\nmyString='''\na=pi;\nvalue a; \nset, format=\"22.20e\";\nvalue a; \n'''\nmyMad.input(myString);\n```\n\n# \nThis is an example to get familiar with if and deferred expression. Please note the after the block delimited with {...} the ; can be omitted. Pay attention to circular call!\n\n\n\n```python\nmyString='''\nif (1==1){\noption, echo=false, info=true;\na=pi;\nb:=a;\nc=a;\nvalue a; \nvalue b;\nvalue c;\na=CLIGHT*cos(a);\nvalue a;\nvalue b;\nvalue c;}\n! BEWARE of circular call!\n!a:=a+1;\n! When evaluating you will get a fatal error\n! value a; \noption, echo=true, info=true;\n'''\nmyMad.input(myString);\n```\n\n# ---\nThis is an example to get familiar with **while** and **macros** loops.\n\n\n```python\nmyString='''\na(myvariable1,myvariable2): macro = {\nvalue, myvariable1;\nvalue, myvariable1*myvariable2;\n}\n\nN=1;\nwhile (N<10){\nexec, a(N,N);\nN=N+1;\n}\n'''\nmyMad.input(myString);\n```\n\n---\n### List of functions\nIn MAD-X the following functions are available\n\n- SQRT(x) square root,\n- LOG(x) natural logarithm,\n- LOG10(x) logarithm base 10,\n- EXP(x) exponential,\n- SIN(x) trigonometric sine,\n- COS(x) trigonometric cosine,\n- TAN(x) trigonometric tangent,\n- ASIN(x) arc sine,\n- ACOS(x) arc cosine,\n- ATAN(x) arc tangent,\n- SINH(x) hyperbolic sine,\n- COSH(x) hyperbolic cosine,\n- TANH(x) hyperbolic tangent,\n- SINC(x) cardinal sine function,\n- ABS(x) absolute value,\n- ERF(x) Gauss error,\n- ERFC(x) complementary error,\n- FLOOR(x) floor, largest previous integer,\n- CEIL(x) ceiling, smallest next integer,\n- ROUND(x) round, closest integer,\n- FRAC(x) fractional part of number,\n- RANF() random number, uniformly distributed in [0,1],\n- GAUSS() random number, gaussian distribution with unit standard deviation,\n- TGAUSS(x) random number, gaussian distribution with unit standard deviation, truncated at x standard deviations;\n\n---\n### List of physical constant\n\n| MAD-X name | symbol | value |unit|\n|:-:|:-:|:-:|:-:|\n|PI| π |4 * atan(1)| 1|\n|TWOPI|2π| 2 * PI| 1|\n|DEGRAD| 180/π |180 / PI| deg/rad|\n|RADDEG| π/180 |PI / 180 |rad/deg|\n|E| e |exp(1) |1|\n|EMASS| me |0.510998928e−3| GeV|\n|PMASS| mp |0.938272046| GeV|\n|NMASS| u |0.931494061| GeV|\n|MUMASS| mµ| 0.1056583715 |GeV|\n|CLIGHT| c| 299792458| m/s|\n|QELECT| e| 1.602176565e−19| A.s|\n|HBAR| ¯h| 6.58211928e−25| MeV.s|\n|ERAD| re| 2.8179403267e−15| m|\n|PRAD| re(me/mp)| ERAD*EMASS/PMASS| m|\n", "meta": {"hexsha": "279bbf90c6092e9fbbc6004a560696692231bdfd", "size": 602581, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorial1_Part1.ipynb", "max_stars_repo_name": "fusterma/JUAS2022", "max_stars_repo_head_hexsha": "d7ab8ef76355deeedff2bebfb96c8e6596c3a2b1", "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": "Tutorial1_Part1.ipynb", "max_issues_repo_name": "fusterma/JUAS2022", "max_issues_repo_head_hexsha": "d7ab8ef76355deeedff2bebfb96c8e6596c3a2b1", "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": "Tutorial1_Part1.ipynb", "max_forks_repo_name": "fusterma/JUAS2022", "max_forks_repo_head_hexsha": "d7ab8ef76355deeedff2bebfb96c8e6596c3a2b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-08T10:43:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T10:43:51.000Z", "avg_line_length": 113.9956488838, "max_line_length": 114701, "alphanum_fraction": 0.7991373774, "converted": true, "num_tokens": 11092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.08005748712682206}} {"text": "[Table of Contents](http://nbviewer.ipython.org/github/rlabbe/Kalman-and-Bayesian-Filters-in-Python/blob/master/table_of_contents.ipynb)\n\\appendix\n# Installation, Python, NumPy, and FilterPy\n\n\n```python\n#format the book\n%matplotlib inline\nfrom __future__ import division, print_function\nfrom book_format import load_style\nload_style()\n```\n\n\n\n\n\n\n\n\n\n\nThis book is written in Jupyter Notebook, a browser based interactive Python environment that mixes Python, text, and math. I choose it because of the interactive features - I found Kalman filtering nearly impossible to learn until I started working in an interactive environment. It is difficult to form an intuition about many of the parameters until you can change them and immediately see the output. An interactive environment also allows you to play 'what if' scenarios. \"What if I set $\\mathbf{Q}$ to zero?\" It is trivial to find out with Jupyter Notebook.\n\nAnother reason I choose it is because most textbooks leaves many things opaque. For example, there might be a beautiful plot next to some pseudocode. That plot was produced by software, but software that is not available to the reader. I want everything that went into producing this book to be available to you. How do you plot a covariance ellipse? You won't know if you read most books. With Jupyter Notebook all you have to do is look at the source code.\n\nEven if you choose to read the book online you will want Python and the SciPy stack installed so that you can write your own Kalman filters. There are many different ways to install these libraries, and I cannot cover them all, but I will cover a few typical scenarios.\n\n## Installing the SciPy Stack\n\nThis book requires IPython, Jupyter, NumPy, SciPy, SymPy, and Matplotlib. The SciPy stack of NumPy, SciPy, and Matplotlib depends on third party Fortran and C code, and is not trivial to install from source code. The SciPy website strongly urges using a pre-built installation, and I concur with this advice.\n\nI use the Anaconda distribution from Continuum Analytics. This is an excellent distribution that combines all of the packages listed above, plus many others. Installation is very straightforward, and it can be done alongside other Python installations you might already have on your machine. It is free to use. You may download it from here: http://continuum.io/downloads I strongly recommend using the latest Python 3 version that they provide.\n\nThere are other choices for installing the SciPy stack. You can find instructions here: http://scipy.org/install.html\n\nMany Linux distributions come with these packages preinstalled. However, they are often somewhat dated and they will need to be updated as the book depends on recent versions of all. Updating a specific Linux installation is beyond the scope of this book. An advantage of the Anaconda distribution is that it does not modify your local Python installation, so you can install it and not break your linux distribution. \n\n## Installing FilterPy\n\nFilterPy is a Python library that implements all of the filters used in this book, and quite a few others. Installation is easy using `pip`. Issue the following from the command prompt:\n\n pip install filterpy\n \n \nFilterPy is written by me, and the latest development version is always available at https://github.com/rlabbe/filterpy.\n \n \n\n## Downloading and Running the Book\n\nThe book is stored in a github repository. From the command line type the following:\n\n git clone https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python.git\n \nIf you do not have git installed, browse to https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python where you can download the book via your browser.\n\nNow, from the command prompt change to the directory that was just created, and then run Jupyter notebook:\n\n cd Kalman-and-Bayesian-Filters-in-Python\n juptyer notebook\n\nA browser window should launch showing you all of the chapters in the book. Browse to the first chapter by clicking on it, then open the notebook in that subdirectory by clicking on the link.\n\nMore information about running the notebook can be found here:\n\nhttp://jupyter-notebook-beginner-guide.readthedocs.org/en/latest/execute.html\n\n## Using Juptyer Notebook\n\nA complete tutorial on Jupyter Notebook is beyond the scope of this book. Many are available online. In short, Python code is placed in cells. These are prefaced with text like `In [1]:`, and the code itself is in a boxed area. If you press CTRL-ENTER while focus is inside the box the code will run and the results will be displayed below the box. Like this:\n\n\n```python\nprint(3+7.2)\n```\n\n 10.2\n\n\nIf you have this open in Jupyter Notebook now, go ahead and modify that code by changing the expression inside the print statement and pressing CTRL+ENTER. The output should be changed to reflect what you typed in the code cell.\n\n## SymPy\n\nSymPy is a Python package for performing symbolic mathematics. The full scope of its abilities are beyond this book, but it can perform algebra, integrate and differentiate equations, find solutions to differential equations, and much more. For example, we use use it to compute the Jacobian of matrices and expected value integral computations.\n\nFirst, a simple example. We will import SymPy, initialize its pretty print functionality (which will print equations using LaTeX). We will then declare a symbol for SymPy to use.\n\n\n```python\nimport sympy\nsympy.init_printing(use_latex='mathjax')\n\nphi, x = sympy.symbols('\\phi, x')\nphi\n```\n\n\n\n\n$$\\phi$$\n\n\n\nNotice how it prints the symbol `phi` using LaTeX. Now let's do some math. What is the derivative of $\\sqrt{\\phi}$?\n\n\n```python\nsympy.diff('sqrt(phi)')\n```\n\n\n\n\n$$\\frac{1}{2 \\sqrt{\\phi}}$$\n\n\n\nWe can factor equations\n\n\n```python\nsympy.factor(phi**3 -phi**2 + phi - 1)\n```\n\n\n\n\n$$\\left(\\phi - 1\\right) \\left(\\phi^{2} + 1\\right)$$\n\n\n\nand we can expand them.\n\n\n```python\n((phi+1)*(phi-4)).expand()\n```\n\n\n\n\n$$\\phi^{2} - 3 \\phi - 4$$\n\n\n\nYou can evauate an equation for specific values of its variables:\n\n\n```python\nw =x**2 -3*x +4\nprint(w.subs(x, 4))\nprint(w.subs(x, 12))\n```\n\n 8\n 112\n\n\nYou can also use strings for equations that use symbols that you have not defined:\n\n\n```python\nx = sympy.expand('(t+1)*2')\nx\n```\n\n\n\n\n$$2 t + 2$$\n\n\n\nNow let's use SymPy to compute the Jacobian of a matrix. Given the function\n\n$$h=\\sqrt{(x^2 + z^2)}$$\n\nfind the Jacobian with respect to x, y, and z.\n\n\n```python\nx, y, z = sympy.symbols('x y z')\n\nH = sympy.Matrix([sympy.sqrt(x**2 + z**2)])\n\nstate = sympy.Matrix([x, y, z])\nH.jacobian(state)\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{x}{\\sqrt{x^{2} + z^{2}}} & 0 & \\frac{z}{\\sqrt{x^{2} + z^{2}}}\\end{matrix}\\right]$$\n\n\n\nNow let's compute the discrete process noise matrix $\\mathbf Q$ given the continuous process noise matrix \n$$\\mathbf Q = \\Phi_s \\begin{bmatrix}0&0&0\\\\0&0&0\\\\0&0&1\\end{bmatrix}$$\n\nThe integral is \n\n$$\\mathbf Q = \\int_0^{\\Delta t} \\mathbf F(t)\\mathbf Q\\mathbf F^T(t)\\, dt$$\n\nwhere \n$$\\mathbf F(\\Delta t) = \\begin{bmatrix}1 & \\Delta t & {\\Delta t}^2/2 \\\\ 0 & 1 & \\Delta t\\\\ 0& 0& 1\\end{bmatrix}$$\n\n\n```python\ndt = sympy.symbols('\\Delta{t}')\nF_k = sympy.Matrix([[1, dt, dt**2/2],\n [0, 1, dt],\n [0, 0, 1]])\nQ = sympy.Matrix([[0,0,0],\n [0,0,0],\n [0,0,1]])\n\nsympy.integrate(F_k*Q*F_k.T,(dt, 0, dt))\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{\\Delta{t}^{5}}{20} & \\frac{\\Delta{t}^{4}}{8} & \\frac{\\Delta{t}^{3}}{6}\\\\\\frac{\\Delta{t}^{4}}{8} & \\frac{\\Delta{t}^{3}}{3} & \\frac{\\Delta{t}^{2}}{2}\\\\\\frac{\\Delta{t}^{3}}{6} & \\frac{\\Delta{t}^{2}}{2} & \\Delta{t}\\end{matrix}\\right]$$\n\n\n", "meta": {"hexsha": "889e46b154f2e1b53d817501f049a4376c29c38d", "size": 25180, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Appendix-A-Installation.ipynb", "max_stars_repo_name": "MichaelRW/Kalman_and_Bayesian_Filtering", "max_stars_repo_head_hexsha": "2e9394c7942872b155228ed7b21798527961282b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-12-20T18:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T09:24:02.000Z", "max_issues_repo_path": "Appendix-A-Installation.ipynb", "max_issues_repo_name": "MichaelRW/Kalman_and_Bayesian_Filtering", "max_issues_repo_head_hexsha": "2e9394c7942872b155228ed7b21798527961282b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-13T20:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-13T20:46:33.000Z", "max_forks_repo_path": "Appendix-A-Installation.ipynb", "max_forks_repo_name": "MichaelRW/Kalman_and_Bayesian_Filtering", "max_forks_repo_head_hexsha": "2e9394c7942872b155228ed7b21798527961282b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-30T05:28:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T07:08:42.000Z", "avg_line_length": 32.8292046936, "max_line_length": 575, "alphanum_fraction": 0.4827243844, "converted": true, "num_tokens": 3824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.20181322466072713, "lm_q1q2_score": 0.07993179094390924}} {"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n \n\n \n\n\n\n[Python for Probability, Statistics, and Machine Learning](https://www.springer.com/fr/book/9783319307152)\n\nThis chapter takes a geometric view of probability theory and relates it to\nfamiliar concepts in linear algebra and geometry. This approach connects your\nnatural geometric intuition to the key abstractions in probability that can\nhelp guide your reasoning. This is particularly important in probability\nbecause it is easy to be misled. We need a bit of rigor and some\nintuition to guide us.\n\nIn grade school, you were introduced to the natural numbers (i.e., `1,2,3,..`)\nand you learned how to manipulate them by operations like addition,\nsubtraction, and multiplication. Later, you were introduced to positive and\nnegative numbers and were again taught how to manipulate them. Ultimately, you\nwere introduced to the calculus of the real line, and learned how to\ndifferentiate, take limits, and so on. This progression provided more\nabstractions, but also widened the field of problems you could successfully\ntackle. The same is true of probability. One way to think about probability is\nas a new number concept that allows you to tackle problems that have a special\nkind of *uncertainty* built into them. Thus, the key idea is that there is some\nnumber, say $x$, with a traveling companion, say, $f(x)$, and this companion\nrepresents the uncertainties about the value of $x$ as if looking at the number\n$x$ through a frosted window. The degree of opacity of the window is\nrepresented by $f(x)$. If we want to manipulate $x$, then we have to figure\nout what to do with $f(x)$. For example if we want $y= 2 x $, then we have to\nunderstand how $f(x)$ generates $f(y)$. \n\nWhere is the *random* part? To conceptualize this, we need still another\nanalogy: think about a beehive with the swarm around it representing $f(x)$,\nand the hive itself, which you can barely see through the swarm, as $x$. The\nrandom piece is you don't know *which* bee in particular is going to sting you!\nOnce this happens the uncertainty evaporates.\nUp until that happens, all we have is a concept of a swarm (i.e., density of\nbees) which represents a *potentiality* of which bee will ultimately sting.\nIn summary, one way to think about probability is as a way of carrying through\nmathematical reasoning (e.g., adding, subtracting, taking\nlimits) with a notion of potentiality that is so-transformed by these\noperations.\n\n## Understanding Probability Density\n\nIn order to understand the heart of modern probability, which is built\non the Lesbesgue theory of integration, we need to extend the concept\nof integration from basic calculus. To begin, let us consider the\nfollowing piecewise function\n\n$$\nf(x) = \\begin{cases}\n 1 & \\mbox{if } 0 < x \\leq 1 \\\\\\\n 2 & \\mbox{if } 1 < x \\leq 2 \\\\\\\n 0 & \\mbox{otherwise }\n \\end{cases}\n$$\n\n as shown in [Figure](#fig:intro_001). In calculus, you learned\nRiemann integration, which you can apply here as\n\n\n\n
\n\n

\n\n\n\n\n$$\n\\int_0^2 f(x) dx = 1 + 2 = 3\n$$\n\n which has the usual interpretation as the area of the two rectangles\nthat make up $f(x)$. So far, so good.\n\nWith Lesbesgue integration, the idea is very similar except that we\nfocus on the y-axis instead of moving along the x-axis. The question\nis given $f(x) = 1$, what is the set of $x$ values for which this is\ntrue? For our example, this is true whenever $x\\in (0,1]$. So now we\nhave a correspondence between the values of the function (namely, `1`\nand `2`) and the sets of $x$ values for which this is true, namely,\n$\\lbrace (0,1] \\rbrace$ and $\\lbrace (1,2] \\rbrace$, respectively. To\ncompute the integral, we simply take the function values (i.e., `1,2`)\nand some way of measuring the size of the corresponding interval\n(i.e., $\\mu$) as in the following:\n\n$$\n\\int_0^2 f d\\mu = 1 \\mu(\\lbrace (0,1] \\rbrace) + 2 \\mu(\\lbrace (1,2] \\rbrace)\n$$\n\nWe have suppressed some of the notation above to emphasize generality. Note\nthat we obtain the same value of the integral as in the Riemann case when\n$\\mu((0,1]) = \\mu((1,2]) = 1$. By introducing the $\\mu$ function as a way of\nmeasuring the intervals above, we have introduced another degree of freedom in\nour integration. This accommodates many weird functions that are not tractable\nusing the usual Riemann theory, but we refer you to a proper introduction to\nLesbesgue integration for further study [[jones2001lebesgue]](#jones2001lebesgue). Nonetheless,\nthe key step in the above discussion is the introduction of the $\\mu$ function,\nwhich we will encounter again as the so-called probability density function.\n\n## Random Variables\n\nMost introductions to probability jump straight into *random variables* and\nthen explain how to compute complicated integrals. The problem with this\napproach is that it skips over some of the important subtleties that we will now\nconsider. Unfortunately, the term *random variable* is not very descriptive. A\nbetter term is *measurable function*. To understand why this is a better term,\nwe have to dive into the formal constructions of probability by way of a simple\nexample.\n\nConsider tossing a fair six-sided die. There are only six outcomes possible,\n\n$$\n\\Omega=\\lbrace 1,2,3,4,5,6 \\rbrace\n$$\n\nAs we know, if the die is fair, then the probability of each outcome is $1/6$.\nTo say this formally, the measure of each set (i.e., $\\lbrace 1 \\rbrace,\\lbrace\n2 \\rbrace,\\ldots,\\lbrace 6 \\rbrace$) is $\\mu(\\lbrace 1 \\rbrace ) =\\mu(\\lbrace 2\n\\rbrace ) \\ldots = \\mu(\\lbrace 6 \\rbrace ) = 1/6$. In this case, the $\\mu$\nfunction we discussed earlier is the usual *probability* mass function, denoted by\n$\\mathbb{P}$. The measurable function maps a set into a\nnumber on the real line. For example, $ \\lbrace 1 \\rbrace \\mapsto 1 $ is\none such uninteresting function.\n\nNow, here's where things get interesting. Suppose you were asked to construct a\nfair coin from the fair die. In other words, we want to throw the die and then\nrecord the outcomes as if we had just tossed a fair coin. How could we do this?\nOne way would be to define a measurable function that says if the die comes up\n`3` or less, then we declare *heads* and otherwise declare *tails*. This has\nsome strong intuition behind it, but let's articulate it in terms of formal\ntheory. This strategy creates two different non-overlapping sets $\\lbrace\n1,2,3 \\rbrace$ and $\\lbrace 4,5,6 \\rbrace$. Each set has the same probability\n*measure*,\n\n$$\n\\begin{eqnarray*}\n\\mathbb{P}(\\lbrace 1,2,3 \\rbrace) & = & 1/2 \\\\\\\n\\mathbb{P}(\\lbrace 4,5,6 \\rbrace) & = & 1/2\n\\end{eqnarray*}\n$$\n\n And the problem is solved. Everytime the die comes up\n$\\lbrace 1,2,3 \\rbrace$, we record heads and record tails otherwise.\n\nIs this the only way to construct a fair coin experiment from a\nfair die? Alternatively, we can define the sets as $\\lbrace 1 \\rbrace$,\n$\\lbrace 2 \\rbrace$, $\\lbrace 3,4,5,6 \\rbrace$. If we define the corresponding\nmeasure for each set as the following\n\n$$\n\\begin{eqnarray*}\n\\mathbb{P}(\\lbrace 1 \\rbrace) & = & 1/2 \\\\\\\n\\mathbb{P}(\\lbrace 2 \\rbrace) & = & 1/2 \\\\\\\n\\mathbb{P}(\\lbrace 3,4,5,6 \\rbrace) & = & 0\n\\end{eqnarray*}\n$$\n\n then, we have another solution to the fair coin problem. To\nimplement this, all we do is ignore every time the die shows `3,4,5,6` and\nthrow again. This is wasteful, but it solves the problem. Nonetheless,\nwe hope you can see how the interlocking pieces of the theory provide a\nframework for carrying the notion of uncertainty/potentiality from one problem\nto the next (e.g., from the fair die to the fair coin). \n\nLet's consider a slightly more interesting problem where we toss two dice. We\nassume that each throw is *independent*, meaning that the outcome of one does\nnot influence the other. What are the sets in this case? They are all pairs\nof possible outcomes from two throws as shown below,\n\n$$\n\\Omega = \\lbrace (1,1),(1,2),\\ldots,(5,6),(6,6) \\rbrace\n$$\n\n What are the measures of each of these sets? By virtue of the\nindependence claim, the measure of each is the product of the respective measures\nof each element. For instance,\n\n$$\n\\mathbb{P}((1,2)) = \\mathbb{P}(\\lbrace 1 \\rbrace) \\mathbb{P}(\\lbrace 2 \\rbrace) = \\frac{1}{6^2}\n$$\n\n With all that established, we can ask the following\nquestion: what is the probability that the sum of the dice equals\nseven? As before, the first thing to do is characterize the\nmeasurable function for this as $X:(a,b) \\mapsto (a+b)$. Next, we\nassociate all of the $(a,b)$ pairs with their sum. We can create a\nPython dictionary for this as shown,\n\n\n```python\nd={(i,j):i+j for i in range(1,7) for j in range(1,7)}\n```\n\n The next step is to collect all of the $(a,b)$ pairs that sum to\neach of the possible values from two to twelve.\n\n\n```python\nfrom collections import defaultdict\ndinv = defaultdict(list)\nfor i,j in d.iteritems():\n dinv[j].append(i)\n```\n\n**Programming Tip.**\n\nThe `defaultdict` object from the built-in collections module creates dictionaries with\ndefault values when it encounters a new key. Otherwise, we would have had to\ncreate default values manually for a regular dictionary.\n\n\n\n For example, `dinv[7]` contains the following list of pairs that\nsum to seven,\n\n\n```python\n[(1, 6), (2, 5), (5, 2), (6, 1), (4, 3), (3, 4)]\n```\n\n\n\n\n [(1, 6), (2, 5), (5, 2), (6, 1), (4, 3), (3, 4)]\n\n\n\nThe next step is to compute the probability measured for each of these items.\nUsing the independence assumption, this means we have to compute the sum of the\nproducts of the individual item probabilities in `dinv`. Because we know that\neach outcome is equally likely, every term in the sum equals $1/36$. Thus, all\nwe have to do is count the number of items in the corresponding list for each\nkey in `dinv` and divide by `36`. For example, `dinv[11]` contains `[(5, 6),\n(6, 5)]`. The probability of `5+6=6+5=11` is the probability of this set which\nis composed of the sum of the probabilities of the individual elements\n`{(5,6),(6,5)}`. In this case, we have $\\mathbb{P}(11) = \\mathbb{P}(\\lbrace\n(5,6) \\rbrace)+ \\mathbb{P}(\\lbrace (6,5) \\rbrace) = 1/36 + 1/36 = 2/36$.\nRepeating this procedure for all the elements, we derive the probability mass\nfunction as shown below,\n\n\n```python\nX={i:len(j)/36. for i,j in dinv.iteritems() }\nprint X\n{2: 0.027777777777777776,\n 3: 0.05555555555555555,\n 4: 0.08333333333333333,\n 5: 0.1111111111111111,\n 6: 0.1388888888888889,\n 7: 0.16666666666666666,\n 8: 0.1388888888888889,\n 9: 0.1111111111111111,\n 10: 0.08333333333333333,\n 11: 0.05555555555555555,\n 12: 0.027777777777777776}\n```\n\n {2: 0.027777777777777776, 3: 0.05555555555555555, 4: 0.08333333333333333, 5: 0.1111111111111111, 6: 0.1388888888888889, 7: 0.16666666666666666, 8: 0.1388888888888889, 9: 0.1111111111111111, 10: 0.08333333333333333, 11: 0.05555555555555555, 12: 0.027777777777777776}\n\n\n\n\n\n {2: 0.027777777777777776,\n 3: 0.05555555555555555,\n 4: 0.08333333333333333,\n 5: 0.1111111111111111,\n 6: 0.1388888888888889,\n 7: 0.16666666666666666,\n 8: 0.1388888888888889,\n 9: 0.1111111111111111,\n 10: 0.08333333333333333,\n 11: 0.05555555555555555,\n 12: 0.027777777777777776}\n\n\n\n**Programming Tip.**\n\nIn the preceding code note that `36.` is written with\nthe trailing decimal mark. This is a good habit to get into because division\nin Python 2.x is integer division by default, which is not what we want here.\nThis can be fixed with a top-level `from __future__ import division`, but\nthat's easy to forget to do, especially when you are passing code\naround and others may not reflexively do the future import.\n\n\n\nThe above example exposes the elements of probability theory that\nare in play for this simple problem while deliberately suppressing some of the\ngory technical details. With this framework, we can ask other questions like\nwhat is the probability that half the product of three dice will exceed the\ntheir sum? We can solve this using the same method as in the following. First,\nlet's create the first mapping,\n\n\n```python\nd={(i,j,k):((i*j*k)/2>i+j+k) for i in range(1,7) \n for j in range(1,7) \n for k in range(1,7)}\n```\n\n The keys of this dictionary are the triples and the values are the\nlogical values of whether or not half the product of three dice exceeds their sum.\nNow, we do the inverse mapping to collect the corresponding lists,\n\n\n```python\ndinv = defaultdict(list)\nfor i,j in d.iteritems(): dinv[j].append(i)\n```\n\n Note that `dinv` contains only two keys, `True` and `False`. Again,\nbecause the dice are independent, the probability of any triple is $1/6^3$.\nFinally, we collect this for each outcome as in the following,\n\n\n```python\nX={i:len(j)/6.0**3 for i,j in dinv.iteritems() }\nprint X\n{False: 0.37037037037037035, True: 0.6296296296296297}\n```\n\n {False: 0.37037037037037035, True: 0.6296296296296297}\n\n\n\n\n\n {False: 0.37037037037037035, True: 0.6296296296296297}\n\n\n\n Thus, the probability of half the product of three dice exceeding their sum is\n`136/(6.0**3) = 0.63`. The set that is induced by the random variable has only\ntwo elements in it, `True` and `False`, with $\\mathbb{P}(\\mbox{True})=136/216$\nand $\\mathbb{P}(\\mbox{False})=1-136/216$.\n\nAs a final example to exercise another layer of generality, let is consider the\nfirst problem with the two dice where we want the probability of a\nseven, but this time one of the dice is no longer fair. The distribution for\nthe unfair die is the following:\n\n$$\n\\begin{eqnarray*}\n\\mathbb{P}(\\lbrace 1\\rbrace)=\\mathbb{P}(\\lbrace 2 \\rbrace)=\\mathbb{P}(\\lbrace 3 \\rbrace) = \\frac{1}{9} \\\\\\\n\\mathbb{P}(\\lbrace 4\\rbrace)=\\mathbb{P}(\\lbrace 5 \\rbrace)=\\mathbb{P}(\\lbrace 6 \\rbrace) = \\frac{2}{9} \n\\end{eqnarray*}\n$$\n\nFrom our earlier work, we know the elements corresponding to the sum of seven\nare the following:\n\n$$\n\\lbrace (1,6),(2,5),(3,4),(4,3),(5,2),(6,1) \\rbrace\n$$\n\n Because we still have the independence assumption, all we need to\nchange is the probability computation of each of elements. For example, given\nthat the first die is the unfair one, we have\n\n$$\n\\mathbb{P}((1,6)) = \\mathbb{P}(1)\\mathbb{P}(6) = \\frac{1}{9} \\times \\frac{1}{6}\n$$\n\n and likewise for $(2,5)$ we have the following:\n\n$$\n\\mathbb{P}((2,5)) = \\mathbb{P}(2)\\mathbb{P}(5) = \\frac{1}{9} \\times \\frac{1}{6}\n$$\n\n and so forth. Summing all of these gives the following:\n\n$$\n\\mathbb{P}_X(7) = \\frac{1}{9} \\times \\frac{1}{6} \n +\\frac{1}{9} \\times \\frac{1}{6} \n +\\frac{1}{9} \\times \\frac{1}{6} \n +\\frac{2}{9} \\times \\frac{1}{6} \n +\\frac{2}{9} \\times \\frac{1}{6} \n +\\frac{2}{9} \\times \\frac{1}{6} = \\frac{1}{6}\n$$\n\n Let's try computing this using Pandas instead\nof Python dictionaries. First, we construct\na `DataFrame` object with an index of tuples\nconsisting of all pairs of possible dice outcomes.\n\n\n```python\nfrom pandas import DataFrame\nd=DataFrame(index=[(i,j) for i in range(1,7) for j in range(1,7)],\n columns=['sm','d1','d2','pd1','pd2','p'])\n```\n\n Now, we can populate the columns that we set up above\nwhere the outcome of the first die is the `d1` column and\nthe outcome of the second die is `d2`,\n\n\n```python\nd.d1=[i[0] for i in d.index]\nd.d2=[i[1] for i in d.index]\n```\n\n Next, we compute the sum of the dices in the `sm`\ncolumn,\n\n\n```python\nd.sm=map(sum,d.index)\n```\n\n With that established, the DataFrame now looks like\nthe following:\n\n\n```python\nd.head(5) # show first five lines\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
smd1d2pd1pd2p
(1, 1)211NaNNaNNaN
(1, 2)312NaNNaNNaN
(1, 3)413NaNNaNNaN
(1, 4)514NaNNaNNaN
(1, 5)615NaNNaNNaN
\n
\n\n\n\n Next, we fill out the probabilities for each face of the\nunfair die (`d1`) and the fair die (`d2`),\n\n\n```python\nd.loc[d.d1<=3,'pd1']=1/9.\nd.loc[d.d1 > 3,'pd1']=2/9.\nd.pd2=1/6.\nd.head(10)\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 \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
smd1d2pd1pd2p
(1, 1)2110.1111110.166667NaN
(1, 2)3120.1111110.166667NaN
(1, 3)4130.1111110.166667NaN
(1, 4)5140.1111110.166667NaN
(1, 5)6150.1111110.166667NaN
(1, 6)7160.1111110.166667NaN
(2, 1)3210.1111110.166667NaN
(2, 2)4220.1111110.166667NaN
(2, 3)5230.1111110.166667NaN
(2, 4)6240.1111110.166667NaN
\n
\n\n\n\n Finally, we can compute the joint probabilities\nfor the sum of the shown faces as the following:\n\n\n```python\nd.p = d.pd1 * d.pd2\nd.head(5)\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
smd1d2pd1pd2p
(1, 1)2110.1111110.1666670.0185185
(1, 2)3120.1111110.1666670.0185185
(1, 3)4130.1111110.1666670.0185185
(1, 4)5140.1111110.1666670.0185185
(1, 5)6150.1111110.1666670.0185185
\n
\n\n\n\n With all that established, we can compute the\ndensity of all the dice outcomes by using `groupby` as in the\nfollowing,\n\n\n```python\nd.groupby('sm')['p'].sum()\n```\n\n\n\n\n sm\n 2 0.018519\n 3 0.037037\n 4 0.055556\n 5 0.092593\n 6 0.129630\n 7 0.166667\n 8 0.148148\n 9 0.129630\n 10 0.111111\n 11 0.074074\n 12 0.037037\n Name: p, dtype: float64\n\n\n\n These examples have shown how the theory of probability\nbreaks down sets and measurements of those sets and how these can be\ncombined to develop the probability mass functions for new random\nvariables. \n\n## Continuous Random Variables\n\nThe same ideas work with continuous variables but managing the sets\nbecomes trickier because the real line, unlike discrete sets, has many\nlimiting properties already built into it that have to be handled\ncarefully. Nonetheless, let's start with an example that should\nillustrate the analogous ideas. Suppose a random variable $X$ is\nuniformly distributed on the unit interval. What is the probability\nthat the variable takes on values less than 1/2? \n\nIn order to build intuition onto the discrete case, let's go back to our\ndice-throwing experiment with the fair dice. The sum of the values of the dice\nis a measurable function,\n\n$$\nY \\colon \\lbrace 1,2,\\dots,6 \\rbrace^2 \\mapsto \\lbrace 2,3,\\ldots, 12 \\rbrace\n$$\n\n That is, $Y$ is a mapping of the cartesian product of sets to a\ndiscrete set of outcomes. In order to compute probabilities of the set of\noutcomes, we need to derive the probability measure for $Y$, $\\mathbb{P}_Y$,\nfrom the corresponding probability measures for each die. Our previous discussion\nwent through the mechanics of that. This means that\n\n$$\n\\mathbb{P}_Y \\colon \\lbrace 2,3,\\ldots,12 \\rbrace \\mapsto [0,1]\n$$\n\n Note there is a separation between the function definition and where the\ntarget items of the function are measured in probability. More bluntly,\n\n$$\nY \\colon A \\mapsto B\n$$\n\n with,\n\n$$\n\\mathbb{P}_Y \\colon B \\mapsto [0,1]\n$$\n\n Thus, to compute $\\mathbb{P}_Y$, which is derived \nfrom other random variables, we have to express the equivalence classes\nin $B$ in terms of their progenitor $A$ sets. \n\nThe situation for continuous variables follows the same pattern, but\nwith many more deep technicalities that we are going to skip. For the continuous\ncase, the random variable is now,\n\n$$\nX \\colon \\mathbb{R} \\mapsto \\mathbb{R}\n$$\n\n with corresponding probability measure,\n\n$$\n\\mathbb{P}_X \\colon \\mathbb{R} \\mapsto [0,1]\n$$\n\n But where are the corresponding sets here? Technically, these are the\n*Borel* sets, but we can just think of them as intervals. Returning to our\nquestion, what is the probability that a uniformly distributed random variable\non the unit interval takes values less than $1/2$? Rephrasing this question\naccording to the framework, we have the following:\n\n$$\nX \\colon [0,1] \\mapsto [0,1]\n$$\n\n with corresponding,\n\n$$\n\\mathbb{P}_X \\colon [0,1] \\mapsto [0,1]\n$$\n\n To answer the question, by the definition of the uniform random\nvariable on the unit interval, we compute the following integral,\n\n$$\n\\mathbb{P}_X([0,1/2]) = \\mathbb{P}_X(0 < X < 1/2) = \\int_0^{1/2} dx = 1/2\n$$\n\n where the above integral's $dx$ sweeps through intervals of the\n$B$-type. The measure of any $dx$ interval (i.e., $A$-type set) is equal to\n$dx$, by definition of the uniform random variable. To get all the moving parts\ninto one notationally rich integral, we can also write this as,\n\n$$\n\\mathbb{P}_X(0 < X < 1/2) = \\int_0^{ 1/2 } d\\mathbb{P}_X(dx) = 1/2\n$$\n\nNow, let's consider a slightly more complicated and interesting example. As\nbefore, suppose we have a uniform random variable, $X$ and let us introduce\nanother random variable defined,\n\n$$\nY = 2 X\n$$\n\n Now, what is the probability that $0 < Y < \\frac{1}{2}$? \nTo express this in our framework, we write,\n\n$$\nY \\colon [0,1] \\mapsto [0,2]\n$$\n\n with corresponding,\n\n$$\n\\mathbb{P}_Y \\colon [0,2] \\mapsto [0,1]\n$$\n\n To answer the question, we need to measure the set $[0,1/2]$, with\nthe probability measure for $Y$, $\\mathbb{P}_Y([0,1/2])$. How can we do this?\nBecause $Y$ is derived from the $X$ random variable, as with the fair-dice\nthrowing experiment, we have to create a set of equivalences in the target\nspace (i.e., $B$-type sets) that reflect back on the input space (i.e.,\n$A$-type sets). That is, what is the interval $[0,1/2]$ equivalent to in terms\nof the $X$ random variable? Because, functionally, $Y=2 X$, then the $B$-type\ninterval $[0,1/2]$ corresponds to the $A$-type interval $[0,1/4]$. From the\nprobability measure of $X$, we compute this with the integral,\n\n$$\n\\mathbb{P}_Y([0,1/2]) =\\mathbb{P}_X([0,1/4])= \\int_0^{1/4} dx = 1/4\n$$\n\nNow, let's up the ante and consider the following random variable,\n\n$$\nY = X^2\n$$\n\n where now $X$ is still uniformly distributed, but now over the\ninterval $[-1/2,1/2]$. We can express this in our framework as,\n\n$$\nY \\colon [-1/2,1/2] \\mapsto [0,1/4]\n$$\n\n with corresponding,\n\n$$\n\\mathbb{P}_Y \\colon [0,1/4] \\mapsto [0,1]\n$$\n\n What is the $\\mathbb{P}_Y(Y < 1/8)$? In other words, what is the\nmeasure of the set $B_Y= [0,1/8]$? As before, because $X$ is derived from our\nuniformly distributed random variable, we have to reflect the $B_Y$ set onto\nsets of the $A$-type. The thing to recognize is that because $X^2$\nis symmetric about zero, all $B_Y$ sets reflect back into two sets.\nThis means that for any set $B_Y$, we have the correspondence $B_Y = A_X^+ \\cup\nA_X^{-}$. So, we have,\n\n$$\nB_Y=\\Big\\lbrace 00$. In this case, $Y>X$ because $Z$ cannot be positive\notherwise. For the density function, we are interested in the set \n$\\lbrace 0 < Z < z \\rbrace $. We want to compute\n\n$$\n\\mathbb{P}(Z X$. For $Z < z $,\nwe have $Y > X(1/z+1)$. Putting this together gives\n\n$$\nA_1 = \\lbrace \\max (X,X(1/z+1)) < Y < 1 \\rbrace\n$$\n\n Integrating this over $Y$ as follows,\n\n$$\n\\int_0^1\\lbrace\\max(X,X(1/z+1)) \\frac{X}{1-X}\n$$\n\n and integrating this one more time over $X$ gives\n\n$$\n\\int_0^{\\frac{z}{1+z}} \\frac{-X+z-Xz}{z} dX = \\frac{z}{2(z+1)} \\mbox{ where } z > 0\n$$\n\n Note that this is the computation for the *probability*\nitself, not the probability density function. To get that, all we have\nto do is differentiate the last expression to obtain\n\n$$\nf_Z(z) = \\frac{1}{(z+1)^2} \\mbox{ where } z > 0\n$$\n\n Now we need to compute this density using the same process\nfor when $z < -1$. We want the interval $ Z < z $ for when $z < -1$.\nFor a fixed $z$, this is equivalent to $ X(1+1/z) < Y$. Because $z$\nis negative, this also means that $Y < X$. Under these terms, we\nhave the following integral,\n\n$$\n\\int_0^1 \\lbrace X(1/z+1) 0 \\\\\\\n \\frac{1}{2 z^2} & \\mbox{if } z < -1 \\\\\\\n 0 & \\mbox{otherwise }\n\\end{cases}\n$$\n\n We will leave it as an exercise to show that this\nintegrates out to one.\n\n## Independent Random Variables\n\nIndependence is a standard assumption. Mathematically, the\nnecessary and sufficient condition for independence between two\nrandom variables $X$ and $Y$ is the following:\n\n$$\n\\mathbb{P}(X,Y) = \\mathbb{P}(X)\\mathbb{P}(Y)\n$$\n\n Two random variables $X$ and $Y$ \nare *uncorrelated* if,\n\n$$\n\\mathbb{E}(X-\\overline{X})\\mathbb{E}(Y-\\overline{Y})=0\n$$\n\n where $\\overline{X}=\\mathbb{E}(X)$ Note that uncorrelated random\nvariables are sometimes called *orthogonal* random variables. Uncorrelatedness\nis a weaker property than independence, however. For example, consider the\ndiscrete random variables $X$ and $Y$ uniformly distributed over the set\n$\\lbrace 1,2,3 \\rbrace$ where\n\n$$\nX = \n\\begin{cases} \n1 & \\mbox{if } \\omega =1 \\\\\\\n0 & \\mbox{if } \\omega =2 \\\\\\\n-1 & \\mbox{if } \\omega =3\n\\end{cases}\n$$\n\n and also,\n\n$$\nY = \n\\begin{cases} \n0 & \\mbox{if } \\omega =1 \\\\\\\n1 & \\mbox{if } \\omega =2 \\\\\\\n0 & \\mbox{if } \\omega =3\n\\end{cases}\n$$\n\n Thus, $\\mathbb{E}(X)=0$ and $\\mathbb{E}(X Y)=0$, so\n$X$ and $Y$ are uncorrelated. However, we have\n\n$$\n\\mathbb{P}(X=1,Y=1)=0\\neq \\mathbb{P}(X=1)\\mathbb{P}(Y=1)=\\frac{1}{9}\n$$\n\n So, these two random variables are *not* independent.\nThus, uncorrelatedness does not imply independence, generally, but\nthere is the important case of Gaussian random variables for which\nit does. To see this, consider the probability density function\nfor two zero-mean, unit-variance Gaussian random variables $X$ and\n$Y$,\n\n$$\nf_{X,Y}(x,y) = \\frac{e^{\\frac{x^2-2 \\rho x\n y+y^2}{2 \\left(\\rho^2-1\\right)}}}{2 \\pi \n \\sqrt{1-\\rho^2}}\n$$\n\n where $\\rho:=\\mathbb{E}(X Y)$ is the correlation coefficient. In\nthe uncorrelated case where $\\rho=0$, the probability density function factors\ninto the following,\n\n$$\nf_{X,Y}(x,y)=\\frac{e^{-\\frac{1}{2}\\left(x^2+y^2\\right)}}{2\\pi}=\\frac{e^{-\\frac{x^2}{2}}}{\\sqrt{2\\pi}}\\frac{e^{-\\frac{y^2}{2}}}{\\sqrt{2\\pi}} =f_X(x)f_Y(y)\n$$\n\n which means that $X$ and $Y$ are independent.\n\nIndependence and conditional independence are closely related, as in the following:\n\n$$\n\\mathbb{P}(X,Y\\vert Z) =\\mathbb{P}(X\\vert Z) \\mathbb{P}(Y\\vert Z)\n$$\n\n which says that $X$ and $Y$ and independent conditioned\non $Z$. Conditioning independent random variables can break\ntheir independence. For example, consider two independent\nBernoulli-distributed random variables, $X_1, X_2\\in\\lbrace 0,1\n\\rbrace$. We define $Z=X_1+X_2$. Note that $Z\\in \\lbrace\n0,1,2 \\rbrace$. In the case where $Z=1$, we have,\n\n$$\n\\mathbb{P}(X_1\\vert Z=1) >0\n$$\n\n$$\n\\\n\\mathbb{P}(X_2\\vert Z=1) >0\n$$\n\n Even though $X_1,X_2$ are independent,\nafter conditioning on $Z$, we have the following,\n\n$$\n\\mathbb{P}(X_1=1,X_2=1\\vert Z=1)=0\\neq \\mathbb{P}(X_1=1\\vert Z=1)\\mathbb{P}(X_2=1\\vert Z=1)\n$$\n\n Thus, conditioning on $Z$ breaks the independence of\n$X_1,X_2$. This also works in the opposite direction ---\nconditioning can make dependent random variables independent.\nDefine $Z_n=\\sum_i^n X_i$ with $X_i$ independent, integer-valued\nrandom variables. The $Z_n$ variables are \ndependent because they stack the same telescoping set of\n$X_i$ variables. Consider the following,\n\n\n
\n\n$$\n\\begin{equation}\n\\mathbb{P}(Z_1=i,Z_3=j\\vert Z_2=k) = \\frac{\\mathbb{P}(Z_1=i,Z_2=k,Z_3=j)}{\\mathbb{P}(Z_2 =k)}\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\\n=\\frac{\\mathbb{P}(X_1 =i)\\mathbb{P}(X_2 =k-i)\\mathbb{P}(X_3 =j-k) }{\\mathbb{P}(Z_2 =k)}\n\\end{equation} \n\\label{eq:condIndep} \\tag{2}\n$$\n\n where the factorization comes from the independence of\nthe $X_i$ variables. Using the definition of conditional\nprobability,\n\n$$\n\\mathbb{P}(Z_1=i\\vert Z_2)=\\frac{\\mathbb{P}(Z_1=i,Z_2=k)}{\\mathbb{P}(Z_2=k)}\n$$\n\n We can continue to expand Equation ref{eq:condIndep},\n\n$$\n\\mathbb{P}(Z_1=i,Z_3=j\\vert Z_2=k) =\\mathbb{P}(Z_1 =i\\vert Z_2) \\frac{\\mathbb{P}( X_3 =j-k)\\mathbb{P}( Z_2 =k)}{\\mathbb{P}( Z_2 =k)}\n$$\n\n$$\n\\\n =\\mathbb{P}(Z_1 =i\\vert Z_2)\\mathbb{P}(Z_3 =j\\vert Z_2)\n$$\n\n where $\\mathbb{P}(X_3=j-k)\\mathbb{P}(Z_2=k)=\n\\mathbb{P}(Z_3=j,Z_2)$. Thus, we see that dependence between\nrandom variables can be broken by conditioning to create\nconditionally independent random variables. As we have just\nwitnessed, understanding how conditioning influences independence\nis important and is the main topic of\nstudy in Probabilistic Graphical Models, a field\nwith many algorithms and concepts to extract these\nnotions of conditional independence from graph-based\nrepresentations of random variables.\n\n\n## Classic Broken Rod Example\n\nLet's do one last example to exercise fluency in our methods by\nconsidering the following classic problem: given a rod of unit-length,\nbroken independently and randomly at two places, what is the\nprobability that you can assemble the three remaining pieces into a\ntriangle? The first task is to find a representation of a triangle as\nan easy-to-apply constraint. What we want is something like the\nfollowing:\n\n$$\n\\mathbb{P}(\\mbox{ triangle exists }) = \\int_0^1 \\int_0^1 \\lbrace \\mbox{ triangle exists } \\rbrace dX dY\n$$\n\n where $X$ and $Y$ are independent and uniformly distributed\nin the unit-interval. Heron's formula for the area of the triangle,\n\n$$\n\\mbox{ area } = \\sqrt{(s-a)(s-b)(s-c)s}\n$$\n\n where $s = (a+b+c)/2$ is what we need. The idea is that this\nyields a valid area only when each of the terms under the square root is\ngreater than or equal to zero. Thus, suppose that we have\n\n$$\n\\begin{eqnarray*}\na & = & X \\\\\\\nb & = & Y-X \\\\\\\nc & = & 1-Y \n\\end{eqnarray*}\n$$\n\n assuming that $Y>X$. Thus, the criterion for a valid triangle boils down\nto\n\n$$\n\\lbrace (s > a) \\wedge (s > b) \\wedge (s > c) \\wedge (XX$. By symmetry, we get the same result for $X>Y$. Thus, the\nfinal result is the following:\n\n$$\n\\mathbb{P}(\\mbox{ triangle exists }) = \\frac{1}{8}+\\frac{1}{8} = \\frac{1}{4}\n$$\n\nWe can quickly check using this result using Python for the case $Y>X$ using\nthe following code:\n\n\n```python\n>>> import numpy as np\n>>> x,y = np.random.rand(2,1000) # uniform rv\n>>> a,b,c = x,(y-x),1-y # 3 sides\n>>> s = (a+b+c)/2\n>>> np.mean((s>a) & (s>b) & (s>c) & (y>x)) # approx 1/8=0.125\n```\n\n\n\n\n 0.13700000000000001\n\n\n\n**Programming Tip.**\n\nThe chained logical `&` symbols above tell Numpy that the logical operation\nshould be considered element-wise.\n", "meta": {"hexsha": "d6db31ff12126224d149c346b95dd70595705237", "size": 177773, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/probability/notebooks/intro.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/intro.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/intro.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": 78.9050155348, "max_line_length": 114721, "alphanum_fraction": 0.7991033509, "converted": true, "num_tokens": 11995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.25982563796098374, "lm_q1q2_score": 0.07985949611141357}} {"text": "```python\n!conda info\n```\n\n Current conda install:\n \n platform : win-64\n conda version : 4.3.22\n conda is private : False\n conda-env version : 4.3.22\n conda-build version : not installed\n python version : 3.6.1.final.0\n requests version : 2.14.2\n root environment : C:\\Users\\USER\\Anaconda3 (writable)\n default environment : C:\\Users\\USER\\Anaconda3\n envs directories : C:\\Users\\USER\\Anaconda3\\envs\n C:\\Users\\USER\\AppData\\Local\\conda\\conda\\envs\n C:\\Users\\USER\\.conda\\envs\n package cache : C:\\Users\\USER\\Anaconda3\\pkgs\n C:\\Users\\USER\\AppData\\Local\\conda\\conda\\pkgs\n channel URLs : https://repo.continuum.io/pkgs/free/win-64\n https://repo.continuum.io/pkgs/free/noarch\n https://repo.continuum.io/pkgs/r/win-64\n https://repo.continuum.io/pkgs/r/noarch\n https://repo.continuum.io/pkgs/pro/win-64\n https://repo.continuum.io/pkgs/pro/noarch\n https://repo.continuum.io/pkgs/msys2/win-64\n https://repo.continuum.io/pkgs/msys2/noarch\n config file : C:\\Users\\USER\\.condarc\n netrc file : None\n offline mode : False\n user-agent : conda/4.3.22 requests/2.14.2 CPython/3.6.1 Windows/10 Windows/10.0.14393 \n administrator : False\n\n\n# Variables\n\n\n```python\nx = 2\ny = '3'\nprint(x+int(y))\n\nz = [1, 2, 3] #List\nw = (2, 3, 4) #Tuple\n\nimport numpy as np\nq = np.array([1, 2, 3]) #numpy.ndarray\ntype(q)\n```\n\n 5\n\n\n\n\n\n numpy.ndarray\n\n\n\n# Console input and output\n\n\n```python\nMyName = input('My name is: ')\nprint('Hello, '+MyName)\n```\n\n My name is: david\n Hello, david\n\n\n# File input and output\n\n\n```python\nfid = open('msg.txt','w')\nfid.write('demo of writing.\\n')\nfid.write('Second line')\nfid.close()\n\nfid = open('msg.txt','r')\nmsg = fid.readline()\nprint(msg)\nmsg = fid.readline()\nprint(msg)\n\nfid.close()\n```\n\n demo of writing.\n \n Second line\n\n\n\n```python\nfid = open('msg.txt','r')\nmsg = fid.readlines()\nprint(msg)\n```\n\n ['demo of writing.\\n', 'Second line']\n\n\n\n```python\nfid = open('msg.txt','r')\nmsg = fid.read()\nprint(msg)\n```\n\n demo of writing.\n Second line\n\n\n\n```python\nimport numpy as np\nx = np.linspace(0, 2*np.pi,4)\ny = np.cos(x)\n\n#Stack arrays in sequence vertically (row wise).\ndata = np.vstack((x,y)) #上下對隊齊好\ndataT = data.T #Transpose\n\nnp.savetxt('data.txt', data, delimiter=',')\nz = np.loadtxt('data.txt', delimiter=',')\n\nprint(x)\nprint(y)\nprint(data)\nprint(dataT)\nprint(z)\n```\n\n [ 0. 2.0943951 4.1887902 6.28318531]\n [ 1. -0.5 -0.5 1. ]\n [[ 0. 2.0943951 4.1887902 6.28318531]\n [ 1. -0.5 -0.5 1. ]]\n [[ 0. 1. ]\n [ 2.0943951 -0.5 ]\n [ 4.1887902 -0.5 ]\n [ 6.28318531 1. ]]\n [[ 0. 2.0943951 4.1887902 6.28318531]\n [ 1. -0.5 -0.5 1. ]]\n\n\n\n```python\nimport numpy as np\nx = np.linspace(0, 2*np.pi,20)\ny = np.cos(x)\nz = np.sin(x)\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\n#使用 help(plt.plot) 可以看到所有畫圖玩法\nplt.plot(x,y,'b')\nplt.plot(x,y,'go', label = 'cos(x)')\nplt.plot(x,z,'r')\nplt.plot(x,z,'go', label = 'sin(x)')\nplt.legend(loc='best') # 放到最好的位置\nplt.xlim([0, 2*np.pi])\n```\n\n\n```python\nimport numpy as np\nx = np.linspace(0, 2*np.pi,20)\ny = np.cos(x)\nz = np.sin(x)\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\n#使用 help(plt.plot) 可以看到所有畫圖玩法\nplt.subplot(2,1,1) #分成兩張圖 形式是(row, column, order)\nplt.plot(x,y,'b')\nplt.plot(x,y,'go', label = 'cos(x)')\nplt.legend(loc='best') #放到最好的位置\n\nplt.subplot(2,1,2) #分成兩張圖\nplt.plot(x,z,'r')\nplt.plot(x,z,'go', label = 'sin(x)')\nplt.legend(loc='best') #放到最好的位置\n\nplt.xlim([0, 2*np.pi])\n```\n\n# Functions, Conditions, Loop\n\n\n```python\nimport numpy as np\n\ndef f(x):\n return x**2\n\nx = np.linspace(0,5,10)\ny = f(x)\n\nprint(y)\n```\n\n [ 0. 0.30864198 1.2345679 2.77777778 4.9382716\n 7.71604938 11.11111111 15.12345679 19.75308642 25. ]\n\n\n\n```python\nimport numpy as np\n\ndef f(x): #這是個奇怪的練習用函數\n res = x\n if res < 3:\n res = np.nan #<3就傳 Not a Number \n elif res < 15:\n res = x**3\n else:\n res = x**4\n return res\n\nx = np.linspace(0,10,20)\ny = np.empty_like(x) \n#Return a new array with the same shape and type as a given array.\n#傳一個跟x一樣的array回來\n\ni = 0\nfor xi in x:\n y[i] = f(xi)\n i = i + 1\nprint(y)\n \n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.plot(x,y,'bp')\nplt.xlim([0,11])\n```\n\n# Matrices, linear equations\n\n\n```python\nA = np.array([[1,2],[3,2]])\nB = np.array([1,0])\n\n# x = A^-1 * b\nsol1 = np.dot(np.linalg.inv(A),B)\nprint(sol1)\nsol2 = np.linalg.solve(A,B)\nprint(sol2)\n\n\nimport sympy as sym\nsym.init_printing() \n#This will automatically enable the best printer available in your environment.\n\nx,y = sym.symbols('x y')\nz = sym.linsolve([3*x+2*y-1,x+2*y],(x,y))\nz\n#sym.pprint(z) The ASCII pretty printer\n```\n\n# Non-linear equation\n\n\n```python\nfrom scipy.optimize import fsolve\n\ndef f(z): #用z參數來表示x和y,做函數運算 \n x = z[0]\n y = z[1]\n return [x+2*y, x**2+y**2-1]\n\nz0 = [0,1]\nz = fsolve(f,z0)\nprint(z)\nprint(f(z))\n```\n\n [-0.89442719 0.4472136 ]\n [0.0, -1.1102230246251565e-16]\n\n\n# Integration\n\n\n```python\nfrom scipy.integrate import quad\n\ndef f(x):\n return x**2\n\nquad(f,0,2) #計算積分值\n\nimport sympy as sym\nsym.init_printing()\nx = sym.Symbol('x')\nf = sym.integrate(x**2,x)\nf.subs(x,2) #將值帶入函數中\nf\n```\n\n# Derivative\n\n\n```python\nfrom scipy.misc import derivative\n\ndef f(x):\n return x**2\n\nprint(derivative(f,2,dx=0.01)) #dx表示精確程度\n\nimport sympy as sym\nsym.init_printing()\nx = sym.Symbol('x')\nf = sym.diff(x**3,x)\nf.subs(x,2) #將值帶入函數中,得解\nf\n```\n\n# Interpolation\n\n\n```python\nfrom scipy.interpolate import interp1d #中間的字是1不是L喔!!!\n\nx = np.arange(0,6,1)\ny = np.array([0.2,0.3,0.5,1.0,0.9,1.1])\n\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.plot(x,y,'bo')\n\nxp = np.linspace(0,5,100) #為了顯示差別把點增加\n\ny1 = interp1d(x,y,kind='linear') #一階\nplt.plot(xp,y1(xp),'r-')\n\ny2 = interp1d(x,y,kind='quadratic') #二階\nplt.plot(xp,y2(xp),'k--')\n\ny3 = interp1d(x,y,kind='cubic') #三階\nplt.plot(xp,y3(xp),'g--')\n\n```\n\n# Linear regression\n\n\n```python\nimport numpy as np\nx = np.array([0,1,2,3,4,5])\ny = np.array([0.1,0.2,0.3,0.5,0.8,2.0 ])\n\n#多項式逼近法,選擇階層\np1 = np.polyfit(x,y,1)\nprint(p1)\np2 = np.polyfit(x,y,2)\nprint(p2)\np3 = np.polyfit(x,y,3)\nprint(p3)\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.plot(x,y,'ro')\n\n# np.polyval表示多項式的值,把係數p_帶入多項式x求出來的值\nxp = np.linspace(0,5,100)\nplt.plot(xp, np.polyval(p1,xp), 'b-', label='linear') #這個字是polyvaL喔!!\nplt.plot(xp, np.polyval(p2,xp), 'g--', label='quadratic')\nplt.plot(xp, np.polyval(p3,xp), 'k:', label='cubic')\nplt.legend(loc='best')\n```\n\n# Nonlinear regression\n\n\n```python\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\nx = np.array([0,1,2,3,4,5])\ny = np.array([0.1,0.2,0.3,0.5,0.8,2.0 ])\n\n#多項式逼近法,選擇階層\np1 = np.polyfit(x,y,1)\nprint(p1)\np2 = np.polyfit(x,y,2)\nprint(p2)\np3 = np.polyfit(x,y,3)\nprint(p3)\n\n#使用指數對數\ndef f(x,a):\n return 0.1 * np.exp(a*x)\na = curve_fit(f,x,y)[0] #非線性回歸,Use non-linear least squares to fit a function,取第0項\nprint('a='+str(a))\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.plot(x,y,'ro')\n\n# np.polyval表示多項式的值,把係數p_帶入多項式x求出來的值\nxp = np.linspace(0,5,100)\nplt.plot(xp, np.polyval(p1,xp), 'b-', label='linear') #這個字是polyvaL喔!!\nplt.plot(xp, np.polyval(p2,xp), 'g--', label='quadratic')\nplt.plot(xp, np.polyval(p3,xp), 'k:', label='cubic')\nplt.plot(xp, f(xp,a), 'c', label='nonlinear')\nplt.legend(loc='best')\n```\n\n# Differential equation\n\n\n```python\nfrom scipy.integrate import odeint\n\ndef dydt(y,t,a):\n return -a * y\n\na = 0.5\nt = np.linspace(0,20)\ny0 = 5.0\ny = odeint(dydt,y0,t,args=(a,))\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.plot(t,y)\nplt.xlabel('time')\nplt.ylabel('y')\n```\n\n# Nonlinear optimization\n\n\n```python\n#概念:要有Objective、Constraint,然後初始猜想值\nimport numpy as np\nfrom scipy.optimize import minimize\n```\n\n\n```python\ndef objective(x): #此函數求最小值\n x1 = x[0]\n x2 = x[1]\n x3 = x[2]\n x4 = x[3]\n return x1*x4*(x1+x2+x3)+x3\n\n#用減法做比較\ndef constraint1(x):\n return x[0]*x[1]*x[2]*x[3] - 25.0\n\n#用減法做比較\ndef constraint2(x):\n sum_sq = 40.0\n for i in range(0,4):\n sum_sq = sum_sq - x[i]**2\n return sum_sq \n\n#初始猜想值\nx0 = [1,5,5,1]\nprint(objective(x0))\n\n#設定值域\nb = (1.0,5.0) #x的值域\nbnds = (b,b,b,b) #四個值域都一樣b\ncon1 = {'type':'ineq','fun': constraint1} #第一個是不等式\ncon2 = {'type':'eq','fun': constraint2} #第二個需要等式\ncons = [con1,con2] #cons合成一個list\n\nsol = minimize(objective,x0,method='SLSQP',\\\n bounds = bnds, constraints = cons)\n\n```\n\n 16\n\n\n\n```python\nprint(sol)\n```\n\n fun: 17.01401724563517\n jac: array([ 14.57227015, 1.37940764, 2.37940764, 9.56415057])\n message: 'Optimization terminated successfully.'\n nfev: 30\n nit: 5\n njev: 5\n status: 0\n success: True\n x: array([ 1. , 4.7429961 , 3.82115462, 1.37940765])\n\n\n\n```python\nprint(sol.fun)\n```\n\n 17.01401724563517\n\n\n\n```python\nprint(sol.x)\n```\n\n [ 1. 4.7429961 3.82115462 1.37940765]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d0691887d6ea707991b21d03335f2630e3df38d5", "size": 151748, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Numeric and scientific python.ipynb", "max_stars_repo_name": "Pytoddler/Data-analysis-and-visualization", "max_stars_repo_head_hexsha": "833b1ae7ae36ee8168f655a1497f081438f9e0aa", "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": "Numeric and scientific python.ipynb", "max_issues_repo_name": "Pytoddler/Data-analysis-and-visualization", "max_issues_repo_head_hexsha": "833b1ae7ae36ee8168f655a1497f081438f9e0aa", "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": "Numeric and scientific python.ipynb", "max_forks_repo_name": "Pytoddler/Data-analysis-and-visualization", "max_forks_repo_head_hexsha": "833b1ae7ae36ee8168f655a1497f081438f9e0aa", "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": 141.6881419234, "max_line_length": 25980, "alphanum_fraction": 0.877533806, "converted": true, "num_tokens": 3596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.1871326821624266, "lm_q1q2_score": 0.07977870580511387}} {"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", "meta": {"hexsha": "e58782627658a6c88787671cc3af3035e1e90122", "size": 24420, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Metody Numeryczne 2020/2. Reprezentacja liczb/Reprezentacja liczb.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 2020/2. Reprezentacja liczb/Reprezentacja liczb.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 2020/2. Reprezentacja liczb/Reprezentacja liczb.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.6169354839, "max_line_length": 142, "alphanum_fraction": 0.4635544636, "converted": true, "num_tokens": 5505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386100696924885, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.07972518596104865}} {"text": "##### Copyright 2018 The TensorFlow Probability Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\"); { display-mode: \"form\" }\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# Fitting Generalized Linear Mixed-effects Models Using Variational Inference\n\n\n \n \n \n \n
\n View on TensorFlow.org\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\n## Abstract\n\n\nIn this colab we demonstrate how to fit a Generalized Linear Mixed-effects Model using Variational Inference and TensorFlow.\n\n\n## Model Family\n\n[Generalized linear mixed-effect models](https://en.wikipedia.org/wiki/Generalized_linear_mixed_model) (GLMM) are similar to [generalized linear models](https://en.wikipedia.org/wiki/Generalized_linear_model) (GLM) except that they incorporate a sample specific noise into the predicted linear response. This is useful in part because it allows rarely seen features to share information with more commonly seen features.\n\n\nAs a generative process, a Generalized Linear Mixed-effects Model (GLMM) is characterized by:\n\n$$\n\\begin{align}\n\\text{for } & r = 1\\ldots R: \\hspace{2.45cm}\\text{# for each random-effect group}\\\\\n &\\begin{aligned}\n \\text{for } &c = 1\\ldots |C_r|: \\hspace{1.3cm}\\text{# for each category (\"level\") of group $r$}\\\\\n &\\begin{aligned}\n \\beta_{rc}\n &\\sim \\text{MultivariateNormal}(\\text{loc}=0_{D_r}, \\text{scale}=\\Sigma_r^{1/2})\n \\end{aligned}\n\\end{aligned}\\\\\\\\\n\\text{for } & i = 1 \\ldots N: \\hspace{2.45cm}\\text{# for each sample}\\\\\n&\\begin{aligned}\n &\\eta_i = \\underbrace{\\vphantom{\\sum_{r=1}^R}x_i^\\top\\omega}_\\text{fixed-effects} + \\underbrace{\\sum_{r=1}^R z_{r,i}^\\top \\beta_{r,C_r(i) }}_\\text{random-effects} \\\\\n &Y_i|x_i,\\omega,\\{z_{r,i} , \\beta_r\\}_{r=1}^R \\sim \\text{Distribution}(\\text{mean}= g^{-1}(\\eta_i))\n\\end{aligned}\n\\end{align}\n$$\n\n\n\nwhere:\n\n$$\n\\begin{align}\nR &= \\text{number of random-effect groups}\\\\\n|C_r| &= \\text{number of categories for group $r$}\\\\\nN &= \\text{number of training samples}\\\\\nx_i,\\omega &\\in \\mathbb{R}^{D_0}\\\\\nD_0 &= \\text{number of fixed-effects}\\\\\nC_r(i) &= \\text{category (under group $r$) of the $i$th sample}\\\\\nz_{r,i} &\\in \\mathbb{R}^{D_r}\\\\\nD_r &= \\text{number of random-effects associated with group $r$}\\\\\n\\Sigma_{r} &\\in \\{S\\in\\mathbb{R}^{D_r \\times D_r} : S \\succ 0 \\}\\\\\n\\eta_i\\mapsto g^{-1}(\\eta_i) &= \\mu_i, \\text{inverse link function}\\\\\n\\text{Distribution} &=\\text{some distribution parameterizable solely by its mean}\n\\end{align}\n$$\n\n\nIn words, this says that every category of each group is associated with an iid MVN, $\\beta_{rc}$. Although the $\\beta_{rc}$ draws are always independent, they are only indentically distributed for a group $r$; notice there is exactly one $\\Sigma_r$ for each $r\\in\\{1,\\ldots,R\\}$.\n\nWhen affinely combined with a sample's group's features ($z_{r,i}$), the result is sample-specific noise on the $i$-th predicted linear response (which is otherwise $x_i^\\top\\omega$).\n\nWhen we estimate $\\{\\Sigma_r:r\\in\\{1,\\ldots,R\\}\\}$ we're essentially estimating the amount of noise a random-effect group carries which would otherwise drown out the signal present in $x_i^\\top\\omega$.\n\nThere are a variety of options for the $\\text{Distribution}$ and [inverse link function](https://en.wikipedia.org/wiki/Generalized_linear_model#Link_function), $g^{-1}$. Common choices are:\n- $Y_i\\sim\\text{Normal}(\\text{mean}=\\eta_i, \\text{scale}=\\sigma)$,\n- $Y_i\\sim\\text{Binomial}(\\text{mean}=n_i \\cdot \\text{sigmoid}(\\eta_i), \\text{total_count}=n_i)$, and, \n- $Y_i\\sim\\text{Poisson}(\\text{mean}=\\exp(\\eta_i))$.\n\nFor more possibilities, see the [`tfp.glm`](https://github.com/tensorflow/probability/tree/master/tensorflow_probability/python/glm) module.\n\n## Variational Inference\n\nUnfortunately, finding the maximum likelihood estimates of the parameters $\\beta,\\{\\Sigma_r\\}_r^R$ entails a non-analytical integral. To circumvent this problem, we instead find the parameters which minimize an upper bound. Writing $\\phi(x)=\\exp(-x^2/2)/\\sqrt{2\\pi}$ we find:\n\n$\\begin{align}\n-\\log \\overbrace{p(\\{y\\}_i^N|\\{x_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R)}^{\\text{evidence}}\n& = -\\log \\int_{\\mathbb{R}^{\\sum_r |C_r|D_r}} \\overbrace{\\left(\\prod_i^N p(y_i | \\eta_i(u)) \\right)}^{\\text{likelihood}} \\overbrace{\\left(\\prod_r^R |\\Sigma_r^{-1/2}| \\prod_c^{|C_r|} \\phi(\\Sigma_r^{-1/2} u_{rc}) \\right)}^{\\text{prior}} \\, du\\\\\n& = -\\log \\int_{\\mathbb{R}^{\\sum_r |C_r|D_r}} \\frac{\n q_\\lambda(u|\\{x_i,y_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R)\n }{\n q_\\lambda(u|\\{x_i,y_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R)} \\left( \\prod_i^N p(y_i | \\eta_i(u)) \\right) \\left(\\prod_r^R |\\Sigma_r^{-1/2}| \\prod_c^{|C_r|} \\phi(\\Sigma_r^{-1/2} u_{rc}) \\right) \\, du\\\\\n& \\le \\text{E}_{q_\\lambda(U|\\{x_i,y_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R)} \\left[ -\\log\n\\frac{\n \\left( \\prod_i^N p(y_i | \\eta_i(U)) \\right) \\left(\\prod_r^R |\\Sigma_r^{-1/2}| \\prod_c^{|C_r|} \\phi(\\Sigma_r^{-1/2} U_{rc}) \\right)\n }{\n q_\\lambda(U|\\{x_i,y_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R)\n } \\right]\\\\\n&= \\text{KL}\\left[q_\\lambda(U|\\{x_i,y_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R) \\Bigg| \\left( \\prod_i^N p(y_i | \\eta_i(U)) \\right) \\left(\\prod_r^R |\\Sigma_r^{-1/2}| \\prod_c^{|C_r|} \\phi(\\Sigma_r^{-1/2} U_{rc}) \\right) \\right]\n\\end{align}$\n\nThe inequality follows from [Jensen's Inequality](https://en.wikipedia.org/wiki/Jensen%27s_inequality).\n\nSo, instead of solving:\n\n$$\\begin{align}\n\\{\\beta^*, \\{\\Sigma_r^*\\}_r^R\\} = \\operatorname{\\arg\\min}_{\\beta,\\{\\Sigma_r\\}_r^R} \\left\\{\n -\\log p(\\{y\\}_i^N|\\{x_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R)\n\\right\\}\n\\end{align}$$\n\nwe solve:\n\n$$\\begin{align}\n\\{\\lambda^*, \\beta^*, \\{\\Sigma_r^*\\}_r^R\\} = \\operatorname{\\arg\\min}_{\\lambda,\\beta,\\{\\Sigma_r\\}_r^R} \\left\\{\n\\text{KL}\\left[q_\\lambda(U|\\{x_i,y_i,z_i\\}_i^N,\\beta,\\{\\Sigma_r\\}_r^R) \\Bigg| \\left( \\prod_i^N p(y_i | \\eta_i(U)) \\right) \\left(\\prod_r^R |\\Sigma_r^{-1/2}| \\prod_c^{|C_r|} \\phi(\\Sigma_r^{-1/2} U_{rc}) \\right) \\right]\n\\right\\}\n\\end{align}$$\n\n## Toy Problem\n\n[Gelman et al.'s (2007) \"radon dataset\"](http://www.stat.columbia.edu/~gelman/arm/) is a dataset sometimes used to demonstrate approaches for regression. (E.g., this closely related [PyMC3 blog post](http://twiecki.github.io/blog/2014/03/17/bayesian-glms-3/).) The radon dataset contains indoor measurements of Radon taken throughout the United States. [Radon](https://en.wikipedia.org/wiki/Radon) is naturally ocurring radioactive gas which is [toxic](http://www.radon.com/radon_facts/) in high concentrations.\n\nFor our demonstration, let's suppose we're interested in validating the hypothesis that Radon levels are higher in households containing a basement. We also suspect Radon concentration is related to soil-type, i.e., geography matters.\n\nTo frame this as an ML problem, we'll try to predict log-radon levels based on a linear function of the floor on which the reading was taken. We'll also use the county as a random-effect and in so doing account for variances due to geography. In other words, we'll use a [generalized linear mixed-effect model](https://en.wikipedia.org/wiki/Generalized_linear_mixed_model).\n\n\n```\n%matplotlib inline\n\n\nfrom pprint import pprint\nimport collections\nimport matplotlib.pyplot as plt; plt.style.use('ggplot')\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns; sns.set_context('notebook')\nimport tensorflow.compat.v1 as tf\nimport warnings\n```\n\n### Obtain Dataset:\n\n\n```\nfrom six.moves import urllib\nCACHE_DIR = os.path.join(os.sep, 'tmp', 'radon')\n\ndef cache_or_download_file(cache_dir, url_base, filename):\n \"\"\"Read a cached file or download it.\"\"\"\n filepath = os.path.join(cache_dir, filename)\n if tf.gfile.Exists(filepath):\n return filepath\n if not tf.gfile.Exists(cache_dir):\n tf.gfile.MakeDirs(cache_dir)\n url = os.path.join(url_base, filename)\n print(\"Downloading {url} to {filepath}.\".format(url=url, filepath=filepath))\n urllib.request.urlretrieve(url, filepath)\n return filepath\n\n\ndef download_radon_dataset(cache_dir=CACHE_DIR):\n \"\"\"Download the radon dataset and read as Pandas dataframe.\"\"\"\n url_base = 'http://www.stat.columbia.edu/~gelman/arm/examples/radon/'\n # Alternative source:\n # url_base = ('https://raw.githubusercontent.com/pymc-devs/uq_chapter/'\n # 'master/reference/data/')\n srrs2 = pd.read_csv(cache_or_download_file(cache_dir, url_base, 'srrs2.dat'))\n srrs2.rename(columns=str.strip, inplace=True)\n cty = pd.read_csv(cache_or_download_file(cache_dir, url_base, 'cty.dat'))\n cty.rename(columns=str.strip, inplace=True)\n return srrs2, cty\n\n\ndef preprocess_radon_dataset(srrs2, cty, state='MN'):\n \"\"\"Preprocess radon dataset as done in \"Bayesian Data Analysis\" book.\"\"\"\n srrs2 = srrs2[srrs2.state==state].copy()\n cty = cty[cty.st==state].copy()\n \n # We will now join datasets on Federal Information Processing Standards\n # (FIPS) id, ie, codes that link geographic units, counties and county\n # equivalents. http://jeffgill.org/Teaching/rpqm_9.pdf\n srrs2['fips'] = 1000 * srrs2.stfips + srrs2.cntyfips\n cty['fips'] = 1000 * cty.stfips + cty.ctfips\n\n df = srrs2.merge(cty[['fips', 'Uppm']], on='fips')\n df = df.drop_duplicates(subset='idnum')\n df = df.rename(index=str, columns={'Uppm': 'uranium_ppm'})\n \n df['radon'] = df.activity.apply(lambda x: x if x > 0. else 0.1)\n \n # Remap categories to start from 0 and end at max(category).\n county_name = sorted(df.county.unique())\n df['county'] = df.county.astype(\n pd.api.types.CategoricalDtype(categories=county_name)).cat.codes\n county_name = map(str.strip, county_name)\n \n df['log_radon'] = df['radon'].apply(np.log)\n df['log_uranium_ppm'] = df['uranium_ppm'].apply(np.log) \n df = df[['log_radon', 'floor', 'county', 'log_uranium_ppm']]\n \n return df, county_name\n```\n\n\n```\ndf, counties = preprocess_radon_dataset(*download_radon_dataset())\n```\n\n\n```\ndf.head()\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
log_radonfloorcountylog_uranium_ppm
00.78845710-0.689048
10.78845700-0.689048
21.06471100-0.689048
30.00000000-0.689048
41.13140201-0.847313
\n
\n\n\n\n### Specializing the GLMM Family\n\nIn this section, we specialize the GLMM family to the task of predicting radon levels. To do this, we first consider the fixed-effect special case of a GLMM.\n\nUsing R notation, we might consider the following GLM:\n\n log(radon) ~ 1 + floor\n\nThis model posits that the `radon` response is governed by the floor of a building (e.g., \"ground floor\" of a \"two story\" home). More concretely it states that the `log(radon)` reading is explainable (in expectation) by the formula `offset + weight_floor[floor]`, i.e., there's a weight learned for every floor and a universal `intercept` term. In R's \"tilde notation\", the `1` indicates there's a weight associated with the \"null feature\", i.e., a weight associated with every sample.\n\nGiven our data, seems like it might be a good start. I.e.,\n\n\n```\ndf['log_radon'].plot(kind='density');\nplt.xlabel('log(radon)')\nplt.figure()\ndf['floor'].value_counts().plot(kind='bar')\nplt.xlabel('Floor')\nplt.ylabel('Count')\n```\n\nAlthough this seems like a good start, including something about geography is probably even better. I.e.,\n\n radon ~ 1 + floor + county\n\nThis model posits that the `radon` response is goverened by `offset + weight_floor[floor] + weight_county[county]`, i.e., the same as before except with a county-specific weight.\n\nIn the absence of a training set, `radon ~ 1 + floor + county` feels right. However, if we studied the training data, we'd discover that there's there's a large number of counties with a very small number of measurements. I.e.,\n\n\n```\nfig, ax = plt.subplots(figsize=(22, 5));\ncounty_freq = df['county'].value_counts()\ncounty_freq.plot(kind='bar');\nplt.xlabel('County Code');\nplt.ylabel('Count');\n```\n\nThis is worrisome. If we attempted to fit this model, the `weight_county` vector would likely end up memorizing the results for counties which had only a few training samples. Not good.\n\nGLMM's offer a happy middle to the above two GLMs. I.e., we might consider fitting,\n\n radon ~ 1 + floor + (1 | county)\n\nThis model is exactly the same as the first, except we've introduced the random-effect, `(1 | county)`. Adding this random effect has the effect of allowing per-county random fluctuations in radon In words, `(1 | county)` means that across samples and within a county, the random fluctuation in observed radon will be the same draw from a random Normal . Furthermore, since the covariance is shared among a group (i.e., a \"random effect\"), the counties with more observations provide a hint at the variance of counties with few observations (since the variance is estimated from the whole group).\n\n## Experiment\n\nWe'll now try to fit the `radon ~ 1 + floor + (1 | county)` GLMM using variational inference in TensorFlow. Our only remaining trick is to use stochastic gradient descent. (For brevity, we omit additional details.)\n\n### Imports\n\n\n```\nimport tensorflow_probability as tfp\n\ntfd = tfp.distributions\ntfb = tfp.bijectors\n```\n\nThe following code allows `Session` customization. Feel free to play with the `session_options` arguments and see how computational performance changes.\n\n\n```\ndef session_options(enable_gpu_ram_resizing=True,\n enable_xla=False):\n \"\"\"Convenience function which sets common `tf.Session` options.\"\"\"\n config = tf.ConfigProto()\n config.log_device_placement = True\n if enable_gpu_ram_resizing:\n # `allow_growth=True` makes it possible to connect multiple colabs to your\n # GPU. Otherwise the colab malloc's all GPU ram.\n config.gpu_options.allow_growth = True\n if enable_xla:\n # Enable on XLA. https://www.tensorflow.org/performance/xla/.\n config.graph_options.optimizer_options.global_jit_level = (\n tf.OptimizerOptions.ON_1)\n return config\n\ndef reset_sess(config=None):\n \"\"\"Convenience function to create the TF graph and session, or reset them.\"\"\"\n if config is None:\n config = session_options()\n tf.reset_default_graph()\n global sess\n try:\n sess.close()\n except:\n pass\n sess = tf.InteractiveSession(config=config)\n\nreset_sess()\n```\n\n### Setup\n\nFor transparency, we'll record all knob settings here.\n\n\n```\nhparams = tf.contrib.training.HParams(\n train_test_split = 0.8,\n train_batch_size = 100,\n test_batch_size = 10,\n\n dtype=np.float32,\n init_raw_scale=np.log(np.expm1(1.)), # approx= 0.5413\n scale_diag_offset=1e-3,\n\n surrogate_posterior_rank=1,\n\n num_monte_carlo_draws=2,\n\n train_iterations = int(3e3),\n\n learning_rate_start = 1e-2,\n learning_rate_num_epochs_per_decay = 10,\n learning_rate_decay_factor = 0.99,\n)\n```\n\n### Data Munging\n\nWe'll use `tf.data.Dataset` to feed the data into the TensorFlow graph. For a nice tutorial on different data loading patterns, see [\"How to use Dataset in TensorFlow\"](https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428).\n\n\n```\ndef dataset(df, batch_size):\n with tf.compat.v1.name_scope(name='dataset'):\n feature_cols=['county', 'floor']\n label_cols=['log_radon']\n dataset = tf.data.Dataset.from_tensor_slices((\n df[feature_cols].values.astype(np.int32),\n df[label_cols].values.astype(np.float32),\n )).repeat().batch(batch_size)\n iter_ = tf.data.Iterator.from_structure(\n dataset.output_types, dataset.output_shapes)\n init_op = iter_.make_initializer(dataset)\n features, labels = iter_.get_next()\n features.set_shape([batch_size, 2])\n labels.set_shape([batch_size, 1])\n return init_op, features, labels\n\n\nDataStats = collections.namedtuple(\n 'DataStats',\n [\n 'num_train',\n 'num_test',\n 'num_unique_county',\n 'num_unique_floor',\n ])\n\n\ndef split_dataset(df, train_test_split, train_batch_size, test_batch_size):\n \"\"\"Creates train/test split data.\"\"\"\n with tf.compat.v1.name_scope(name='split_dataset'):\n train_df = df.sample(frac=train_test_split, random_state=42)\n test_df = df.drop(train_df.index)\n data_stats = DataStats(\n num_train=len(train_df),\n num_test=len(test_df),\n num_unique_county=1 + df['county'].max(),\n num_unique_floor=1 + df['floor'].max(),\n )\n train_init_op, train_features, train_labels = dataset(\n train_df,\n train_batch_size)\n test_init_op, test_features, test_labels = dataset(\n test_df,\n test_batch_size)\n return [\n tf.group([train_init_op, test_init_op]), # dataset_init\n train_features,\n train_labels,\n test_features,\n test_labels,\n data_stats,\n ]\n```\n\n### Specify Model\n\n\n```\ndef make_prior():\n def _fn():\n dims = data_stats.num_unique_county\n prior_raw_scale = tf.get_variable(\n name='prior_raw_scale',\n initializer=np.array(hparams.init_raw_scale, hparams.dtype))\n scale = tf.nn.softplus(prior_raw_scale) + hparams.scale_diag_offset\n return tfd.Independent(\n tfd.Normal(loc=np.zeros(dims, hparams.dtype), scale=scale),\n reinterpreted_batch_ndims=1,\n name='prior')\n return tf.make_template('make_prior', _fn)()\n\n\ndef make_likelihood(x, u):\n def _fn():\n intercept = tf.get_variable(\n name='intercept',\n initializer=np.zeros(1, hparams.dtype))\n weights_floor = tf.pad(\n tf.get_variable(\n name='weights_floor',\n initializer=np.zeros(data_stats.num_unique_floor - 1,\n hparams.dtype)),\n paddings=[[1, 0]])\n random_effect = tf.transpose(tf.gather(tf.transpose(u), x[:, 0]))\n fixed_effect = intercept + tf.gather(weights_floor, x[:, 1])\n predicted_linear_response = fixed_effect + random_effect\n likelihood_raw_scale = tf.get_variable(\n name='likelihood_raw_scale',\n initializer=np.array(hparams.init_raw_scale, hparams.dtype))\n scale = tf.nn.softplus(likelihood_raw_scale) + hparams.scale_diag_offset\n return tfd.Independent(\n tfd.Normal(loc=predicted_linear_response[..., tf.newaxis],\n scale=scale),\n reinterpreted_batch_ndims=2,\n name='likelihood')\n\n return tf.make_template('make_likelihood', _fn)()\n\n\ndef make_surrogate_posterior():\n dims = data_stats.num_unique_county\n def _tril():\n loc = tf.get_variable(\n name='surrogate_loc',\n shape=[dims],\n initializer=tf.zeros_initializer())\n raw_scale_tril = tf.get_variable(\n name='surrogate_raw_scale_tril',\n initializer=np.zeros(dims * (dims + 1) // 2, hparams.dtype))\n scale_tril = tfp.math.fill_triangular(raw_scale_tril)\n new_diag = hparams.scale_diag_offset + tf.nn.softplus(\n hparams.init_raw_scale + tf.diag_part(scale_tril))\n scale_tril = tf.linalg.set_diag(scale_tril, new_diag)\n return tfd.MultivariateNormalTriL(\n loc=loc,\n scale_tril=scale_tril,\n name='surrogate_posterior')\n def _lowrank():\n rank = 1\n loc = tf.get_variable(\n name='surrogate_loc',\n shape=[dims],\n initializer=tf.zeros_initializer())\n raw_scale = tf.get_variable(\n name='surrogate_raw_scale',\n initializer=np.zeros(dims * (1 + rank), hparams.dtype))\n return tfd.MultivariateNormalDiagPlusLowRank(\n loc=loc,\n scale_diag=tf.nn.softplus(hparams.init_raw_scale + raw_scale[:dims]),\n scale_perturb_factor=tf.reshape(raw_scale[dims:], [dims, rank]),\n name='surrogate_posterior')\n return tf.make_template(\n 'make_surrogate_posterior',\n _tril if hparams.surrogate_posterior_rank >= dims else _lowrank)()\n```\n\n### Main\n\n\n```\nreset_sess()\n\n[\n data_init,\n train_features,\n train_labels,\n test_features,\n test_labels,\n data_stats,\n] = split_dataset(\n df,\n hparams.train_test_split,\n hparams.train_batch_size,\n hparams.test_batch_size,\n)\n\nprior = make_prior()\nprint(prior)\n\nsurrogate_posterior = make_surrogate_posterior()\nprint(surrogate_posterior)\n\nminibatch_correction_factor = data_stats.num_train / hparams.train_batch_size\n\ndef unnormalized_approx_posterior_log_prob(u):\n likelihood = make_likelihood(train_features, u)\n print(likelihood)\n return (likelihood.log_prob(train_labels) * minibatch_correction_factor\n + prior.log_prob(u))\n\nelbo_loss = tfp.vi.monte_carlo_variational_loss(\n p_log_prob=unnormalized_approx_posterior_log_prob,\n q=surrogate_posterior,\n discrepancy_fn=tfp.vi.kl_reverse, # same as: Evidence Lower BOund\n num_draws=hparams.num_monte_carlo_draws,\n name='elbo_loss')\nprint(elbo_loss)\n\nglobal_step = tf.train.get_or_create_global_step()\nlearning_rate = tf.train.exponential_decay(\n learning_rate=hparams.learning_rate_start,\n global_step=global_step,\n decay_steps=minibatch_correction_factor * hparams.learning_rate_num_epochs_per_decay,\n decay_rate=hparams.learning_rate_decay_factor,\n staircase=True)\nopt = tf.train.AdamOptimizer(learning_rate=learning_rate)\ntrain = opt.minimize(elbo_loss, global_step=global_step)\n\npprint(tf.trainable_variables())\n\nvar_init = tf.global_variables_initializer()\n```\n\n tfp.distributions.Independent(\"make_prior/prior/\", batch_shape=(), event_shape=(85,), dtype=float32)\n tfp.distributions.MultivariateNormalDiagPlusLowRank(\"make_surrogate_posterior/surrogate_posterior/\", batch_shape=(), event_shape=(85,), dtype=float32)\n tfp.distributions.Independent(\"elbo_loss/expectation/make_likelihood/likelihood/\", batch_shape=(2,), event_shape=(100, 1), dtype=float32)\n Tensor(\"elbo_loss/expectation/Mean:0\", shape=(), dtype=float32)\n [,\n ,\n ,\n ,\n ,\n ]\n\n\n\n```\nloss_ = np.zeros(hparams.train_iterations)\n\nsess.run([var_init, data_init])\n\nfor iter_ in range(hparams.train_iterations):\n [\n _,\n train_features_,\n train_labels_,\n test_features_,\n test_labels_,\n loss_[iter_],\n ] = sess.run([\n train,\n train_features,\n train_labels,\n test_features,\n test_labels,\n elbo_loss,\n ])\n if iter_ % 200 == 0 or iter_ == hparams.train_iterations - 1:\n print(\"iter:{:>4} loss:{:.3f}\".format(\n iter_, loss_[iter_]))\n```\n\n iter: 0 loss:1966.783\n iter: 200 loss:1020.058\n iter: 400 loss:833.788\n iter: 600 loss:994.871\n iter: 800 loss:883.134\n iter:1000 loss:892.679\n iter:1200 loss:846.151\n iter:1400 loss:857.963\n iter:1600 loss:902.009\n iter:1800 loss:893.753\n iter:2000 loss:814.118\n iter:2200 loss:841.195\n iter:2400 loss:906.226\n iter:2600 loss:881.371\n iter:2800 loss:839.190\n iter:2999 loss:832.338\n\n\n### Results\n\n\n```\nsurrogate_posterior_cov = surrogate_posterior.covariance()\nsurrogate_posterior_scale = tf.cholesky(surrogate_posterior_cov )\n\nwith tf.variable_scope('make_likelihood', reuse=True):\n intercept = tf.get_variable(name='intercept')\n weights_floor = tf.get_variable(name='weights_floor')\n\n[\n surrogate_posterior_scale_,\n surrogate_posterior_cov_,\n intercept_,\n weights_floor_,\n prior_scale_,\n] = sess.run([\n surrogate_posterior_scale,\n surrogate_posterior_cov,\n intercept,\n weights_floor,\n prior.distribution.scale,\n])\n\n\nprint(' intercept: ', intercept_)\nprint('weights_floor: ', weights_floor_)\nprint(' prior_scale: ', prior_scale_)\n```\n\n intercept: [ 1.46341455]\n weights_floor: [-0.71115714]\n prior_scale: 0.333418\n\n\nWe will now plot the training-set loss as a function of training iteration. Note that although the `learning_rate` decays to `0`, there's still noise in the loss owing to the learned parameters being evaluated over different mini-batches.\n\n\n```\nplt.plot(loss_, 'b-');\nplt.xlabel('iter');\nplt.ylabel('loss');\n```\n\nWe now plot a nonparametric estimate of the density of the diagonal of the surrogate posterior covariance. Roughly speaking, this shows us how much intrinsic variability there is in each county's `log(radon)` readings.\n\n\n```\nsurrogate_posterior_diag_scale_ = np.diag(surrogate_posterior_scale_)\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n sns.kdeplot(surrogate_posterior_diag_scale_, shade=True, color=\"r\");\n plt.xlabel('posterior std. deviation');\n plt.ylabel('density');\n```\n\nWe now show a heat map of the covariance matrix. This shows us that just looking at the diagonal was a perfectly reasonable thing to do; the matrix is clearly [diagonally dominant](https://en.wikipedia.org/wiki/Diagonally_dominant_matrix).\n\n\n```\nsns.heatmap(surrogate_posterior_cov_)\nplt.title('Surrogate Posterior Covariance')\n```\n\nWe now conjecture that the county-wise standard deviations might be log-correlated with the number of observations for that county.\n\n\n```\ncnt = np.histogram(\n df['county'],\n np.arange(data_stats.num_unique_county+1))[0]\n\ny = np.stack([cnt, surrogate_posterior_diag_scale_]).T\ny = y[y[:,0].argsort()] # sort by zero-th col\nsns.regplot(x=np.log(y[:,0]), y=y[:, 1], color='g')\nplt.xlabel('county log-count');\nplt.ylabel('posterior std. deviation');\n```\n\nIndeed--we do appear to have learned a log-linear relationship between std. deviation and county frequency. This is neat because we never expressed this idea in the model; it is simply apparently true.\n\n## Comparing to `lme4` in R\n\n\n```\n%%shell\nexit # Trick to make this block not execute.\n\nradon = read.csv('srrs2.dat', header = TRUE)\nradon = radon[radon$state=='MN',]\nradon$radon = ifelse(radon$activity==0., 0.1, radon$activity)\nradon$log_radon = log(radon$radon)\n\n# install.packages('lme4')\nlibrary(lme4)\nfit <- lmer(log_radon ~ 1 + floor + (1 | county), data=radon)\nfit\n\n# Linear mixed model fit by REML ['lmerMod']\n# Formula: log_radon ~ 1 + floor + (1 | county)\n# Data: radon\n# REML criterion at convergence: 2171.305\n# Random effects:\n# Groups Name Std.Dev.\n# county (Intercept) 0.3282\n# Residual 0.7556\n# Number of obs: 919, groups: county, 85\n# Fixed Effects:\n# (Intercept) floor\n# 1.462 -0.693\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\nThe following table summarizes the results.\n\n\n```\nprint(pd.DataFrame(data=dict(intercept=[1.462, intercept_[0]],\n floor=[-0.693, weights_floor_[0]],\n scale=[0.3282, prior_scale_]),\n index=['lme4', 'vi']))\n```\n\n floor intercept scale\n lme4 -0.693000 1.462000 0.328200\n vi -0.711157 1.463415 0.333418\n\n\nThis table indicates the VI results are within ~10% of `lme4`'s. This is somewhat surprising since:\n- `lme4` is based on [Laplace's method](https://www.jstatsoft.org/article/view/v067i01/) (not VI),\n- we used mini-batch SGD,\n- no effort was made in this colab to actually converge,\n- minimal effort was made to tune hyperparameters,\n- no effort was taken regularize or preprocess the data (eg, center features, etc.).\n\n## Conclusion\n\nIn this colab we described Generalized Linear Mixed-effects Models and showed how to use variational inference to fit them using TensorFlow. Although the toy problem only had a few 100 training samples, the techniques used here are identical to what's needed at scale.\n", "meta": {"hexsha": "9dbd24dd575852795d48aefb9933bbe5ab1c1bf3", "size": 207701, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tensorflow_probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Model_Variational_Inference.ipynb", "max_stars_repo_name": "wataruhashimoto52/probability", "max_stars_repo_head_hexsha": "12e3f256544eadea6e863868da825614f4423eb0", "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": "tensorflow_probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Model_Variational_Inference.ipynb", "max_issues_repo_name": "wataruhashimoto52/probability", "max_issues_repo_head_hexsha": "12e3f256544eadea6e863868da825614f4423eb0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensorflow_probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Model_Variational_Inference.ipynb", "max_forks_repo_name": "wataruhashimoto52/probability", "max_forks_repo_head_hexsha": "12e3f256544eadea6e863868da825614f4423eb0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-19T13:05:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-19T13:05:15.000Z", "avg_line_length": 124.5209832134, "max_line_length": 29508, "alphanum_fraction": 0.820207895, "converted": true, "num_tokens": 8465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618332444287, "lm_q2_score": 0.17553806931030444, "lm_q1q2_score": 0.07956470709977617}} {"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\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnamedatetimemonthyeardate_of_birthoutcome_typeoutcome_subtypeanimal_typesex_upon_outcomeage_upon_outcomebreedcolor
0A775354Charley2019-11-12T13:29:00.0002019-11-12T13:29:00.0002013-06-28T00:00:00.000AdoptionNaNDogNeutered Male6 yearsCocker Spaniel MixBlack/White
1A775130*Slinky2019-11-12T13:17:00.0002019-11-12T13:17:00.0002016-06-25T00:00:00.000AdoptionFosterDogSpayed Female3 yearsPit Bull MixBlue/White
2A808385NaN2019-11-12T13:16:00.0002019-11-12T13:16:00.0002018-11-08T00:00:00.000TransferPartnerDogNeutered Male1 yearPug/Chihuahua ShorthairWhite/Brown
3A799709*Deeogee2019-11-12T13:15:00.0002019-11-12T13:15:00.0002018-07-11T00:00:00.000AdoptionFosterDogNeutered Male1 yearBeagle MixBrown Brindle
4A713661Coco2019-11-12T12:46:00.0002019-11-12T12:46:00.0002013-10-10T00:00:00.000Return to OwnerNaNDogSpayed Female6 yearsLabrador Retriever MixBlack/White
\n
\n\n\n\n\n```python\nadoption.shape\n```\n\n\n\n\n (100000, 12)\n\n\n\nThe target in this project will be to predict whether or not an animal will be adopted or not (transferred to another shelter or, sadly, euthanized) so that perhaps animal shelters, though overwhelmed, can give some extra love or use unique methods to get those animals that may not have the best odds forever homes.\n\n\n```python\nadoption['outcome_type'].value_counts(dropna=False)\n```\n\n\n\n\n Adoption 44389\n Transfer 29848\n Return to Owner 17520\n Euthanasia 6300\n Died 968\n Rto-Adopt 507\n Disposal 387\n Missing 61\n Relocate 17\n NaN 3\n Name: outcome_type, dtype: int64\n\n\n\n\n```python\n# this might be a feature that can create leakage, will come back to it.\nadoption['outcome_subtype'].value_counts(dropna=False)\n```\n\n\n\n\n NaN 54846\n Partner 24931\n Foster 7953\n Rabies Risk 2791\n SCRP 2642\n Suffering 2504\n Snr 2272\n In Kennel 508\n Aggressive 360\n Offsite 281\n Medical 254\n In Foster 242\n At Vet 171\n Behavior 82\n Enroute 65\n Underage 29\n Court/Investigation 21\n In Surgery 19\n Possible Theft 15\n Field 8\n Barn 4\n Prc 1\n Customer S 1\n Name: outcome_subtype, dtype: int64\n\n\n\n# Classification or Regression?\n\nThere are 9 classes of outcomes but for this project I'd like to focus on the animals that were adopted or not. There are a large number of animals that were returned to owners but that would just be due to them getting out etc but they do have a home so I will not include those in my project. \"Rto-adopt\" or return to owner adoption will also be included with \"return to owner.\"\n\nFor animals that were adopted I will consider that to be: \n-adoption \n-rto-adopt (return to owner through adoption) \n\n\nI will combine the following for not adopted: \n-transfer \n-euthanasia \n-relocate \n-missing (animals that went missing from the shelter--still unsuccessful in getting them homes) \n\"Died\" and \"disposal\" are animals that may have died while at the shelter or were brought in that needed to be properly disposed of so I will not include these either as they may have been very ill when brought in.\n\n# How is the target distributed?\n## Are the classes imbalanced?\n\n\n```python\nadoption['outcome_type'].value_counts(normalize=True)\n```\n\n\n\n\n Adoption 0.443903\n Transfer 0.298489\n Return to Owner 0.175205\n Euthanasia 0.063002\n Died 0.009680\n Rto-Adopt 0.005070\n Disposal 0.003870\n Missing 0.000610\n Relocate 0.000170\n Name: outcome_type, dtype: float64\n\n\n\nwill need to drop the rows where the outcome type are the ones listed above to be excluded: \n-Return to owner \n-Rto-adopt \n-Died \n-Disposal\n\n\n\n```python\n# adoption updated to drop the outcomes we are excluding:\nadoption_upd = adoption[~adoption['outcome_type'].isin(['Return to Owner', \n 'Rto-Adopt', \n 'Died', \n 'Disposal'])]\n```\n\n\n```python\nprint(adoption_upd.shape)\nadoption_upd['outcome_type'].value_counts()\n```\n\n (80618, 12)\n\n\n\n\n\n Adoption 44389\n Transfer 29848\n Euthanasia 6300\n Missing 61\n Relocate 17\n Name: outcome_type, dtype: int64\n\n\n\n\n```python\n# need to redefine classes as binary. Adoption as 'adopted' and \n# the rest as 'not adopted'.\ndef new_status(outcome):\n if outcome == 'Transfer' or outcome == 'Euthanasia' or outcome == 'Missing' or outcome == 'Relocate':\n return 'Not adopted'\n else:\n return 'Adopted'\n\n```\n\n\n```python\nadoption_upd = adoption_upd.copy()\nadoption_upd['new_outcome_type'] = adoption_upd['outcome_type'].apply(new_status)\n```\n\n\n```python\nadoption_upd['new_outcome_type'].value_counts(normalize=True)\n```\n\n\n\n\n Adopted 0.550646\n Not adopted 0.449354\n Name: new_outcome_type, dtype: float64\n\n\n\nThe classes now are combined into a binary classification and the classes are not imbalanced.\n\n\n```python\n# drop the original 'Outcome_Type' column:\nadoption_upd.drop(columns='outcome_type')\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 \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 \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
animal_idnamedatetimemonthyeardate_of_birthoutcome_subtypeanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_type
0A775354Charley2019-11-12T13:29:00.0002019-11-12T13:29:00.0002013-06-28T00:00:00.000NaNDogNeutered Male6 yearsCocker Spaniel MixBlack/WhiteAdopted
1A775130*Slinky2019-11-12T13:17:00.0002019-11-12T13:17:00.0002016-06-25T00:00:00.000FosterDogSpayed Female3 yearsPit Bull MixBlue/WhiteAdopted
2A808385NaN2019-11-12T13:16:00.0002019-11-12T13:16:00.0002018-11-08T00:00:00.000PartnerDogNeutered Male1 yearPug/Chihuahua ShorthairWhite/BrownNot adopted
3A799709*Deeogee2019-11-12T13:15:00.0002019-11-12T13:15:00.0002018-07-11T00:00:00.000FosterDogNeutered Male1 yearBeagle MixBrown BrindleAdopted
5A808367Daily2019-11-12T12:38:00.0002019-11-12T12:38:00.0002016-11-07T00:00:00.000PartnerDogIntact Female3 yearsAustralian Cattle Dog/Labrador RetrieverCreamNot adopted
.......................................
99995A679740NaN2014-05-26T16:55:00.0002014-05-26T16:55:00.0002014-03-25T00:00:00.000PartnerDogIntact Male2 monthsCatahoula MixBrown Brindle/WhiteNot adopted
99996A679715NaN2014-05-26T16:54:00.0002014-05-26T16:54:00.0002014-03-25T00:00:00.000PartnerDogIntact Female2 monthsCatahoula MixTan/WhiteNot adopted
99997A677532*Taco2014-05-26T16:52:00.0002014-05-26T16:52:00.0002014-03-15T00:00:00.000NaNCatNeutered Male2 monthsDomestic Shorthair MixWhiteAdopted
99998A677530*Chimichanga2014-05-26T16:51:00.0002014-05-26T16:51:00.0002014-03-15T00:00:00.000NaNCatNeutered Male2 monthsDomestic Shorthair MixBlackAdopted
99999A679225Phoebe2014-05-26T16:40:00.0002014-05-26T16:40:00.0002011-05-17T00:00:00.000NaNDogSpayed Female3 yearsMaltese/Miniature PoodleApricotAdopted
\n

80618 rows × 12 columns

\n
\n\n\n\n# Choose Observations\n\nAs mentioned above, since the focus of my project is predicting if animals that are in need of forever homes will be adopted or not, I have already excluded the following observations from my model: \n-Return to Owner \n-Rto-Adopt \n-Died \n-Disposal \n\nThere are 3 missing values for the outcome ,so we can try to look at the outcome subtype to see if we can determine what happened to them but the remaining animals have been categorized into 'adopted' or 'not adopted.'\n\n\n```python\nadoption_upd.isnull().sum()\n```\n\n\n\n\n animal_id 0\n name 30058\n datetime 0\n monthyear 0\n date_of_birth 0\n outcome_type 3\n outcome_subtype 36354\n animal_type 0\n sex_upon_outcome 3\n age_upon_outcome 25\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n# How to Split Data:\n\nThe description of the data set said that Austin is becoming a more pet-friendly city so there may be more animals going in and out of shelters in the more recent data vs the earlier data. I will therefore split the data based on time with the most recent data being the test set and then create a test and validation set with the remaining data. \n\ntest = adoption_upd[(adoption_upd['datetime'].dt.year == 2019)] \nval = adoption_upd[(adoption_upd['datetime'].dt.year == 2018)] \ntrain = adoption_upd[(adoption_upd['datetime'].dt.year < 2018)]\n\n\n```python\nadoption_upd.dtypes\n```\n\n\n\n\n animal_id object\n name object\n datetime object\n monthyear object\n date_of_birth object\n outcome_type object\n outcome_subtype object\n animal_type object\n sex_upon_outcome object\n age_upon_outcome object\n breed object\n color object\n new_outcome_type object\n dtype: object\n\n\n\n\n```python\nadoption_upd['datetime'] = pd.to_datetime(adoption_upd['datetime'], infer_datetime_format=True)\n```\n\n\n```python\nadoption_upd['datetime'].dt.year.value_counts()\n```\n\n\n\n\n 2015 14792\n 2019 14292\n 2016 14120\n 2017 14058\n 2018 13361\n 2014 9995\n Name: datetime, dtype: int64\n\n\n\n\n```python\n# how big to make test set? 2019:\n# 14292 observations\n```\n\n# Evaluation Metrics\n\nsince the classes aren't imbalanced I can use accuracy but will also explore the precision and recall for this problem.\n\nprecision positive: correctly predict all the animals that were adopted. \n\n\\begin{align}\nprecision = \\frac{accurately \\ predicted \\ adopted}{total\\ predicted \\ adopted}\n\\end{align}\n\n\nrecall positive: of all the animals that were adopted, how many were we able to identify?\n\\begin{align}\nrecall = \\frac{accurately \\ predicted \\ adopted}{actually \\ adopted}\n\\end{align}\n\n\n# Begin to clean data and feature selection\n\n\n```python\n# lets look at the 3 missing values for the outcome type:\nadoption_upd[adoption_upd['outcome_type'].isnull()]\n# both the outcome type and outcome subtype are missing. Since only 3 rows,\n# will drop these observations from the data.\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 \n \n \n
animal_idnamedatetimemonthyeardate_of_birthoutcome_typeoutcome_subtypeanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_type
2565A803963Little Bit2019-09-27 17:59:002019-09-27T17:59:00.0002017-09-09T00:00:00.000NaNNaNDogIntact MaleNaNMiniature SchnauzerGray/BlackAdopted
53725A737705*Heddy2016-11-19 16:35:002016-11-19T16:35:00.0002013-11-02T00:00:00.000NaNNaNDogNaNNaNLabrador Retriever MixBlack/WhiteAdopted
94975A686025NaN2014-08-16 08:35:002014-08-16T08:35:00.0002013-08-15T00:00:00.000NaNNaNOtherUnknown1 yearBat MixBrownAdopted
\n
\n\n\n\nwill create a wrangle function to do things at one time, \nlist: \nadoption_upd.dropna(subset = ['outcome_type']) \nthe name column has a lot of missing values, will change NaN's to unknown\nadoption_upd['name].fillna(\"unknown\", inplace = True) \n \nthe outcome subtype is missing 36353 values, almost half of all of our data, since we will know all of the outcome types and this may cause leakage into the test set because certain outcomes can be deduced from the outcome subtype, I will drop that entire column. \nadoption_upd.drop(columns='outcome_subtype')\n\n\n\n```python\n# the sex_upon_outcome column has 3 missing values, 1 of which is a row that\n# will be dropped because the outcome type is missing, but noticed an 'unknown'\n# value so check to see if that's common:\nadoption_upd['sex_upon_outcome'].value_counts()\n# will one hot encode this column.\n```\n\n\n\n\n Neutered Male 27563\n Spayed Female 26009\n Intact Female 10091\n Intact Male 9376\n Unknown 7576\n Name: sex_upon_outcome, dtype: int64\n\n\n\n\n```python\n# age_upon_outcome has 25 missing values but date_of_birth has none, lets\n# look at how many times 'unknown' shows up in the data:\nadoption_upd.isin(['Unknown']).sum()\n# the name already has 18 unknowns, so will stick to changing NaN's to unknown.\n```\n\n\n\n\n animal_id 0\n name 18\n datetime 0\n monthyear 0\n date_of_birth 0\n outcome_type 0\n outcome_subtype 0\n animal_type 0\n sex_upon_outcome 7576\n age_upon_outcome 0\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n\n```python\nadoption_upd.isin(['Other']).sum()\n```\n\n\n\n\n animal_id 0\n name 0\n datetime 0\n monthyear 0\n date_of_birth 0\n outcome_type 0\n outcome_subtype 0\n animal_type 4455\n sex_upon_outcome 0\n age_upon_outcome 0\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n\n```python\n# to see what kind of animals come in to the shelter\nadoption_upd['animal_type'].value_counts()\n# initially was thinking of only using cats and dogs but am curious to see the other types.\n```\n\n\n\n\n Dog 39760\n Cat 35962\n Other 4455\n Bird 432\n Livestock 9\n Name: animal_type, dtype: int64\n\n\n\nsince there are no missing or unknown values for DOB which still seems strange \nespecially for stray animals that were found but maybe they approximated. We can \ncreate a column where we subtract 2019 from the born on year to get the age and see \nif there are a lot of differences.\n\n\n```python\nadoption_upd['date_of_birth'] = pd.to_datetime(adoption_upd['date_of_birth'], infer_datetime_format=True)\n```\n\n\n```python\n# lets see what happens when we subtract 11-2019 from the date of birth \nnow = pd.Timestamp('now')\nadoption_upd['calculated_age']=(now.year - adoption_upd['date_of_birth'].dt.year) - ((now.month - adoption_upd['date_of_birth'].dt.month) < 0)\n# lets compare the 'calculated_age' column to the 'age_upon_outcome'\n```\n\n\n\n\n 0 6\n 1 3\n 2 1\n 3 1\n 5 3\n ..\n 99995 5\n 99996 5\n 99997 5\n 99998 5\n 99999 8\n Name: calculated_age, Length: 80618, dtype: int64\n\n\n\n\n```python\n# how many different breeds are there:\nadoption_upd['breed'].value_counts()\n# 2042...very high cardinality, may need to focus on cats and dogs afterall.\n```\n\n\n\n\n Domestic Shorthair Mix 26076\n Pit Bull Mix 4723\n Labrador Retriever Mix 4375\n Chihuahua Shorthair Mix 3977\n Domestic Shorthair 3537\n ... \n West Highland/Patterdale Terr 1\n Alaskan Husky/Australian Shepherd 1\n Dachshund Longhair/Miniature Poodle 1\n Schipperke/Catahoula 1\n Queensland Heeler/Dachshund 1\n Name: breed, Length: 2042, dtype: int64\n\n\n\n\n```python\n# how many colors are there\nadoption_upd['color'].value_counts()\n#512 different values, high cardinality as well.\n```\n\n\n\n\n Black/White 8567\n Black 7240\n Brown Tabby 5508\n Brown 3377\n Brown Tabby/White 2806\n ... \n Tricolor/Brown Brindle 1\n Agouti/Cream 1\n Cream/Blue Point 1\n Gray/Blue Merle 1\n Tricolor/Orange 1\n Name: color, Length: 512, dtype: int64\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5ee75a0bfda559f0b8191ec77325112855b302f4", "size": 45675, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "module1/LS_DS_231_assignment (1).ipynb", "max_stars_repo_name": "mljarman/DS-Unit-2-Applied-Modeling", "max_stars_repo_head_hexsha": "de878dab12cf4deac01fd1881a9fc1414ac6285c", "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": "module1/LS_DS_231_assignment (1).ipynb", "max_issues_repo_name": "mljarman/DS-Unit-2-Applied-Modeling", "max_issues_repo_head_hexsha": "de878dab12cf4deac01fd1881a9fc1414ac6285c", "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": "module1/LS_DS_231_assignment (1).ipynb", "max_forks_repo_name": "mljarman/DS-Unit-2-Applied-Modeling", "max_forks_repo_head_hexsha": "de878dab12cf4deac01fd1881a9fc1414ac6285c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9545454545, "max_line_length": 393, "alphanum_fraction": 0.4483415435, "converted": true, "num_tokens": 7248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.22815650216092534, "lm_q1q2_score": 0.07954565766147816}} {"text": "\n# Single-particle properties and nuclear data\n\n \n**Morten Hjorth-Jensen**, [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/) and [Department of Physics and Astronomy](https://www.pa.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA\n\nDate: **Jul 4, 2017**\n\nCopyright 2013-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n## Stability of matter\nTo understand why matter is stable, and thereby shed light on the limits of \nnuclear stability, is one of the \noverarching aims and intellectual challenges \nof basic research in nuclear physics. To relate the stability of matter\nto the underlying fundamental forces and particles of nature as manifested in nuclear matter, is central\nto present and planned rare isotope facilities. \nImportant properties of nuclear systems which can reveal information about these topics \nare for example masses, and thereby binding energies, and density distributions of nuclei. \nThese are quantities which convey important information on \nthe shell structure of nuclei, with their \npertinent magic numbers and shell closures or the eventual disappearence of the latter \naway from the valley of stability.\n\n\n\n\n## Drip lines\n\nNeutron-rich nuclei are particularly interesting for the above endeavour. As a particular chain\nof isotopes becomes more and more neutron rich, one reaches finally the limit of stability, the so-called\ndripline, where one additional neutron makes the next isotopes unstable with respect \nto the previous ones. The appearence or not of magic numbers and shell structures,\nthe formation of neutron skins and halos\ncan thence be probed via investigations of quantities like the binding energy\nor the charge radii and neutron rms radii of neutron-rich nuclei. \nThese quantities have in turn important \nconsequences for theoretical models of nuclear structure and their application in astrophysics.\n\n\n\n\n## More on [Neutron-rich nuclei](http://iopscience.iop.org/1402-4896/2013/T152)\n\n\nNeutron radius of ${}^{208}\\mbox{Pb}$, recently extracted from the PREX \nexperiment at Jefferson Laboratory can be used to constrain the equation of state of \nneutron matter. A related quantity to the\nneutron rms radius $r_n^{\\mathrm{rms}}=\\langle r^2\\rangle_n^{1/2}$ is the neutron skin \n$r_{\\mathrm{skin}}=r_n^{\\mathrm{rms}}-r_p^{\\mathrm{rms}}$,\nwhere $r_p^{\\mathrm{rms}}$ is the corresponding proton rms radius. \nThere are several properties which relate the thickness of the neutron skin to quantities in nuclei and \nnuclear matter, such as the symmetry energy at the saturation point for nuclear matter, the slope\nof the equation of state for neutron matter\nor the low-energy electric dipole strength due to the pigmy dipole resonance.\n\n\n\n\n\n\n## Motivation\nHaving access to precise measurements of masses, radii, and\nelectromagnetic moments for a wide range of nuclei allows to study\ntrends with varying neutron excess. A quantitative description of\nvarious experimental data with quantified uncertainty still remains a\nmajor challenge for nuclear structure theory. Global theoretical\nstudies of isotopic chains, such as the Ca chain shown in the figure below here, make it possible to test systematic\nproperties of effective interactions between nucleons. Such calculations also\nprovide critical tests of limitations of many-body methods. As one\napproaches the particle emission thresholds, it becomes increasingly\nimportant to describe correctly the coupling to the continuum of\ndecays and scattering channels. While the\nfull treatment of antisymmetrization and short-range correlations has\nbecome routine in first principle approaches (to be defined later) to nuclear bound states, the\nmany-body problem becomes more difficult when long-range correlations\nand continuum effects are considered.\n\n\n\n\n## FRIB limits\n\n\n\n\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\n

Artist'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\n

Single-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 at . \n\n* The c++ program uses the c++ library armadillo, see .\n\n\n\n\n## Program to solve Schroedinger's equation\nThe code sets up the Hamiltonian matrix by defining the the minimun and maximum values of $r$ with a\nmaximum value of integration points. These are set in the initialization function. It plots the \neigenfunctions of the three lowest eigenstates.\n\n\n```\n#Program which solves the one-particle Schrodinger equation \n#for a potential specified in function\n#potential(). This example is for the harmonic oscillator in 3d\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\n#Function for initialization of parameters\ndef initialize():\n RMin = 0.0\n RMax = 10.0\n lOrbital = 0\n Dim = 400\n return RMin, RMax, lOrbital, Dim\n# Here we set up the harmonic oscillator potential\ndef potential(r):\n return r*r\n\n#Get the boundary, orbital momentum and number of integration points\nRMin, RMax, lOrbital, Dim = initialize()\n\n#Initialize constants\nStep = RMax/(Dim+1)\nDiagConst = 2.0 / (Step*Step)\nNondiagConst = -1.0 / (Step*Step)\nOrbitalFactor = lOrbital * (lOrbital + 1.0)\n\n#Calculate array of potential values\nv = np.zeros(Dim)\nr = np.linspace(RMin,RMax,Dim)\nfor i in xrange(Dim):\n r[i] = RMin + (i+1) * Step;\n v[i] = potential(r[i]) + OrbitalFactor/(r[i]*r[i]);\n\n#Setting up tridiagonal matrix and find eigenvectors and eigenvalues\nHamiltonian = np.zeros((Dim,Dim))\nHamiltonian[0,0] = DiagConst + v[0];\nHamiltonian[0,1] = NondiagConst;\nfor i in xrange(1,Dim-1):\n Hamiltonian[i,i-1] = NondiagConst;\n Hamiltonian[i,i] = DiagConst + v[i];\n Hamiltonian[i,i+1] = NondiagConst;\nHamiltonian[Dim-1,Dim-2] = NondiagConst;\nHamiltonian[Dim-1,Dim-1] = DiagConst + v[Dim-1];\n# diagonalize and obtain eigenvalues, not necessarily sorted\nEigValues, EigVectors = np.linalg.eig(Hamiltonian)\n# sort eigenvectors and eigenvalues\npermute = EigValues.argsort()\nEigValues = EigValues[permute]\nEigVectors = EigVectors[:,permute]\n# now plot the results for the three lowest lying eigenstates\nfor i in xrange(3):\n print EigValues[i]\nFirstEigvector = EigVectors[:,0]\nSecondEigvector = EigVectors[:,1]\nThirdEigvector = EigVectors[:,2]\nplt.plot(r, FirstEigvector**2 ,'b-',r, SecondEigvector**2 ,'g-',r, ThirdEigvector**2 ,'r-')\nplt.axis([0,4.6,0.0, 0.025])\nplt.xlabel(r'$r$')\nplt.ylabel(r'Radial probability $r^2|R(r)|^2$')\nplt.title(r'Radial probability distributions for three lowest-lying states')\nplt.savefig('eigenvector.pdf')\nplt.savefig('eigenvector.png')\nplt.show()\n```\n\n\n\n## Exercise 1: Masses and binding energies\n\nThe data on binding energies can be found in the file bedata.dat at the github address of the [course](https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs)\n\n\n**a)**\nWrite a small program which reads in the proton and neutron numbers and the binding energies \nand make a plot of all neutron separation energies for the chain of oxygen (O), calcium (Ca), nickel (Ni), tin (Sn) and lead (Pb) isotopes, that is you need to plot\n\n$$\nS_n= BE(N,Z)-BE(N-1,Z).\n$$\n\nComment your results.\n\n**b)**\nInclude in the same figure(s) the liquid drop model results of Eq. (2.17) of Alex Brown's text, namely\n\n$$\nBE(N,Z)= \\alpha_1A-\\alpha_2A^{2/3}-\\alpha_3\\frac{Z^2}{A^{1/3}}-\\alpha_4\\frac{(N-Z)^2}{A},\n$$\n\nwith $\\alpha_1=15.49$ MeV, $\\alpha_2=17.23$ MeV, $\\alpha_3=0.697$ MeV and $\\alpha_4=22.6$ MeV. Comment your results\n\n**c)**\nMake a plot of the binding energies as function of the number of nucleons $A$ using the data in the file on bindingenergies and the above liquid drop model. Make a figure similar to figure 2.5 of Alex Brown where you set the various parameters $\\alpha_i=0$. Comment your results.\n\n**d)**\nUse the liquid drop model to find the neutron drip lines for Z values up to 120.\nAnalyze then the fluorine isotopes and find, where available the corresponding experimental data, and compare the liquid drop model predicition with experiment. Comment your results.\nA program example in C++ and the input data file *bedata.dat* can be found found at the github repository for the [course](https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs)\n\n\n\n\n\n\n\n\n## Exercise 2: Eigenstates and eigenvalues of single-particle problems\n\nThe program for finding the eigenvalues of the harmonic oscillator are in the github folder\n.\n\nYou can use this program to solve the exercise below, or write your own using your preferred programming language, be it python, fortran or c++ or other languages. Here I will mainly provide fortran, python and c++.\n\n\n**a)**\nCompute the eigenvalues of the three lowest states with a given orbital momentum and oscillator frequency $\\omega$. Study these results as functions of the the maximum value of $r$ and the number of integration points $n$, starting with $r_{\\mathrm{max}}=10$. Compare the computed ones with the exact values and comment your results.\n\n**b)**\nPlot thereafter the eigenfunctions as functions of $r$ for the lowest-lying state with a given orbital momentum $l$.\n\n**c)**\nReplace thereafter the harmonic oscillator potential with a Woods-Saxon potential using the parameters discussed above. Compute the lowest five eigenvalues and plot the eigenfunction of the lowest-lying state. How does this compare with the harmonic oscillator? Comment your results and possible implications for nuclear physics studies.\n\n\n\n\n\n\n\n\n## Exercise 3: Operators and Slater determinants\n\nConsider the Slater determinant\n\n$$\n\\Phi_{\\lambda}^{AS}(x_{1}x_{2}\\dots x_{N};\\alpha_{1}\\alpha_{2}\\dots\\alpha_{N})\n=\\frac{1}{\\sqrt{N!}}\\sum_{p}(-)^{p}P\\prod_{i=1}^{N}\\psi_{\\alpha_{i}}(x_{i}).\n$$\n\nwhere $P$ is an operator which permutes the coordinates of two particles. We have assumed here that the \nnumber of particles is the same as the number of available single-particle states, represented by the\ngreek letters $\\alpha_{1}\\alpha_{2}\\dots\\alpha_{N}$.\n\n\n**a)**\nWrite out $\\Phi^{AS}$ for $N=3$.\n\n**b)**\nShow that\n\n$$\n\\int dx_{1}dx_{2}\\dots dx_{N}\\left\\vert\n\\Phi_{\\lambda}^{AS}(x_{1}x_{2}\\dots x_{N};\\alpha_{1}\\alpha_{2}\\dots\\alpha_{N})\n\\right\\vert^{2} = 1.\n$$\n\n**c)**\nDefine a general onebody operator $\\hat{F} = \\sum_{i}^N\\hat{f}(x_{i})$ and a general twobody operator $\\hat{G}=\\sum_{i>j}^N\\hat{g}(x_{i},x_{j})$ with $g$ being invariant under the interchange of the coordinates of particles $i$ and $j$. Calculate the matrix elements for a two-particle Slater determinant\n\n$$\n\\langle\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}|\\hat{F}|\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}\\rangle,\n$$\n\nand\n\n$$\n\\langle\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}|\\hat{G}|\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}\\rangle.\n$$\n\nExplain the short-hand notation for the Slater determinant.\nWhich properties do you expect these operators to have in addition to an eventual permutation\nsymmetry?\n\n\n\n\n\n\n\n\n## Exercise 4: First simple shell-model calculation\n\nWe will now consider a simple three-level problem, depicted in the figure below. This is our first and very simple model of a possible many-nucleon (or just fermion) problem and the shell-model.\nThe single-particle states are labelled by the quantum number $p$ and can accomodate up to two single particles, viz., every single-particle state is doubly degenerate (you could think of this as one state having spin up and the other spin down). \nWe let the spacing between the doubly degenerate single-particle states be constant, with value $d$. The first state\nhas energy $d$. There are only three available single-particle states, $p=1$, $p=2$ and $p=3$, as illustrated\nin the figure.\n\n\n**a)**\nHow many two-particle Slater determinants can we construct in this space?\nWe limit ourselves to a system with only the two lowest single-particle orbits and two particles, $p=1$ and $p=2$. We assume that we can write the Hamiltonian as\n\n$$\n\\hat{H}=\\hat{H}_0+\\hat{H}_I,\n$$\n\nand that the onebody part of the Hamiltonian with single-particle operator $\\hat{h}_0$ has the property\n\n$$\n\\hat{h}_0\\psi_{p\\sigma} = p\\times d \\psi_{p\\sigma},\n$$\n\nwhere we have added a spin quantum number $\\sigma$. \nWe assume also that the only two-particle states that can exist are those where two particles are in the \nsame state $p$, as shown by the two possibilities to the left in the figure.\nThe two-particle matrix elements of $\\hat{H}_I$ have all a constant value, $-g$.\n\n**b)**\nShow then that the Hamiltonian matrix can be written as\n\n$$\n\\left(\\begin{array}{cc}2d-g &-g \\\\\n-g &4d-g \\end{array}\\right),\n$$\n\n**c)**\nFind the eigenvalues and eigenvectors. What is mixing of the state with two particles in $p=2$ to the wave function with two-particles in $p=1$? Discuss your results in terms of a linear combination of Slater determinants.\n\n**d)**\nAdd the possibility that the two particles can be in the state with $p=3$ as well and find the Hamiltonian matrix, the eigenvalues and the eigenvectors. We still insist that we only have two-particle states composed of two particles being in the same level $p$. You can diagonalize numerically your $3\\times 3$ matrix.\n\nThis simple model catches several birds with a stone. It demonstrates how we can build linear combinations\nof Slater determinants and interpret these as different admixtures to a given state. It represents also the way we are going to interpret these contributions. The two-particle states above $p=1$ will be interpreted as \nexcitations from the ground state configuration, $p=1$ here. The reliability of this ansatz for the ground state, \nwith two particles in $p=1$,\ndepends on the strength of the interaction $g$ and the single-particle spacing $d$.\nFinally, this model is a simple schematic ansatz for studies of pairing correlations and thereby superfluidity/superconductivity \nin fermionic systems. \n\n\n\n\n

Schematic 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\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 \n \n \n \n \n \n \n \n \n
clusterxy
00410
10710
2048
3068
4034
50105
60126
70114
8022
9052
10093
110123
\n
\n\n\n\n\n```python\nlogger.setLevel('WARN')\nclass k_means_cluster():\n def __init__(self, max_itier=15):\n self.max_itier = max_itier\n \n def pick_init_points(self, df_points, k):\n df_clusters = df_points.sample(k, axis=0)\n df_clusters.reset_index(drop=True, inplace=True)\n df_clusters['cluster'] = df_clusters.index\n return df_clusters\n \n def assign_point_to_cluster(self, point, df_clusters):\n from scipy.spatial.distance import cdist\n logger.info('\\n point:{}\\n df_clusters:{}'.format(point, df_clusters))\n \n p = point[['x','y']].to_frame().T\n c = df_clusters.loc[:,['x','y']]\n logger.info('\\n p:{}\\n c:{}'.format(p, c))\n \n dist = cdist(p, c)\n logger.info('dist:{}'.format(dist))\n \n cluster = np.argmin(dist)\n logger.info('cluster:{}'.format(cluster))\n \n return pd.Series([cluster, point.x, point.y], index=['cluster', 'x', 'y'])\n \n def calc_centriod(self, df_points):\n centroid = df_points.groupby('cluster').mean()\n logger.info('\\n centroid:\\n{}'.format(centroid))\n return centroid\n \n def cluster(self, df_points, k):\n df_clusters = self.pick_init_points(df_points, k)\n \n for _ in xrange(self.max_itier): \n df_points = df_points.apply(self.assign_point_to_cluster, args=(df_clusters,), axis=1)\n logger.info('iter: \\n df_points:\\n{}'.format(df_points))\n clusters = self.calc_centriod(df_points)\n \n #todo: stop condition\n \n df_clusters = clusters\n \n return df_points, df_clusters\n \n \n \ntest = k_means_cluster()\nk = 3\ncluster_colors = sns.color_palette(\"hls\", k)\ndf_points_res, df_clusters_res = test.cluster(df_points, k)\nplt.scatter(df_points_res.x, df_points_res.y, c=map(lambda x: cluster_colors[x], df_points_res.cluster.astype(np.int)))\n```\n\n#### 7.3.4 The Algorithm of Bradley, Fayyad, and Reina\ndesigned to cluster data in a *high-dimensional* Euclidean space.\n\nstrong assumption about the shape of clusters:\n\n1. normally distributed about a centriod.\n\n2. the dimensions must be independent.\n\n\n```python\nplt.imshow(plt.imread('./res/fig7_10.png'))\n```\n\nThe points of the data file are read in chunks.\n\nThe main-memory data other than the chunk consists of three types of objects:\n\n1. The Discard Set: \n simple summaries of the clusters themselves.\n\n2. The Compressed Set: \n summaries of the points that have been found close to one another, but not close to any cluster. Each represented set of points is called a *minicluster*.\n\n3. The Retained Set: \n remaining points.\n\n\n```python\nplt.imshow(plt.imread('./res/fig7_11.png'))\n```\n\nThe discard and compressed sets are represented by $2d + 1$ values, if the data is $d$-dimensional. \nThese numbers are:\n\n+ The number of points represented, $N$.\n\n+ The sum of the components of all the points in each dimension. a vector $SUM$ of length $d$.\n\n+ The sum of the squares of the components of all the points in each dimension. a vector $SUMSQ$ of length $d$.\n\nOur real goal is to represent a set of points by their count, their centroid and the standard deviation in each dimension.\n\n+ count: $N$.\n\n+ centriod: $SUM_i / N$.\n\n+ standard deviation: $SUMSQ_i / N - (SUM_i / N)^2$\n\n#### 7.3.5 Processing Data in the BFR algorithm\n1. First, all points that are sufficiently close to the centriod of a cluster are added to that cluster, **Discard Set**.\n\n2. For the points that are not sufficiently close to any centriod, we cluster them, along with the points in the retained set. \n + Clusters of more than one point are summarized and added to the **Compressed Set**. \n + Singleton clusters become the **Retained Set** of points.\n \n3. Merge minicusters of compressed set if possible.\n\n4. Points of discard and compressed set are written out to secondary memory.\n\n5. Finally, if this is the last chunk of input data, we need do something with the compressed and retained set. \n + Treat them as outliers. \n + Assign them to the nearest cluster. \n + Combine minclusters of compressed set.\n \n##### How to decide whether a new point $p$ is close enough to a cluster?\n1. Add $p$ to a cluster if it not only has the centriod closest to $p$, but it is very unlikely that, after all the points have been processed, some other cluster centriod will be found to be nearer to $p$. \n complex statiscal calculation. \n \n2. We can measure the probability that, if $p$ belongs to a cluster, it would be found as far as it is from the centriod of that cluster. \n normally distributed, independent $\\to$ **Mahalanobis distance**: \n Let $p = [p_1, p_2, \\dotsc, p_d]$ be a point and $c = [c_1, c_2, \\dotsc, c_d]$ be the centriod of a cluster.\n $$\\sqrt{\\sum_{i=1}^{d} ( \\frac{p_i - c_i}{\\sigma_i} )^2 }$$\n \n We choose that cluster whose centriod has the least Mahalanobis distance, and we add $p$ to that cluster provided the Mahalanobis distance is less than a threshold. 概率论上足够接近。\n\n#### 7.3.6 Exercises for Section 7.3\n`#todo`\n\n### 7.4 The CURE Algorithm\nCURE(Clustering Using REpresentatives)\n\n1. assumes a Euclidean space\n\n2. it does not assume anything about the shape of clusters.\n\nProcess:(key factor: fixed fraction for moving and how close is sufficient to merge).\n\n1. Initialization \n 1. Sample, and then cluster. \n Hierarchial clustering is advisable. \n \n 2. pick a subset as **representative points**(as far from one another as possible in the same cluster).\n \n 3. Move each of the representative poins a **fixed fraction** of the distance between its location and the centriod of its cluster. (Euclidean space).\n \n2. Merge: if two clusters have a pair of representative points that are **sufficiently close**. \n Repeat until convergence.\n \n3. Point assignment: \n We assign $p$ to the cluster of the representative point that is closest to $p$.\n\n\n```python\nplt.figure(figsize=(10,5))\nplt.imshow(plt.imread('./res/fig7_12.png'))\nplt.figure(figsize=(12,5))\nplt.imshow(plt.imread('./res/fig7_13.png'))\nplt.figure(figsize=(12,5))\nplt.imshow(plt.imread('./res/fig7_14.png'))\n```\n\n#### 7.4.3 Exercises for Section 7.4\n`#todo`\n\n### 7.5 Clustering in Non-Euclidean Spaces\nGRGPF algorithm:\n\n1. sample $\\to$ handles non-main-memory data.\n\n2. hierarchical: B-tree \n leaves: summaries of some clustes. \n interior nodes: subsets of the information describing the clusters reachable through that node.\n\n3. point-assignment.\n\n#### 7.5.1 Representing Clusters\nThe following features form the representation of a cluster.\n\n1. $N$, the number of points in the cluster.\n\n2. The clustroid of the cluster and its ROWSUM: $\\sum_{p_i \\in C} \\| p - p_i \\|_2$\n\n3. $k$ points that are closest to the clustroid, and their rowsums. \n assumption: new clustriod would be one of them.\n\n4. $k$ points that are furthest from the clustroid, and their rowsums. \n assumption: if two clusters are close, then a pair of points distant from their respective clustriods would be close.\n\n#### 7.5.2 Initializing the Cluster Tree\nEach leaf of the tree holds as many cluster representations as can fit $\\to$ B-tree or R-tree.\n\nAn interior node of the cluster tree holds a sample of the clustroids of its subtrees.\n\ninit:\n\n1. taking a main-memory sample and clustering it hierarchically $\\to$ a tree $T$.\n\n2. selecting from $T$ certain of its points that represent clusters of approximately some disired size $n$ $\\to$ the **leaf** of the cluster-representing tree.\n\n3. grouping clusters with a commom ancestor in $T$ into **interior nodes**. \n rebalancing, similar to the reorganization of a B-tree.\n\n#### 7.5.3 Adding Points in the GRGPF Algorithm\nFrom root to a leaf, we always choose the node closest to the new point $p$.\n\nFinally,, we pick the cluster whose clustriod is closest to $p$. then: \n\n1. Add 1 to $N$.\n\n2. Add $d(p,q)$ to sumrows of all $q$ that are in the cluster before.\n\n3. estimate: $$ROWSUM(p) = ROWSUM(c) + N d^2(p,c)$$\n\n4. if $p$ is one of the $k$ closest or furthest points from the clustroid, then replacing one. \n if $p$ is closer to other points than the clustroid, then replacing it.\n \nit is possible that the true clustroid will no longer be one of the original $k$ closest points $\\to$ brought data on disk into main memory periodically for a recomputation of the cluster featrues.\n\n#### 7.5.4 Splitting and Merging Clusters\n##### split\nThe GRGPF Algorithm assumes that there is a limit on the radius ($\\sqrt(ROWSUM(c)/N)$). \n\nIf a cluster's radius grows too large $\\to$ split it into two. As in a B-tree, this splitting can ripple all the way up to the root.\n\n##### merge\nIf the tree is too large to fit in main memory, we raise the limit on the radius and consider merging pairs of clusters. and then:\n\n+ recalculate all rowsums: \n for $p \\in c_1$, $c_1 \\cap c_2 = C$: \n $$ROWSUM_c(p) = ROWSUM_{c_1}(p) + N_{c_2} (d^2(p,c_1) + d^2(c_1,c_2)) + ROWSUM_{c_2}(c_2) $$\n\n+ filter the new clustriod and $k$ closest points, $k$ furthest points from orginal $4k+1$ features of $c_1$ and $c_2$.\n\n`#todo: exercise`\n\n### 7.6 Clustering for Streams and Parallelism\n#### 7.6.1 The Stream-Computin Model\nN-points sliding window\n\nwe make no restriction regarding the space of point.\n\nwe assumes that the statistics of the stream elements varies with time, because sampling is good for constant statistics.\n\n#### 7.6.2 A Streaming-Clustering Algorithm\nSimplified BDMO Algorithm that builds on the methodology for counting ones in a steam in Sec. 4.6\n\nBucket:\n\n1. its size is the number of points.\n\n2. its size obey the restriction that there are one or two of each size, up to some limit. And the sequence of allowable bucket size does not need start with 1, but each size is twice the previous size.\n\n3. all sizes: nondecreasing as we go back in time.\n\n4. The contents: \n\n + The size.\n \n + The timestamp.\n \n + A collection of records after clustering:\n \n - the number of points in the cluster.\n \n - the centriod.\n \n - Any other parameters necessary.\n\n#### 7.6.3 Initializing Buckets\nsmallest bucket size $p$, a power of 2.\n\nevery $p$ stream elements arrived, we create a new bucket, and then cluster them.\n\n#### 7.6.4 Mergin Buckets\n1. drop the out-date buckets (go beyong $N$ points).\n\n2. merge buckets if there are three identical size.\n\nThree examples:\n\n1. k-means approach in a Euclidean space. \n assumption: the cluster are changing very slowly.\n \n2. expect the cluster centriods to migrate sufficiently quickly. \n create more than $k$ clusters in each bucket.\n \n3. non-Euclidean space and no constrain on the number of clusters. \n like GRGPF Algorithm.\n\n#### 7.6.5 Ansering Queries\nQuestion about the most recent $m$ points in the stream.\n\n###### Answer\nchoose the smallest set of buckets that cover the last $m$ points. (Always less than $2m$). \n\n+ assume that the points between $2m$ and $m+1$ will not affect the result.\n\n+ Or use a more complex bucketing shceme in Sec 4.6.6 to cover at most the last $m(1+\\epsilon)$.\n\nthen pool all their clusters in the clusters and merge them.\n\n#### 7.6.6 Clustering in a Parallel Environment\n1. Create many Map tasks. \n Each task is assigned a subset of the points, and cluster them.\n \n2. only one Reduce task. \n merge the clusters produced by Map tasks.\n\n`#todo: exercise`\n", "meta": {"hexsha": "8b53c621357ffe5397e297f26cfab0ef5bd77361", "size": 652844, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mining_of_Massive_Datasets/Clustering/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "Mining_of_Massive_Datasets/Clustering/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "Mining_of_Massive_Datasets/Clustering/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 442.0067704807, "max_line_length": 116284, "alphanum_fraction": 0.9215248972, "converted": true, "num_tokens": 6349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478896, "lm_q2_score": 0.2254166262422842, "lm_q1q2_score": 0.07939213746575557}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\nimport math\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sympy\n```\n\n# High-School Maths Exercise\n## Getting to Know Jupyter Notebook. Python Libraries and Best Practices. Basic Workflow\n\n### Problem 1. Markdown\nJupyter Notebook is a very light, beautiful and convenient way to organize your research and display your results. Let's play with it for a while.\n\nFirst, you can double-click each cell and edit its content. If you want to run a cell (that is, execute the code inside it), use Cell > Run Cells in the top menu or press Ctrl + Enter.\n\nSecond, each cell has a type. There are two main types: Markdown (which is for any kind of free text, explanations, formulas, results... you get the idea), and code (which is, well... for code :D).\n\nLet me give you a...\n#### Quick Introduction to Markdown\n##### Text and Paragraphs\nThere are several things that you can do. As you already saw, you can write paragraph text just by typing it. In order to create a new paragraph, just leave a blank line. See how this works below:\n```\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n```\n**Result:**\n\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n\n##### Headings\nThere are six levels of headings. Level one is the highest (largest and most important), and level 6 is the smallest. You can create headings of several types by prefixing the header line with one to six \"#\" symbols (this is called a pound sign if you are ancient, or a sharp sign if you're a musician... or a hashtag if you're too young :D). Have a look:\n```\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n```\n\n**Result:**\n\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n\nIt is recommended that you have **only one** H1 heading - this should be the header of your notebook (or scientific paper). Below that, you can add your name or just jump to the explanations directly.\n\n##### Emphasis\nYou can create emphasized (stonger) text by using a **bold** or _italic_ font. You can do this in several ways (using asterisks (\\*) or underscores (\\_)). In order to \"escape\" a symbol, prefix it with a backslash (\\). You can also strike thorugh your text in order to signify a correction.\n```\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not \\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n```\n\n**Result:**\n\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not\\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n\n##### Lists\nYou can add two types of lists: ordered and unordered. Lists can also be nested inside one another. To do this, press Tab once (it will be converted to 4 spaces).\n\nTo create an ordered list, just type the numbers. Don't worry if your numbers are wrong - Jupyter Notebook will create them properly for you. Well, it's better to have them properly numbered anyway...\n```\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n```\n\n**Result:**\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n \nTo create an unordered list, type an asterisk, plus or minus at the beginning:\n```\n* This is\n* An\n + Unordered\n - list\n```\n\n**Result:**\n* This is\n* An\n + Unordered\n - list\n \n##### Links\nThere are many ways to create links but we mostly use one of them: we present links with some explanatory text. See how it works:\n```\nThis is [a link](http://google.com) to Google.\n```\n\n**Result:**\n\nThis is [a link](http://google.com) to Google.\n\n##### Images\nThey are very similar to links. Just prefix the image with an exclamation mark. The alt(ernative) text will be displayed if the image is not available. Have a look (hover over the image to see the title text):\n```\n Do you know that \"taco cat\" is a palindrome? Thanks to The Oatmeal :)\n```\n\n**Result:**\n\n Do you know that \"taco cat\" is a palindrome? Thanks to The Oatmeal :)\n\nIf you want to resize images or do some more advanced stuff, just use HTML. \n\nDid I mention these cells support HTML, CSS and JavaScript? Now I did.\n\n##### Tables\nThese are a pain because they need to be formatted (somewhat) properly. Here's a good [table generator](http://www.tablesgenerator.com/markdown_tables). Just select File > Paste table data... and provide a tab-separated list of values. It will generate a good-looking ASCII-art table for you.\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**Result:**\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##### Code\nJust use triple backtick symbols. If you provide a language, it will be syntax-highlighted. You can also use inline code with single backticks.\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 my first markdown try

\n

I'll do my best to make it structured

\n

Let's test all the headings

\n

Three left

\n
Two left
\n
Aaaaand the last one
\n\n

Now let's see what is this thing called paragraph. Hmmm looks interesting.

\n\n

Actually I can put new lines and new paragraphs.
Awsome!

\n\n

Let's see how we can put image to our first try with Markdown.

\n\n\n

Now 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

\n
Now let's try some lists data
\n
    \n
  1. Coffee
  2. \n
  3. Sugar
  4. \n
      \n
    • Chocolate
    • \n
    • Waffles
    • \n
    • Biscuits
    • \n
    \n
  5. Bread
  6. \n
\n

And some code format:

\n \n```python\n for i in range(1, 10):\n print(i)\n```\n\n

And some code inline format:

\n\nThis is called anonymous function: `lambda s: s + 1` in python.\n\n

Let's see what is a link - Software University

\n

Sample table example:

\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
CompanyContactCountry
Alfreds FutterkisteMaria AndersGermany
Centro comercial MoctezumaFrancisco ChangMexico
Ernst HandelRoland MendelAustria
Island TradingHelen BennettUK
Laughing Bacchus WinecellarsYoshi TannamuriCanada
Magazzini Alimentari RiunitiGiovanni RovelliItaly
\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\nEquation of a line: $$y=ax + b$$\nRoots of the quadric equation $ax^2+bx+c=0$: $$\\begin{array}{*{20}c} {x_{1,2} = \\large{\\frac{{ - b \\pm \\sqrt {b^2 - 4ac} }}{{2a}}}} \\\\ \\end{array}$$\n\nTaylor series expansion: $$f(x)|_{x=a} = f(a) + f^\\prime(a)(x-a)+\\frac{f^n(a)}{2!}(x-a)^2+\\dots+\\frac{f^{(n)}(a)}{n!}(x-a)^n+\\dots$$\nBinominal theorem: $$(x+y)^n=\\binom{n}{0}x^ny^0+\\binom{n}{1}x^{n-1}y^1+\\dots+\\binom{n}{n}x^0y^n=\\sum^n_{k=0}\\binom{n}{k}x^{n-k}y^k$$\nAn integral: $$\\normalsize{\\int^{+\\infty}_{-\\infty}e^{-x^2}dx = \\sqrt {\\pi}}$$\nA short matrix: $$\\begin{pmatrix}\n2 & 1 & 3\\\\\n2 & 6 & 8\\\\\n6 & 8 & 18\n\\end{pmatrix}$$\nA long matrix: $$A = \\begin{pmatrix}\na_{11} & a_{12} & \\dots & a_{1n}\\\\\na_{21} & a_{22} & \\dots & a_{2n}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\na_{m1} & a_{m2} & \\dots & a_{mn}\\\\\n\\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\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\nsympy.init_printing()\nx = sympy.symbols('x')\na, b, c = sympy.symbols('a b c')\nsympy.solve(a * x**2 + b*x + c)\nsympy.solve(a * x**2 + b*x + c, x)\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\ndef solve_quadratic_equation(a, b, c):\n \"\"\"\n Returns the real solutions of the quadratic equation ax^2 + bx + c = 0\n \"\"\"\n solution_check = b ** 2 - 4 * a * c \n if a != 0:\n if solution_check > 0: \n x1 = (-b + math.sqrt(-4 * a * c + b ** 2)) / (2 * a)\n x2 = -(b + math.sqrt(-4 * a * c + b ** 2)) / (2 * a)\n return [x2, x1]\n elif solution_check == 0: \n x = -b / (2 * a)\n return [x]\n else: \n return []\n else:\n if solution_check > 0: \n x = -(c / b)\n return [x]\n \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)) # []\nprint(solve_quadratic_equation(0, 2, 3)) # [-1.5]\n```\n\n [-1.0, 2.0]\n [4.0]\n []\n [-1.5]\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\ndef center_spines(ax, centerx=0, centery=0):\n \"\"\"Centers the axis spines at on the axis 'ax' \"\"\"\n\n # Set the axis's spines to be centered at the given point\n # (Setting all 4 spines so that the tick marks go in both directions)\n ax.spines['left'].set_position(('data', centerx))\n ax.spines['bottom'].set_position(('data', centery))\n ax.spines['right'].set_position(('data', centerx - 1))\n ax.spines['top'].set_position(('data', centery - 1))\n\n # Hide the line (but not ticks) for \"extra\" spines\n for side in ['right', 'top']:\n ax.spines[side].set_color('none')\n\n # On both the x and y axes\n for axis, center in zip([ax.xaxis, ax.yaxis], [centerx, centery]):\n # Hide the ticklabels at \n formatter = CenteredFormatter()\n formatter.center = center\n axis.set_major_formatter(formatter)\n\n # Add offset ticklabels at using annotation\n # (Should probably make these update when the plot is redrawn...)\n xlabel, ylabel = map(formatter.format_data, [centerx, centery])\n ax.annotate('%s' % xlabel, (centerx, centery),\n xytext=(-2, -4), textcoords='offset points',\n ha='right', va='top')\n\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n# Custom formatter\nclass CenteredFormatter(mpl.ticker.ScalarFormatter):\n \"\"\"Acts exactly like the default Scalar Formatter, but yields an empty\n label for ticks at \"center\".\"\"\"\n center = 0\n def __call__(self, value, pos=None):\n if value == self.center:\n return ''\n else:\n return mpl.ticker.ScalarFormatter.__call__(self, value, pos)\n```\n\n\n```python\ndef get_plot_graph(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.plot(x, y)\n plt.xticks(np.arange(-10, 13, 2))\n plt.yticks(np.arange(-10, 13, 2))\n ax.set_aspect('equal')\n center_spines(ax)\n return plt.show()\n\nx = np.linspace(-3, 5, 1000)\ny = 2 * x + 3\nget_plot_graph(x, y)\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(ae^{bx}) \\\\\nln(y) = ln(a) + ln(e^{bx}) \\\\ \nln(y) = bx + ln(a) \\\\ \nP = bx + Q$$\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 x = np.linspace(min_x, max_x, num_points)\n y = f(x)\n return get_plot_graph(x, y)\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 x = np.linspace(min_x, max_x, num_points) \n vectorized_fs = [np.vectorize(f) for f in functions]\n ys = [vectorized_f(x) for vectorized_f in vectorized_fs]\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 for y in ys:\n plt.plot(x, y)\n plt.xticks(np.arange(-6, 13, 2))\n plt.yticks(np.arange(-6, 13, 2))\n ax.set_aspect('equal')\n center_spines(ax)\n return 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. Use `numpy` (look up how to use inverse trigonometric functions).\n\n\n```python\ndef plot_math_functions(x, ys, labels):\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 for i in range(len(ys)):\n y = ys[i]\n plt.plot(x, y, label = labels[i])\n plt.xticks(np.arange(-2, 2, 0.5))\n plt.yticks(np.arange(-3, 5, 0.5))\n #ax.set_aspect('equal')\n center_spines(ax)\n plt.title(\"Inverse Trigonometric Functions\")\n plt.legend(loc='lower right')\n return plt.show()\ndef plot_inverse_trigonoetric_function(min_x, max_x, num_points):\n x = np.linspace(min_x, max_x, num_points)\n labels = ['arcsin', 'arccos', 'arctan', 'arccot']\n ys = [np.arcsin(x), np.arccos(x), np.arctan(x), np.pi/2-np.arctan(x)]\n return plot_math_functions(x, ys, labels)\n```\n\n\n```python\nplot_inverse_trigonoetric_function(-1, 1, 10000)\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": "22c883c6dfbb12fce9cc20893e7771f6a73471e2", "size": 159846, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "high_school_maths/High-School Maths Exercise.ipynb", "max_stars_repo_name": "PetkoAndreev/Python-Math-Concepts-For-Developers", "max_stars_repo_head_hexsha": "756639ff35bc81e1050f850dd30e76948da290d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-27T07:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T07:57:24.000Z", "max_issues_repo_path": "high_school_maths/High-School Maths Exercise.ipynb", "max_issues_repo_name": "PetkoAndreev/Python-Math-Concepts-For-Developers", "max_issues_repo_head_hexsha": "756639ff35bc81e1050f850dd30e76948da290d9", "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_school_maths/High-School Maths Exercise.ipynb", "max_forks_repo_name": "PetkoAndreev/Python-Math-Concepts-For-Developers", "max_forks_repo_head_hexsha": "756639ff35bc81e1050f850dd30e76948da290d9", "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": 146.782369146, "max_line_length": 23348, "alphanum_fraction": 0.8544849418, "converted": true, "num_tokens": 9142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056014026228, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.0791891125007718}} {"text": "\n \n \n
\n prepared by Abuzer Yakaryilmaz (QLatvia) and
Maksim Dimitrijev(QLatvia) \n
\n\n
This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros.
\n$\\newcommand{\\bra}[1]{\\langle #1|}$\n$ \\newcommand{\\ket}[1]{|#1\\rangle} $\n$ \\newcommand{\\braket}[2]{\\langle #1|#2\\rangle} $\n$ \\newcommand{\\dot}[2]{ #1 \\cdot #2} $\n$ \\newcommand{\\biginner}[2]{\\left\\langle #1,#2\\right\\rangle} $\n$ \\newcommand{\\mymatrix}[2]{\\left( \\begin{array}{#1} #2\\end{array} \\right)} $\n$ \\newcommand{\\myvector}[1]{\\mymatrix{c}{#1}} $\n$ \\newcommand{\\myrvector}[1]{\\mymatrix{r}{#1}} $\n$ \\newcommand{\\mypar}[1]{\\left( #1 \\right)} $\n$ \\newcommand{\\mybigpar}[1]{ \\Big( #1 \\Big)} $\n$ \\newcommand{\\sqrttwo}{\\frac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\dsqrttwo}{\\dfrac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\onehalf}{\\frac{1}{2}} $\n$ \\newcommand{\\donehalf}{\\dfrac{1}{2}} $\n$ \\newcommand{\\hadamard}{ \\mymatrix{rr}{ \\sqrttwo & \\sqrttwo \\\\ \\sqrttwo & -\\sqrttwo }} $\n$ \\newcommand{\\vzero}{\\myvector{1\\\\0}} $\n$ \\newcommand{\\vone}{\\myvector{0\\\\1}} $\n$ \\newcommand{\\vhadamardzero}{\\myvector{ \\sqrttwo \\\\ \\sqrttwo } } $\n$ \\newcommand{\\vhadamardone}{ \\myrvector{ \\sqrttwo \\\\ -\\sqrttwo } } $\n$ \\newcommand{\\myarray}[2]{ \\begin{array}{#1}#2\\end{array}} $\n$ \\newcommand{\\X}{ \\mymatrix{cc}{0 & 1 \\\\ 1 & 0} } $\n$ \\newcommand{\\Z}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & -1} } $\n$ \\newcommand{\\Htwo}{ \\mymatrix{rrrr}{ \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} } } $\n$ \\newcommand{\\CNOT}{ \\mymatrix{cccc}{1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 0} } $\n$ \\newcommand{\\norm}[1]{ \\left\\lVert #1 \\right\\rVert } $\n$ \\newcommand{\\pstate}[1]{ \\lceil \\mspace{-1mu} #1 \\mspace{-1.5mu} \\rfloor } $\n\n# Qiskit, Qutip installation and test\n\n\n
\n\n## Install Qiskit\n\nYou can install Qiskit by executing the following cell.\n\n\n```python\n!pip install \"qiskit[visualization]\" --user\n```\n\n Requirement already satisfied: qiskit[visualization] in /home/dev/.local/lib/python3.8/site-packages (0.28.0)\n Requirement already satisfied: qiskit-ignis==0.6.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (0.6.0)\n Requirement already satisfied: qiskit-terra==0.18.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (0.18.0)\n Requirement already satisfied: qiskit-ibmq-provider==0.15.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (0.15.0)\n Requirement already satisfied: qiskit-aqua==0.9.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (0.9.4)\n Requirement already satisfied: qiskit-aer==0.8.2 in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (0.8.2)\n Requirement already satisfied: ipywidgets>=7.3.0; extra == \"visualization\" in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (7.6.3)\n Requirement already satisfied: pylatexenc>=1.4; extra == \"visualization\" in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (2.10)\n Requirement already satisfied: pydot; extra == \"visualization\" in /usr/lib/python3/dist-packages (from qiskit[visualization]) (1.4.1)\n Requirement already satisfied: pillow>=4.2.1; extra == \"visualization\" in /usr/lib/python3/dist-packages (from qiskit[visualization]) (7.0.0)\n Requirement already satisfied: matplotlib>=2.1; extra == \"visualization\" in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (3.4.2)\n Requirement already satisfied: seaborn>=0.9.0; extra == \"visualization\" in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (0.11.1)\n Requirement already satisfied: pygments>=2.4; extra == \"visualization\" in /home/dev/.local/lib/python3.8/site-packages (from qiskit[visualization]) (2.9.0)\n Requirement already satisfied: numpy>=1.13 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ignis==0.6.0->qiskit[visualization]) (1.21.0)\n Requirement already satisfied: setuptools>=40.1.0 in /usr/lib/python3/dist-packages (from qiskit-ignis==0.6.0->qiskit[visualization]) (45.2.0)\n Requirement already satisfied: retworkx>=0.8.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ignis==0.6.0->qiskit[visualization]) (0.9.0)\n Requirement already satisfied: scipy!=0.19.1,>=0.19 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ignis==0.6.0->qiskit[visualization]) (1.7.0)\n Requirement already satisfied: ply>=3.10 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (3.11)\n Requirement already satisfied: fastjsonschema>=2.10 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (2.15.1)\n Requirement already satisfied: tweedledum<2.0,>=1.1 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (1.1.0)\n Requirement already satisfied: sympy>=1.3 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (1.8)\n Requirement already satisfied: psutil>=5 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (5.8.0)\n Requirement already satisfied: python-dateutil>=2.8.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (2.8.2)\n Requirement already satisfied: jsonschema>=2.6 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (3.2.0)\n Requirement already satisfied: python-constraint>=1.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (1.4.0)\n Requirement already satisfied: symengine>0.7; platform_machine == \"x86_64\" or platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"amd64\" or platform_machine == \"arm64\" in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (0.7.2)\n Requirement already satisfied: dill>=0.3 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit[visualization]) (0.3.4)\n Requirement already satisfied: websocket-client>=1.0.1 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.15.0->qiskit[visualization]) (1.1.0)\n Requirement already satisfied: requests-ntlm>=1.1.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.15.0->qiskit[visualization]) (1.1.0)\n Requirement already satisfied: requests>=2.19 in /usr/lib/python3/dist-packages (from qiskit-ibmq-provider==0.15.0->qiskit[visualization]) (2.22.0)\n Requirement already satisfied: urllib3>=1.21.1 in /usr/lib/python3/dist-packages (from qiskit-ibmq-provider==0.15.0->qiskit[visualization]) (1.25.8)\n Requirement already satisfied: scikit-learn>=0.20.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (0.24.2)\n Requirement already satisfied: h5py<3.3.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (3.2.1)\n Requirement already satisfied: yfinance<0.1.63 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (0.1.62)\n Requirement already satisfied: dlx<=1.0.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (1.0.4)\n Requirement already satisfied: docplex>=2.21.207 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (2.21.207)\n Requirement already satisfied: pandas in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (1.3.0)\n Requirement already satisfied: fastdtw<=0.3.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (0.3.4)\n Requirement already satisfied: quandl in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit[visualization]) (3.6.1)\n Requirement already satisfied: pybind11>=2.6 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aer==0.8.2->qiskit[visualization]) (2.7.0)\n Requirement already satisfied: ipython>=4.0.0; python_version >= \"3.3\" in /home/dev/.local/lib/python3.8/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (7.25.0)\n Requirement already satisfied: traitlets>=4.3.1 in /home/dev/.local/lib/python3.8/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.0.5)\n Requirement already satisfied: nbformat>=4.2.0 in /home/dev/.local/lib/python3.8/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.1.3)\n Requirement already satisfied: jupyterlab-widgets>=1.0.0; python_version >= \"3.6\" in /home/dev/.local/lib/python3.8/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.0.0)\n Requirement already satisfied: widgetsnbextension~=3.5.0 in /home/dev/.local/lib/python3.8/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.5.1)\n Requirement already satisfied: ipykernel>=4.5.1 in /home/dev/.local/lib/python3.8/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.0.1)\n Requirement already satisfied: cycler>=0.10 in /home/dev/.local/lib/python3.8/site-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (0.10.0)\n Requirement already satisfied: pyparsing>=2.2.1 in /home/dev/.local/lib/python3.8/site-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (2.4.7)\n Requirement already satisfied: kiwisolver>=1.0.1 in /home/dev/.local/lib/python3.8/site-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (1.3.1)\n Requirement already satisfied: mpmath>=0.19 in /home/dev/.local/lib/python3.8/site-packages (from sympy>=1.3->qiskit-terra==0.18.0->qiskit[visualization]) (1.2.1)\n Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.18.0->qiskit[visualization]) (1.14.0)\n Requirement already satisfied: pyrsistent>=0.14.0 in /home/dev/.local/lib/python3.8/site-packages (from jsonschema>=2.6->qiskit-terra==0.18.0->qiskit[visualization]) (0.18.0)\n Requirement already satisfied: attrs>=17.4.0 in /home/dev/.local/lib/python3.8/site-packages (from jsonschema>=2.6->qiskit-terra==0.18.0->qiskit[visualization]) (21.2.0)\n Requirement already satisfied: ntlm-auth>=1.0.2 in /home/dev/.local/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.15.0->qiskit[visualization]) (1.5.0)\n Requirement already satisfied: cryptography>=1.3 in /usr/lib/python3/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.15.0->qiskit[visualization]) (2.8)\n Requirement already satisfied: threadpoolctl>=2.0.0 in /home/dev/.local/lib/python3.8/site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.4->qiskit[visualization]) (2.2.0)\n Requirement already satisfied: joblib>=0.11 in /home/dev/.local/lib/python3.8/site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.4->qiskit[visualization]) (1.0.1)\n Requirement already satisfied: lxml>=4.5.1 in /home/dev/.local/lib/python3.8/site-packages (from yfinance<0.1.63->qiskit-aqua==0.9.4->qiskit[visualization]) (4.6.3)\n Requirement already satisfied: multitasking>=0.0.7 in /home/dev/.local/lib/python3.8/site-packages (from yfinance<0.1.63->qiskit-aqua==0.9.4->qiskit[visualization]) (0.0.9)\n Requirement already satisfied: pytz>=2017.3 in /usr/lib/python3/dist-packages (from pandas->qiskit-aqua==0.9.4->qiskit[visualization]) (2019.3)\n Requirement already satisfied: more-itertools in /home/dev/.local/lib/python3.8/site-packages (from quandl->qiskit-aqua==0.9.4->qiskit[visualization]) (8.8.0)\n Requirement already satisfied: inflection>=0.3.1 in /home/dev/.local/lib/python3.8/site-packages (from quandl->qiskit-aqua==0.9.4->qiskit[visualization]) (0.5.1)\n Requirement already satisfied: pickleshare in /home/dev/.local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.5)\n Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /home/dev/.local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.0.19)\n Requirement already satisfied: backcall in /home/dev/.local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.0)\n Requirement already satisfied: jedi>=0.16 in /home/dev/.local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.18.0)\n Requirement already satisfied: decorator in /home/dev/.local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.4.2)\n Requirement already satisfied: matplotlib-inline in /home/dev/.local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.1.2)\n Requirement already satisfied: pexpect>4.3; sys_platform != \"win32\" in /usr/lib/python3/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.6.0)\n Requirement already satisfied: ipython-genutils in /home/dev/.local/lib/python3.8/site-packages (from traitlets>=4.3.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.0)\n Requirement already satisfied: jupyter-core in /home/dev/.local/lib/python3.8/site-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.7.1)\n Requirement already satisfied: notebook>=4.4.1 in /home/dev/.local/lib/python3.8/site-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.4.0)\n Requirement already satisfied: tornado>=4.2 in /home/dev/.local/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.1)\n Requirement already satisfied: debugpy>=1.0.0 in /home/dev/.local/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.3.0)\n Requirement already satisfied: jupyter-client in /home/dev/.local/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.1.12)\n Requirement already satisfied: wcwidth in /home/dev/.local/lib/python3.8/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.5)\n Requirement already satisfied: parso<0.9.0,>=0.8.0 in /home/dev/.local/lib/python3.8/site-packages (from jedi>=0.16->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.8.2)\n Requirement already satisfied: jinja2 in /home/dev/.local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.0.1)\n Requirement already satisfied: nbconvert in /home/dev/.local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.1.0)\n Requirement already satisfied: terminado>=0.8.3 in /home/dev/.local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.10.1)\n Requirement already satisfied: prometheus-client in /home/dev/.local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.11.0)\n Requirement already satisfied: pyzmq>=17 in /home/dev/.local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (22.1.0)\n Requirement already satisfied: argon2-cffi in /home/dev/.local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (20.1.0)\n Requirement already satisfied: Send2Trash>=1.5.0 in /home/dev/.local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.7.1)\n Requirement already satisfied: MarkupSafe>=2.0 in /home/dev/.local/lib/python3.8/site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (2.0.1)\n Requirement already satisfied: mistune<2,>=0.8.1 in /home/dev/.local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.8.4)\n Requirement already satisfied: entrypoints>=0.2.2 in /usr/lib/python3/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.3)\n Requirement already satisfied: bleach in /home/dev/.local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.3.0)\n Requirement already satisfied: defusedxml in /home/dev/.local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.1)\n Requirement already satisfied: jupyterlab-pygments in /home/dev/.local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.1.2)\n Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in /home/dev/.local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.5.3)\n Requirement already satisfied: testpath in /home/dev/.local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.5.0)\n Requirement already satisfied: pandocfilters>=1.4.1 in /home/dev/.local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.4.3)\n Requirement already satisfied: ptyprocess; os_name != \"nt\" in /home/dev/.local/lib/python3.8/site-packages (from terminado>=0.8.3->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.0)\n Requirement already satisfied: cffi>=1.0.0 in /home/dev/.local/lib/python3.8/site-packages (from argon2-cffi->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.14.6)\n Requirement already satisfied: packaging in /home/dev/.local/lib/python3.8/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (21.0)\n Requirement already satisfied: webencodings in /home/dev/.local/lib/python3.8/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.5.1)\n Requirement already satisfied: async-generator in /home/dev/.local/lib/python3.8/site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.10)\n Requirement already satisfied: nest-asyncio in /home/dev/.local/lib/python3.8/site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.5.1)\n Requirement already satisfied: pycparser in /home/dev/.local/lib/python3.8/site-packages (from cffi>=1.0.0->argon2-cffi->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (2.20)\n\n\n__*Restart the kernel*__ (check \"Kernel\" menu) to apply the changes to the current notebook.\n\nYou may also visit the following links for further information.\n\n- https://github.com/Qiskit/qiskit-tutorials/blob/master/INSTALL.md\n\n- https://pypi.org/project/qiskit/0.15.0/\n\n__*Restart the kernel*__ (check \"Kernel\" menu) to apply the changes to the current notebook.\n\n
\n\n### Tips\n\n_Any terminal/shell command can be executed in the notebook cells by putting exclamation mark (!) to the beginning of the command._\n\n_$\\rightarrow$ For updating Qiskit version, execute the following command on a code cell_\n\n !pip install -U qiskit --user\n \n_$\\rightarrow$ For uninstall Qiskit, execute the following command on a code cell_\n\n !pip uninstall qiskit\n\n\n```python\n!pip install -U qiskit --user\n#!pip uninstall qiskit\n```\n\n Requirement already up-to-date: qiskit in /home/dev/.local/lib/python3.8/site-packages (0.28.0)\n Requirement already satisfied, skipping upgrade: qiskit-ignis==0.6.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit) (0.6.0)\n Requirement already satisfied, skipping upgrade: qiskit-ibmq-provider==0.15.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit) (0.15.0)\n Requirement already satisfied, skipping upgrade: qiskit-aqua==0.9.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit) (0.9.4)\n Requirement already satisfied, skipping upgrade: qiskit-terra==0.18.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit) (0.18.0)\n Requirement already satisfied, skipping upgrade: qiskit-aer==0.8.2 in /home/dev/.local/lib/python3.8/site-packages (from qiskit) (0.8.2)\n Requirement already satisfied, skipping upgrade: scipy!=0.19.1,>=0.19 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ignis==0.6.0->qiskit) (1.7.0)\n Requirement already satisfied, skipping upgrade: numpy>=1.13 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ignis==0.6.0->qiskit) (1.21.0)\n Requirement already satisfied, skipping upgrade: retworkx>=0.8.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ignis==0.6.0->qiskit) (0.9.0)\n Requirement already satisfied, skipping upgrade: setuptools>=40.1.0 in /usr/lib/python3/dist-packages (from qiskit-ignis==0.6.0->qiskit) (45.2.0)\n Requirement already satisfied, skipping upgrade: websocket-client>=1.0.1 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.15.0->qiskit) (1.1.0)\n Requirement already satisfied, skipping upgrade: requests-ntlm>=1.1.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.15.0->qiskit) (1.1.0)\n Requirement already satisfied, skipping upgrade: python-dateutil>=2.8.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.15.0->qiskit) (2.8.2)\n Requirement already satisfied, skipping upgrade: requests>=2.19 in /usr/lib/python3/dist-packages (from qiskit-ibmq-provider==0.15.0->qiskit) (2.22.0)\n Requirement already satisfied, skipping upgrade: urllib3>=1.21.1 in /usr/lib/python3/dist-packages (from qiskit-ibmq-provider==0.15.0->qiskit) (1.25.8)\n Requirement already satisfied, skipping upgrade: pandas in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (1.3.0)\n Requirement already satisfied, skipping upgrade: quandl in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (3.6.1)\n Requirement already satisfied, skipping upgrade: docplex>=2.21.207 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (2.21.207)\n Requirement already satisfied, skipping upgrade: yfinance<0.1.63 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (0.1.62)\n Requirement already satisfied, skipping upgrade: dlx<=1.0.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (1.0.4)\n Requirement already satisfied, skipping upgrade: h5py<3.3.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (3.2.1)\n Requirement already satisfied, skipping upgrade: fastdtw<=0.3.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (0.3.4)\n Requirement already satisfied, skipping upgrade: psutil>=5 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (5.8.0)\n Requirement already satisfied, skipping upgrade: sympy>=1.3 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (1.8)\n Requirement already satisfied, skipping upgrade: scikit-learn>=0.20.0 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aqua==0.9.4->qiskit) (0.24.2)\n Requirement already satisfied, skipping upgrade: tweedledum<2.0,>=1.1 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit) (1.1.0)\n Requirement already satisfied, skipping upgrade: ply>=3.10 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit) (3.11)\n Requirement already satisfied, skipping upgrade: jsonschema>=2.6 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit) (3.2.0)\n Requirement already satisfied, skipping upgrade: python-constraint>=1.4 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit) (1.4.0)\n Requirement already satisfied, skipping upgrade: fastjsonschema>=2.10 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit) (2.15.1)\n Requirement already satisfied, skipping upgrade: symengine>0.7; platform_machine == \"x86_64\" or platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"amd64\" or platform_machine == \"arm64\" in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit) (0.7.2)\n Requirement already satisfied, skipping upgrade: dill>=0.3 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-terra==0.18.0->qiskit) (0.3.4)\n Requirement already satisfied, skipping upgrade: pybind11>=2.6 in /home/dev/.local/lib/python3.8/site-packages (from qiskit-aer==0.8.2->qiskit) (2.7.0)\n Requirement already satisfied, skipping upgrade: cryptography>=1.3 in /usr/lib/python3/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.15.0->qiskit) (2.8)\n Requirement already satisfied, skipping upgrade: ntlm-auth>=1.0.2 in /home/dev/.local/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.15.0->qiskit) (1.5.0)\n Requirement already satisfied, skipping upgrade: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.15.0->qiskit) (1.14.0)\n Requirement already satisfied, skipping upgrade: pytz>=2017.3 in /usr/lib/python3/dist-packages (from pandas->qiskit-aqua==0.9.4->qiskit) (2019.3)\n Requirement already satisfied, skipping upgrade: more-itertools in /home/dev/.local/lib/python3.8/site-packages (from quandl->qiskit-aqua==0.9.4->qiskit) (8.8.0)\n Requirement already satisfied, skipping upgrade: inflection>=0.3.1 in /home/dev/.local/lib/python3.8/site-packages (from quandl->qiskit-aqua==0.9.4->qiskit) (0.5.1)\n Requirement already satisfied, skipping upgrade: lxml>=4.5.1 in /home/dev/.local/lib/python3.8/site-packages (from yfinance<0.1.63->qiskit-aqua==0.9.4->qiskit) (4.6.3)\n Requirement already satisfied, skipping upgrade: multitasking>=0.0.7 in /home/dev/.local/lib/python3.8/site-packages (from yfinance<0.1.63->qiskit-aqua==0.9.4->qiskit) (0.0.9)\n Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /home/dev/.local/lib/python3.8/site-packages (from sympy>=1.3->qiskit-aqua==0.9.4->qiskit) (1.2.1)\n Requirement already satisfied, skipping upgrade: joblib>=0.11 in /home/dev/.local/lib/python3.8/site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.4->qiskit) (1.0.1)\n Requirement already satisfied, skipping upgrade: threadpoolctl>=2.0.0 in /home/dev/.local/lib/python3.8/site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.4->qiskit) (2.2.0)\n Requirement already satisfied, skipping upgrade: attrs>=17.4.0 in /home/dev/.local/lib/python3.8/site-packages (from jsonschema>=2.6->qiskit-terra==0.18.0->qiskit) (21.2.0)\n Requirement already satisfied, skipping upgrade: pyrsistent>=0.14.0 in /home/dev/.local/lib/python3.8/site-packages (from jsonschema>=2.6->qiskit-terra==0.18.0->qiskit) (0.18.0)\n\n\n
\n\n## Install QuTiP\n\nType\n\n !pip install qutip\n \ndirectly inside the cell of a Jupyter notebook.\n \nFor a workaround without pip you may execute the following commands in the Anaconda terminal:\n
    \n
  • conda create -n qutip-env
  • \n
  • conda config --append channels conda-forge
  • \n
  • conda install qutip
  • \n
\n\n\n```python\n!pip install qutip\n```\n\n Requirement already satisfied: qutip in /home/dev/.local/lib/python3.8/site-packages (4.6.2)\n Requirement already satisfied: scipy>=1.0 in /home/dev/.local/lib/python3.8/site-packages (from qutip) (1.7.0)\n Requirement already satisfied: packaging in /home/dev/.local/lib/python3.8/site-packages (from qutip) (21.0)\n Requirement already satisfied: numpy>=1.16.6 in /home/dev/.local/lib/python3.8/site-packages (from qutip) (1.21.0)\n Requirement already satisfied: pyparsing>=2.0.2 in /home/dev/.local/lib/python3.8/site-packages (from packaging->qutip) (2.4.7)\n\n\n
\n\n## Check Qiskit installation\n\n\n\n\n```python\nimport qiskit\nversions = qiskit.__qiskit_version__\nprint(\"The version of Qiskit is\",versions['qiskit'])\nprint()\nprint(\"The version of each component:\")\nfor key in versions:\n print(key,\"->\",versions[key])\n```\n\n The version of Qiskit is 0.28.0\n \n The version of each component:\n qiskit-terra -> 0.18.0\n qiskit-aer -> 0.8.2\n qiskit-ignis -> 0.6.0\n qiskit-ibmq-provider -> 0.15.0\n qiskit-aqua -> 0.9.4\n qiskit -> 0.28.0\n qiskit-nature -> None\n qiskit-finance -> None\n qiskit-optimization -> None\n qiskit-machine-learning -> None\n\n\n /home/dev/.local/lib/python3.8/site-packages/qiskit/aqua/__init__.py:86: DeprecationWarning: The package qiskit.aqua is deprecated. It was moved/refactored to qiskit-terra For more information see \n warn_package('aqua', 'qiskit-terra')\n\n\n
\n\n## Execute an example program\n\n\n1) Create a quantum circuit\n\n\n```python\n# import the objects from qiskit\nfrom qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\nfrom random import randrange\n\n# create a quantum circuit and its register objects\nqreg = QuantumRegister(2) # quantum register with two quantum bits\ncreg = ClassicalRegister(2) # classical register with two classical bits\ncircuit = QuantumCircuit(qreg,creg) # quantum circuit composed by a quantum register and a classical register\n\n# apply a Hadamard gate to the first qubit\ncircuit.h(qreg[0])\n\n# set the second qubit to state |1>\ncircuit.x(qreg[1])\n\n# apply CNOT(first_qubit,second_qubit)\ncircuit.cx(qreg[0],qreg[1])\n\n# measure the both qubits\ncircuit.measure(qreg,creg)\n\nprint(\"The execution of the cell was completed, and the circuit was created :)\")\n```\n\n The execution of the cell was completed, and the circuit was created :)\n\n\n2) Draw the circuit\n\n_Run the cell once more if the figure is not shown_\n\n\n```python\n# draw circuit \ncircuit.draw(output='mpl')\n\n# the output will be a \"matplotlib.Figure\" object\n```\n\n3) Execute the circuit 1024 times in the local simulator and print the observed the outcomes\n\n\n```python\n## execute the circuit 1024 times\njob = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024)\n# get the result\ncounts = job.result().get_counts(circuit)\nprint(counts)\n```\n\n {'10': 510, '01': 514}\n\n\n4) Check QuTiP - draw a Bloch sphere\n\n\n```python\nfrom qiskit.visualization import plot_bloch_vector, bloch\nfrom matplotlib.pyplot import text\nfrom math import pi, cos, sin\nfrom qutip import *\n\ntheta = pi/2\nphi = 4*pi/3\n\nx = sin(theta)*cos(phi)\ny = sin(theta)*sin(phi)\nz = cos(theta)\n\nsphere = bloch\nsphere.Bloch\nb = Bloch()\nb.ylpos = [1.1, -1.2]\nb.xlabel = ['$\\\\left|0\\\\right>+\\\\left|1\\\\right>$', '$\\\\left|0\\\\right>-\\\\left|1\\\\right>$']\nb.ylabel = ['$\\\\left|0\\\\right>+i\\\\left|1\\\\right>$', '$\\\\left|0\\\\right>-i\\\\left|1\\\\right>$']\nb.vector_color = ['b','b','b','b','b','b','r']\nb.add_vectors([[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]])\nb.add_vectors([x,y,z])\nb.show()\n\n# re-execute this cell if you DO NOT see the Bloch sphere\n```\n\n## Successfully Installed \n\n\n```python\n\n```\n", "meta": {"hexsha": "095ccb4c87ce81c96a1dc34e4bd88eb5c73603c5", "size": 154778, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "test/Qiskit_QuTiP_installation_and_test.ipynb", "max_stars_repo_name": "dev-aditya/QWorld_Summer_School_2021", "max_stars_repo_head_hexsha": "1b8711327845617ca8dc32ff2a20f461d0ee01c7", "max_stars_repo_licenses": ["Apache-2.0", "CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-15T10:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T10:57:16.000Z", "max_issues_repo_path": "test/Qiskit_QuTiP_installation_and_test.ipynb", "max_issues_repo_name": "dev-aditya/QWorld_Summer_School_2021", "max_issues_repo_head_hexsha": "1b8711327845617ca8dc32ff2a20f461d0ee01c7", "max_issues_repo_licenses": ["Apache-2.0", "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": "test/Qiskit_QuTiP_installation_and_test.ipynb", "max_forks_repo_name": "dev-aditya/QWorld_Summer_School_2021", "max_forks_repo_head_hexsha": "1b8711327845617ca8dc32ff2a20f461d0ee01c7", "max_forks_repo_licenses": ["Apache-2.0", "CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-11T11:12:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:15:08.000Z", "avg_line_length": 257.1063122924, "max_line_length": 97112, "alphanum_fraction": 0.8826060551, "converted": true, "num_tokens": 11132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.16451646494473968, "lm_q1q2_score": 0.07904665359376335}} {"text": "\n\n\n```python\n### Running in Google Colab? You'll want to uncomment and run these cell once each time you start this notebook.\n\n\"\"\"\n!wget https://raw.githubusercontent.com/psheehan/CIERA-HS-Program/master/Projects/SGRB-AfterglowModeling/t90.txt\n!wget https://raw.githubusercontent.com/psheehan/CIERA-HS-Program/master/Projects/SGRB-AfterglowModeling/090510_OmuJy.txt\n!wget https://raw.githubusercontent.com/psheehan/CIERA-HS-Program/master/Projects/SGRB-AfterglowModeling/130603b_OmuJy.txt\n!wget https://github.com/psheehan/CIERA-HS-Program/blob/master/Projects/SGRB-AfterglowModeling/multiwave_OmuJy.txt\n\"\"\"\n```\n\n# Short Gamma-Ray Burst Afterglow Fitting\n\n\n```python\n# Loading some packages to get us started\n\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n%config InlineBackend.figure_format='retina'\n\nfrom IPython.display import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport astropy.io.ascii as ascii\nfrom astropy import cosmology\nfrom astropy import units as u\nfrom astropy.cosmology import FlatLambdaCDM\n\ncosmo = FlatLambdaCDM(H0=70 * u.km / u.s / u.Mpc, Tcmb0=2.725 * u.K, Om0=0.3)\n```\n\n# Introduction\n\n---\n\n\n\n## Gamma-Rays\n\nConsider the electromagnetic spectrum:\n\n\n\nOn the far right end of the spectrum, we see radio waves. Radio waves are at the lowest energy end of the spectrum. As we move across the spectrum to the left, we increase in energy and frequency. Visible light appears near the middle of the spectrum. Gamma-rays are the highest energy class of light and are only produced on Earth by high energy processes like fusion or gamma decay.\n\n---\n\n\n\n## Gamma-Ray Bursts\n\nIn the 1960s, astronomers started detecting bursts of gamma-ray emission. The high energy flashes did not repeat and were randomly scattered across the sky. After much work, astronomers realized that these bursts of gamma-rays were coming from other galaxies. To produce the high energy $\\textbf{photons}$ (packets of light) that make up gamma-ray bursts (GRBs) a source with a lot of energy is needed! All of these clues led astronomers to believe that are the result of explosions in our universe.\n\nGRBs are not $\\textbf{isotropic}$ (spherically symmetric). In fact, much of the explosion's energy is focused along the two poles. The beam that the gamma-rays are accelerated along is referred to as the $\\textbf{jet}$. The structure of the explosion means that in order to detect a GRB we must be directly in the path of the GRB.\n\n\n\n# Exercise 1\n\n## Short vs. Long Gamma-Ray Bursts (GRBs)\n\nIt became clear that there were two populations of GRBs - those with short durations and long durations. Below, we will plot the durations of GRBs discovered by the space telescope $\\textit{Swift}$ from January 2004 to January 2020. Your job is to run the two cells below, examine the plot and choose a cutoff between short and long duration GRBs.\n\n\n```python\n# data file includes a list of GRBs and the duration of the burst, T90\nswift_cat = ascii.read('t90.txt')\n\n# T90 is the amount of time for 90% of the burst's light to be absorbed\nt90 = swift_cat['T90']\n\n# If you print the list of GRB names, you'll see that each GRB is named by the date\n# it was detected on.\ngrb_name = swift_cat['GRBname']\n```\n\n\n```python\nb=np.logspace(-1,3,40)\nplt.hist(t90,b,color='xkcd:lilac')\nplt.loglog()\nplt.tick_params(direction = 'in', length = 10, labelsize = 16, right = True)\nplt.tick_params(which = 'minor', direction = 'in', length = 6, right = True)\nplt.xlabel('Time (seconds)')\nplt.ylabel('Count')\nplt.title('Histogram of Burst Duration')\nplt.show()\n```\n\n#### Question 1: Looking at the plot, are you convinced that there are two distinct populations of GRBs? Why?\n\nAnswer: \n\n#### How many seconds would you choose as a cutoff between short and long GRBs? Keep in mind that the axes are in 'log' units.\n\nAnswer:\n\nIn reality, we use a few other parameters to classify GRBs as short or long. However, duration of the burst is still a useful tool to classify GRBs.\n\nFor this project, we will be focusing on short gamma-ray bursts.\n\n## Gamma-Ray Burst Afterglows\n\nAccompanying each GRB is a multiwavelength afterglow. Afterglows as produced by fast-moving ejecta from the explosion colliding with gas that exists in the space between stars. The relativistic (aka VERY fast) collisions between the ejecta and the gas produce what is called $\\textbf{synchrotron emission}$. Though we won't go into the mechanics of synchrotron emission here, it's important to know that it creates a $\\textbf{jetted multiwavelength afterglow}$. Below is a diagram of an top hat afterglow. In the far right part of the diagram, you see the explosion (jet) colliding with the gas (ambient medium) to produce an afterglow.\n\n\n\nStudying observations of GRB afterglows can teach us about the properties of the burst, including how dense the environment around the explosion is. Below are answers to questions you may have as you simulate afterglow lightcurves.\n\n#### 1. What does multiwavelength mean?\nMultiwavelength means that light is emitted in more than one part of the electromagnetic spectrum (see the first figure!). An afterglow emits in the radio, the visible (hereafter called \"optical\") and the X-ray.\n\nIdentifying the multiwavelength components of the afterglow is important because our X-ray, optical and radio detectors are better at localizing sources than gamma-ray detectors. A better localization allows astronomers to study the host environment of the burst and build a better understanding of what precipitated the explosion.\n\n#### 2. What is a lightcurve?\nA lightcurve is a plot of time (x-axis) vs brightness (y-axis). Lightcurves are a ubiquitous tool for studying time-domain astronomy. A lightcurve shows us if a source dims, brightens, or stays the same over time. For a steady source like a galaxy, a lightcurve will be flat. A supernova's lightcurve will rise quickly and then fall over time. The lightcurve of a variable star (a star which brightens and dims periodically) will look like this:\n\n\n\nShort GRB afterglow lightcurves are most like supernova lightcurves.\n\n#### 3. What is a jet and why is it important?\n\nA jet is a collimated source of relativistic emission. Among other things, a jet is characterized by it's opening angle and shape.\n\nBoth the shape and the opening angle of the jet determine if the afterglow will be detectable to an $\\textbf{off-axis}$ (not directly in the path of the jet) observer.\n\n#### 4. What does an afterglow jet look like?\n\nGood question! The short answer is that astronomers don't know for sure yet but have many theories. The simulations we'll be using below allow the user to try out a few different jet shapes. These jet shapes include:\n\n$\\textbf{Top Hat Jet}$: flux concentrated equally across a narrow beam, outside of which no flux escapes.\n\n$\\textbf{Gaussian Jet}$: Similar to a top hat jet except a greater amount of flux is concentrated in the center of the beam.\n\n$\\textbf{Power Law Jet}$: Flux concentrated in the middle of the jet but decays as you move to larger viewing angles.\n\n\n## Using $\\texttt{afterglowpy}$\n\nWe'll be using the Python package $\\texttt{afterglowpy}$ (Ryan et al. 2015, Ryan et al. 2019) to simulate multiwavelength afterglow (AG) lightcurves and match them to actual observations.\n\nFrom https://github.com/geoffryan/afterglowpy/blob/master/README.md:\n\n\njetType can be:\n1. -1 (Top Hat)\n2. 0 (Gaussian)\n3. 1 (Power Law w/ core)\n4. 2 (Gaussian w/ core)\n5. 3 (Cocoon)\n6. 4 (Smooth Power Law).\n\n\n# Exercise 2a)\n\nThe first three cells are mostly complete and will produce an optical Top Hat jet AG lightcurve plot. Using these cells as an example, produce a AG lightcurves for a Gaussian Jet and a Smooth Power Law Jet.\n\n\n```python\n# in order to do run the cells below, uncomment these two lines, run this cell, and then \n# recomment since you only have to do it once!\n\n!pip install afterglowpy \n\nimport afterglowpy as grb\n```\n\n\n```python\n# Example based on Github code by Geoff Ryan (github.com/geoffryan/afterglowpy/)\n\n# JET PARAMETERS:\n\nthetaObs = 0.05 # Viewing angle in radians\nE0 = 1.0e51 # Isotropic-equivalent energy in erg\nthetaC = 0.2 # Half-opening angle in radians, range of 0.015 - 0.021 radians\nthetaW = 0.1 # Truncation angle, unused for top-hat\nb = 0.01 # power law index, unused for top-hat\nn0 = 1.0 # circumburst density in cm^{-3}\np = 2.2 # electron energy distribution index\neps_e = 0.1 # epsilon_e\neps_B = 0.01 # epsilon_B\nxi_N = 1.0 # Fraction of electrons accelerated\nspecType = 0 # global cooling time, no inverse compton\nq = 0 # keep as 0\nts = 0 # keep as 0\nz = 0.356 # redshift, keep this\n\ndist = cosmo.luminosity_distance(z) # outputs distances in Mpc, keep this\ndL = dist.value * 3.086e24 # Luminosity distance of burst in cm, keep this\n```\n\n\n```python\n# creating a grid of times for the x-axis of our afterglow lightcurves\n\nprint(\"Choose time range\")\n\nta = 2.0 * grb.day2sec\ntb = 50 * grb.day2sec\ntsec = np.geomspace(ta, tb, num=100)\n\n# Calculate flux in a single optical band (all times have same frequency)\nnu = np.empty(tsec.shape)\nnu[:] = 4.8e14\n\n# For convenience, place positional arguments in an array and keywords into a dict\n\nY = np.array([thetaObs, E0, thetaC, thetaW, b, specType, q, ts, n0, p, eps_e, eps_B, xi_N, dL])\nZ = {'z': z}\n\n# Calculate!\n\njetType_top = -1 # top hat jet\n\nprint(\"Calculate Top Hat Jet\")\nFnu_top = grb.fluxDensity(tsec, nu, jetType_top, 0, *Y, **Z)\n\n# Change time units back to days\n\nt = tsec * grb.sec2day\n\n# Plot!\nprint(\"Plot!\")\n\nplt.plot(t,Fnu_top)\nplt.yscale('log')\nplt.xlabel('Time since Burst (Days)')\nplt.ylabel(r'$F_{nu}$ (mJy)')\nplt.title('Example 1: Top Hat Optical Afterglow Lightcurve')\nplt.show()\n```\n\n# Exercise 2b\n\nCalculate Top Hat, Gaussian and Power Law jet afterglow lightcurves.\n\n\n```python\n# Set up array of relevant times\nta = 2.0 * grb.day2sec\ntb = 50.0 * grb.day2sec\ntsec = np.geomspace(ta, tb, num=100)\n\n# Calculate flux in a single optical band (all times have same frequency)\n\nnu = np.empty(tsec.shape)\nnu[:] = 4.8e14 # approximate r-band frequency\n\n# recall number that corresponds to Gaussian jet\njetType_gau = \n\n# recall number that corresponds to Power Law jet\njetType_pl = \n\n# Calculate the brightness of your jet!\n\nprint('Calculate Top Hat Jet')\nFnu_top = grb.fluxDensity() # fill in\nprint('Calculate Gaussian Jet')\nFnu_gau = grb.fluxDensity() # fill in\nprint('Calculate Power Law Jet')\nFnu_pl = grb.fluxDensity() # fill in\n\n# change time back to days\n\nt = tsec * grb.sec2day\n\nprint(\"Plot!\")\n\nplt.plot(t,Fnu_top, ls = ':', lw=4, label = 'Top Hat') # fill in label\nplt.plot(t,Fnu_gau, label = 'Gaussian') # fill in label\nplt.plot(t,Fnu_pl, ls = '-.', label = 'Power Law') # fill in label\nplt.yscale('log')\nplt.xlabel('Days since burst') # fill in\nplt.ylabel(r'$F_{nu}$ (muJy)') # fill in\nplt.title('Afterglow Models')\nplt.legend(fontsize=14)\nplt.show()\n```\n\n# Exercise 3a\n\nReplot your four afterglows from Exercise 2 with the real optical afterglow dataset of the SGRB 130603B. Determine which afterglow jet model best fits the data. Explain why in the cell below.\n\n\n```python\n# Load in SGRB 130603B dataset\n\nobs = np.loadtxt('130603b_OmuJy.txt')\n\ntime = obs[:,0]\nfilt = obs[:,2]\nflux = obs[:,3]\nferr = obs[:,4]\ndet = obs[:,5]\n\n# Add condition to only choose points at a certain wavelengths where something was detected\n\ncond = (filt > 0.5) & (filt < 0.7) & (det == 1)\n\ntime=time[cond]\nfil = filt[cond]\nfl = flux[cond] * 1e-6 # convert micro-Jansky to Jansky to match model units\nflerr = ferr[cond] * 1e-6 # convert micro-Jansky to Jansky\n\n# Plotting the data with error bars\n\nplt.errorbar(time,fl,yerr=flerr,capsize=3,fmt='o',color='xkcd:shocking pink')\n\n# Re-plot your Top Hat, Gaussian, Power Law and Gaussian w/ core afterglow models\n\nplt.plot(t, , ls = ':',lw=4, label = 'Top Hat') # fill in\nplt.plot(t, , label = 'Gaussian') # fill in \nplt.plot(t, , ls = '-.', label = 'Power Law') # fill in\nplt.yscale('log')\n\nplt.xlabel('Days since burst')\nplt.ylabel(r'$F_{nu}$ (Jy)')\nplt.legend()\nplt.show()\n```\n\n#### Question: Which jet type(s) fit the optical afterglow of GRB 130603B the best?\n\nAnswer:\n\n## Exercise 3a Challenge: Choose the model you think fits the data best and adjust the jet parameters (what goes into Y) to determine the best fit by eye.\n\nRecommended: E0, thetaC, thetaW. Try it below and record your best fits to the data.\n\n\n```python\nthetaObs = 0.0 # Viewing angle in radians\nE0 = 1.0e53 # Isotropic-equivalent energy in erg\nthetaC = 0.1 # Half-opening angle in radians\nthetaW = 0.1 # Truncation angle, unused for top-hat\nb = .01 # power law index, unused for top-hat\nn0 = 1.0 # circumburst density in cm^{-3}\np = 2.2 # electron energy distribution index\neps_e = 0.1 # epsilon_e\neps_B = 0.01 # epsilon_B\nxi_N = 1.0 # Fraction of electrons accelerated\nspecType = 0 # global cooling time, no inverse compton\n\n# repeat process to get new lightcurves\n\n\n\n# plot\n\n\n\n```\n\n# Exercise 4\n\nNow determine the best energy fit value for SGRB 090510.\n\n\n```python\nthetaObs = 0.05 # Viewing angle in radians\nE0 = # choose # Isotropic-equivalent energy in erg\nthetaC = 0.1 # Half-opening angle in radians\nthetaW = 0.1 # Truncation angle, unused for top-hat\nb = .01 # power law index, unused for top-hat\nn0 = 1.0 # circumburst density in cm^{-3}\np = 2.2 # electron energy distribution index\neps_e = 0.1 # epsilon_e\neps_B = 0.01 # epsilon_B\nxi_N = 1.0 # Fraction of electrons accelerated\n```\n\n\n```python\n# Load in SGRB 090510 dataset (see 130603B for example)\n\nobs = np.loadtxt('090510_OmuJy.txt')\n\ntime = obs[:,0]\nfilt = obs[:,1]\nflux = obs[:,2]\nferr = obs[:,3]\ndet = obs[:,4]\n\ncond = \n\ntime =\nfil = \nfl = \nflerr = \n```\n\n\n```python\n# Choose time range\n\nta = grb.day2sec * # choose lower time\ntb = grb.day2sec * # choose upper time\ntsec = np.geomspace() # write\n\nprint('Time range chosen')\n\n# Calculate flux in a single optical band (all times have same frequency)\n\nnu = np.empty(tsec.shape)\nnu[:] = 4.8e14 # approximate r-band frequency\n\nY = np.array([thetaObs, E0, thetaC, thetaW, b, specType, q, ts, n0, p, eps_e, eps_B, xi_N, dL])\nZ = {'z': z}\n\n# Calculate!\n\nFnu_gau = \n\nprint(\"Calculated Gaussian Jet flux\")\n\n# Convert time back to days and plot!\n\nt = \n\nprint(\"Plot Observed Data\")\n\nplt.errorbar(time,fl,yerr=flerr,capsize=3,fmt='o',color='xkcd:shocking pink')\n\nprint(\"Plot Models\")\n\nplt.plot(t,Fnu_gau, label = 'Gaussian')\nplt.yscale('log')\nplt.xlabel('Time since burst (days)')\nplt.ylabel(r'$F_{nu}$ (Jy)')\nplt.title('090510 Afterglow Models')\nplt.legend(fontsize=14)\nplt.show()\n```\n\n# Exercise 4\n\n## Creating multiwavelength afterglow lightcurves\n\nSGRB 050724 was the first short gamma-ray burst whose afterglow was detected in the X-ray, optical, near-infrared and radio parts of the EM spectrum. As time went by, astronomers started sampling the afterglows more frequenctly across wavelengths. Here, we will compare the multiwavelength observations from the 130603B with our lightcurves for different jet types. Data from Table 1, Fong, Berger, Metzger et al. 2013 (https://iopscience.iop.org/article/10.1088/0004-637X/780/2/118/pdf).\n\n## Unit conversions\n\nIn order to produce lightcurves in the correct units, we must provide the models with the correct units of frequency, $\\nu$. We can calculate $\\nu$ from wavelength $\\lambda$ by:\n\n\\begin{equation}\nc = \\lambda * \\nu\n\\end{equation}\n\nWhere $c$ is the speed of light ($c=3*10^{10}$ cm/s), $\\nu$ is frequency, and $\\lambda$ is wavelength.\n\nBelow is the electromagnetic spectrum with approximate values for $\\lambda$. As $\\texttt{afterglowpy}$ only accepts $\\nu$ values, you'll need to convert to frequency to calculate your multiwavelength afterglow lightcurves. Below is an EM spectrum with frequency and wavelength so you can check you have approximately the correct values. However, I'll give you the exact wavelength values below to calculate.\n\n\n\n# Part 4a) \n\nCalculating frequency of each band\n\n\n```python\n# calculate X-ray, optical, near infrared and radio frequencies in Hz given \n\nc = 3e10 # units = cm/s\n\nlambda_xray = 1.24e-7 # cm units\nnu_xray = \n\nlambda_opt = 0.62e-4 # cm units\nnu_opt = \n\nlambda_nir = 1.2e-4 # cm units\nnu_nir = \n\nlambda_rad = 4.5e0 # cm units\nnu_rad = \n```\n\n\n```python\n# Preliminary Jet parameters - leave for now, can play with later!\n\nthetaObs = 0.05 # Viewing angle in radians\nE0 = 1.0e51 # Isotropic-equivalent energy in erg\nthetaC = 0.1 # Half-opening angle in radians\nthetaW = 0.1 # Truncation angle, unused for top-hat\nb = .01 # power law index, unused for top-hat\nn0 = 1.0 # circumburst density in cm^{-3}\np = 2.2 # electron energy distribution index\neps_e = 0.1 # epsilon_e\neps_B = 0.01 # epsilon_B\nxi_N = 1.0 # Fraction of electrons accelerated\nspecType = 0 # global cooling time, no inverse compton\n```\n\n# Part 4b) \n\nLoad in observed multiwavelength data and sort it part filter (X-ray, Optical, Near-Infrared, and Radio) by detection (q = 1) or upper limit (q = 0). Upper limits can be useful because they can help us rule out models that are too bright.\n\n\n```python\n# Load in data\n\nobs = np.loadtxt('multiwave_OmuJy.txt')\n\ndt = obs[:,0] # time in days\nfilt = obs[:,1] # filter in microns (1 micron = 10000 centimeters)\n\nprint(filt) # print to see which part of the spectrum the data was taken at\n\nflux = obs[:,2] # flux in microJansky\nferr = obs[:,3] # flux error in microJansky\n\ndet = obs[:,4] # detection = 1, upper limit = 0\n\n# Separate data by filter and if detection or upper limit\n\n\n\n```\n\n# Part 4c)\n\nCreate multiwavelength models using frequencies calculated in Part 4a) and plot with observations.\n\n\n```python\n# Choose appropriate time range\n\nta = grb.day2sec * # choose lower time\ntb = grb.day2sec * # choose upper time\ntsec = np.geomspace() # write\n\n# calculate multiwavelength lightcurves\n\nprint(\"Calc Radio\")\nFnuR = grb.fluxDensity()\nprint(\"Calc Optical\")\nFnuO = grb.fluxDensity()\nprint(\"Calc Near Infrared\")\nFnuN = grb.fluxDensity()\nprint(\"Calc X-ray\")\nFnuX = grb.fluxDensity()\n\n# plot data by filter - make sure to use different markers for detections and upper limits\n\n\n\n\n# plot models\n\nprint(\"Plot\")\n\nt = \n\nplt.plot(t,FnuR, label = 'Radio')\nplt.plot(t,FnuO, label = 'Optical')\nplt.plot(t,FnuN, label = 'Near-Infrared')\nplt.plot(t,FnuX, label = 'X-ray')\n\nplt.yscale('log')\nplt.xlabel('') # add in\nplt.ylabel(r'') # add in\nplt.title('') # add in\nplt.legend(fontsize=14)\nplt.show()\n```\n\n# Part 4d)\n\nPlay with your Jet parameters and jetType to get the best fit to all of the detections and upper limits.\n\n\n```python\n# Work space for 4d\n```\n\n#### Question: Which jet type fits the data best?\n\nAnswer:\n\n# Nice job!\n\nIf you finished early, here's a challenge:\n\nWe have been determining the best models by eye for these exercises. However, in practice astronomers like to use statistics to make sure we are finding the best fit. To do this, we must:\n\n1. Determine how to quantitatively measuring how good a fit is\n2. Minimize or maximize this quantity to make sure we have the best fit possible\n \nFeel free to ask more questions! I'm happy to help provide resources for smart ways to do this.\n\n\n```python\n\n```\n", "meta": {"hexsha": "ac847b85a64f6757af67a5c56678554a7bfe440f", "size": 30831, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Projects/SGRB-AfterglowModeling/SGRB_Afterglow_Modeling.ipynb", "max_stars_repo_name": "psheehan/CIERA-HS-Program", "max_stars_repo_head_hexsha": "76f7f0ff994e74e646fa34bbb41c314bf7526e9b", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-25T02:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T21:44:41.000Z", "max_issues_repo_path": "Projects/SGRB-AfterglowModeling/SGRB_Afterglow_Modeling.ipynb", "max_issues_repo_name": "psheehan/CIERA-HS-Program", "max_issues_repo_head_hexsha": "76f7f0ff994e74e646fa34bbb41c314bf7526e9b", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projects/SGRB-AfterglowModeling/SGRB_Afterglow_Modeling.ipynb", "max_forks_repo_name": "psheehan/CIERA-HS-Program", "max_forks_repo_head_hexsha": "76f7f0ff994e74e646fa34bbb41c314bf7526e9b", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-06-25T15:33:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T18:04:36.000Z", "avg_line_length": 32.7989361702, "max_line_length": 647, "alphanum_fraction": 0.5813953488, "converted": true, "num_tokens": 5402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.16238003666671086, "lm_q1q2_score": 0.07865365584552121}} {"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\n\nToggle cell visibility here.\n\n\n## State feedback control - sledenje referenčni vrednosti\n\nZa sistem definiran z enačbo:\n\n$$\n\\dot{x}=\\underbrace{\\begin{bmatrix}-3&4\\\\0&2\\end{bmatrix}}_{A}x+\\underbrace{\\begin{bmatrix}0\\\\1\\end{bmatrix}}_{B}u.\n$$\n\nje dana zahteva, da prva spremenljivka stanj sledi sinusoidni referenčni funkciji s frekvenco 6 rad/s ($\\approx 1$ Hz) brez odstopanja v amplitudi. \n\nV prvem koraku dodamo integrator (z uvedbo fiktivne spremenljivke stanje; postopek je razložen v interaktivnem primeru [Krmiljenje povratne zveze stanj - zmogljivost krmiljenja](SS-31-Krmiljenje_povratne_zveze_stanj_zmogljivost)) tako, da preverimo da razširjen sistem ostane vodljiv, kar je pomembno, da se zaprtozančna prenosna funkcija od reference do $x_1$ začne pri vrednosti 0 dB. Končni razširjen sistem tako zapišemo kot:\n\n$$\n\\dot{x}_a=\\underbrace{\\begin{bmatrix}-3&4&0\\\\0&2&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\nZ namenom zagotovitve dani zahtevi je ključno, da si predstavljamo obliko prenosne funkcije, ki zagotavlja zahtevan odziv, tj. 0 dB od $\\omega=0$ do najmanj $\\omega=6$ in fazo 0 deg v enakem intervalu frekvenc. Ob upoštevanju učinka polov v območje frekvenc izvedn danega intervala je rešitev ta, da prilagodimo pole tako, da le-ti ležijo v območju frekvenc višjih od 65 rad/s.\n\nIzbrani poli so tako $\\lambda_{1,2,3}= 65$ rad/s, matrika ojačanja pa $K_a = \\begin{bmatrix}3024.75&194&68656.25\\end{bmatrix}^T$. \n\nKrmiljeni sistem zapišemo kot:\n\n$$\n\\dot{x}_a=\\underbrace{\\begin{bmatrix}-3&4&0\\\\-3024.75&-192&-68656.25\\\\1&0&0\\end{bmatrix}}_{A_a-B_aK_a}x_a+\\underbrace{\\begin{bmatrix}0\\\\1\\\\0\\end{bmatrix}}_{B_a}v+\\underbrace{\\begin{bmatrix}0\\\\0\\\\-1\\end{bmatrix}}_{B_{\\text{ref}}}x_{1r}\n$$\n\nV tem primeru je prikazana simulacija skupaj z Bodejeveim diagramom prenosne funkcije od reference $x_{1r}$ do spremenljivke stanja $x_1$. \n\n### Kako upravljati s tem interaktivnim primerom?\nZanimivo bi bilo doseči tudi odziv brez odstopka v faznem delu signala. Kako daleč je potrebno, za dosego tega scenarija, prestaviti pole?\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('-3 4 0; 0 2 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([842.25,104,10718.75])\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([-65])) \neig2c.setM(numpy.matrix([[-65],[0]]))\neig3c.setM(numpy.matrix([-65]))\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'}\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=1,\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='Bodejev diagram', figsize=(16,10))\n control.bode_plot(sys)\n fig.suptitle('Bodejev diagram', fontsize=16)\n \n plt.figure(num='Simulacija', figsize=(16,4))\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 \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 = '1050px'\ndisplay(out, alltogether)\n```\n\n\n Output(layout=Layout(height='1050px'))\n\n\n\n VBox(children=(HBox(children=(Dropdown(options=('Nastavi K', 'Nastavi lastne vrednosti'), value='Nastavi K'), …\n\n", "meta": {"hexsha": "602caddb36977f33cd61d9ac4786de7f014ef647", "size": 19499, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-32-Krmiljenje_povratne_zveze_stanj_sledenje.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-32-Krmiljenje_povratne_zveze_stanj_sledenje.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-32-Krmiljenje_povratne_zveze_stanj_sledenje.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": 39.3919191919, "max_line_length": 438, "alphanum_fraction": 0.4891020052, "converted": true, "num_tokens": 4066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.18242552825126704, "lm_q1q2_score": 0.07846985462635774}} {"text": "\n# PHY321: Classical Mechanics 1\n\n \n**Homework 5, due Monday February 17**\n\nDate: **Feb 8, 2021**\n\n### Practicalities about homeworks and projects\n\n1. You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. **Remember to write your name(s)**!\n\n2. Homeworks are available Wednesday/Thursday the week before the deadline. The deadline is at the Friday lecture.\n\n3. How do I(we) hand in? You can hand in the paper and pencil exercises as a hand-written document. For this homework this applies to exercises 1-5. Alternatively, you can hand in everyhting (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical exercise(s) (exercise 6 here) should always be handed in as a jupyter notebook by the deadline at D2L. \n\n### Introduction to homework 5\n\nThis week's sets of classical pen and paper and computational\nexercises are a continuation of the topics from the previous homework set. We keep dealing with simple motion problems and conservation laws; energy, momentum and angular momentum. These conservation laws are central in Physics and understanding them properly lays the foundation for understanding and analyzing more complicated physics problems.\nThe relevant reading background is\n1. chapters 3 and 4 of Taylor (there are many good examples there) and\n\n2. chapters 10-14 of Malthe-Sørenssen.\n\nIn both textbooks there are many nice worked out examples. Malthe-Sørenssen's text contains also several coding examples you may find useful. \n\nThe numerical homework focuses on another motion problem where you can\nuse the code you developed in homework 4, almost entirely. Please take\na look at the posted solution (jupyter-notebook) for homework 4. You\nneed only to change the forces at play. The problem at hand is again a\nclassic one, a block fastened to a spring moving back and forth along the $x$-axis. It is a simpler problem compared to the previous homework. It allows us however to introduce damping (friction) and study more realistic situations. \n\n\n\n### Exercise 1 (15 pt), Work-energy theorem and conservation laws\n\nThis exercise was partly discussed during the lectures. It has not yet been edited in the online notes.\nWe will study a classical electron which moves in the $x$-direction along a surface. The force from the surface is\n\n$$\n\\boldsymbol{F}(x)=-F_0\\sin{(\\frac{2\\pi x}{b})}\\boldsymbol{e}_x.\n$$\n\nThe constant $b$ represents the distance between atoms at the surface of the material, $F_0$ is a constant and $x$ is the position of the electron.\n\n* 1a (2pt) Is this a conservative force? And if so, what does that imply?\n\nThis is indeed a conservative force since it depends only on position and its **curl** is zero. This means that energy is conserved and the integral over the work done by the force is independent of the path taken. \n* 1b (4pt) Use the work-energy theorem to find the velocity $v(x)$. \n\nUsing the work-energy theorem we can find the work $W$ done when moving an electron from a position $x_\\\n0$ to a final position $x$ through the integral\n\n$$\nW=-\\int_{x_0}^x \\boldsymbol{F}(x')dx' = \\int_{x_0}^x F_0\\sin{(\\frac{2\\pi x'}{b})} dx',\n$$\n\nwhich results in\n\n$$\nW=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right].\n$$\n\nSince this is related to the change in kinetic energy we have, with $v_0$ being the initial velocity at a time $t_0$,\n\n$$\nv = \\pm\\sqrt{\\frac{2}{m}\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right]+v_0^2}.\n$$\n\n* 1c (4pt) With the above expression for the force, find the potential energy.\n\nThe potential energy, due to energy conservation is\n\n$$\nV(x)=V(x_0)+\\frac{1}{2}mv_0^2-\\frac{1}{2}mv^2,\n$$\n\nwith $v$ given by the previous answer. \nWe can now, in order to find a more explicit expression for the potential energy at a given value $x$, define a zero level value for the potential. The potential is defined , using the work-energy theorem , as\n\n$$\nV(x)=V(x_0)+\\int_{x_0}^x (-F(x'))dx',\n$$\n\nand if you recall the definition of the indefinite integral, we can rewrite this as\n\n$$\nV(x)=\\int (-F(x'))dx'+C,\n$$\n\nwhere $C$ is an undefined constant. The force is defined as the gradient of the potential, and in that case the undefined constant vanishes. The constant does not affect the force we derive from the potential.\n\nWe have then\n\n$$\nV(x)=V(x_0)-\\int_{x_0}^x \\boldsymbol{F}(x')dx',\n$$\n\nwhich results in\n\n$$\nV(x)=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right]+V(x_0).\n$$\n\nWe can now define\n\n$$\n\\frac{F_0b}{2\\pi}\\cos{(\\frac{2\\pi x_0}{b})}=V(x_0),\n$$\n\nwhich gives\n\n$$\nV(x)=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}\\right].\n$$\n\n* 1d (5pt) Make a plot of the potential energy and discuss the equilibrium points where the force on the electron is zero. Discuss the physical interpretation of stable and unstable equilibrium points. Use energy conservation. \n\nThe following Python code plots the potential\n\n\n```python\n%matplotlib inline\n\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nDeltax = 0.01\n#set up arrays\nxinitial = -2.0\nxfinal = 2.0 \nn = ceil((xfinal-xinitial)/Deltax)\nx = np.zeros(n)\nfor i in range(n):\n x[i] = xinitial+i*Deltax\nV = np.zeros(n)\n# Setting values for the constants. \nF0 = 1.0; b = 1.0; \n# Defining the potential\nV = F0*b/(2*pi)*np.cos(2*pi*x/b)\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x')\nax.set_xlabel('V')\nax.plot(x, V)\nfig.tight_layout()\nplt.show()\n```\n\nWe have stable equilibrium points for every minimum of the $\\cos$ function and unstable equilibrium points where it has its maximimum values. At the minimum the particle has the lowest potential energy and the largest kinetic energy whereas at the maxima it has the largest potential energy and lowest kinetic energy. \n### Exsercise 2 (15pt), Rocket, Momentum and mass\n\nTaylor exercise 3.11. This exercise was partly discussed during the lectures, see the notes on [Energy and Momentum etc, see the part on Momentum conservation ](https://mhjensen.github.io/Physics321/doc/pub/energyconserv/html/energyconserv.html). Taylor's chapter 3.2 covers also this example.\n\n* 3.11 a and b\n\nConsider the rocket of mass $M$ moving with velocity $v$. After a\nbrief instant, the velocity of the rocket is $v+\\Delta v$ and the mass\nis $M-\\Delta M$. Momentum conservation gives\n\n$$\n\\begin{eqnarray*}\nMv&=&(M-\\Delta M)(v+\\Delta v)+\\Delta M(v-v_e)\\\\\n0&=&-\\Delta Mv+M\\Delta v+\\Delta M(v-v_e),\\\\\n0&=&M\\Delta v-\\Delta Mv_e.\n\\end{eqnarray*}\n$$\n\nIn the second step we ignored the term $\\Delta M\\Delta v$ since we\nassume it is small. The last equation gives\n\n$$\n\\begin{eqnarray}\n\\Delta v&=&\\frac{v_e}{M}\\Delta M,\\\\\n\\nonumber\n\\frac{dv}{dt}&=&\\frac{v_e}{M}\\frac{dM}{dt}.\n\\end{eqnarray}\n$$\n\nIntegrating the expression with lower limits $v_0=0$ and $M_0$, one finds\n\n$$\n\\begin{eqnarray*}\nv&=&v_e\\int_{M_0}^M \\frac{dM'}{M'}\\\\\nv&=&-v_e\\ln(M/M_0)\\\\\n&=&-v_e\\ln[(M_0-\\alpha t)/M_0].\n\\end{eqnarray*}\n$$\n\nWe have ignored gravity here. If we add gravity as the external force, we get when integrating an additional terms $-gt$, that is\n\n$$\nv=-v_e\\ln[(M_0-\\alpha t)/M_0]-gt.\n$$\n\n* 3.11c\n\nInserting numbers $v_e=3000$ m/s, $M_0/M=2$ and $g=9.8$ m/s$^{2}$, we find $v=900$ m/s. With $g=0$ the corresponding number is $2100$ m/s, so gravity reduces the speed acquired in the first two minutes to a little less than half its weight-free value.\n\n* 3.11d\n\nIf the thrust $\\Delta Mv_e$ is less than the weight $mg$, the rocket will just sit on the ground until it has shed enough mass that the thrust can overcome the weight, definitely not a good design. \n\n\n### Exercise 3 (10pt), More Rockets\n\nTaylor exercises 3.13 (5pt) and 3.14 (5pt). This is a continuation of the previous exercise and most of the relevant background material can be found in Taylor chapter 3.2. \n\nTaking the velocity from the previous exercise and integrating over time we find the height\n\n$$\ny(t) = y(t_0=0)+\\int_0^tv(t')dt',\n$$\n\nwhich gives\n\n$$\ny(t) = v_et\\ln{M_0}-v_e\\int_0^t \\ln{M(t')}dt'-\\frac{1}{2}gt^2.\n$$\n\nTo do the integral over time we recall that $M(t')=M_0-\\Delta M t'$. We assumed that $\\Delta M=k$ is a constant. We obtain then that the integral gives\n\n$$\n\\int_0^t \\ln{M(t')}dt' = \\frac{1}{k}\\left(M_0\\ln{M_0}-M\\ln{M}\\right)-t,\n$$\n\nwhere we used that $M_0-M=kt$. We have assumed that mass decreases by a constant $k$ times time $t$.\nInserting into $y(t)$ we obtain then\n\n$$\ny(t) = v_et-\\frac{1}{2}gt^2-\\frac{mv_e}{k}\\ln{(\\frac{M_0}{M})}.\n$$\n\nUsing the numbers from the previous exercise with $t=2$ min we obtain that $y\\approx 40$ km.\n\nFor exercise 3.14 (5pt) we have the equation of motion which reads $Ma=kv_e-bv$ or\n\n$$\n\\frac{Mdv}{kv_e-bv}=dt.\n$$\n\nWe have that $dM/dt =-k$ (assumed a constant rate for mass change). We can then replace $dt$ by $-dM/k$ and we have\n\n$$\n\\frac{kdv}{kv_e-bv}=-\\frac{dM}{M}.\n$$\n\nIntegrating gives\n\n$$\nv = \\frac{kv_e}{b}\\left[1-(\\frac{M}{M_0})^{b/k}\\right].\n$$\n\n### Exercise 4 (10pt), Center of mass\n\nTaylor exercise 3.20. Here Taylor's chapter 3.3 can be of use. This relation will turn out to be very useful when we discuss systems of many classical particles.\n\nThe definition of the center of mass for $N$ objects can be written as\n\n$$\nM\\boldsymbol{R}=\\sum_{i=1}^Nm_i\\boldsymbol{r}_i,\n$$\n\nwhere $m_i$ and $\\boldsymbol{r}_i$ are the masses and positions of object $i$, respectively.\n\nAssume now that we have a collection of $N_1$ objects with masses $m_{1i}$ and positions $\\boldsymbol{r}_{1i}$\nwith $i=1,\\dots,N_1$ and a collection of $N_2$ objects with masses $m_{2j}$ and positions $\\boldsymbol{r}_{2j}$\nwith $j=1,\\dots,N_2$.\n\nThe total mass of the two-body system is $M=M_1+M_2=\\sum_{i=1}^{N_1}m_{1i}+\\sum_{j=1}^{N_2}m_{2j}$. The center of mass position $\\boldsymbol{R}$ of the whole system satisfies then\n\n$$\nM\\boldsymbol{R}=\\sum_{i=1}^{N_1}m_{1i}\\boldsymbol{r}_{1i}+\\sum_{j=1}^{N_2}m_{2j}\\boldsymbol{r}_{2j}=M_1\\boldsymbol{R}_1+M_2\\boldsymbol{R}_2,\n$$\n\nwhere $\\boldsymbol{R}_1$ and $\\boldsymbol{R}_2$ are the the center of mass positions of the two separate bodies and the second equality follows from our rewritten definition of the center of mass applied to each body separately. This is the required result.\n\n### Exercise 5 (10pt), Sliding Block and Spring (please not again), Scaling the Equations and getting started with numerical project\n\nThe relevant material with codes etc is covered by the [Lecture Notes on Oscillations](https://mhjensen.github.io/Physics321/doc/pub/harmonic/html/harmonic.html). Taylor's chapter 5, in particular sections 5.1 amd 5.2. 5.4 is relevant for the bonus exercise.\nWe start now with our next numerical application with simple rewrites of our equations. The system we will look at is that of a block fastened to a spring (which in turn is tied to a wall).\nThe force acting on the block from the spring in the $x$-drection only is\n\n$$\nm\\frac{d^2x(t)}{dt^2}=F(x) = -k(x-b),\n$$\n\nwhere $k$ is a material specific constant and $b$ is the equilibrium position. The block has mass $m$ and $t$ is time. Define the initial time as $t_0$. We will for simplicity set the equilibrium position to zero, that is $b=0$.\n\n* 5a (3pt) Does this force conserve energy? If so, with given initial position and velocity $x_0$ and $v_0$, respectively, find the expression for energy conservation in terms of the potential and kinetic energies. \n\nThis force depdens only on the position and its **curl** is also zero. Energy is thus conserved.\nIntegrating the force gives us a potential energy $1/2kx^2$. With initial conditions for the position $x_0$ and the velocity $v_0$ we have that\n\n$$\n\\frac{1}{2}kx^2+\\frac{1}{2}mv^2=\\frac{1}{2}kx_0^2+\\frac{1}{2}mv_0^2.\n$$\n\n* 5b (3pt) Define a constant $\\omega_0=\\sqrt{k/m}$ and show that you can write the acceleration as $a(t) = -\\omega_0^2 x(t)$. What is the dimentionality of $\\omega_0$? (it is normally called a natural frequency). \n\nThe dimensionality of $\\omega_0$ is inverse time. The acceleration is\n\n$$\na=\\frac{d^2x(t)}{dt^2}=\\frac{F}{m} = -\\frac{k}{m}x=-\\omega_0^2x.\n$$\n\n* 5c (4pt) Introduce now a dimensionless time $\\tau = t\\omega_0$. Show that you can rewrite the equation for the acceleration in terms of two first-order differential equations\n\nStarting with\n\n$$\na=\\frac{d^2x}{dt^2}=\\frac{F}{m} = -\\frac{k}{m}x=-\\omega_0^2x,\n$$\n\nand introducing a dimensionless time we have\n\n$$\n\\omega_0^2\\frac{d^2x}{d\\tau^2}=-\\omega_0^2x,\n$$\n\nand dividing by $\\omega_0^2$ we have\n\n$$\n\\frac{d^2x(t)}{d\\tau^2}=\\frac{dv}{d\\tau}=-x.\n$$\n\nThis gives us our first differential equation\n\n$$\n\\frac{dv}{d\\tau} = -x,\n$$\n\nand using the definition of velocity we have\n\n$$\n\\frac{dx}{d\\tau} = v.\n$$\n\nBoth equations (velocity and position) have dimensionality length.\nNote that in principle we should have relabeled $v$ as $\\overline{v}$ to indicate that it has dimension length and not length divided by time.\n\n\n### Exercises 6 and 7\n\nThe results are detailed in the lecture notes on oscillations. The text here is simply an iteration of what we have discussed during the lectures.\n\n\nWe consider only the case where the damping force is proportional to\nthe velocity. This is counter to dragging friction, where the force is\nproportional in strength to the normal force and independent of\nvelocity, and is also inconsistent with wind resistance, where the\nmagnitude of the drag force is proportional the square of the\nvelocity. Rolling resistance does seem to be mainly proportional to\nthe velocity. However, the main motivation for considering damping\nforces proportional to the velocity is that the math is more\nfriendly. This is because the differential equation is linear,\ni.e. each term is of order $x$, $\\dot{x}$, $\\ddot{x}\\cdots$, or even\nterms with no mention of $x$, and there are no terms such as $x^2$ or\n$x\\ddot{x}$. The equations of motion for a spring with damping force\n$-b\\dot{x}$ are\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nJust to make the solution a bit less messy, we rewrite this equation as\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:dampeddiffyq} \\tag{2}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=0,~~~~\\beta\\equiv b/2m,~\\omega_0\\equiv\\sqrt{k/m}.\n\\end{equation}\n$$\n\nBoth $\\beta$ and $\\omega$ have dimensions of inverse time. To find solutions (see appendix C in the text) you must make an educated guess at the form of the solution. To do this, first realize that the solution will need an arbitrary normalization $A$ because the equation is linear. Secondly, realize that if the form is\n\n\n
\n\n$$\n\\begin{equation}\nx=Ae^{rt}\n\\label{_auto2} \\tag{3}\n\\end{equation}\n$$\n\nthat each derivative simply brings out an extra power of $r$. This\nmeans that the $Ae^{rt}$ factors out and one can simply solve for an\nequation for $r$. Plugging this form into Eq. ([2](#eq:dampeddiffyq)),\n\n\n
\n\n$$\n\\begin{equation}\nr^2+2\\beta r+\\omega_0^2=0.\n\\label{_auto3} \\tag{4}\n\\end{equation}\n$$\n\nBecause this is a quadratic equation there will be two solutions,\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\beta\\pm\\sqrt{\\beta^2-\\omega_0^2}.\n\\label{_auto4} \\tag{5}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1t}+A_2e^{r_2t},\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nThe roots listed above, $\\sqrt{\\omega_0^2-\\beta_0^2}$, will be\nimaginary if the damping is small and $\\beta<\\omega_0$. In that case,\n$r$ is complex and the factor $e{rt}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. There are three cases:\n\n\n\n### Underdamped: $\\beta<\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1e^{-\\beta t}e^{i\\omega't}+A_2e^{-\\beta t}e^{-i\\omega't},~~\\omega'\\equiv\\sqrt{\\omega_0^2-\\beta^2}\\\\\n\\nonumber\n&=&(A_1+A_2)e^{-\\beta t}\\cos\\omega't+i(A_1-A_2)e^{-\\beta t}\\sin\\omega't.\n\\end{eqnarray}\n$$\n\nHere we have made use of the identity\n$e^{i\\omega't}=\\cos\\omega't+i\\sin\\omega't$. Because the constants are\narbitrary, and because the real and imaginary parts are both solutions\nindividually, we can simply consider the real part of the solution\nalone:\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:homogsolution} \\tag{7}\nx&=&B_1e^{-\\beta t}\\cos\\omega't+B_2e^{-\\beta t}\\sin\\omega't,\\\\\n\\nonumber \n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2}.\n\\end{eqnarray}\n$$\n\n### Critical dampling: $\\beta=\\omega_0$\n\nIn this case the two terms involving $r_1$ and $r_2$ are identical\nbecause $\\omega'=0$. Because we need to arbitrary constants, there\nneeds to be another solution. This is found by simply guessing, or by\ntaking the limit of $\\omega'\\rightarrow 0$ from the underdamped\nsolution. The solution is then\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:criticallydamped} \\tag{8}\nx=Ae^{-\\beta t}+Bte^{-\\beta t}.\n\\end{equation}\n$$\n\nThe critically damped solution is interesting because the solution\napproaches zero quickly, but does not oscillate. For a problem with\nzero initial velocity, the solution never crosses zero. This is a good\nchoice for designing shock absorbers or swinging doors.\n\n### Overdamped: $\\beta>\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1\\exp{-(\\beta+\\sqrt{\\beta^2-\\omega_0^2})t}+A_2\\exp{-(\\beta-\\sqrt{\\beta^2-\\omega_0^2})t}\n\\end{eqnarray}\n$$\n\nThis solution will also never pass the origin more than once, and then\nonly if the initial velocity is strong and initially toward zero.\n\n\n\n\nGiven $b$, $m$ and $\\omega_0$, find $x(t)$ for a particle whose\ninitial position is $x=0$ and has initial velocity $v_0$ (assuming an\nunderdamped solution).\n\nThe solution is of the form,\n\n$$\n\\begin{eqnarray*}\nx&=&e^{-\\beta t}\\left[A_1\\cos(\\omega' t)+A_2\\sin\\omega't\\right],\\\\\n\\dot{x}&=&-\\beta x+\\omega'e^{-\\beta t}\\left[-A_1\\sin\\omega't+A_2\\cos\\omega't\\right].\\\\\n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2},~~~\\beta\\equiv b/2m.\n\\end{eqnarray*}\n$$\n\nFrom the initial conditions, $A_1=0$ because $x(0)=0$ and $\\omega'A_2=v_0$. So\n\n$$\nx=\\frac{v_0}{\\omega'}e^{-\\beta t}\\sin\\omega't.\n$$\n\nLet us remind ourselves about the differential equation we want to solve (the general case with damping due to friction)\n\n$$\nm\\frac{d^2x}{dt^2} + b\\frac{dx}{dt}+kx(t) =0.\n$$\n\nWe divide by $m$ and introduce $\\omega_0^2=\\sqrt{k/m}$ and obtain\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =0.\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$ (check\nthat the dimensionality is correct) and rewrite our equation as\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =0,\n$$\n\nwhich gives us\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nWe then define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nThis is the equation we will code below. The first version employs the Euler-Cromer method.\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions as simple one-dimensional arrays of time\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.0\n# Start integrating using Euler-Cromer's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n a = -2*gamma*v[i]-x[i]\n # update velocity, time and position\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"BlockEulerCromer\")\nplt.show()\n```\n\nWhen setting up the value of $\\gamma$ we see that for $\\gamma=0$ we get the simple oscillatory motion with no damping.\nChoosing $\\gamma < 1$ leads to the classical underdamped case with oscillatory motion, but where the motion comes to an end.\n\nChoosing $\\gamma =1$ leads to what normally is called critical damping and $\\gamma> 1$ leads to critical overdamping.\nTry it out and try also to change the initial position and velocity. Setting $\\gamma=1$\nyields a situation, as discussed above, where the solution approaches quickly zero and does not oscillate. With zero initial velocity it will never cross zero.\n", "meta": {"hexsha": "75c1c360671e4515460161c963506acc05544c5c", "size": 34892, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw5-checkpoint.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw5-checkpoint.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw5-checkpoint.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 29.4945054945, "max_line_length": 415, "alphanum_fraction": 0.5564312736, "converted": true, "num_tokens": 6752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.18713268669577832, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.0783518775589484}} {"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\n%matplotlib notebook\n\nimport numpy as np\nimport control as control\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nimport sympy as sym\n# from IPython.display import Markdown # For displaying Markdown and LaTeX code\n\nsym.init_printing()\ncontinuous_update=False\n```\n\n## Errore a regime - Sistemi in feedback unitario\n\nData la funzione di trasferimento dell'input $I(s)$ e la funzione di trasferimento del sistema ad anello aperto $G(s)$, l'errore a regime $e(\\infty)$ del sistema ad anello chiuso può, in caso di feedback unitario, essere determinato da:\n\n\\begin{equation}\n e(\\infty)=\\lim_{s\\to0}\\frac{sI(s)}{1+G(s)}.\n\\end{equation}\n\nNel caso di una funzione di ingresso a gradino $I(s)=\\frac{1}{s}$ si ottiene:\n\n\\begin{equation}\n e_{step}(\\infty)=\\frac{1}{1+\\lim_{s\\to0}G(s)},\n\\end{equation}\n\nnel caso di una funzione di ingresso a rampa $I(s)=\\frac{1}{s^2}$:\n\n\\begin{equation}\n e_{ramp}(\\infty)=\\frac{1}{\\lim_{s\\to0}sG(s)},\n\\end{equation}\n\ne nel caso di una funzione di ingresso parabolica $I(s)=\\frac{1}{s^3}$:\n\n\\begin{equation}\n e_{parabolic}(\\infty)=\\frac{1}{\\lim_{s\\to0}s^2G(s)}.\n\\end{equation}\n\n\n### Sistemi senza integratori\n\nUn esempio di una funzione di trasferimento $G(s)$ di un sistema senza integratori può essere:\n\n\\begin{equation}\n G(s) = \\frac{K}{as^2 + bs + c}\n\\end{equation}\n\nL'errore a regime nel caso di sistemi senza integratori è infinito per gli ingressi a rampa e parabolici.\n\n### Sistemi con un integratore\n\nUn esempio di una funzione di trasferimento $G(s)$ di un sistema con un integratore può essere:\n\n\\begin{equation}\n G(s) = \\frac{K(as^2 + bs + c)}{s(ds^2 + es + fc)}\n\\end{equation}\n\nL'errore a regime nel caso di sistemi con un integratore è infinito per gli ingressi parabolici.\n\n---\n\n### Come usare questo notebook?\n\n- Scegli tra il sistema senza integratori a un sistema con un unico integratore.\n- Sposta i cursori per modificare i valori di $a$, $b$, $c$ (coefficienti della funzione di trasferimento) e $K$ (amplificazione).\n\n\n```python\nstyle = {'description_width': 'initial'}\n\nlayout1 = widgets.Layout(width='auto', height='auto') #set width and height\n\nsystemSelect = widgets.ToggleButtons(\n options=[('nessun integratore', 0), ('un integratore', 1)],\n description='Sistema: ',style=style)\nfunctionSelect = widgets.ToggleButtons(\n options=[('gradino', 0), ('rampa', 1), ('parabola', 2)],\n description='Input: ',style=style)\n\nfig=plt.figure(num='Errore a regime')\nfig.set_size_inches((9.8,3))\nfig.set_tight_layout(True)\nf1 = fig.add_subplot(1, 1, 1)\n\nf1.grid(which='both', axis='both', color='lightgray')\n\nf1.set_ylabel('Input, output')\nf1.set_xlabel('$t$ [s]')\n\ninputf, = f1.plot([],[])\nresponsef, = f1.plot([],[])\nerrorf, = f1.plot([],[])\n\nann1=f1.annotate(\"\", xy=([0], [0]), xytext=([0], [0]))\nann2=f1.annotate(\"\", xy=([0], [0]), xytext=([0], [0]))\n\ndisplay(systemSelect)\ndisplay(functionSelect)\n\ndef create_draw_functions(K,a,b,c,index_system,index_input):\n \n num_of_samples = 1000\n total_time = 150\n t = np.linspace(0, total_time, num_of_samples) # time for which response is calculated (start, stop, step)\n \n if index_system == 0:\n \n Wsys = control.tf([K], [a, b, c])\n ess, G_s, s, n = sym.symbols('e_{step}(\\infty), G(s), s, n')\n sys1 = control.feedback(Wsys)\n \n elif index_system == 1:\n \n Wsys = control.tf([K,K,K*a], [1, b, c, 0])\n ess, G_s, s, n = sym.symbols('e_{step}(\\infty), G(s), s, n')\n sys1 = control.feedback(Wsys) \n \n global inputf, responsef, ann1, ann2\n \n if index_input==0:\n infunction = np.ones(len(t))\n infunction[0]=0\n tout, yout = control.step_response(sys1,t)\n s=sym.Symbol('s')\n if index_system == 0:\n limit_val = sym.limit((K/(a*s**2+b*s+c)),s,0)\n elif index_system == 1:\n limit_val = sym.limit((K*s*s+K*s+K*a)/(s*s*s+b*s*s+c*s),s,0)\n e_inf=1/(1+limit_val)\n \n elif index_input==1:\n infunction=t;\n tout, yout, xx = control.forced_response(sys1, t, infunction)\n if index_system == 0:\n limit_val = sym.limit(s*(K/(a*s**2+b*s+c)),s,0) \n elif index_system == 1:\n limit_val = sym.limit(s*((K*s*s+K*s+K*a)/(s*s*s+b*s*s+c*s)),s,0)\n e_inf=1/limit_val\n \n elif index_input==2:\n infunction=t*t\n tout, yout, xx = control.forced_response(sys1, t, infunction)\n if index_system == 0:\n limit_val = sym.limit(s*s*(K/(a*s**2+b*s+c)),s,0)\n elif index_system == 1:\n limit_val = sym.limit(s*s*((K*s*s+K*s+K*a)/(s*s*s+b*s*s+c*s)),s,0)\n e_inf=1/limit_val\n \n ann1.remove()\n ann2.remove() \n \n if type(e_inf) == sym.numbers.ComplexInfinity:\n print('L\\'errore a regime è infinito.')\n elif e_inf==0:\n print('L\\'errore a regime è zero.')\n else:\n print('L\\'errore a regime è uguale a %f.'% (e_inf,)) \n \n# if type(e_inf) == sym.numbers.ComplexInfinity:\n# display(Markdown('Steady-state error is infinite.'))\n# elif e_inf==0:\n# display(Markdown('Steady-state error is zero.'))\n# else:\n# display(Markdown('Steady-state error is equal to %f.'%(e_inf,)))\n\n \n if type(e_inf) != sym.numbers.ComplexInfinity and e_inf>0: \n ann1=plt.annotate(\"\", xy=(tout[-60],infunction[-60]), xytext=(tout[-60],yout[-60]), arrowprops=dict(arrowstyle=\"|-|\", connectionstyle=\"arc3\"))\n ann2=plt.annotate(\"$e(\\infty)$\", xy=(145, 1.), xytext=(145, (yout[-60]+(infunction[-60]-yout[-60])/2)))\n elif type(e_inf) == sym.numbers.ComplexInfinity:\n ann1=plt.annotate(\"\", xy=(0,0), xytext=(0,0), arrowprops=dict(arrowstyle=\"|-|\", connectionstyle=\"arc3\"))\n ann2=plt.annotate(\"\", xy=(134, 1.), xytext=(134, (1 - infunction[-10])/2 + infunction[-10]))\n elif type(e_inf) != sym.numbers.ComplexInfinity and e_inf==0: \n ann1=plt.annotate(\"\", xy=(0,0), xytext=(0,0), arrowprops=dict(arrowstyle=\"|-|\", connectionstyle=\"arc3\"))\n ann2=plt.annotate(\"\", xy=(134, 1.), xytext=(134, (1 - yout[-10])/2 + yout[-10]))\n \n f1.lines.remove(inputf)\n f1.lines.remove(responsef)\n \n inputf, = f1.plot(t,infunction,label='input',color='C0')\n responsef, = f1.plot(tout,yout,label='output',color='C1')\n \n f1.relim()\n f1.autoscale_view()\n \n f1.legend()\n\nK_slider=widgets.IntSlider(min=1,max=8,step=1,value=1,description='$K$',continuous_update=False)\na_slider=widgets.IntSlider(min=0,max=8,step=1,value=1,description='$a$',continuous_update=False)\nb_slider=widgets.IntSlider(min=0,max=8,step=1,value=1,description='$b$',continuous_update=False)\nc_slider=widgets.IntSlider(min=1,max=8,step=1,value=1,description='$c$',continuous_update=False)\n\ninput_data=widgets.interactive_output(create_draw_functions,\n {'K':K_slider,'a':a_slider,'b':b_slider,'c':c_slider,\n 'index_system':systemSelect,'index_input':functionSelect})\n\ndef update_sliders(index):\n global K_slider, a_slider, b_slider, c_slider\n \n Kval=[1, 1, 1]\n aval=[1, 1, 1]\n bval=[2, 2, 2]\n cval=[6, 6, 6]\n \n K_slider.value=Kval[index]\n a_slider.value=aval[index]\n b_slider.value=bval[index]\n c_slider.value=cval[index]\n \ninput_data2=widgets.interactive_output(update_sliders,\n {'index':functionSelect})\n\n\ndisplay(K_slider,a_slider,b_slider,c_slider,input_data)\n```\n\n\n \n\n\n\n\n\n\n\n ToggleButtons(description='Sistema: ', options=(('nessun integratore', 0), ('un integratore', 1)), style=Toggl…\n\n\n\n ToggleButtons(description='Input: ', options=(('gradino', 0), ('rampa', 1), ('parabola', 2)), style=ToggleButt…\n\n\n\n IntSlider(value=1, continuous_update=False, description='$K$', max=8, min=1)\n\n\n\n IntSlider(value=1, continuous_update=False, description='$a$', max=8)\n\n\n\n IntSlider(value=2, continuous_update=False, description='$b$', max=8)\n\n\n\n IntSlider(value=6, continuous_update=False, description='$c$', max=8, min=1)\n\n\n\n Output()\n\n", "meta": {"hexsha": "f44e9811ad622a62bd9536fc2d964fceb0ee8492", "size": 135861, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/02/.ipynb_checkpoints/TD-17-Errore-a-regime-checkpoint.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_it/examples/02/TD-17-Errore-a-regime.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_it/examples/02/TD-17-Errore-a-regime.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": 110.9069387755, "max_line_length": 86305, "alphanum_fraction": 0.7936346707, "converted": true, "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.22000709974589316, "lm_q1q2_score": 0.07827300248433779}} {"text": "```python\nfrom IPython.core.display import display_html\nfrom urllib.request import urlopen\n\ndisplay_html(urlopen('http://bit.ly/1GioOFw').read(), raw=True)\n```\n\n\n\n\n\n\n\n\n\n\n# Recapitulación de resultados empleados\n\n## Control predictivo\n\n## Implementación del retardo distribuido y sus problemas\n\n## Solución por medio de estabilización simultanea\n\n## Solución por medio de introducción de dinámicas\n\n# Implementación de control predictivo: ejemplo escalar\n\n## Resultados del articulo \"Some problems arising in the implementation of distributed-delay control laws\"\n\n# Implementación del método de estabilización simultanea\n\n## Ejemplo 1 - Doble integrador retardado\n\nPara el sistema:\n\n$$\n\\dot{x}(t) =\n\\begin{pmatrix}\n0 & 1 \\\\\n0 & 0\n\\end{pmatrix}\nx(t) +\n\\begin{pmatrix}\n0 \\\\\n1\n\\end{pmatrix}\nu(t - h)\n$$\n\ncon $h = 1$.\n\nEl cual, bajo una ley de control de la forma:\n\n$$\nu(t) = k \\left[ x(t) + \\int_{-h}^0 e^{-A(\\theta + h)} B u(t + \\theta) d\\theta \\right]\n$$\n\ntiene un polinomio caracteristico:\n\n$$\ns^2 + \\left( h k_1 - k_2 \\right) s - k_1\n$$\n\nAl cual podemos aplicar el criterio de estabilidad de Routh-Hurwitz y obtener:\n\n$$\n\\begin{align}\nk_1 &< 0 \\\\\nk_2 &< h k_1\n\\end{align}\n$$\n\nPor lo que la gráfica de D-particiones del sistema en lazo cerrado se verá:\n\n\n\nPor otro lado, para analizar el comportamiento del controlador, sustituimos los datos en la ecuación del controlador:\n\n$$\n\\begin{align}\nu(t) &=\n\\begin{pmatrix}\nk_1 & k_2\n\\end{pmatrix} x(t) +\n\\begin{pmatrix}\nk_1 & k_2\n\\end{pmatrix}\n\\int_{-h}^0 e^{-A(\\theta + h)} B u(t + \\theta) d\\theta \\\\\n&=\n\\begin{pmatrix}\nk_1 & k_2\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1(t) \\\\\nx_2(t)\n\\end{pmatrix} +\n\\begin{pmatrix}\nk_1 & k_2\n\\end{pmatrix}\n\\int_{-h}^0 e^{-A(\\theta + h)} B u(t + \\theta) d\\theta \\\\\n\\end{align}\n$$\n\n$$\n\\begin{align}\nu(t) &=\n\\begin{pmatrix}\nk_1 & k_2\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1(t) \\\\\nx_2(t)\n\\end{pmatrix} +\n\\int_{-h}^0\n\\begin{pmatrix}\nk_1 & k_2\n\\end{pmatrix}\n\\begin{pmatrix}\n1 & - (\\theta +h) \\\\\n0 & 1\n\\end{pmatrix}\n\\begin{pmatrix}\n0 \\\\\n1\n\\end{pmatrix} u(t + \\theta) d\\theta \\\\\n&= k_1 x_1(t) + k_2 x_2(t) - \\int_{-h}^0 k_1 \\theta u(t + \\theta) d\\theta - \\int_{-h}^0 k_1 h u(t + \\theta) d\\theta + \\int_{-h}^0 k_2 u(t + \\theta) d\\theta \\\\\n\\end{align}\n$$\n\ny al aplicar la transformada de Laplace, tenemos:\n\n$$\nu(s) = k_1 x_1(s) + k_2 x_2(s) - h k_1 \\frac{e^{-hs}}{s} u(s) + k_1 \\frac{1 - e^{-hs}}{s^2} u(s) - h k_1 \\frac{1 - e^{-hs}}{s} u(s) + k_2 \\frac{1 - e^{-hs}}{s} u(s)\n$$\n\npor lo que al pasar a un solo lado todos los terminos de $u(s)$:\n\n$$\n\\begin{align}\n\\left[ 1 + h k_1 \\frac{e^{-hs}}{s} - k_1 \\frac{1 - e^{-hs}}{s^2} + h k_1 \\frac{1 - e^{-hs}}{s} - k_2 \\frac{1 - e^{-hs}}{s} \\right] u(s) &= k_1 x_1(s) + k_2 x_2(s) \\\\\n\\left[ 1 + \\frac{h k_1 e^{-hs}}{s} - \\frac{k_1}{s^2} + \\frac{k_1 e^{-hs}}{s^2} + \\frac{h k_1}{s} - \\frac{h k_1 e^{-hs}}{s} - \\frac{k_2}{s} + \\frac{k_2 e^{-hs}}{s} \\right] u(s) &= k_1 x_1(s) + k_2 x_2(s) \\\\\n\\left[ 1 - \\frac{k_1}{s^2} + \\frac{k_1 e^{-hs}}{s^2} + \\frac{h k_1}{s} - \\frac{k_2}{s} + \\frac{k_2 e^{-hs}}{s} \\right] u(s) &= k_1 x_1(s) + k_2 x_2(s) \\\\\n\\left[ 1 + \\frac{k_1 e^{-hs} - k_1}{s^2} + \\frac{h k_1 + k_2 e^{-hs} - k_2}{s} \\right] u(s) &= k_1 x_1(s) + k_2 x_2(s)\n\\end{align}\n$$\n\nobtenemos el polinomio caracteristico de la ecuación de control:\n\n$$\n1 + \\frac{k_1 e^{-hs} - k_1}{s^2} + \\frac{h k_1 + k_2 e^{-hs} - k_2}{s}\n$$\n\ny al sustituir $s = j \\omega$, obtendremos dos ecuaciones, correspondientes a la parte real e imaginaria:\n\n$$\n\\begin{align}\nk_1 \\left[ \\omega h - \\sin{(\\omega h)} \\right] - k_2 \\left[ \\omega - \\cos{(\\omega h)} \\right] &= 0 \\\\\n- k_1 \\left[ 1 - \\cos{(\\omega h)} \\right] + k_2 \\left[ \\omega \\sin{(\\omega h)} \\right] - \\omega^2 &= 0 \\\\\n\\end{align}\n$$\n\npor lo que podemos despejar $k_2$ de ambas ecuaciones y obtener:\n\n$$\nk_2 = \\frac{k_1 \\left[ \\omega h - \\sin{(\\omega h)} \\right]}{\\omega - \\cos{(\\omega h)}} = \\frac{k_1 \\left[ 1 - \\cos{(\\omega h)} \\right] + \\omega^2}{\\omega \\sin{(\\omega h)}}\n$$\n\ny haciendo un poco de algebra, podemos obtener:\n\n$$\n\\frac{k_1 \\left[ \\omega h - \\sin{(\\omega h)} \\right]}{\\omega - \\cos{(\\omega h)}} = \\frac{k_1 \\left[ 1 - \\cos{(\\omega h)} \\right] + \\omega^2}{\\omega \\sin{(\\omega h)}}\n$$\n\n$$\n\\frac{k_1 \\left[ \\omega h - \\sin{(\\omega h)} \\right] \\left[ \\omega \\sin{(\\omega h)} \\right]}{\\omega - \\cos{(\\omega h)}} - k_1 \\left[ 1 - \\cos{(\\omega h)} \\right] = \\omega^2\n$$\n\n$$\nk_1 \\frac{\\left[ \\omega h - \\sin{(\\omega h)} \\right] \\left[ \\omega \\sin{(\\omega h)} \\right] - \\left[ 1 - \\cos{(\\omega h)} \\right] \\left[ \\omega - \\cos{(\\omega h)} \\right]}{\\omega - \\cos{(\\omega h)}} = \\omega^2\n$$\n\n$$\nk_1 = \\frac{\\omega^2 \\left[ \\omega - \\cos{(\\omega h)} \\right]}{\\left[ \\omega h - \\sin{(\\omega h)} \\right] \\left[ \\omega \\sin{(\\omega h)} \\right] - \\left[ 1 - \\cos{(\\omega h)} \\right] \\left[ \\omega - \\cos{(\\omega h)} \\right]}\n$$\n\nSi sustituimos un punto por debajo de esta curva, $(k_1, k_2) = (0, 0)$, podemos ver que el polinomio caracteristico es trivialmente estable por el criterio de Routh-Hurwitz:\n\n$$\nP(s) = 1\n$$\n\npor lo que la gráfica de D-particiones para el controlador queda:\n\n\n\nY el sistema con este controlador será estable para los valores de $k_1$ y $k_2$ escogidos tal que se encuentren en la intersección de estas dos regiones:\n\n\n\n## Ejemplo 2 - Oscilador armónico retardado\n\nPara el sistema:\n\n$$\n\\dot{x}(t) =\n\\begin{pmatrix}\n0 & 1 \\\\\n-1 & 0\n\\end{pmatrix}\nx(t) +\n\\begin{pmatrix}\n0 \\\\\n1\n\\end{pmatrix}\nu(t - h)\n$$\n\ncon $h = 1$.\n\nEn lazo cerrado tiene un cuasiplolinomio:\n\n$$\ns^2 + \\frac{1}{2} s\\left[ -j k_1 \\left( e^{jh} - e^{-jh} \\right) - k_2 \\left( e^{jh} + e^{-jh} \\right) \\right] + \\frac{1}{2} \\left[ -k_1 \\left( e^{jh} + e^{-jh} \\right) + j k_2 \\left( e^{jh} - e^{-jh} \\right) \\right]\n$$\n\nCon una gráfica de D-particiones:\n\n\n\nPara el controlador tenemos un cuasipolinomio caracteristico:\n\n$$\ns^2 + 1 + k_1 j \\left( s \\sin{(h)} - \\cos{(h)} + e^{-sh} \\right) + k_2 \\left( \\sin{(h)} + s \\cos{(h)} - s e^{-sh} \\right)\n$$\n\ncon una gráfica de D-Particiones:\n\n\n\n# Implementación del método de introducción de dinámicas\n", "meta": {"hexsha": "cf393b65504d6028ecd9afaa3ae9ace19adc894e", "size": 13989, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPythonNotebooks/Sistemas con retardo en la entrada/Trabajo Final - Sistemas con retardo en la entrada.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/Trabajo Final - Sistemas con retardo en la entrada.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/Trabajo Final - Sistemas con retardo en la entrada.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": 30.8127753304, "max_line_length": 259, "alphanum_fraction": 0.4560011438, "converted": true, "num_tokens": 3039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.23370635157681105, "lm_q1q2_score": 0.07819567759140586}} {"text": "\n\n\n\n# Some Linear Algebra with Cython\n\nCarl Vogel    |   @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\n

or $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\n

is $\\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\n

since 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\n

or $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\n

which 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\n

or $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\n

giving 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\n

where $y \\equiv Ux$. We can easily solve for $y$ using forward substitution. Having done that, we have

\n\n$$\nUx = y\\,,\n$$\n\n

and 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\n
\n\n\n\n# Fit of Zero-Loss Peak\n\n[Download](https://raw.githubusercontent.com/gduscher/MSE672-Introduction-to-TEM/main/Spectroscopy/CH4_02-Fit_Zero_Loss.ipynb)\n \n[](\n https://colab.research.google.com/github/gduscher/MSE672-Introduction-to-TEM/blob/main/Spectroscopy/CH4_02-Fit_Zero_Loss.ipynb)\n\n\npart of \n\n **[MSE672: Introduction to Transmission Electron Microscopy](../_MSE672_Intro_TEM.ipynb)**\n\nby Gerd Duscher, Spring 2021\n\nMicroscopy Facilities
\nJoint Institute of Advanced Materials
\nMaterials Science & Engineering
\nThe University of Tennessee, Knoxville\n\nBackground and methods to analysis and quantification of data acquired with transmission electron microscopes.\n\n\n\n## Content\n\nThe zero-loss peak in an EELS spectrum gives us two important infomations:\n * the origin of the energy-scale\n * the zero-loss peak is the resolution function of our spectrum\n \nOften we need to subtract or know this resolution function very accurately for a precise analysis of EELS spectra.\n\nThe area under the peak gives us the number of electron that are not inelatically scattered, and in relation to the total count a measure for the thickness of the sample.\n\n### Energy Resolution and Zero-Loss Peak\n\nThe first peak in the Electron Energy Loss Spectrum (EELS) is the so called ``Zero-Loss`` peak.\nThis zero-loss peak is formed by all the electrons that are\n- not scattered, \n- elastically scattered, and\n- quasi--elastically scattered.\n\n>\n>We can use it as a measure of the energy resolution of the system.}\n >\n \n This is called a response function in information theory.\n\n\nThe full width at half maximum (FWHM) of the ``Zero-Loss peak`` is what we usually declare as energy resolution in an EELS spectrum.\n\nThe energy resolution has three sources:\n- the energy spread of the electrons before they reach the specimen ($\\Delta\\mbox{E}_0$),\n- the energy spread that is added by quasi-elastic interactions with the specimen($\\Delta\\mbox{E}_{ph}$),\n- the spectrometer resolution ($\\Delta\\mbox{E}_{S_0}$),\n- the energy dispersion ($s/D$).\n\nThese components usually treated as independent and summed up as squares of their values.\nThe measured resolution $\\Delta$E is given by:\n\n\\begin{equation} \\Large \n\\label{energy-resolution} \n\\Delta{\\rm E}^2 \\approx \\Delta\\mbox{E}_0^2 + \\Delta\\mbox{E}_{S_0}^2 + (s/D)^2\n\\end{equation}\n \nPlease note that the quasi-elastic interactions are not added here and, therefore, I assume to go through the vacuum only.\n\n#### Contribution of Electron Source\n - The energy spread before the sample $\\Delta$E$_0$ is the energy spread of the electron source broadened by the Boersch effect. \n- The energy spread of the source is a directly proportional to the temperature due to the Fermi--Dirac distribution. \n- The Boersch effect is an additional broadening caused by the Coulomb interaction of the electrons, and is therefore more pronounced in higher density electron beams.\n- Monochromators will select a part of the original energy spread and thus increase energy resolution.\n#### Contribution of Spectrometer\n- The spectrometer resolution $\\Delta$E$_{S0}$ is due to the aberration of the electron optics.\n- This aberration is worse for larger collection angles.\n- Aberration correctors will improve the spectrometer resolution.\n\n#### Contribution of Detector}\n\nThe spatial resolution of the electron detector $s$ (equivalent to the width of the slid of a serial spectrometer) and the spectrometer dispersion $D$ are the final contributions to the total energy resolution.\n### Choices of Dispersion\n- A small energy dispersion will allow a high energy resolution\\\\\n- A large energy dispersion enables to samples a large energy window \n\n\n## Load important packages\n\n### Check Installed Packages\n\n\n\n```python\nimport sys\nfrom pkg_resources import get_distribution, DistributionNotFound\n\ndef test_package(package_name):\n \"\"\"Test if package exists and returns version or -1\"\"\"\n try:\n version = get_distribution(package_name).version\n except (DistributionNotFound, ImportError) as err:\n version = '-1'\n return version\n\n# Colab setup ------------------\nif 'google.colab' in sys.modules:\n !pip install pyTEMlib -q\n# pyTEMlib setup ------------------\nelse:\n if test_package('pyTEMlib') < '0.2021.3.22':\n print('installing pyTEMlib')\n !{sys.executable} -m pip install --upgrade pyTEMlib -q\n# ------------------------------\nprint('done')\n```\n\n done\n\n\n### Import all relevant libraries\n\nPlease note that the EELS_tools package from pyTEMlib is essential.\n\n\n```python\nimport sys\nif 'google.colab' in sys.modules:\n %pylab --no-import-all inline\nelse: \n %pylab --no-import-all notebook\n %gui qt\n \nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom scipy.optimize import leastsq ## fitting routine of scipy\n\n# Import libraries from the book\nimport pyTEMlib\nimport pyTEMlib.file_tools as ft # File input/ output library\nfrom pyTEMlib import eels_tools \n\n# For archiving reasons it is a good idea to print the version numbers out at this point\nprint('pyTEM version: ',pyTEMlib.__version__)\n```\n\n Populating the interactive namespace from numpy and matplotlib\n pyTEM version: 0.2021.04.02\n\n\n## Load and plot a spectrum\nplease see [Introduction to EELS](CH4_01-Introduction.ipynb) for details\n\n\n```python\n# Load file\nfilename = '../example_data/AL-DFoffset0.00.dm3'\neels_dataset = ft.open_file(filename)\nif eels_dataset.data_type.name != 'SPECTRUM':\n print('We need an EELS spectrum for this notebook')\neels_dataset.plot()\n```\n\n Cannot overwrite file. Using: AL_DFoffset0.00-1.hf5\n\n\n\n \n\n\n\n\n\n\n### Important Parameters in an EELS spectrum\n\n\n```python\neels_dataset.metadata = eels_tools.read_dm3_eels_info(eels_dataset.original_metadata)\neels_dataset.view_metadata()\n```\n\n single_exposure_time : 0.1\n exposure_time : 10.0\n number_of_frames : 100\n collection_angle : 100.0\n convergence_angle : 0.0\n acceleration_voltage : 199990.28125\n microscope : Libra COM\n\n\n\n\n\n```python\n\n```\n\n## Simple Zero-Loss Integration\n\nThe inelastic mean free path is hard to determine and depends on the effective collection angle (convolution of collection and convergence angle) and the acceleration voltage. None of these parameters are likely to be tabulated for your experimental set-up.\n\nHowever, the relative thickness is a valuable parameter to judge your sample location and the validity of your spectrum.\n\n\nIn a good sample 70 to 90% of the electrons do not interact. \nThe relative thickness $t$ in terms of the inelatic mean free path (IMFP) is given by:\n$$ t = \\ln\\left(\\frac{I_{total}}{I_{ZL}} \\right) * IMFP$$\n\nwith:\n\n$I_{total}$: total intensity of spectrum\n\n$I_{ZL}$: intensity of zero-loss peak\n\nWe first estimate the intensity of the zero-loss peak by a summation of the spectrum in a specific energy-loss range.\n\n\n\n```python\nspectrum = np.array(eels_dataset)\nenergy_scale = eels_dataset.energy_loss.values\noffset = eels_dataset.energy_loss[0]\ndispersion = ft.get_slope(eels_dataset.energy_loss)\nstart = int((-2-offset)/dispersion)\nend = int((4-offset)/dispersion)\n\nsumZL = sum(spectrum[start:end])\nsumSpec = sum(spectrum)\n\nprint(f\"Counts in zero-loss {sumZL:.0f} , total counts {sumSpec:.0f}\")\nprint(f\"{(sumSpec-sumZL)/sumSpec*100:.1f} % of spectrum interact with specimen\") \n\ntmfp = np.log(sumSpec/sumZL)\nprint ('Sample thickness in Multiple of the ')\nprint (f'thickness [IMFP]: {tmfp:.3f}')\n\n```\n\n Counts in zero-loss 4123429588 , total counts 4875544752\n 15.4 % of spectrum interact with specimen\n Sample thickness in Multiple of the \n thickness [IMFP]: 0.168\n\n\n## Fitting the Zero-Loss with a Gausian\nWhile a Gaussian does not describe the shape of the zero-loss peak well, we will use it to determine the zero-loss peak position.\n\n>\n> The energy resolution is best measured from the zero-loss without sample (through vacuum), because the quasi elastic scattering will result in a small but noticeable broadening of the zero-loss.\n>\n\nThe maximum of the fitted Gaussian is then the origin of the energy scale.\n\n\n```python\n###\n# This function is also in the eels_tools of pyTEMlib\n\ndef fix_energy_scale( spec, energy):\n \n startx = np.argmax(spec)\n end = startx+3\n start = startx-3\n for i in range(10):\n if spec[startx-i]<0.3*spec[startx]:\n start = startx-i\n if spec[startx+i]<0.3*spec[startx]:\n end = startx+i\n if end-start<3:\n end = startx+2\n start = startx-2\n \n x = np.array(energy[start:end])\n y = np.array(spec[start:end]).copy()\n \n y[np.nonzero(y<=0)] = 1e-12\n\n\n def gauss(x, p): # p[0]==mean, p[1]= area p[2]==fwhm, \n return p[1] * np.exp(-(x- p[0])**2/(2.0*( p[2]/2.3548)**2))\n\n def errfunc(p, x, y):\n err = (gauss(x, p)-y )/np.sqrt(y) # Distance to the target function\n return err\n \n p0 = [energy[startx],1000.0,1] # Inital guess is a normal distribution\n p1, success = leastsq(errfunc, p0[:], args=(x, y))\n\n fit_mu, area, FWHM = p1\n \n return FWHM, fit_mu\n```\n\n\n```python\nFWHM, fit_mu = fix_energy_scale(spectrum, energy_scale)\nprint(f'FWHM: {FWHM:.2f} eV , with shift of {fit_mu:.2f} eV')\n```\n\n FWHM: -0.18 eV , with shift of -0.13 eV\n\n\n\n```python\nGap = 2\n\n## energy range of fit\nstartx = int(abs(offset/dispersion ))+1 ## zero eV\nwidthx = int(abs(Gap /dispersion )) ## fit width\n## We need 6 parameter to fit the resolution function\n## and so at least 6 channels for the fit\nif widthx*2 < 6:\n Gap = 3*dispersion\n widthx = 3\n\nendx = int(startx+widthx)\nstartx = int(startx-widthx)\n\nprint('Fit of Zero Loss from channel ', startx, ' to ',endx)\nprint('Fit of Zero Loss from ', startx*dispersion+offset, 'eV to ',endx*dispersion+offset, 'eV')\n\n# energy scale and spectrum in the fitting window\nx = energy_scale[startx:endx]\ny = np.array(spectrum[startx:endx]).flatten()\n\n\ndef gauss(x, p): \n \"\"\"\n Gaussian distribution\n Input: \n p: list or array p[0]=position, p[1]= area p[2]==fwhm, \n x: energy axis \n \"\"\"\n p[2] = abs(p[2])\n return p[1] * np.exp(-(x- p[0])**2/(2.0*( p[2]/2.3548)**2))\n\n\n# Fit a Gaussian\ny[np.nonzero(y<=0)] = 1e-12\np0 = [0,1000.0,1] # Inital guess is a normal distribution\nerrfunc = lambda p, x, y: (gauss(x, p) - y)/np.sqrt(y) # Distance to the target function\np1, success = leastsq(errfunc, p0[:], args=(x, y)) # The Fit\n\nprint(f'Zero-loss position was {p1[0]:.2f} eV')\nenergy_scale=energy_scale-p1[0]\nprint('Corrected energy axis')\np1[0]=0.0\nGauss = gauss(energy_scale,p1)\n\n\nprint(f'Width (FWHM) is {p1[2]:.2f} eV')\nprint(f'Probability is {sum(Gauss)/sumSpec*1e2:.2f} %')\ntmfp = np.log(sumSpec/sum(Gauss))\nprint(f'Thickness is {tmfp:.3f} * IMFP')\n\nerr = (y - gauss(x, p1))/np.sqrt(y)\nprint ('Goodness of Fit: ' ,sum(err**2)/len(y)/sumSpec*1e2, '%')\n\n\nabs(offset/dispersion )\nstart =int((-2-offset)/dispersion)\nend = int((8-offset)/dispersion)\n\nplt.figure()\n\nplt.plot(energy_scale, spectrum/sumSpec*1e2,label='spectrum')\nplt.plot(energy_scale, Gauss/sumSpec*1e2, label='Gaussian')\nplt.plot(energy_scale, (spectrum-Gauss)/sumSpec*1e2, label='difference')\nplt.legend()\nplt.title (' Gauss Fit of Zero-Loss Peak')\nplt.xlim(-4,4)\nIzl = Gauss.sum()\nItotal = spectrum.sum()\ntmfp = np.log(Itotal/Izl)\nprint('Sum of Gaussian: ', Izl)\nprint('Sum of Spectrum: ', Itotal)\nprint ('thickness [IMFP]: ', tmfp)\nplt.ylabel('scattering probability [%]')\nplt.xlabel('energy-loss [eV]');\n```\n\n Fit of Zero Loss from channel 81 to 279\n Fit of Zero Loss from -1.9790236416234848 eV to 2.0059675176665905 eV\n Zero-loss position was -0.13 eV\n Corrected energy axis\n Width (FWHM) is 0.20 eV\n Probability is 79.14 %\n Thickness is 0.234 * IMFP\n Goodness of Fit: 1.2907932776862232 %\n\n\n\n \n\n\n\n\n\n\n Sum of Gaussian: 3858665454.638932\n Sum of Spectrum: 4875544600.0\n thickness [IMFP]: 0.2339104195526817\n\n\nIn the above figure, we show a zero-loss peak fitted with a Gaussian. \n- oom in so that you can see the zero-Loss only.\n- The zero--loss peak is about 8% high and you can read off the FWHM by going left and right where the zero-loss peak reaches 4%. \n\n- Therefore, the FWHM of this zero-loss peak is about 0.18 eV. This is obviously a high resolution spectrum.\n- Also, the shape of the zero-loss is not perfectly symmetric and the tails of the zero-loss peak extend far in both directions. \n- The position of the maximum of the zero-loss peak is used for calibrating the energy scale. The maximum indicates zero energy--loss. \n\n## Fitting the Zero-Loss with a Product of Two Lorentzians\nTo better describe the full shape we use the product of two Lorentzians.\n\nCompare the residuals of the Gaussian and Lorentzian fit. \n\nYou will zoom in closely to see the difference between experimental and model zero-loss peak here.\n\n\n```python\n#################################################################\n## fit Zero Loss peak with ZLfunct =\n## = convolution of Gauss with a product of two Lorentzians\n################################################################## \nwidth = 30\n\n\nstartx = np.argmax(spectrum)\nendx = startx+width\nstartx = startx-width\nprint (startx, endx, endx-startx)\n\n\nx = np.array(energy_scale[startx:endx])\ny = np.array(spectrum[startx:endx])\n\nprint(f\"Energy range for fit of zero-loss: {energy_scale[startx]:.2f} to {energy_scale[endx]:.2f}\")\n\n#guess = [0.02, 8000000, 0.1, 0.2, 1000,0.2,0.5, 1000,-0.5,-1.3, 1.01,1.0]\nguess = [ 0.2, 1000,0.02,0.2, 1000,0.2 ]\n\np0 = np.array(guess)\n\ndef ZL(p, y, x):\n err = (y - eels_tools.zl_func(p, x))#/np.sqrt(y)\n return err\n\npZL, lsq = leastsq(ZL, p0, args=(y, x), maxfev=2000)\nprint('Fit of a Product of two Lorentzians')\nprint('Positions: ',pZL[2],pZL[5], 'Distance: ',pZL[2]-pZL[5])\nprint('Width: ', pZL[0],pZL[3])\nprint('Areas: ', pZL[1],pZL[4])\nerr = (y - eels_tools.zl_func(pZL, x))/np.sqrt(np.abs(y))\nprint (f'Goodness of Fit: {sum(err**2)/len(y)/sumSpec*1e2:.5}%')\n\nzLoss = eels_tools.zl_func(pZL, energy_scale)\n\nplt.figure()\nplt.plot(energy_scale,spectrum/sumSpec*1e2 , label = 'spectrum')\n\nplt.plot(energy_scale, zLoss/sumSpec*1e2, label ='resolution function')\nplt.plot(energy_scale, (spectrum-zLoss)/sumSpec*1e2 , label = 'difference')\n\nplt.title ('Lorentzian Product Fit of Zero-Loss Peak')\n#plt.xlim(-5,5)\nplt.hlines(0, energy_scale[0], energy_scale[-1],color = 'gray')\nIzl = zLoss.sum()\nItotal = spectrum.sum()\ntmfp = np.log(Itotal/Izl)\nprint(f'Sum of Zero-Loss: {Izl:.0f} counts')\nprint(f'Sum of Spectrum: {Itotal:.0f} counts')\nprint (f'thickness [IMFP]: {tmfp:.5f}')\n```\n\n 143 203 60\n Energy range for fit of zero-loss: -0.60 to 0.61\n Fit of a Product of two Lorentzians\n Positions: 0.03100509789201818 -0.019130863289707808 Distance: 0.05013596118172599\n Width: 0.2949903227714955 0.1917939380558402\n Areas: 7619.761715379692 8587.87266432794\n Goodness of Fit: 0.0027237%\n\n\n\n \n\n\n\n\n\n\n Sum of Zero-Loss: 4083170973 counts\n Sum of Spectrum: 4875544576 counts\n thickness [IMFP]: 0.17736\n\n\n## Calibrating Energy Dispersion\n- The software controlling the spectrometer (or image filter) will allow you to select your energy dispersion.\n- The dispersion is set through the magnification within the spectrometer and each dispersion setting is internally a set of values for the lenses (quadrupoles).\n- This setting will only be accurate to about 10\\% which is not accurate enough to automatically rely on it.\n- Therefore, we usually calibrate the energy dispersion ourselves. \n- The drift tube high voltage power supply is reasonable accurate to do this dispersion calibration.\n\n**Practical Steps**\n- We collect a zero--loss (preferably but not necessarily in vacuum) without applied drift tube voltage. The zero--loss should be at the right hand of the display.\n- Then we collect a zero--loss peak with applied drift tube voltage, so that the zero-loss peak is at the left side of the display. \n\n\n\n\n- We now measure the number of channels between the two zero-loss peaks (make sure that there is no other energy dispersion selected. \n- We divide the voltage by this number and get the accurate energy dispersion. \n- In the case of the spectrum in figure above it is 300 eV / 265 channels = 1.17 eV/channel.\n\n>\n>The selected energy dispersion was 1.0 eV / channel}.\n>\n\n## Conclusion\n\nWe use a Gaussian fit to determine the zero energy channel and thus the origin of the energy-scale\n\nWe use a product of two Lorentzians to fit the zero-loss peak, we will use that fit as the resolution function for further analysis (everythin we measure is convoluted by that function).\n\nHere we used the area under the zero-loss peak to determine the relative thickness ( a relative thickness of 0.3 * IMFP is considered ideal for most experiments)\n\n## Navigation\n- **Up Chapter 4: [Imaging](CH4_00-Spectroscopy.ipynb)** \n- **Back: [Overview](CH4_01-Introduction.ipynb)** \n- **Next: [Analysing Low-Loss Spectra with Drude Theory](CH4_03-Drude.ipynb)** \n- **List of Content: [Front](../_MSE672_Intro_TEM.ipynb)** \n\n\n```python\n\n```\n", "meta": {"hexsha": "0c7cb6f625c8e82faf16f39f1e3739fa160275c6", "size": 361080, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Spectroscopy/CH4_02-Fit_Zero_Loss.ipynb", "max_stars_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_stars_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-22T18:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T20:17:34.000Z", "max_issues_repo_path": "Spectroscopy/CH4_02-Fit_Zero_Loss.ipynb", "max_issues_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_issues_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "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": "Spectroscopy/CH4_02-Fit_Zero_Loss.ipynb", "max_forks_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_forks_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-01-26T16:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T14:53:16.000Z", "avg_line_length": 97.8006500542, "max_line_length": 73507, "alphanum_fraction": 0.7471668328, "converted": true, "num_tokens": 4900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.1847675084034608, "lm_q1q2_score": 0.07806512866353166}} {"text": "Robotic Systems (draft)\n=================\n\nKris Hauser\n\nUniversity of Illinois at Urbana-Champaign\n\nLast update: 12/28/2020\n\nTable of Contents\n=================\n\n* [Preface](Preface.ipynb) **90% complete**\n\n* Section I. Introduction\n * [Chapter 1. What is robotics?](WhatIsRobotics.ipynb)\n * [Chapter 2. Anatomy of a robot](AnatomyOfARobot.ipynb)\n\n* Section II. Modeling\n\n * [Chapter 3. Coordinate transformations](CoordinateTransformations.ipynb)\n * [Chapter 4. 3D rotations](3DRotations.ipynb)\n * [Chapter 5. Robot kinematics](Kinematics.ipynb)\n * [Chapter 6. Inverse kinematics](InverseKinematics.ipynb)\n * [Chapter 7. Representing geometry](Geometry.ipynb) **text complete, figures 85% complete**\n\n* Section III. Motion Planning\n\n * [Chapter 8. What is motion planning?](WhatIsMotionPlanning.ipynb)\n * [Chapter 9. Motion planning in simple geometric spaces](GeometricMotionPlanning.ipynb) \n * [Chapter 10. Motion planning in higher dimensions](MotionPlanningHigherDimensions.ipynb) **text complete, figures 85% complete**\n * [Chapter 11. Planning with dynamics and uncertainty](PlanningWithDynamicsAndUncertainty.ipynb) **text 95% complete, figures 70% complete**\n * [Chapter 12. Advanced topics in planning](AdvancedTopicsInPlanning.ipynb) **15% complete**\n\n* Section IV. Dynamics and Control\n\n * [Chapter 13. What are dynamics and control?](WhatAreDynamicsAndControl.ipynb) **Text 90% complete, figures 70% complete**\n * [Chapter 14. Robot dynamics](RobotDynamics.ipynb) **incomplete**\n * [Chapter 15. Stabilizing controlled systems](Control.ipynb) **50% complete**\n * [Chapter 16. Control of articulated robots](RobotControl.ipynb) **text 95% complete, figures 75% complete**\n * [Chapter 17. Optimal control](OptimalControl.ipynb) **text 95% complete, figures 0% complete**\n\n* Section V. Perception **incomplete**\n * Chapter 18. State estimation\n * Chapter 19. 3D Mapping\n * Chapter 20. Image processing\n * Chapter 21. Computer vision\n\n* Section VI. Learning and Calibration **incomplete**\n * [Chapter 22. Calibration](Calibration.ipynb) **text 75% complete, figures 40% complete**\n * Chapter 23. Function approximation **incomplete**\n * Chapter 24. Supervised machine learning **incomplete**\n * Chapter 25. Reinforcement learning **incomplete**\n\n* Section VII. Robotic Systems in Practice **incomplete**\n * Chapter 26. System integration\n * Chapter 27. Systems engineering\n * Chapter 28. Human-robot interaction\n * Chapter 29. Applications\n\n* Appendix A. Mathematical Preliminaries\n\n * [A.1. Linear algebra](LinearAlgebra.ipynb)\n * [A.2. Real analysis and calculus of many variables](Calculus.ipynb)\n * [A.3. Probability distributions](Probability.ipynb)\n \n* Appendix B. Numerical Methods\n\n * [B.1. Numerical errors](NumericalErrors.ipynb)\n * [B.2. Matrix computations](MatrixComputations.ipynb) **20% complete**\n * [B.3. Optimization](Optimization.ipynb) **text 90% complete, figures 10% complete**\n\n* Appendix C. Computational Methods \n\n * [C.1. Data structures](DataStructures.ipynb)\n * [C.2. Graph search](GraphSearch.ipynb)\n \n\nAbout\n=================\n\nThis book is a work in progress! The source material is my lecture notes from courses at Indiana University, Duke University, and University of Illinois at Urbana-Champaign, which are progressively being converted to Jupyter Notebook and HTML format. \n\nThe conversion tools that I am using may create broken matrix equations, links, references, or incorrectly formatted figures. I am trying to correct them as I go, but I may miss some. If you notice anything that needs correcting, please email me at [kkhauser@illinois.edu](mailto:kkhauser@illinois.edu). Or better yet, make the corrections in the notebook directly and [issue a Git pull request](https://help.github.com/articles/about-pull-requests/).\n\n\nOptions for Working with Jupyter Notebook\n==================\n\nThe book comes in [HTML](https://motion.cs.illinois.edu/RoboticSystems/) and Jupyter Notebook formats, and running the full Jupyter Notebook provides the most complete experience, with inline quizzes and code examples that you can visualize and edit live in your browser.\n\nThere are three routes to running the Jupyter notebooks:\n- [Binder](#Running-on-Binder)\n- [Google Colab](#Running-on-Google-Colab)\n- [Local Jupyter installation](#Jupyter-Notebook-installation-on-local-machine)\n\n### Running on Binder\n\n[Binder](https://mybinder.org/) is a very nice service that we've pre-configured to have all dependencies needed to run this book. Just click here:\n\n[](https://mybinder.org/v2/gh/krishauser/RoboticSystemsBook-binder/main?urlpath=git-pull%3Frepo%3Dhttps%253A%252F%252Fgithub.com%252Fkrishauser%252FRoboticSystemsBook%26urlpath%3Dtree%252FRoboticSystemsBook%252FBook.ipynb%26branch%3Dmaster)\n\nThat's it!\n\n*Binder pros*:\n\n- Stupidly easy to start.\n- Runs everywhere.\n- Almost completely full-featured; runs interactive Klamp't visualizations.\n- Integrates nicely with Github; automatically gets updates to the Github repo.\n\n*Binder cons*:\n\n- Relative slow boot time (10–20s).\n- Can't easily save / restore your work – you will need to manually Download or Save to Browser Storage.\n\n### Running on Google Colab\n\nI am progressively updating the book to be compatible with Google Colab, and this is the second-easiest way to get started. Just click on the following link:\n\n[](https://colab.research.google.com/github/krishauser/RoboticSystemsBook/blob/master/Book.ipynb )\n\n*Colab pros*:\n\n- Runs everywhere\n- Integrates nicely with Github; automatically gets updates to the Github repo.\n- Klamp't can output static visualizations of 3D worlds and animations\n\n*Colab cons*:\n\n- Equations are not numbered and cross-references don't work. \n- Need to insert / run extra code cells to enable interactive quizzes and code.\n- Klamp't visualization windows are not interactive due to Colab incompatibility with custom IPython widgets.\n- The Table of Contents feature only works with cells that start with a header. These are being updated slowly...\n\n*Colab installation*: \n\nNo installation needed. \n\nTo run interactive quizzes and code, you will need to insert and run a code cell containing the following code:\n\n```c++\n%cd ~\n!git clone --depth 1 https://github.com/krishauser/RoboticSystemsBook\n%cd RoboticSystemsBook\nimport rsbook_code\n!pip install klampt\n```\n\nwhich will import the code examples for this book and install Klampt.\n\n### Jupyter Notebook installation on local machine\n\n[Jupyter Notebook](https://jupyter.org/) is the native source of this book, and installing this on your machine will allow you to run truly interactive examples. \n\n*Jupyter pros*\n\n- Runs interactive Klamp't windows.\n- All features supported.\n- Can switch to native OpenGL visualization for more features, if desired.\n- Closer to production robotics code.\n\n*Jupyter cons*\n\n- Need to install on your local machine. Possible compability issues with other Python installs, e.g., Anaconda.\n\n*Jupyter Installation*:\n\n1. Install software for running the notebook:\n\n * [Git](https://git-scm.com/download)\n * Python 3.5+ and [Jupyter Notebook](http://jupyter.org), or a Python distribution like Anaconda.\n * [Klamp't](https://github.com/krishauser/Klampt) 0.8.5+ Python API.\n * [Klampt-jupyter-extension](http://github.com/krishauser/Klampt-jupyter-extension) for live Klamp't windows.\n * [jupyter_contrib_nbextensions](https://github.com/ipython-contrib/jupyter_contrib_nbextensions) for LaTeX and table of content support. \n \nOn most systems (Linux, Windows, OSX), the Klamp't Python API can be installed using `pip` as follows:\n\n```bash\npip install klampt\n```\n\n(Note that the Klamp't source is the most up-to-date way to install Klamp't, and is mostly pain-free on Linux and OSX platforms. )\n\nTo install Klampt-jupyter-extension, run\n\n```bash\ngit clone https://github.com/krishauser/Klampt-jupyter-extension.git\ncd Klampt-jupyter-extension\nmake install-user\ncd ..\n```\n\nNext, to enable the best reading experience, we will install the `jupyter_contrib_nbextensions` package and enable the \"(some) LaTeX environments for Jupyter\", \"Table of Contents\", and \"Codefolding\" Jupyter Notebook plugins. To do so, run\n\n```bash\npip install jupyter_contrib_nbextensions\njupyter contrib nbextension install --user\njupyter nbextension enable --py widgetsnbextension\njupyter nbextension enable codefolding/main\njupyter nbextension enable latex_envs/latex_envs\njupyter nbextension enable toc2/main\njupyter nbextension enable equation-numbering/main\n```\n\n2. Download the book source from Github:\n\n```bash\ngit clone https://github.com/krishauser/RoboticSystemsBook\n```\n\n3. Run Jupyter Notebook from the RoboticSystemsBook directory using the console command:\n\n```bash\ncd RoboticSystemsBook\njupyter notebook\n```\n\nThis will launch a web browser interface to Jupyter.\n\n5. Open the Jupyter Notebook files to browse (this page is named `Book.ipynb`). Happy reading!\n\n(Note: you must run Jupyter in the `RoboticSystemsBook` folder to have access to the interactive quizzes and exercises, which use code in the `rsbook_code` folder)\n\n\nKnown issues\n============\n\nJupyter Notebook LaTeX rendering uses MathJAX inside Markdown, which occasionally has trouble rendering complex equations. If you see stray code like `= \\begin{equation}` etc, this is a [known rendering problem](https://github.com/jupyter/notebook/issues/2865) with multiple matrices. It seems like this problem is more prevalent in static HTML and Colab; try opening the book in a native Jupyter Notebook or on Binder if these rendering issues prevent you from understanding the equation.\n\n\n```python\n\n```\n", "meta": {"hexsha": "6e2ccf5109503b08361387cb7579bc9601fb7713", "size": 13886, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Book.ipynb", "max_stars_repo_name": "patricknaughton01/RoboticSystemsBook", "max_stars_repo_head_hexsha": "0fc67cbccee0832b5f9b00d848c55697fa69bedf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 116, "max_stars_repo_stars_event_min_datetime": "2018-08-27T15:32:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T10:41:37.000Z", "max_issues_repo_path": "Book.ipynb", "max_issues_repo_name": "patricknaughton01/RoboticSystemsBook", "max_issues_repo_head_hexsha": "0fc67cbccee0832b5f9b00d848c55697fa69bedf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-04T12:56:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T23:13:33.000Z", "max_forks_repo_path": "Book.ipynb", "max_forks_repo_name": "patricknaughton01/RoboticSystemsBook", "max_forks_repo_head_hexsha": "0fc67cbccee0832b5f9b00d848c55697fa69bedf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2019-06-20T20:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T14:01:34.000Z", "avg_line_length": 39.5612535613, "max_line_length": 498, "alphanum_fraction": 0.6327236065, "converted": true, "num_tokens": 2415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.15610489155639232, "lm_q1q2_score": 0.07805244577819616}} {"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nPromijeni vidljivost ovdje.''')\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\n\nPromijeni vidljivost ovdje.\n\n\n## Unutaranja stabilnost - primjer 3\n\n### Kako koristiti ovaj interaktivni primjer?\n\nPokušajte promijeniti matricu dinamike $A$ stabilnog linearnog sustava (prikazanog ispod) kako biste dobili sustav s konvergentnim i divergentnim modovima, a zatim promijenite početne uvjete kako biste sakrili divergentni mod.\n\n$$\n\\dot{x} = \\underbrace{\\begin{bmatrix}0&1\\\\-1&-2\\end{bmatrix}}_{A}x\n$$\n\nPokušajte odgovoriti:\n- Kako se može podesiti prikladno početno stanje?\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#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.,1.],[-1.,-2.]])\nX0 = numpy.matrix([[0.],[0.]])\n\nAw = matrixWidget(2,2)\nAw.setM(A)\nX0w = matrixWidget(2,1)\nX0w.setM(X0)\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\n\n```python\n# Main cell\n\ndef main_callback(A, X0, DW):\n sols = numpy.linalg.eig(A)\n sys = sss(A,[[0],[1]],[1,0],0)\n pole = control.pole(sys)\n if numpy.real(pole[0]) != 0:\n p1r = abs(numpy.real(pole[0]))\n else:\n p1r = 1\n if numpy.real(pole[1]) != 0:\n p2r = abs(numpy.real(pole[1]))\n else:\n p2r = 1\n if numpy.imag(pole[0]) != 0:\n p1i = abs(numpy.imag(pole[0]))\n else:\n p1i = 1\n if numpy.imag(pole[1]) != 0:\n p2i = abs(numpy.imag(pole[1]))\n else:\n p2i = 1\n \n print('Svojstvene vrijednosti od A su:',round(sols[0][0],4),'i',round(sols[0][1],4))\n \n #T = numpy.linspace(0, 60, 1000)\n T, yout, xout = control.initial_response(sys,X0=X0,return_x=True)\n \n fig = plt.figure(\"Slobodni odziv\", figsize=(16,5))\n ax = fig.add_subplot(121)\n plt.plot(T,xout[0])\n plt.grid()\n ax.set_xlabel('vrijeme [s]')\n ax.set_ylabel(r'$x_1$')\n\n ax1 = fig.add_subplot(122)\n plt.plot(T,xout[1])\n plt.grid()\n ax1.set_xlabel('vrijeme [s]')\n ax1.set_ylabel(r'$x_2$')\n\n \n\n \nalltogether = widgets.HBox([widgets.VBox([widgets.Label('$A$:',border=3),\n Aw]),\n widgets.Label(' ',border=3),\n widgets.VBox([widgets.Label('$X_0$:',border=3),\n X0w]),\n START])\nout = widgets.interactive_output(main_callback, {'A':Aw, 'X0':X0w, 'DW':DW})\nout.layout.height = '400px'\ndisplay(out, alltogether)\n```\n\n\n Output(layout=Layout(height='400px'))\n\n\n\n HBox(children=(VBox(children=(Label(value='$A$:'), matrixWidget(children=(HBox(children=(FloatText(value=0.0, …\n\n\n\n```python\n#create dummy widget 2\nDW2 = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\nDW2.value = -1\n\n#create button widget\nSTART2 = widgets.Button(\n description='Prikaži odgovore',\n disabled=False,\n button_style='', # 'success', 'info', 'warning', 'danger' or ''\n tooltip='Klikni za prikaz odgovora',\n icon='check'\n)\n \ndef on_start_button_clicked2(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 DW2.value> 0 :\n DW2.value = -1\n else: \n DW2.value = 1\n pass\nSTART2.on_click(on_start_button_clicked2)\n\ndef main_callback2(DW2):\n if DW2 > 0:\n display(Markdown(r'''>Odgovor: Početno stanje mora biti linearna kombinacija samo svojstvenih vektora pridruženih stabilnim polovima.\n $$ $$\n Primjer:\n $$\n A = \\begin{bmatrix} 3 & 1 \\\\ 0 & -2 \\end{bmatrix}, \\quad x_0 = \\begin{bmatrix} -\\frac{1}{5} \\\\ 1 \\end{bmatrix} \\text{gdje je $x_0$ svojstveni vektor pridružen stabilnom polu $-2$ .}\n $$'''))\n else:\n display(Markdown(''))\n\n#create a graphic structure to hold all widgets \nalltogether2 = widgets.VBox([START2])\n\nout2 = widgets.interactive_output(main_callback2,{'DW2':DW2})\n#out.layout.height = '300px'\ndisplay(out2,alltogether2)\n```\n\n\n Output()\n\n\n\n VBox(children=(Button(description='Prikaži odgovore', icon='check', style=ButtonStyle(), tooltip='Klikni za pr…\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "07a19fd9b7cf589c975d321908090ea0c3aa1a90", "size": 13275, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_hr/examples/04/SS-20-Unutarnja_stabilnost_primjer_3.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_hr/examples/04/SS-20-Unutarnja_stabilnost_primjer_3.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_hr/examples/04/SS-20-Unutarnja_stabilnost_primjer_3.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": 32.6167076167, "max_line_length": 235, "alphanum_fraction": 0.4914500942, "converted": true, "num_tokens": 2221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.18952110048512089, "lm_q1q2_score": 0.07791418435827512}} {"text": "# Duboko učenje\n\n### 2. laboratorijska vježba - Konvolucijski modeli\n\n*Zagreb, 20.04.2020.*\n\n## Izjava\n\nTekstovi zadataka se koriste samo u edukativne svrhe, te njihova prava još uvijek pripadaju autorima. Tekstovi zadatka preuzeti su sa [sljedeće poveznice](https://dlunizg.github.io/lab2/). Također, bilo kakve izmjene su isključivo radi estetike, i ne mijenjaju intelektualnog vlasnika na mene ili bilo kog tko uređuje ovu datoteku.\n\n## Sadržaj\n\n- [Zadatak 1](#Zadatak-1-%C2%A0%C2%A0%C2%A0-(25%))\n- [Zadatak 2](#Zadatak-2-%C2%A0%C2%A0%C2%A0-(25%))\n- [Zadatak 3](#Zadatak-3-%C2%A0%C2%A0%C2%A0-(25%))\n- [Zadatak 4](#Zadatak-4-%C2%A0%C2%A0%C2%A0-(25%))\n\n# Učitavanje resursa\n\n\n```python\nimport json\nimport os\n\nfrom matplotlib import pyplot as plt\nimport torch\n\nfrom IPython.core.display import display, HTML, Markdown, SVG\n\nfrom task_3 import prepare_MNIST, CNNT3\nfrom task_4 import prepare_CIFAR, CNNT4, analyze_evaluation, cifar_labels\nfrom task_4 import SAVE_DIR as t4_save_dir\n```\n\n# Zadatak 1     (25%)\n\n### Uvod u konvolucijske mreže\n\n#### [Zadatak 2 ->](#Zadatak-2-%C2%A0%C2%A0%C2%A0-(25%))\n\n## Postavke zadatka\n\n\n```python\nt1_do_train = False # True ako želite pokrenuti trening u podzadatku 8, False inače.\n```\n\n### Podzadatak 1\n\nDovršite implementacije potpuno povezanog sloja, sloja nelinearnosti te funkcije gubitka u razredima `FC`, `ReLU` i `SoftmaxCrossEntropyWithLogits`.\n\n**Odgovor**:\n\nImplementacije su ponuđene u `layers.py`\n\n### Podzadatak 2\n\nKako biste bili sigurni da ste ispravno napisali sve slojeve testirajte gradijente pozivom skripte `check_grads.py`. Zadovoljavajuća relativna greška bi trebala biti manja od $10^{-5}$ ako vaši tenzori imaju dvostruku preciznost.\n\n**Odgovor**:\n\nPrvo treba izgraditi modul:\n\n\n```python\n!python3 setup_cython.py build_ext --inplace\n```\n\n running build_ext\r\n\n\nZatim treba pokrenuti program:\n\n\n```python\n!python3 check_grads.py\n```\n\n Convolution\n Check grad wrt input\n Relative error = 1.387713497584426e-09\n Error norm = 2.708619411758534e-10\n Check grad wrt params\n Check weights:\n Relative error = 3.960080099515749e-11\n Error norm = 2.606048252692708e-10\n Check biases:\n Relative error = 2.2273920054210374e-12\n Error norm = 2.6553929139417377e-11\n \n MaxPooling\n Check grad wrt input\n Relative error = 3.2756455233944856e-12\n Error norm = 9.520047457286901e-11\n \n ReLU\n Check grad wrt input\n Relative error = 3.275620779981156e-12\n Error norm = 5.448211281921029e-11\n \n FC\n Check grad wrt input\n Relative error = 1.5526408894548135e-09\n Error norm = 7.755267280874444e-10\n Check grad wrt params\n Check weights:\n Relative error = 7.022404000356437e-10\n Error norm = 7.706474875193658e-10\n Check biases:\n Relative error = 8.472355095041804e-10\n Error norm = 1.4085252676109427e-10\n \n SoftmaxCrossEntropyWithLogits\n Relative error = 1.4583572252144326e-06\n Error norm = 4.934061917260249e-10\n \n L2Regularizer\n Check grad wrt params\n Relative error = 7.289869002753903e-06\n Error norm = 2.336430571622429e-09\n\n\n**Komentar**:\n\nPonekad greška `L2Regularizer` može premašiti $10^{-5}$. Valja napomenuti da se uvijek koristi jednostruka (`float32`) preciznost, pa je to za očekivati.\n\n### Podzadatak 3\n\nSada prevedite Cython modul `im2col_cython.pyx` pozivom `python3 setup_cython.py build_ext --inplace` te po potrebi izmijenite varijable `DATA_DIR` i `SAVE_DIR`.\n\n**Odgovor**: Ovo smo već napravili u prethodnom koraku.\n\n### Podzadatak 4\n\nProučite i skicirajte model zadan objektom `net` u skripti `train.py`.\n\n**Odgovor**:\n\nNavedena mreža ilustrirana je sljedećom shemom:\n\n\n```python\nSVG(filename=\"res/task1_schematic.svg\")\n```\n\n\n\n\n \n\n \n\n\n\nOva shema je izrađena uz pomoć alata [NN SVG](https://alexlenail.me/NN-SVG/).\n\n### Podzadatak 5\n\nOdredite veličine tenzora te broj parametara u svakom sloju.\n\n**Odgovor**:\n\n- Prvi konvulucijski sloj\n - ulaz: $N \\times 1 \\times 28 \\times 28$\n - $16$ filtera, $1$ kanal, dimenzija $5 \\times 5$ uz pomak od $16$ elemenata: $416$ parametara.\n - izlaz: $N \\times 16 \\times 28 \\times 28$\n- Prvi udruživački sloj po maksimumu\n - ulaz: $N \\times 16 \\times 28 \\times 28$\n - nema parametara\n - izlaz: $N \\times 16 \\times 14 \\times 14$\n- Drugi konvolucijski sloj\n - ulaz: $N \\times 16 \\times 14 \\times 14$\n - $32$ filtera, $16$ kanala, dimenzija $5 \\times 5$ uz pomak od $32$ elementa tj. $12832$ parametara\n - izlaz: $N \\times 32 \\times 14 \\times 14$\n- Drugi udruživački sloj po maksimumu\n - ulaz: $N \\times 32 \\times 14 \\times 14$\n - nema parametara\n - izlaz: $N \\times 32 \\times 7 \\times 7$\n\n- Sloj spljošćivanja\n - ulaz: $N \\times 32 \\times 7 \\times 7$\n - nema parametara\n - izlaz: $N \\times 1568$\n\n- Prvi potpuno povezani sloj\n - ulaz: $N \\times 1568$\n - matrica $512 \\times 1568$ i pomak od $512$ elemenata, tj. $803328$ parametara\n - izlaz: $N \\times 512$\n- Drugi potpuno povezani sloj\n - ulaz: $N \\times 512$\n - matrica $10 \\times 512$ i pomak od $10$ elemenata, tj. $5130$ parametara\n - izlaz: $N \\times 10$\n\n### Podzadatak 6\n\nOdredite veličinu receptivnog polja značajki iz posljednjeg (drugog) konvolucijskog sloja.\n\n**Odgovor**:\n\nPo algoritmu pronađenom [ovdje](https://shawnleezx.github.io/blog/2017/02/11/calculating-receptive-field-of-cnn/):\n\n- $l = 1, f = 1$: input\n- $l = 5, f = 1$: conv_1\n- $l = 6, f = 2$: maxpool_1\n- $l = 14, f = 2$: conv_2\n\nDakle, receptivno polje posljednjeg konvolucijskog sloja je $14$.\n\n### Podzadatak 7\n\nProcijenite ukupnu količinu memorije za pohranjivanje aktivacija koje su potrebne za provođenje backpropa ako učimo s mini-grupama od $50$ slika.\n\n**Odgovor**:\n\nTreba pohraniti $50$ gradijenata za sve naučive parametre. Pobrojimo ih po slojevima:\n\n- Prvi konvolucijski: $416$ parametara\n- Drugi konvolucijski: $12832$ parametara\n- Prvi potpuno povezani: $803328$ parametara\n- Drugi potpuno povezani: $5130$ parametara\n\nUbacimo sad ovo u izračun:\n\n\n```python\nt1_s7_conv_1_size = 416\nt1_s7_conv_2_size = 12832\nt1_s7_fc_1_size = 803328\nt1_s7_fc_2_size = 5130\n\nt1_s7_total_size = t1_s7_conv_1_size + t1_s7_conv_2_size + \\\n t1_s7_fc_1_size + t1_s7_fc_2_size\n\nt1_s7_total_size_50_batches = 50 * t1_s7_total_size\n\nt1_s7_total_size_bytes = t1_s7_total_size_50_batches * 4\n```\n\n\n```python\nMarkdown(f\"
Ukupno nam treba **{t1_s7_total_size_bytes} B**, \"\n f\"tj. **{t1_s7_total_size_bytes / 1e6:.02f} MB** memorije.\")\n```\n\n\n\n\n
Ukupno nam treba **164341200 B**, tj. **164.34 MB** memorije.\n\n\n\n**Komentar**: Naravno, s ovo je samo procjena donje granice. Tijekom izvršavanja je potrebna dodatna memorija jer nije kao da se samo pamte gradijenti koji se mijenjaju. Međutim, kako je alokacija i dealokacija ove memorije ovisna o implementaciji knjižnice i programskog jezika, pružamo procjenu samo za naučive gradijente, jer ćemo njih uvijek morati pamtiti. Isto tako, pretpostavilo se da nema kompresije podataka. Uz kompresiju (npr. rijetke matrice) bi ovi brojevi mogli biti manji.\n\n### Podzadatak 8\n\nNapokon, pokrenite učenje modela pozivom skripte `train.py`.\n\n\n```python\nt1_s8_display = \"\"\n\nif t1_do_train:\n !python3 train.py\nelse:\n t1_s8_display = \"
Postavljeno je da se treniranje **ne pokreće** \" +\\\n \"(`t1_do_train == False`).\"\n \nMarkdown(t1_s8_display)\n```\n\n\n\n\n
Postavljeno je da se treniranje **ne pokreće** (`t1_do_train == False`).\n\n\n\n### Podzadatak 9\n\nOdredite vezu između početnog iznosa funkcije gubitka i broja razreda $C$.\n\n**Odgovor**:\n\nŠto je veći broj $C$, to nasumično inicijalizirana mreža, za koju pretpostavljamo da predviđa rezultate kao da izvlači klasifikacije iz uniformne razdiobe, ima više šanse pogriješiti. Stoga, porastom broja $C$ će početni iznos funkcije gubitka rasti.\n\n# Zadatak 2     (25%)\n\n### L2 regularizacija\n\n#### [<- Zadatak 1](#Zadatak-1-%C2%A0%C2%A0%C2%A0-(25%))          [Zadatak 3 ->](#Zadatak-3-%C2%A0%C2%A0%C2%A0-(25%))\n\n## Postavke zadatka\n\n\n```python\nt2_do_train = False # True ako želite pokrenuti trening u podzadatku 1, False inače.\n # Upozorenje - to traje skoro 1 sat!\n\nt2_root_path = \"out_l2reg\"\nt2_results_path = os.path.join(t2_root_path, \"results.json\")\nt2_weight_decays = [1e-3, 1e-2, 1e-1]\n```\n\nU ovom zadatku trebate dodati podršku za L2 regularizaciju parametara.\n\n### Podzadatak 1\n\nDovršite implementaciju sloja `L2Regularizer` te naučite regularizirani model iz prethodnog zadatka koji se nalazi u `train_l2reg.py`.\n\n**Odgovor**:\n\nImplementacija `L2Regularizer` nalazi se u `layers.py`.\n\n\n```python\nt2_s1_display = \"\"\n\nif t2_do_train:\n !python3 train_l2reg.py\nelse:\n t2_s1_display = \"
Postavljeno je da se treniranje **ne pokreće** \" +\\\n \"(`t2_do_train == False`).\"\n \nMarkdown(t2_s1_display)\n```\n\n\n\n\n
Postavljeno je da se treniranje **ne pokreće** (`t2_do_train == False`).\n\n\n\n### Podzadatak 2\n\nProučite efekte regularizacijskog hiper-parametra tako da naučite tri različita modela s $\\lambda = 10^{-3}$, $\\lambda = 10^{-2}$, $\\lambda = 10^{-1}$ te usporedite naučene filtre u prvom sloju i dobivenu točnost.\n\n**Odgovor**:\n\nSpremili smo sliku u datoteke naziva `out_l2reg/lambda0.001`, `out_l2reg/lambda0.010` i `out_l2reg/lambda0.100`. Ako učitamo posljednje datoteke, možemo prikazati sljedeće slike:\n\n\n```python\nt2_s2_folder_paths = [os.path.join(t2_root_path, x) for x in sorted(os.listdir(t2_root_path))]\nt2_s2_image_paths = list()\n```\n\n\n```python\nt2_s2_figure, t2_s2_axes = plt.subplots(3, 1, figsize=(12, 9))\n\nfor i, folder_path in enumerate(t2_s2_folder_paths[:3]):\n current_image_path = os.path.join(folder_path, sorted(os.listdir(folder_path))[-1])\n\n t2_s2_axes[i].imshow(plt.imread(current_image_path), interpolation=\"nearest\")\n t2_s2_axes[i].set_title(f\"λ = {t2_weight_decays[i]}\")\n t2_s2_axes[i].axis(\"off\")\n```\n\nKonsekventno, čitanjem datoteke `out_l2reg/results.json` možemo usporediti dobivene točnosti:\n\n\n```python\nwith open(t2_results_path) as file:\n t2_s2_results = json.load(file)\n```\n\n\n```python\nt2_s2_string = \"
\"\n\nfor i, weight_decay in enumerate(sorted(t2_weight_decays)):\n t2_s2_string += f\"\\n
Točnost za λ = {weight_decay}:   \" +\\\n f\"\".join([\"  \" for _ in range(i)]) +\\\n f\"{t2_s2_results[str(weight_decay)]:.02f}%\"\n \nHTML(t2_s2_string)\n```\n\n\n\n\n
\n
Točnost za λ = 0.001:   99.16%\n
Točnost za λ = 0.01:     98.74%\n
Točnost za λ = 0.1:       96.53%\n\n\n\n**Komentar**:\n\nNa prvi pogled se čini kako je najmanji iznos regularizacije dao najbolju mrežu radi najveće točnosti. Ovo možda i jest istina. Međutim, ako pogledamo slike, možemo uočiti da su za $\\lambda = 10^{-2}$ prvi konvolucijski slojevi daleko interpretabilniji od ostalih - vidimo linije, krivulje, horizontalne i dijagonalne praznine i sl. Dok u dubokom učenje interpretabilnost ne rezultira bolji rezultatima, tj. obično bude i suprotno, radi se u prvom sloju, koji izvlači značajke iz slike. Prema tome, vjerojatno ćemo, ako se radi o slikama koje su jednostavne kao MNIST, imati bolje rezultate ako su i filteri prvog sloja interpretabilni.\n\n# Zadatak 3     (25%)\n\n### Usporedba s PyTorchem\n\n#### [<- Zadatak 2](#Zadatak-2-%C2%A0%C2%A0%C2%A0-(25%))          [Zadatak 4 ->](#Zadatak-4-%C2%A0%C2%A0%C2%A0-(25%))\n\n## Postavke zadatka\n\n\n```python\nt3_do_train = False # True ako želite pokrenuti trening u podzadatku 1, False inače.\n # Upozorenje - to traje skoro 1 sat!\n\nt3_root_path = \"out_task3\"\nt3_results_filename = \"results.json\"\nt3_weight_decays = [1e-3, 1e-2, 1e-1]\n```\n\nU PyTorchu definirajte i naučite model koji je ekvivalentan regulariziranom modelu iz [2. zadatka](#Zadatak-2). Koristite identičnu arhitekturu i parametre učenja da biste reproducirali rezultate. Konvoluciju zadajte operacijama [`torch.nn.Conv2d`](https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d) ili [`torch.nn.functional.conv2d`](https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.conv2d).\n\n### Podzadatak 1\n\nTijekom učenja vizualizirajte filtre u prvom sloju kao u prethodnoj vježbi. Nakon svake epohe učenja pohranite filtre i gubitak u datoteku (ili koristite [Tensorboard](https://pytorch.org/docs/stable/tensorboard.html)).\n\n\n```python\nt3_s1_display = \"\"\n\nif t3_do_train:\n t3_s1_mnist_dict = prepare_MNIST()\n\n for weight_decay in [1e-3, 1e-2, 1e-1]:\n model = CNNT3()\n model.float()\n\n model.tr(t3_s1_mnist_dict[\"x\"][0], t3_s1_mnist_dict[\"y\"][0],\n t3_s1_mnist_dict[\"x\"][1], t3_s1_mnist_dict[\"y\"][1],\n weight_decay=weight_decay)\nelse:\n t3_s1_display = \"
Postavljeno je da se treniranje ne pokreće \" +\\\n \"(t3_do_train == False).\"\n\nHTML(t3_s1_display)\n```\n\n\n\n\n
Postavljeno je da se treniranje ne pokreće (t3_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 = \"
Postavljeno je da se treniranje **ne pokreće**\" +\\\n \"(`t4_do_train == False`).\"\n\nMarkdown(t4_s2_display)\n```\n\n\n\n\n
Postavljeno je da se treniranje **ne pokreće**(`t4_do_train == False`).\n\n\n\n### Podzadatak 3\n\nNapišite funkciju `evaluate` koja na temelju predviđenih i točnih indeksa razreda određuje pokazatelje klasifikacijske performanse: ukupnu točnost klasifikacije, matricu zabune (engl. confusion matrix) u kojoj retci odgovaraju točnim razredima a stupci predikcijama te mjere preciznosti i odziva pojedinih razreda. U implementaciji prvo izračunajte matricu zabune, a onda sve ostale pokazatelje na temelju nje. Tijekom učenja pozivajte funkciju `evaluate` nakon svake epohe na skupu za učenje i validacijskom skupu te na grafu pratite sljedeće vrijednosti: prosječnu vrijednost funkcije gubitka, stopu učenja te ukupnu točnost klasifikacije. Preporuka je da funkciji provedete samo unaprijedni prolaz kroz dane primjere koristeći `torch.no_grad()` i pritom izračunati matricu zabune. Pazite da slučajno ne pozovete i operaciju koja provodi učenje tijekom evaluacije. Na kraju funkcije možete izračunati ostale pokazatelje te ih isprintati.\n\n**Odgovor**:\n\nImplementacija je ostvarena unutar klase `CNNT4` koja je unutar modula `task_4.py`:\n\n\n```python\nwith open(t4_results_tr_file_path) as file:\n t4_s3_results_tr = json.load(file)\n \nwith open(t4_results_val_file_path) as file:\n t4_s3_results_val = json.load(file)\n \nwith open(t4_learning_rates_file_path) as file:\n t4_s3_learning_rates = json.load(file)\n```\n\n\n```python\nt4_s3_metric_fig, t4_s3_metric_ax = plt.subplots(1, 2, figsize=(16,6), sharey=True)\nt4_s3_tr_metric_fig, t4_s3_tr_metric_ax = plt.subplots(1, 2, figsize=(16,6))\n\nt4_s3_metric_ax[0].set_title(\"Točnost po epohama\")\nt4_s3_metric_ax[0].set_xlabel(\"Epohe\")\nt4_s3_metric_ax[0].set_ylabel(\"%\")\n\nt4_s3_metric_ax[0].plot(range(len(t4_s3_results_tr[\"acc\"])),\n [x * 100 for x in t4_s3_results_tr[\"acc\"]],\n label=\"Točnost učenja\",\n marker=\"o\")\nt4_s3_metric_ax[0].plot(range(len(t4_s3_results_val[\"acc\"])),\n [x * 100 for x in t4_s3_results_val[\"acc\"]],\n label=\"Točnost validacije\",\n marker=\"o\")\n\n\nt4_s3_metric_ax[1].set_title(\"F1-mjera po epohama\")\nt4_s3_metric_ax[1].set_xlabel(\"Epohe\")\nt4_s3_metric_ax[1].set_ylabel(\"%\")\n\nt4_s3_metric_ax[1].plot(range(len(t4_s3_results_tr[\"f1\"])),\n [x * 100 for x in t4_s3_results_tr[\"f1\"]],\n label=\"F1-mjera učenja\",\n marker=\"o\")\nt4_s3_metric_ax[1].plot(range(len(t4_s3_results_val[\"f1\"])),\n [x * 100 for x in t4_s3_results_val[\"f1\"]],\n label=\"F1-mjera validacije\",\n marker=\"o\")\n\n\nt4_s3_tr_metric_ax[0].set_title(\"Unakrsna entropija po epohama\")\nt4_s3_tr_metric_ax[0].set_xlabel(\"Epohe\")\nt4_s3_tr_metric_ax[0].set_ylabel(\"Gubitak\")\n\nt4_s3_tr_metric_ax[0].plot(range(len(t4_s3_results_tr[\"loss\"])),\n t4_s3_results_tr[\"loss\"],\n label=\"Gubitak učenja\",\n marker=\"o\")\nt4_s3_tr_metric_ax[0].plot(range(len(t4_s3_results_val[\"loss\"])),\n t4_s3_results_val[\"loss\"],\n label=\"Gubitak validacije\",\n marker=\"o\")\n\n\nt4_s3_tr_metric_ax[1].set_title(\"Stopa učenja po epohama\")\nt4_s3_tr_metric_ax[1].set_xlabel(\"Epohe\")\nt4_s3_tr_metric_ax[1].set_ylabel(\"Stopa učenja\")\nt4_s3_tr_metric_ax[1].set_yscale(\"log\")\n\nt4_s3_tr_metric_ax[1].plot(range(len(t4_s3_learning_rates)),\n t4_s3_learning_rates,\n label=\"Stopa učenja\",\n marker=\"o\")\n\nfor i in range(2):\n t4_s3_metric_ax[i].legend()\n t4_s3_tr_metric_ax[i].legend()\n```\n\n**Komentar**:\n\nGornji red grafova dijeli y-os (jer se radi o metrikama koje su koliko-toliko srodne). Primijetite da donji desni graf ima logaritamsku y-os.\n\n### Podzadatak 4\n\nVizualizirajte slučajno inicijalizirane težine konvolucijskog sloja.\n\n**Odgovor**:\n\nPrikazat ćemo prvi konvolucijski sloj na početku učenja (nasumično inicijaliziran) i na kraju učenja:\n\n\n```python\nt4_s4_image_names = sorted([x for x in os.listdir(t4_root_path) if x.endswith(\".png\")],\n key=lambda x: x.lower())\nt4_first_last = t4_s4_image_names[0], t4_s4_image_names[-1]\n```\n\n\n```python\nt4_s4_figure, t4_s4_axes = plt.subplots(1, 2, figsize=(16, 8))\n\nfor i, (image_name, title) in enumerate(zip(t4_first_last,\n [\"Početak učenja\", \"Kraj učenja\"])):\n t4_s4_axes[i].imshow(plt.imread(os.path.join(t4_root_path, image_name)), interpolation=\"nearest\")\n t4_s4_axes[i].set_title(title)\n t4_s4_axes[i].axis(\"off\")\n```\n\n**Komentar**:\n\nJako je teško vidjeti razliku ova dva sloja. Razlog za to je što smo koristili grupnu normalizaciju (engl. *batch normalization*), pa nam L2 regularizacija nije bila potrebna. No, zbog toga što grupna normalizacija ne sređuje težine, već ima svoje parametre koje utječu na podatke koji protječu kroz mrežu, taj utjecaj nije vidljiv u samim filtrima 1. konvolucijskog sloja, već bi se nad njim trebala napraviti transformacija koja bi onda bila ekvivalentna 1. filtru konvolucijskog sloja **bez** grupne normalizacije.\n\nIzrada takve transformacije je izvan okvira ove vježbe.\n\n### Podzadatak 5\n\nPrikažite $20$ netočno klasificiranih slika s najvećim gubitkom te ispišite njihov točan razred, kao i $3$ razreda za koje je model dao najveću vjerojatnost.\n\n**Odgovor**:\n\nOvo ćemo postići koristeći metodu `analyze_evaluation` u modulu `task_4.py`. Također, prije snimanja normalizirat ćemo slike po uputama. To možemo učiniti koristeći rječnik koji nam vraća metoda `prepare_CIFAR` jer će ona vratiti rječnik s unosima `mean` i `std` koji predstavljaju očekivanu vrijednost i standardnu devijaciju.\n\nPrvo moramo učitati model i prebaciti ga u mod evaluacije:\n\n\n```python\nt4_s5_model = torch.load(t4_model_path)\nt4_s5_model.eval();\n```\n\nZatim možemo pozvati `analyze_evaluation` nad njim i testnim skupom (testni skup je 3. član trojke koje vraća metoda `prepare_CIFAR` za `x` i `y`:\n\n\n```python\nanalyze_evaluation(model=t4_s5_model,\n x=t4_s2_cifar_dict[\"x\"][2],\n y=t4_s2_cifar_dict[\"y\"][2],\n mean=t4_s2_cifar_dict[\"mean\"],\n std=t4_s2_cifar_dict[\"std\"])\n```\n\n 100%|██████████| 10000/10000 [00:00<00:00, 67816.98it/s]\n\n\nImena labela nalaze se u listi `cifar_labels`. Pomoću njih možemo prikazati $20$ najgorih slika:\n\n\n```python\nwith open(t4_s5_best_classes_path) as file:\n t4_s5_best_classes = json.load(file)\n \nwith open(t4_s5_worst_classes_path) as file:\n t4_s5_worst_classes = json.load(file)\n```\n\n\n```python\nt4_s5_n_cols = 5\nt4_s5_figure, t4_s5_axes = plt.subplots(20 // t4_s5_n_cols, t4_s5_n_cols, figsize=(14, 12))\n\nfor i, image_path in enumerate(sorted([x for x in os.listdir(t4_s5_path) if x.endswith(\".png\")])):\n a = i // t4_s5_n_cols\n b = i % t4_s5_n_cols\n\n t4_s5_axes[a][b].imshow(plt.imread(os.path.join(t4_s5_path, image_path)), interpolation=\"nearest\")\n t4_s5_axes[a][b].set_title(f\"{cifar_labels[t4_s5_worst_classes[i][1]]} \" +\\\n f\"umjesto {cifar_labels[t4_s5_worst_classes[i][0]]}\")\n t4_s5_axes[a][b].axis(\"off\")\n t4_s5_axes[a][b].title.set_fontsize(10)\n```\n\n**Komentar**:\n\nVidimo da je klasifikator najnesigurniji za neke nejednoznačne slike. Neke slike je teško opravdati kao pogreške:\n- $7$ (Zrakoplov umjesto Mačka)\n- $9$ (Automobil umjesto Ptica)\n- $12$ (Ptica umjesto Jelen)\n- $13$ (Jelen umjesto Ptica)\n- $15$ (Pas umjesto Konj)\n\nKod ovih slika bi vjerojatno pomogao veći raspon rezolucija jer se radi o slikama koje objekt prikazuju iz blizine, dakle u detaljima koji se vjerojatno veći nega za ostatak slika.\n\nFinalno, prikazat ćemo $3$ razreda za koje mreža najbolje rasuđuje:\n\n\n```python\nt4_t5_display = f\"
Mreža najtočnije rasuđuje sljedeće razrede:\\n\"\n\nfor class_id, prob in t4_s5_best_classes:\n t4_t5_display += f\"- **{cifar_labels[class_id]}**: {prob * 100:.02f}%\\n\"\n \nMarkdown(t4_t5_display)\n```\n\n\n\n\n
Mreža najtočnije rasuđuje sljedeće razrede:\n- **Automobil**: 85.80%\n- **Brod**: 85.40%\n- **Kamion**: 83.80%\n\n\n\n", "meta": {"hexsha": "667b3dd141f714466b12ea4cf37f5af77d7f8db3", "size": 389502, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "LAB2/LAB2.ipynb", "max_stars_repo_name": "Yalfoosh/DUBUCE", "max_stars_repo_head_hexsha": "3f53923c27b1bce0ac592b20c5bb98649cb7fb75", "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": "LAB2/LAB2.ipynb", "max_issues_repo_name": "Yalfoosh/DUBUCE", "max_issues_repo_head_hexsha": "3f53923c27b1bce0ac592b20c5bb98649cb7fb75", "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": "LAB2/LAB2.ipynb", "max_forks_repo_name": "Yalfoosh/DUBUCE", "max_forks_repo_head_hexsha": "3f53923c27b1bce0ac592b20c5bb98649cb7fb75", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-23T02:06:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T02:06:47.000Z", "avg_line_length": 225.1456647399, "max_line_length": 128772, "alphanum_fraction": 0.890547417, "converted": true, "num_tokens": 9601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.17106119167858438, "lm_q1q2_score": 0.07687363958312025}} {"text": "# A short & practical introduction to Tensor Flow!\n\nPart 4\n\nThe goal of this notebook is to train a LSTM character prediction model over [Text8](http://mattmahoney.net/dc/textdata) data.\n\nThis is a personal wrap-up of all the material provided by [Google's Deep Learning course on Udacity](https://www.udacity.com/course/deep-learning--ud730), so all credit goes to them. \n\nAuthor: Pablo M. Olmos (olmos@tsc.uc3m.es)\n\n** This notebook cerntainly needs more comments to make it self-contained**\n\nDate: March 2017\n\n\n```python\n# These are all the modules we'll be using later. Make sure you can import them\n# before proceeding further.\nfrom __future__ import print_function\nimport os\nimport numpy as np\nimport random\nimport string\nimport tensorflow as tf\nimport zipfile\nfrom six.moves import range\nfrom six.moves.urllib.request import urlretrieve\n```\n\n\n```python\n# Lets check what version of tensorflow we have installed. The provided scripts should run with tf 1.0 and above\n\nprint(tf.__version__)\n```\n\n 1.3.0\n\n\n\n```python\nurl = 'http://mattmahoney.net/dc/'\n\ndef maybe_download(filename, expected_bytes):\n \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n if not os.path.exists(filename):\n filename, _ = urlretrieve(url + filename, filename)\n statinfo = os.stat(filename)\n if statinfo.st_size == expected_bytes:\n print('Found and verified %s' % filename)\n else:\n print(statinfo.st_size)\n raise Exception(\n 'Failed to verify ' + filename + '. Can you get to it with a browser?')\n return filename\n\n\nfilename = maybe_download('../../DataSets/textWordEmbeddings/text8.zip', 31344016) ## Change according to the folder where you saved the dataset provided\n```\n\n Found and verified ../../DataSets/textWordEmbeddings/text8.zip\n\n\n\n```python\ndef read_data(filename):\n with zipfile.ZipFile(filename) as f:\n name = f.namelist()[0]\n data = tf.compat.as_str(f.read(name))\n return data\n \ntext = read_data(filename)\nprint('Data size %d' % len(text))\n```\n\n Data size 100000000\n\n\n\n```python\ntext[0:20]\n```\n\n\n\n\n ' anarchism originate'\n\n\n\nCreate a small validation set\n\n\n```python\nvalid_size = 1000\nvalid_text = text[:valid_size]\ntrain_text = text[valid_size:]\ntrain_size = len(train_text)\nprint(train_size, train_text[:64])\nprint(valid_size, valid_text[:64])\n```\n\n 99999000 ons anarchists advocate social relations based upon voluntary as\n 1000 anarchism originated as a term of abuse first used against earl\n\n\nUtility functions to map characters to vocabulary IDs and back\n\n\n```python\nvocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' '\nfirst_letter = ord(string.ascii_lowercase[0])\n\ndef char2id(char):\n if char in string.ascii_lowercase:\n return ord(char) - first_letter + 1\n elif char == ' ':\n return 0\n else:\n print('Unexpected character: %s' % char)\n return 0\n```\n\n\n```python\ndef id2char(dictid):\n if dictid > 0:\n return chr(dictid + first_letter - 1)\n else:\n return ' '\n \nprint(char2id('a'), char2id('z'), char2id(' '), char2id('ï'))\nprint(id2char(1), id2char(26), id2char(0))\n```\n\n Unexpected character: ï\n 1 26 0 0\n a z \n\n\nFunction to generate a training batch for the LSTM model.\n\n\n```python\nbatch_size=64 ## Number of batches, but also number of segments in which we divide the text. We read batch_size \n ## batches in parallel, each read from a different segment. The implementation is not obvious, the\n ## key seems to be the zip function inside the for loop below\n \nnum_unrollings=10 ## Each sequence is num_unrolling character long\n\n### NOW I GET IT!! Every batch is a batch_size times 27 (num letters) matrix. Every row correspond to a letter. Each letter \n### comes from a different sequence of (num_unrollings) so that the 64 letters cannot be read together.\n## In the next batch, we have the following letter for each of the 64 training sequences!!\n\nclass BatchGenerator(object):\n \n def __init__(self, text, batch_size, num_unrollings):\n self._text = text\n self._text_size = len(text)\n self._batch_size = batch_size\n self._num_unrollings = num_unrollings\n segment = self._text_size // batch_size #We split the text into batch_size pieces\n self._cursor = [ offset * segment for offset in range(batch_size)] #Cursor pointing every piece\n self._last_batch = self._next_batch()\n \n #\n def _next_batch(self):\n \"\"\"Generate a single batch from the current cursor position in the data.\"\"\"\n batch = np.zeros(shape=(self._batch_size, vocabulary_size), dtype=np.float)\n for b in range(self._batch_size):\n batch[b, char2id(self._text[self._cursor[b]])] = 1.0 #One hot encoding\n #print(self._text[self._cursor[b]])\n self._cursor[b] = (self._cursor[b] + 1) % self._text_size\n return batch\n \n def next(self):\n \"\"\"Generate the next array of batches from the data. The array consists of\n the last batch of the previous array, followed by num_unrollings new ones.\n \"\"\"\n batches = [self._last_batch]\n for step in range(self._num_unrollings):\n batches.append(self._next_batch())\n self._last_batch = batches[-1]\n return batches\n \n \ndef characters(probabilities):\n \"\"\"Turn a 1-hot encoding or a probability distribution over the possible\n characters back into its (mostl likely) character representation.\"\"\"\n return [id2char(c) for c in np.argmax(probabilities, 1)]\n\ndef batches2string(batches):\n \"\"\"Convert a sequence of batches back into their (most likely) string\n representation.\"\"\"\n s = [''] * batches[0].shape[0]\n for b in batches:\n s = [''.join(x) for x in zip(s, characters(b))] #Clever! The ZIP is the key function here!\n return s \n\ntrain_batches = BatchGenerator(train_text, batch_size, 10)\nvalid_batches = BatchGenerator(valid_text, 1, 1)\n\n\n```\n\n\n```python\nprint(batches2string(train_batches.next()))\nprint(batches2string(train_batches.next()))\n```\n\n ['ons anarchi', 'when milita', 'lleria arch', ' abbeys and', 'married urr', 'hel and ric', 'y and litur', 'ay opened f', 'tion from t', 'migration t', 'new york ot', 'he boeing s', 'e listed wi', 'eber has pr', 'o be made t', 'yer who rec', 'ore signifi', 'a fierce cr', ' two six ei', 'aristotle s', 'ity can be ', ' and intrac', 'tion of the', 'dy to pass ', 'f certain d', 'at it will ', 'e convince ', 'ent told hi', 'ampaign and', 'rver side s', 'ious texts ', 'o capitaliz', 'a duplicate', 'gh ann es d', 'ine january', 'ross zero t', 'cal theorie', 'ast instanc', ' dimensiona', 'most holy m', 't s support', 'u is still ', 'e oscillati', 'o eight sub', 'of italy la', 's the tower', 'klahoma pre', 'erprise lin', 'ws becomes ', 'et in a naz', 'the fabian ', 'etchy to re', ' sharman ne', 'ised empero', 'ting in pol', 'd neo latin', 'th risky ri', 'encyclopedi', 'fense the a', 'duating fro', 'treet grid ', 'ations more', 'appeal of d', 'si have mad']\n ['ists advoca', 'ary governm', 'hes nationa', 'd monasteri', 'raca prince', 'chard baer ', 'rgical lang', 'for passeng', 'the nationa', 'took place ', 'ther well k', 'seven six s', 'ith a gloss', 'robably bee', 'to recogniz', 'ceived the ', 'icant than ', 'ritic of th', 'ight in sig', 's uncaused ', ' lost as in', 'cellular ic', 'e size of t', ' him a stic', 'drugs confu', ' take to co', ' the priest', 'im to name ', 'd barred at', 'standard fo', ' such as es', 'ze on the g', 'e of the or', 'd hiver one', 'y eight mar', 'the lead ch', 'es classica', 'ce the non ', 'al analysis', 'mormons bel', 't or at lea', ' disagreed ', 'ing system ', 'btypes base', 'anguages th', 'r commissio', 'ess one nin', 'nux suse li', ' the first ', 'zi concentr', ' society ne', 'elatively s', 'etworks sha', 'or hirohito', 'litical ini', 'n most of t', 'iskerdoo ri', 'ic overview', 'air compone', 'om acnm acc', ' centerline', 'e than any ', 'devotional ', 'de such dev']\n\n\n\n```python\n#OK with this one\ndef logprob(predictions, labels):\n \"\"\"Log-probability of the true labels in a predicted batch.\"\"\"\n predictions[predictions < 1e-10] = 1e-10\n return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]\n\n#OK with this one\ndef sample_distribution(distribution):\n \"\"\"Sample one element from a distribution assumed to be an array of normalized\n probabilities.\n \"\"\"\n \n r = random.uniform(0,1)\n s = 0\n for i in range(len(distribution)):\n s += distribution[i]\n if s >= r:\n return i\n return len(distribution) - 1\n\n#OK with this one\ndef sample(prediction):\n \"\"\"Turn a (column) prediction into 1-hot encoded samples.\"\"\"\n p = np.zeros(shape=[1, vocabulary_size], dtype=np.float)\n p[0, sample_distribution(prediction[0])] = 1.0\n return p\n\n\ndef random_distribution():\n \"\"\"Generate a random column of probabilities.\"\"\"\n b = np.random.uniform(0.0, 1.0, size=[1, vocabulary_size])\n return b / np.sum(b, 1)[:, None]\n\n```\n\n\n```python\ntrain_batches.next()[0].shape\n```\n\n\n\n\n (64, 27)\n\n\n\n# Simple LSTM Model\n\nRecall the fundamental model\n\n\n\n\nAlso, the un-regularized cost function is\n\n\\begin{align}\nJ(\\boldsymbol{\\theta})=\\frac{1}{N}\\sum_{n=1}^N\\sum_{t=1}^{T_n}d(\\boldsymbol{y}_t^{(n)},\\sigma(\\boldsymbol{h}_t^{(n)}))\n\\end{align}\nwhere $d(\\cdot,\\cdot)$ is the cross-entropy loss function.\n\nAbout the TF implementation below, see the following excellent [post](http://www.thushv.com/sequential_modelling/long-short-term-memory-lstm-networks-implementing-with-tensorflow-part-2/)\n\n> \nNow calculating logits for softmax is a little bit tricky. This a temporal (time-based) network. So after each processing each num_unrolling batches through the LSTM cell, we update h_{t-1}=h_t and c_{t-1}=c_t before calculating logits and the loss. This is done by using tf.control_dependencies. What this does is that, logits will not be calculated until saved_output and saved_states are updated. Finally, as you can see, num_unrolling acts as the amount of history we are remembering.\n\nIn other words, in the computation graph everytime something is updated, all the dependent op nodes are updated and this is propagated through the graph. If we want to wait until the very end to compute the loss, we wait using the command tf.control_dependencies.\n\nAbout the zip() and zip(*) operators, see this [post](https://docs.python.org/2/library/functions.html#zip)\n\n\n```python\nnum_nodes = 64\n\ngraph = tf.Graph()\nwith graph.as_default():\n \n # Parameters:\n \n #i(t) parameters\n # Input gate: input, previous output, and bias.\n ix = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1)) ##W^ix\n im = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1)) ## W^ih\n ib = tf.Variable(tf.zeros([1, num_nodes])) ##b_i\n \n #f(t) parameters\n # Forget gate: input, previous output, and bias.\n fx = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1)) ##W^fx\n fm = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1)) ##W^fh\n fb = tf.Variable(tf.zeros([1, num_nodes])) ##b_f\n \n #g(t) parameters\n # Memory cell: input, state and bias. \n cx = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1)) ##W^gx\n cm = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1)) ##W^gh\n cb = tf.Variable(tf.zeros([1, num_nodes])) ##b_g\n \n #o(t) parameters\n # Output gate: input, previous output, and bias.\n ox = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1)) ##W^ox\n om = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1)) ##W^oh\n ob = tf.Variable(tf.zeros([1, num_nodes])) ##b_o\n \n # Variables saving state across unrollings.\n saved_output = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False) #h(t)\n saved_state = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False) #s(t)\n \n \n # Classifier weights and biases (over h(t) to labels)\n w = tf.Variable(tf.truncated_normal([num_nodes, vocabulary_size], -0.1, 0.1))\n b = tf.Variable(tf.zeros([vocabulary_size]))\n \n # Definition of the cell computation.\n def lstm_cell(i, o, state):\n \"\"\"Create a LSTM cell. See e.g.: http://arxiv.org/pdf/1402.1128v1.pdf\n Note that in this formulation, we omit the various connections between the\n previous state and the gates.\"\"\"\n input_gate = tf.sigmoid(tf.matmul(i, ix) + tf.matmul(o, im) + ib)\n forget_gate = tf.sigmoid(tf.matmul(i, fx) + tf.matmul(o, fm) + fb)\n update = tf.matmul(i, cx) + tf.matmul(o, cm) + cb \n state = forget_gate * state + input_gate * tf.tanh(update) #tf.tanh(update) is g(t)\n output_gate = tf.sigmoid(tf.matmul(i, ox) + tf.matmul(o, om) + ob)\n return output_gate * tf.tanh(state), state #h(t) is output_gate * tf.tanh(state)\n\n # Input data. Now it makes sense!!!\n \n train_data = list()\n for _ in range(num_unrollings + 1):\n train_data.append(tf.placeholder(tf.float32, shape=[batch_size,vocabulary_size]))\n train_inputs = train_data[:num_unrollings]\n train_labels = train_data[1:] # labels are inputs shifted by one time step.\n\n # Unrolled LSTM loop.\n \n outputs = list()\n output = saved_output\n aux = output\n state = saved_state\n for i in train_inputs:\n output, state = lstm_cell(i, output, state)\n outputs.append(output)\n\n # State saving across unrollings.\n with tf.control_dependencies([saved_output.assign(output),saved_state.assign(state)]):\n #Classifier.\n logits = tf.nn.xw_plus_b(tf.concat(axis=0,values=outputs), w, b)\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.concat(axis=0, values=train_labels),logits=logits))\n\n # Optimizer.\n \n \"\"\"Next, we are implementing the optimizer. Remember! we should use “gradient clipping” (tf.clip_by_global_norm) \n to avoid “Exploding gradient” phenomenon. Also, we decay the learning_rate over time.\"\"\"\n global_step = tf.Variable(0)\n \n learning_rate = tf.train.exponential_decay(10.0, global_step, 5000, 0.1, staircase=True)\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n \n \"\"\" optimizer.compute_gradients(loss) yields (gradient, value) tuples. gradients, v = zip(*optimizer.compute_gradients(loss))\n performs a transposition, creating a list of gradients and a list of values.\n gradients, _ = tf.clip_by_global_norm(gradients, 1.25)\n then clips the gradients, and optimizer = optimizer.apply_gradients(zip(gradients, v), global_step=global_step)\n re-zips the gradient and value lists back into an iterable of (gradient, value) \n tuples which is then passed to the optimizer.apply_gradients method.\"\"\"\n \n gradients, v = zip(*optimizer.compute_gradients(loss))\n gradients, _ = tf.clip_by_global_norm(gradients, 1.25)\n optimizer = optimizer.apply_gradients(zip(gradients, v), global_step=global_step)\n\n # Predictions.\n train_prediction = tf.nn.softmax(logits)\n \n # Sampling and validation eval: batch 1, no unrolling.\n sample_input = tf.placeholder(tf.float32, shape=[1, vocabulary_size])\n saved_sample_output = tf.Variable(tf.zeros([1, num_nodes]))\n saved_sample_state = tf.Variable(tf.zeros([1, num_nodes]))\n # Create an op that groups multiple operations.\n reset_sample_state = tf.group(saved_sample_output.assign(tf.zeros([1, num_nodes])),\n saved_sample_state.assign(tf.zeros([1, num_nodes])))\n \n sample_output, sample_state = lstm_cell(sample_input, saved_sample_output, saved_sample_state)\n \n with tf.control_dependencies([saved_sample_output.assign(sample_output),saved_sample_state.assign(sample_state)]):\n sample_prediction = tf.nn.softmax(tf.nn.xw_plus_b(sample_output, w, b))\n\n```\n\n\n```python\nnum_steps = 1001\nsummary_frequency = 100\n\nwith tf.Session(graph=graph) as session:\n tf.global_variables_initializer().run()\n print('Initialized')\n mean_loss = 0\n for step in range(num_steps):\n batches = train_batches.next()\n feed_dict = dict()\n for i in range(num_unrollings + 1):\n feed_dict[train_data[i]] = batches[i]\n _, l, predictions, lr = session.run(\n [optimizer, loss, train_prediction, learning_rate], feed_dict=feed_dict)\n mean_loss += l\n if step % summary_frequency == 0:\n if step > 0:\n mean_loss /= summary_frequency\n # The mean loss is an estimate of the loss over the last few batches.\n print(\n 'Average loss at step %d: %f learning rate: %f' % (step, mean_loss, lr))\n mean_loss = 0\n labels = np.concatenate(list(batches)[1:])\n print('Minibatch perplexity: %.2f' % float(\n np.exp(logprob(predictions, labels))))\n if step % (summary_frequency * 10) == 0:\n # Generate some samples.\n print('=' * 80)\n for _ in range(5):\n feed = sample(random_distribution())\n sentence = characters(feed)[0]\n reset_sample_state.run()\n for _ in range(79):\n prediction = sample_prediction.eval({sample_input: feed})\n feed = sample(prediction)\n sentence += characters(feed)[0]\n print(sentence)\n print('=' * 80)\n # Measure validation set perplexity.\n reset_sample_state.run()\n valid_logprob = 0\n for _ in range(valid_size):\n b = valid_batches.next()\n predictions = sample_prediction.eval({sample_input: b[0]})\n valid_logprob = valid_logprob + logprob(predictions, b[1])\n print('Validation set perplexity: %.2f' % float(np.exp(\n valid_logprob / valid_size)))\n```\n\n Initialized\n Average loss at step 0: 3.294209 learning rate: 10.000000\n Minibatch perplexity: 26.96\n ================================================================================\n mxovr oqde yfxkdo lgo slt r jyl uqoizrtvtz rozih o giopvwtirvvfji ioisixishdut\n rteew vmekfznhts utnotduqtnvitnip niki eb e pv dbopsfvpm el ittceecbnryravioe j\n ltvbgee kzaauloap jdlvnh vthfvkvqtisnr oqnr yc gs om icihhdfriiaradwnooezke v c\n b zowgrzzlfsfin qtpnbleqteoiss pf tta jn wd ohsv zgwsictzraulredxokf os ev qwab\n lpeottcin ffinel hxcylubmceenohedvin cm nbp tednlatrxipat yqvwnosbgnlwmviaeruox\n ================================================================================\n Validation set perplexity: 20.10\n Average loss at step 100: 2.598391 learning rate: 10.000000\n Minibatch perplexity: 10.37\n Validation set perplexity: 10.75\n Average loss at step 200: 2.253659 learning rate: 10.000000\n Minibatch perplexity: 9.72\n Validation set perplexity: 9.11\n Average loss at step 300: 2.097530 learning rate: 10.000000\n Minibatch perplexity: 7.71\n Validation set perplexity: 7.79\n Average loss at step 400: 1.997222 learning rate: 10.000000\n Minibatch perplexity: 7.69\n Validation set perplexity: 7.62\n Average loss at step 500: 1.932652 learning rate: 10.000000\n Minibatch perplexity: 6.26\n Validation set perplexity: 7.12\n Average loss at step 600: 1.907986 learning rate: 10.000000\n Minibatch perplexity: 6.14\n Validation set perplexity: 6.84\n Average loss at step 700: 1.857451 learning rate: 10.000000\n Minibatch perplexity: 5.60\n Validation set perplexity: 6.70\n Average loss at step 800: 1.818764 learning rate: 10.000000\n Minibatch perplexity: 6.20\n Validation set perplexity: 6.71\n Average loss at step 900: 1.830710 learning rate: 10.000000\n Minibatch perplexity: 7.22\n Validation set perplexity: 6.35\n Average loss at step 1000: 1.824062 learning rate: 10.000000\n Minibatch perplexity: 5.82\n ================================================================================\n h is notsowifs wite is engliaily hurds ninekture that finch ebord of pearist sub\n riced frvmic in in hidu of the ind d finlibul the leate and nothorlod and trever\n pily hlil and ros is inferrick in llils thhirai erlic brozg o redortining clihe \n s in the vire of the ifterible frog kid a and will priling madiep precents to so\n c lith severneric sever fill listration of the impress jo the mycri five zeres c\n ================================================================================\n Validation set perplexity: 6.17\n\n\n\n```python\nbatches = train_batches.next()\n```\n\n\n```python\nbatches[0]\n```\n\n\n\n\n array([[ 0., 0., 0., ..., 0., 0., 0.],\n [ 0., 0., 0., ..., 0., 0., 1.],\n [ 0., 0., 0., ..., 0., 0., 0.],\n ..., \n [ 0., 0., 0., ..., 0., 0., 0.],\n [ 0., 0., 0., ..., 0., 0., 0.],\n [ 0., 0., 0., ..., 0., 0., 0.]])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7f36570c191a510c86fb8c85f0b87af2085f2970", "size": 29011, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/Part_4/LSTMs.ipynb", "max_stars_repo_name": "olmosUC3M/Introduction-to-Tensor-Flow-and-Deep-Learning", "max_stars_repo_head_hexsha": "3d173606f273f6b3e2bf3cbdccea1c4fe59af71f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-03-05T14:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-13T23:53:08.000Z", "max_issues_repo_path": "Notebooks/Part_4/LSTMs.ipynb", "max_issues_repo_name": "olmosUC3M/Introduction-to-Tensor-Flow-and-Deep-Learning", "max_issues_repo_head_hexsha": "3d173606f273f6b3e2bf3cbdccea1c4fe59af71f", "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": "Notebooks/Part_4/LSTMs.ipynb", "max_forks_repo_name": "olmosUC3M/Introduction-to-Tensor-Flow-and-Deep-Learning", "max_forks_repo_head_hexsha": "3d173606f273f6b3e2bf3cbdccea1c4fe59af71f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-31T20:26:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T20:26:47.000Z", "avg_line_length": 39.5784447476, "max_line_length": 971, "alphanum_fraction": 0.552238806, "converted": true, "num_tokens": 5669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.15610490333452268, "lm_q1q2_score": 0.0768329813490937}} {"text": "# Nuclear Fuel Fabrication\n\nNuclear fuel production is a highly constrained and optimized process.\n\n## Learning Objectives\n\n- Differentiate fuel characteristics and materials in various reactor designs \n- List safety constraints driving fuel designs\n- Order the steps in PWR UOx fuel fabrication\n- Explain the role of fuel and cladding in providing a barrier to radionuclide release\n- Name appropriate criteria for selection of cladding materials\n- Compare the mechanims of typical fuel failures\n- Evaluate the potential costs of defects\n- Name the contributors to fuel fabrication costs\n\n\n## Safety Constraint: Controlling the Reactor\n\nControl rods and burnable poisons will be covered in detail next week in the reactor physics module. For now, note that cadmium and boron are important for managing excess reactivity because of their large absorption cross sections.\n\n\n\n\n## Safety Constraint: Containing the Fission Products\n\n\n\n\n## CANDU\n\n\n- natural uranium\n- heavy water ($D_2O$)\n- online refuelling\n- each bundle: 50 cm long 10 cm diameter\n\n\n\n\n\n\n\n\n\n\n## PWR \n\n- UO2 fuel\n- Zircalloy cladding (typically)\n- Height: 4.1m\n- Hardware mostly Zircaloy (Zr with Sn, Fe, Cr)\n- Grid spacers: Zircaloy, Inconel, stainless steel\n- End pieces: Stainless steel, Inconel\n- 200-250 fuel assemblies per core\n- Each Assembly: \n - 14 x 14 to 17 x 17 fuel elements\n - 21cm x 21cm\n - Fuel element size: 1 cm diameter, \n - Fuel element height: 3.9m\n - Assembly weight: 1400lb\n - Enrichment: 3-5%\n - May have separate burnable poison rods\n \n \n \n \n \n \n\n\n```python\nrod = 400 # pellets per rod\nassembly = 17*17 - 5*5 # assembly array minus control rod tubes\ncore = 193 # typical number of assemblies per core\nprint(\"Total pellets in a core\", core*assembly*rod)\nprint(\"Total rods in a core\", core*assembly)\n```\n\n ('Total pellets in a core', 20380800)\n ('Total rods in a core', 50952)\n\n\n## BWR\n\nA BWR has about 600-800 fuel assemblies per core. Each assembly:\n\n- 14ft (4.5m) tall\n- Zircalloy channel around the assembly\n- Hardware mostly Zircaloy (Zr with Sn, Fe, Cr)\n- Grid spacers: Zircaloy\n- Channel (aka shroud): Zircaloy\n- End pieces: Stainless steel\n- Each assembly\n - 700lb\n - 5.5x5.5 inches (14 cm x 14 cm) square assembly\n - Fuel element array: 8 x 8 or 10 x 10\n - Fuel element size: 1.25 cm diameter, height = 4.1m\n - Enrichment: 2.5-4.5%\n - May have Gd in some rods and variable enrichment in 3D\n\n\n\n\n### Zircalloy\n\nThere is a phenomenal review paper called \"Selection of fuel cladding material for nuclear fission reactors.\" https://www.researchgate.net/publication/257519826_Selection_of_fuel_cladding_material_for_nuclear_fission_reactors . Many of the following images come directly from that paper.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# PWR Fuel Fabrication Steps\n\n\n\nThe \"pellet manufacturing\" step is somewhat complex.\n\n\n\n# Fuel Failure\n\n\nTypes of failure have changed over time and vary among reactor fuel types. The IAEA did [a comprehensive review of this topic recently.](http://www-pub.iaea.org/MTCD/Publications/PDF/Pub1445_web.pdf). In it, the following causes of fuel failure were noted:\n\n- Debris (particularly in BWRs)\n- Pellet-Cladding Interaction \n- Grid to Rod Fretting (particularly in PWRs)\n- Fuel Handling Incidents\n- Crud and Corrosion\n\n## Modeling of Failure\n\n\\begin{align}\nR &= r\\times\\frac{D}{N}\\\\ \n\\mbox{where}&\\\\\nR&=\\mbox{ an annual rod failure rate (leaking rods/rods in core)}\\\\\nN &= \\mbox{ the number of rods in core for all operating reactors with or without refuelling in the respective year}\\\\\nD &=\\mbox{ the number of leaking assemblies found and discharged from all operating reactors in a year}\\\\\nr &=\\mbox{ the average number of leaking rods per leaking assembly}\\\\\n\\end{align}\n\nThe rate, r, according to IAEA, is equal to 1.1 for BWR, WWER-440 and CANDU fuel, and 1.3 for PWR and WWER-1000 fuel.\n\n\n \n\n\n\n```python\ndef rate(r, d, n):\n return r*d/n\n\nr = 1.3 # pwr/wwer\nn = 17*17*200*213 # 213 pwr type reactors in the study\nd = 6\nprint(rate(r,d,n))\n\n```\n\n 6.33559140309e-07\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n## Debris\n\n### Discussion: Filters can help with debris, but what other effects do they have on the reactor?\n\n\n\n## PCI \n\nThe following summary is from [an OECD report on PCI:](https://www.oecd-nea.org/science/pubs/2005/6004-pellet-clad.pdf)\n\n> Fuel and pellet behaviour mechanisms activated in PCI situations\n> \n> The behaviour of pellets in the interaction depends on many mechanisms potentially activated prior to, or during PCI, namely:\n> \n> - Densification/solid fission products and gaseous swelling under irradiation.\n> - Release of fission gases and volatile species.\n> - Evolution of thermal conductivity, elasticity constants, thermal and irradiation creep, temperature-induced or microstructure-induced phenomena (porosities, re-crystallisation).\n> - Geometry of the pellets and their modifications by cracking. \n> \n> As concerns the clad:\n> \n> - Evolution of elasticity, plasticity, creep parameters (irradiation, temperature-induced).\n> - Dependence on the microstructure and manufacturing process and its evolution under fluence.\n> - Oxidation, hydridation.\n> - Sensitivity to stress corrosion-cracking.\n> \n> As concerns the interface:\n> - Formation of contact materials or bonding layers: zirconia/uranate compound including fission products.\n> - Friction. \n\nIncreased burnups lead to higher cladding failure rates.\n\n\n\n\n
Cupped fuel pellets seek to give fission product gases a place to escape.
\n\n\nU. S. Nuclear Waste Technical Review Board (NWTRB) fuel cladding failure chart (Figure 20 on page 56) and December 2010 report https://sanonofresafety.files.wordpress.com/2013/06/usnwtrb-evaloftechbasisforextendeddrystorageandtransportofusednuclearfuel2010-dec-eds_rpt.pdf\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Grid to Rod Fretting\n\n\n\n\n\n\n\n## Crud and corrosion\n\nOver the course of operation, 'crud' develops on the fuel rods. It is composed primarily of nickel and iron that likely leaches from the stainless steel tubes running through the steem generator. The crud deposits on the fuel rods encourage corrosion of the cladding.\n\n\n\n
From Michigan Engineering and the CASL Project
\n\n## Review: BWR or PWR\n\n\n\n## Metal Fuels\n\nOne of the key downsides to oxide fuel is its lower thermal conductivity. \n\n\n\n
Thermal profile in a UOx fuel rod
\n\n\nMetal fuels attempt to solve this problem. \n\n\n\n\n\n
IFR. (Metal fuel, sodium coolant)
\n\nThe EBR-II reactor was a prototype for IFR. \n\n> The fuel consists of uranium rods 5 millimeters in diameter and 33 cm (13 inches) long . Enriched to 67% uranium-235 when fresh, the concentration dropped to approximately 65% upon removal. The rods also contained 10% zirconium. Each fuel element is placed inside a thin-walled stainless steel tube along with a small amount of sodium metal. The tube is welded shut at the top to form a unit 73 cm (29 inches) long. \n\n\n\n\n### Metal Fuel Fabrication\n- Begin with a furnace containing a molten mixture of actinides, some fission products, and alloying constituents\n- Make a mold having an array of quartz tubes\n- Insert mold in furnace, seal, and evacuate\n- Lower mold into melt and increase pressure to force metal melt into tubes\n- Raise mold, cool, break to yield metal fuel pellets ~0.5m long.\n- Insert in metal clad as with oxide fuels\n\n\n\n\n---\n\n## TRISO Fuels\n\n- withstand high temperature (>= 1800C)\n- fission product containment\n- Can be embedded in graphite blocks or pebbles. \n- Can be embedded homogeneously or heterogeneously.\n\n\n\n
closeup
\n\n\n---\n\n\n
closeup
\n\n\n\n---\n### Prismatic Compacts\n\n\n
Prismatic
\n\n\n---\n\n\n
Prismatic
\n\n\n---\n\n### Pebble Compacts\n\n\n\n\n
PBMR
\n\n\n
PBMR
\n\n\n#### Annular pebbles\n\n\n
Annular Pebbles, PBFHR
\n\n\n\n\n---\n\n## Excercise: Using your intuition, sketch the temperature profiles for :\n- oxide fuel, \n- metal fuel, \n- prismatic triso compacts, \n- pebble triso compacts, \n- and annular triso compacts.\n\n\n\n\n\n\n## Liquid Fuels\n\nSalts are a common fuel carrier. They have exceptional heat transfer behavior and remain in liquid phase due to a very high boiling point (1430C in the case of FLiBe). They also have a high melting point in comparison to other coolants (melting point 459.1C in the case of FLiBe).\n\n### Discussion: What does this high melting point mean in the event of a LOCA ?\n\n\n\n\n\n\n\n\n\n\n\n\n## Discussion: Common carrier and coolant salts are FLiBe and FLiNaK. Can you think of (neutronic) reasons why?\n\n\n## Problems with liquid fuels\n\nNo material is perfect. \n\n\n### Lithium acivation to tritium. \n\n$^6$Li + n $\\Rightarrow$ $^4$He (2.05MeV) + $^3$T (2.75MeV)\n\n### Noble Metal plate-out\n\nMost fission products are able to form stable fluorides in FLiNaK and FLiBe fuel salts, but noble metals tend to plate out.\n\n\n\n---\n\n## References\n\nThis section was developed to complement pages 86-119 of [1]. \n\n[1] N. Tsoulfanidis, The Nuclear Fuel Cycle. La Grange Park, Illinois, USA: American Nuclear Society, 2013.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "2753fa49e0f1394744448813592a47a83cb1be76", "size": 21867, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fuel-fabrication/fuel-fabrication.ipynb", "max_stars_repo_name": "atomicaristides/NPRE412", "max_stars_repo_head_hexsha": "b2ae552303f3e4894628c8401d3bedd2db85a551", "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": "fuel-fabrication/fuel-fabrication.ipynb", "max_issues_repo_name": "atomicaristides/NPRE412", "max_issues_repo_head_hexsha": "b2ae552303f3e4894628c8401d3bedd2db85a551", "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": "fuel-fabrication/fuel-fabrication.ipynb", "max_forks_repo_name": "atomicaristides/NPRE412", "max_forks_repo_head_hexsha": "b2ae552303f3e4894628c8401d3bedd2db85a551", "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": 40.270718232, "max_line_length": 427, "alphanum_fraction": 0.6380847853, "converted": true, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.07655671314942339}} {"text": "\n\n# Section 5: Modelling & Simulation\n\n---\n\n# Table of Contents\n\n* [System Requirements (Part 1)](#System-Requirements)\n * [Model Introduction](#Model-Introduction)\n * [Requirements Analysis](#Requirements-Analysis) \n * [Visual System Mapping: Entity Relationship Diagram](#Visual-System-Mapping:-Entity-Relationship-Diagram)\n * [Visual System Mapping: Stock & Flow Diagram](#Visual-System-Mapping:-Stock-&-Flow-Diagram)\n * [Mathematical Specification](#Mathematical-Specification)\n* [System Design (Part 2)](#System-Design)\n * [Differential Specification](#Differential-Specification)\n * [cadCAD Standard Notebook Layout](#cadCAD-Standard-Notebook-Layout)\n 0. [Dependencies](#0.-Dependencies)\n 1. [State Variables](#1.-State-Variables)\n 2. [System Parameters](#2.-System-Parameters)\n 3. [Policy Functions](#3.-Policy-Functions)\n 4. [State Update Functions](#4.-State-Update-Functions)\n 5. [Partial State Update Blocks](#5.-Partial-State-Update-Blocks)\n 6. [Configuration](#6.-Configuration)\n 7. [Execution](#7.-Execution)\n 8. [Simulation Output Preparation](#8.-Simulation-Output-Preparation)\n 9. [Simulation Analysis](#9.-Simulation-Analysis)\n* [System Validation (Part 3)](#System-Validation)\n * [Policy Functions](#Policy-Functions)\n * [Model Improvements](#Model-Improvements)\n * [Differential Specification Updates](#Differential-Specification-Updates)\n * [Mathematical Specification Updates](#Mathematical-Specification-Updates)\n * [Model Limitations](#Model-Limitations)\n\n\n\n---\n\n# System Requirements\n\n
\n\n## Model Introduction\n\n> Ecosystem: a biological community of interacting organisms and their physical environment.\n\n
\n\n
\n\n
\n\n
\n\n## Requirements Analysis\n\n[Link to Simulation Analysis](#9.-Simulation-Analysis)\n\nIllustrative real-world model applications:\n* Forecast animal food consumption, to determine the sustainability of a farming operation, and to plan for worst-case scenarios.\n* Given a food supply of a number of standard crops, of varying cost, how do we optimize economic performance of the farming operation?\n* Given the ecological impact of a certain crop on the fertility of the soil, how do we balance the economic performance and ecological sustainability of the farming operation?\n\n### Questions\n\n1. How long will our model ecosystem be able to sustain itself for?\n2. What population size can our model ecosystem support?\n\n### Assumptions\n\n1. The population will increase over time.\n2. The food supply will decrease over time.\n3. There is some relationship between the population and food supply.\n\n### Constraints / Scope\n\n* The intention of this toy model is to allow us to learn about cadCAD, the modelling process, simulation configuration, and the engineering design process!\n\n## Visual System Mapping: Entity Relationship Diagram\n\n\n
\n\n
\n\n## Visual System Mapping: Stock & Flow Diagram\n\n
\n\n
\n\n## Mathematical Specification\n\n> ...differential equations play a prominent role in many disciplines including engineering, physics, economics, and biology.\n\n### Differential Equations\n* A population consumes a food source, and reproduces at a rate proportional to the food source.\n* The food source is consumed at a rate proportional to the population.\n\n\\begin{align}\n\\large population_t &\\large= population_{t-1} + {\\Delta population} \\quad \\textrm{(sheep)} \\tag{1} \\\\\n\\large food_t &\\large= food_{t-1} + {\\Delta food} \\quad \\textrm{(tons of grass)} \\tag{2} \\\\\n\\end{align}\n\nwhere the rate of change ($\\Delta$) is:\n\\begin{align}\n\\large {\\Delta population} &\\large= \\alpha * food_{t-1} \\quad \\textrm{(sheep/month)} \\\\\n\\large {\\Delta food} &\\large= -\\beta * population_{t-1} \\quad \\textrm{(tons of grass/month)}\n\\end{align}\n\n# System Design\n\n
\n\n## Differential Specification\n\n
\n\n
\n\n## cadCAD Standard Notebook Layout\n\n
\n\n
\n\n# 0. Dependencies\n\n\n```python\n# Standard libraries: https://docs.python.org/3/library/\nimport math\n\n# Analysis and plotting modules\nimport pandas as pd\n# import plotly\n```\n\n\n```python\n# cadCAD configuration modules\nfrom cadCAD.configuration.utils import config_sim\nfrom cadCAD.configuration import Experiment\n\n# cadCAD simulation engine modules\nfrom cadCAD.engine import ExecutionMode, ExecutionContext\nfrom cadCAD.engine import Executor\n```\n\n# 1. State Variables\n\n> A state variable is one of the set of variables that are used to describe the mathematical \"state\" of a dynamical system. ([Wikipedia](https://en.wikipedia.org/wiki/State_variable))\n\n\n```python\ninitial_state = {\n 'population': 50, # number of sheep\n 'food': 1000 # tons of grass\n}\ninitial_state\n```\n\n## **Time** as a system state\n\n
\n\n
\n\n* 1 **timestep** == 1 month\n\n# 2. System Parameters\n\n> System parameterization is the process of choosing variables that impact the behaviour of the model. These parameters allow us to perform simulation techniques like parameter sweeps, Monte Carlo simulations, A/B tests, and see how the system behaves under a different model parameter set.\n\n[Link to Simulation Analysis](#9.-Simulation-Analysis)\n\n\n```python\nsystem_params = {\n 'reproduction_rate': [0.01], # sheep per month\n 'consumption_rate': [0.1], # tons of grass per month\n}\nsystem_params\n```\n\n# 3. Policy Functions\n\n> A Policy Function computes one or more signals to be passed to State Update Functions. They describe the logic and behaviour of a system component or mechanism.\n\nWe'll cover this in the next section!\n\n# 4. State Update Functions\n\n> We create State Update Functions to design the way our model state changes over time. These will usually represent the system differential specification.\n\n```python\ndef state_update_function(params, substep, state_history, previous_state, policy_input):\n variable_value = 0\n return 'variable_name', variable_value\n```\n\n* `params` is a Python dictionary containing the **system parameters** \n* `substep` is an integer value representing a step within a single `timestep`\n* `state_history` is a Python list of all previous states\n* `previous_state` is a Python dictionary that defines what the state of the system was at the **previous timestep** or **substep**\n* `policy_input` is a Python dictionary of signals or actions from **policy functions**\n\n\n```python\ndef new_population(current_population, alpha, food_supply):\n \"\"\"\n The population state after one timestep, according to the differential equation (1):\n current_population + alpha * food_supply\n \"\"\"\n return math.ceil(current_population + alpha * food_supply)\n```\n\n\n```python\nmath.ceil(5.5)\n```\n\n\n```python\n# Relevant state variables\ncurrent_population = initial_state['population']\nfood_supply = initial_state['food']\n\n# Relevant parameters\nreproduction_rate = system_params['reproduction_rate'][0] # \"alpha\" in our differential equation\n\nnew_population(current_population, reproduction_rate, food_supply)\n```\n\n\n```python\ndef s_population(params, substep, state_history, previous_state, policy_input):\n \"\"\"\n Update the population state according to the differential equation (1):\n current_population + alpha * food_supply\n \"\"\"\n population = previous_state['population']\n alpha = params['reproduction_rate']\n food_supply = previous_state['food']\n \n return 'population', max(new_population(population, alpha, food_supply), 0)\n```\n\n\n```python\npopulation = 60\nprint(\"A tuple!\")\n'population', max(math.ceil(population), 0)\n```\n\n\n```python\nnext_state = {\n # current_population + alpha * food_supply\n 'population': math.ceil(50 + 0.01 * 1000),\n 'food': 1000\n}\nnext_state\n```\n\n\n```python\ndef s_food(params, substep, state_history, previous_state, policy_input):\n \"\"\"\n Update the food supply state according to the differential equation (2):\n food supply - beta * population\n \"\"\"\n food = previous_state['food'] - params['consumption_rate'] * previous_state['population']\n return 'food', max(food, 0)\n```\n\n\n```python\nmax(-10, 0)\n```\n\n# 5. Partial State Update Blocks\n## Tying it all together\n\n> A series of Partial State Update Blocks is a structure for composing State Update Functions and Policy Functions in series or parallel, as a representation of the system model. \n\n
\n\n
\n\n**Updates run in series**\n\n\n```python\npartial_state_update_blocks = [\n # Run first\n {\n 'policies': {}, # Ignore for now\n # State variables\n 'variables': {\n 'population': s_population\n }\n },\n # Run second\n {\n 'policies': {}, # Ignore for now\n # State variables\n 'variables': {\n 'food': s_food\n }\n }\n]\n```\n\n**Updates run in parallel**\n\n\n```python\npartial_state_update_blocks = [\n {\n 'policies': {}, # Ignore for now\n # State variables\n 'variables': {\n # Updated in parallel\n 'population': s_population,\n 'food': s_food\n }\n }\n]\n```\n\n# 6. Configuration\n\n> The configuration stage is about tying all the previous model components together and choosing how the simulation should run.\n\n
\n\n
\n\nConfiguration parameters:\n* `'N': 1` - the number of times we'll run the simulation (you'll see them called \"Monte Carlo runs\" later in the course, when we look at tools to analyze system models)\n* `'T': range(400)` - the number of timesteps the simulation will run for\n* `'M': system_params` - the parameters of the system\n\n\n```python\nsim_config = config_sim({\n \"N\": 1,\n \"T\": range(400),\n \"M\": system_params\n})\n```\n\n\n```python\nrange(400)\n```\n\n\n```python\nlist(range(400))[0:10]\n```\n\n\n```python\nfrom cadCAD import configs\ndel configs[:] # Clear any prior configs\n```\n\n\n```python\nexperiment = Experiment()\nexperiment.append_configs(\n initial_state = initial_state,\n partial_state_update_blocks = partial_state_update_blocks,\n sim_configs = sim_config\n)\nconfigs[-1].__dict__\n```\n\n# 7. Execution\n\n> The Execution Engine takes a model and configuration, and computes the simulation output.\n\n## Configuring the cadCAD simulation execution\n\n\n```python\nexec_context = ExecutionContext()\n```\n\n\n```python\nsimulation = Executor(exec_context=exec_context, configs=configs)\n```\n\n## Time to simulate our ecosystem model!\n\n\n```python\nraw_result, tensor_field, sessions = simulation.execute()\n```\n\n# 8. Simulation Output Preparation\n> The simulation results are returned as a list of Python dictionaries, which we then convert to a Pandas dataframe. At this stage of the process you'll manipulate and analyze your results to answer questions about your model.\n\n\n```python\nsimulation_result = pd.DataFrame(raw_result)\n```\n\n\n```python\nraw_result[:5]\n```\n\n\n```python\nsimulation_result.head()\n```\n\n# 9. Simulation Analysis\n\n[Link to System Requirements](#Requirements-Analysis)\n\n\n```python\npd.options.plotting.backend = \"plotly\"\n```\n\nAfter plotting the results, let's go and update the parameters, and then select `Cell` and `Run All Above`:\n\n[Link to System Parameters](#2.-System-Parameters)\n\n\n```python\nsimulation_result.plot(\n kind='line',\n x='timestep',\n y=['population','food']\n)\n```\n\n\n```python\npd.set_option('display.max_rows', len(simulation_result))\ndisplay(simulation_result)\npd.reset_option('display.max_rows')\n```\n\n\n```python\n# https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html\nsimulation_result.query('food == 0').head()\n```\n\n# System Validation\n\n
\n\n## Policy Functions\n\nAn illustrative example:\n\n```python\ncondition = True\n\ndef policy_function(params, substep, state_history, previous_state):\n '''\n This logic belongs in the policy function,\n but could also have been placed directly in the state update function.\n '''\n signal_value = 1 if condition else 0\n return {'signal_name': signal_value}\n```\n\n```python\ndef state_update_function(params, substep, state_history, previous_state, policy_input):\n state_value = policy_input['signal_name']\n return 'state_name', state_value\n```\n\n
\n\n
\n\n
\n\n
\n\n### Policy Aggregation\n\n
\n\n
\n\n## Model Improvements\n\n### Differential Specification Updates\n\n
\n\n
\n\nState update functions `s_population()` and `s_food()` from the last part:\n\n\n```python\ndef s_population(params, substep, state_history, previous_state, policy_input):\n population = previous_state['population'] + params['reproduction_rate'] * previous_state['food']\n return 'population', max(math.ceil(population), 0)\n\ndef s_food(params, substep, state_history, previous_state, policy_input):\n food = previous_state['food'] - params['consumption_rate'] * previous_state['population']\n return 'food', max(food, 0)\n```\n\nAdapting to use **policy functions** to drive the process, and **state update functions** to update the state according to the **differential specification**:\n\n\n```python\ndef p_reproduction(params, substep, state_history, previous_state):\n population_reproduction = params['reproduction_rate'] * previous_state['food']\n return {'delta_population': population_reproduction}\n\ndef p_consumption(params, substep, state_history, previous_state):\n food_consumption = params['consumption_rate'] * previous_state['population']\n return {'delta_food': -food_consumption}\n```\n\n\n```python\ndef s_population(params, substep, state_history, previous_state, policy_input):\n population = previous_state['population'] + policy_input['delta_population'] \n return 'population', max(math.ceil(population), 0)\n\ndef s_food(params, substep, state_history, previous_state, policy_input):\n food = previous_state['food'] + policy_input['delta_food'] \n return 'food', max(food, 0)\n```\n\n### Mathematical Specification Updates\n\n\\begin{align}\n\\large population_t &\\large= population_{t-1} + {\\Delta population} \\quad \\textrm{(sheep)} \\tag{1} \\\\\n\\large food_t &\\large= food_{t-1} + {\\Delta food} \\quad \\textrm{(tons of grass)} \\tag{2}\n\\end{align}\n\nwhere the rate of change ($\\Delta$) is:\n\\begin{align}\n\\large {\\Delta population} &\\large= \\alpha * food_{t-1} \\quad \\textrm{(sheep/month)} \\\\\n\\large {\\Delta food} &\\large= -\\beta * population_{t-1} + \\gamma \\quad \\textrm{(tons of grass/month)}\n\\end{align}\n\nwhere:\n\n$\n\\begin{align}\n\\alpha: \\quad &\\textrm{'reproduction_rate'}\\\\\n\\beta: \\quad &\\textrm{'consumption_rate'}\\\\\n\\gamma: \\quad &\\textrm{'growth_rate'}\n\\end{align}\n$\n\n* A population consumes a food source, and reproduces at a rate proportional to the food source $\\alpha$ (alpha).\n* The food source is consumed at a rate proportional to the population $\\beta$ (beta), and grows at a constant rate $\\gamma$ (gamma).\n\n
\n\n
\n\n\n```python\ninitial_state = {\n 'population': 50, # number of sheep\n 'food': 1000 # tons of grass\n}\n\nsystem_params = {\n 'reproduction_rate': [0.01], # number of sheep / month\n 'consumption_rate': [0.01], # tons of grass / month\n 'growth_rate': [10.0], # tons of grass / month\n}\n```\n\n\n```python\nfrom collections import Counter\n```\n\n\n```python\nA = Counter({'delta_food': 5, 'delta_population': 10})\nB = Counter({'delta_food': 5})\nA + B\n```\n\n\n```python\nA = Counter({'delta_food': 5, 'delta_population': 10})\nB = Counter({'delta_food': -2})\nA + B\n```\n\n\n```python\ndef p_growth(params, substep, state_history, previous_state):\n delta_food = params['growth_rate']\n return {'delta_food': delta_food}\n```\n\n\n```python\npartial_state_update_blocks = [\n {\n 'policies': {\n 'reproduction': p_reproduction,\n 'consumption': p_consumption, # Signal: `delta_food`\n 'growth': p_growth # Signal: `delta_food`\n },\n 'variables': {\n 'population': s_population,\n 'food': s_food # Receives policy_input of (consumption + growth) as `delta_food`\n }\n }\n]\n```\n\n\n```python\ndel configs[:]\n\nsim_config = config_sim({\n 'N': 1,\n 'T': range(400),\n 'M': system_params\n})\n\nexperiment.append_configs(\n initial_state = initial_state,\n partial_state_update_blocks = partial_state_update_blocks,\n sim_configs = sim_config\n)\n```\n\n\n```python\nexec_context = ExecutionContext()\n\nsimulation = Executor(exec_context=exec_context, configs=configs)\nraw_result, tensor_field, sessions = simulation.execute()\n```\n\n\n```python\nsimulation_result = pd.DataFrame(raw_result)\nsimulation_result\n```\n\n\n```python\ndf = simulation_result.copy()\ndf = df[df.simulation == 0]\ndf\n```\n\n\n```python\ndf.plot(kind='line', x='timestep', y=['population','food'])\n```\n\n\n```python\ndf = df[['population', 'food']]\ndf.head()\n```\n\n\n```python\ndf.pct_change()\n```\n\n\n```python\ndiff = df.diff()\ndiff\n```\n\n\n```python\ndiff = diff.query('food <= 0')\ndiff\n```\n\n\n```python\ndf.iloc[75]\n```\n\n## Model Limitations\n\n1. The population never dies.\n2. The system reaches a steady state of no population or food supply change.\n\n#### Addition of a population death rate, \"epsilon\" / $\\epsilon$, that's dependent on the population size:\n
\n\n\\begin{align}\n\\large population_t &\\large= population_{t-1} + {\\Delta population} \\quad \\textrm{(sheep)} \\tag{1} \\\\\n\\large food_t &\\large= food_{t-1} + {\\Delta food} \\quad \\textrm{(tons of grass)} \\tag{2}\n\\end{align}\n\nwhere the rate of change ($\\Delta$) is:\n\\begin{align}\n\\large {\\Delta population} &\\large= \\alpha * food_{t-1} - \\epsilon * population_{t-1} \\quad \\textrm{(sheep/month)} \\\\\n\\large {\\Delta food} &\\large= -\\beta * population_{t-1} + \\gamma \\quad \\textrm{(tons of grass/month)}\n\\end{align}\n\nwhere:\n\n$\n\\begin{align}\n\\alpha: \\quad &\\textrm{'reproduction_rate'}\\\\\n\\epsilon: \\quad &\\textrm{'death_rate'}\\\\\n\\beta: \\quad &\\textrm{'consumption_rate'}\\\\\n\\gamma: \\quad &\\textrm{'growth_rate'}\\\\\n\\end{align}\n$\n\n* A population consumes a food source, and reproduces at a rate proportional to the food source $\\alpha$ (alpha), and dies at a rate proportional to the population size $\\epsilon$ (epsilon).\n* The food source is consumed at a rate proportional to the population $\\beta$ (beta), and grows at a constant rate $\\gamma$ (gamma).\n\n
\n\n
\n\n\n```python\ndef p_death(params, substep, state_history, previous_state):\n population_death = params['death_rate'] * previous_state['population']\n return {'delta_population': -population_death}\n```\n\n\n```python\ninitial_state = {\n 'population': 50, # number of sheep\n 'food': 1000 # tons of grass\n}\n\nsystem_params = {\n 'reproduction_rate': [0.01],\n 'death_rate': [0.01],\n 'consumption_rate': [0.01],\n 'growth_rate': [10.0],\n}\n```\n\n\n```python\npartial_state_update_blocks = [\n {\n 'policies': {\n 'reproduction': p_reproduction,\n 'death': p_death,\n 'consumption': p_consumption,\n 'growth': p_growth\n },\n 'variables': {\n 'population': s_population,\n 'food': s_food\n }\n }\n]\n```\n\n\n```python\nsim_config = config_sim({\n 'N': 1,\n 'T': range(1000),\n 'M': system_params\n})\n\nexperiment.append_configs(\n initial_state = initial_state,\n partial_state_update_blocks = partial_state_update_blocks,\n sim_configs = sim_config\n)\n```\n\n\n```python\nexec_context = ExecutionContext()\n\nsimulation = Executor(exec_context=exec_context, configs=configs)\nraw_result, tensor_field, sessions = simulation.execute()\n```\n\n\n```python\nsimulation_result = pd.DataFrame(raw_result)\n```\n\n\n```python\ndf = simulation_result.copy()\ndf = df[df.simulation == 1]\ndf\n```\n\n\n```python\ndf.plot(kind='line', x='timestep', y=['population','food'])\n```\n\n


\n# Well done!\n



\n", "meta": {"hexsha": "8decb645d00c2e980d9c45e5ef94a1dd1835c651", "size": 39467, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "complete-foundations-bootcamp-output-main/content/section-5-modelling-and-simulation/notebook.ipynb", "max_stars_repo_name": "redditech/cadCad-training", "max_stars_repo_head_hexsha": "a1ab040e9baf1863a75b2c85cb3ea567049b6c2a", "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": "complete-foundations-bootcamp-output-main/content/section-5-modelling-and-simulation/notebook.ipynb", "max_issues_repo_name": "redditech/cadCad-training", "max_issues_repo_head_hexsha": "a1ab040e9baf1863a75b2c85cb3ea567049b6c2a", "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": "complete-foundations-bootcamp-output-main/content/section-5-modelling-and-simulation/notebook.ipynb", "max_forks_repo_name": "redditech/cadCad-training", "max_forks_repo_head_hexsha": "a1ab040e9baf1863a75b2c85cb3ea567049b6c2a", "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": 26.6488858879, "max_line_length": 296, "alphanum_fraction": 0.5443281729, "converted": true, "num_tokens": 5156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1540575588075327, "lm_q1q2_score": 0.07642700430777027}} {"text": "# KVLCC2 Model tests vs. Ikeda and SI\n\n# Purpose\nComparison between damping coefficients (with and without speed) from model tests and predictions with Ikeda and Simplified Ikeda (SI).\n\n# Methodology\nQuickly describe assumptions and processing steps.\n\n# WIP - improvements\n(WORK IN PROGRESS)\nUse this section only if the notebook is not final.\n\nNotable TODOs:\n* todo 1\n* todo 2\n* todo 3\n\n## Results\nDescribe and comment the most important results.\n\n# Suggested next steps\nState suggested next steps, based on results obtained in this notebook.\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.run import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\n\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 461 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.dpi : 100 ## figure dots per inch')\n\n\n\n```python\nimport pyscores2\nimport pyscores2.runScores2\nimport pyscores2.xml_hydrostatics\nfrom pyscores2.output import OutputFile\nfrom rolldecayestimators.ikeda import Ikeda, IkedaR\n\nfrom rolldecayestimators.simplified_ikeda_class import SimplifiedIkeda, SimplifiedIkedaABS\nfrom rolldecayestimators.simplified_ikeda import limits_kawahara\nfrom pyscores2.runScores2 import Calculation\nfrom pyscores2.indata import Indata\nimport joblib\nfrom scipy.optimize import least_squares\nfrom reports.paper_writing import save_fig\n```\n\n\n```python\ndb = database.get_db()\n```\n\n\n```python\nsql = \"\"\"\nSELECT * from run\nINNER JOIN loading_conditions\nON (run.loading_condition_id = loading_conditions.id)\nINNER JOIN models\nON (run.model_number = models.model_number)\nINNER JOIN ships\nON (run.ship_name = ships.name)\nWHERE run.model_number='M5057-01-A' and run.test_type='roll decay' and run.project_number=40178362;\n\"\"\"\ndf_rolldecays = pd.read_sql(sql=sql, con=db.engine)\ndf_rolldecays=df_rolldecays.loc[:,~df_rolldecays.columns.duplicated()]\ndf_rolldecays.set_index('id', inplace=True)\n\ndf_rolldecays['ship_speed'].fillna(0, inplace=True)\n\n```\n\n\n```python\ndf_rolldecays.head()\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 \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 \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 \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 \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 \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 \n \n \n \n \n \n \n \n \n \n \n \n \n
project_numberseries_numberrun_numbertest_numbermodel_numbership_nameloading_condition_idascii_nameship_speedcommentfile_path_asciifile_path_ascii_tempfile_path_logfile_path_hdf5datetest_typefacilityangle1angle2KörfallstypnamelcgkggmCWTFTABWLKXXKZZBTT1CPVolumeA0RHscale_factorlppbeamABULBBKXTWINDCLRVDESRHBLASKEGPDARHCFPAIXPDTDESRTYPESFPBKLBKBPROTDLSKEGRRXSKEGNDESARBRBRAIRUDPTYPEXRUDAIHSKEGRSKEGLOAship_type_id
id
21337401783621941M5057-01-AM5057-01-A16694.00.0Roll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone
21338401783621951M5057-01-AM5057-01-A16695.00.0Roll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone
21339401783621961M5057-01-AM5057-01-A16696.00.0Roll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-11-28roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone
21340401783621971M5057-01-AM5057-01-A16697.015.5Roll decay, 15.5 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-04roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone
\n
\n\n\n\n\n```python\ndef calculate_ikeda(ikeda):\n\n output = pd.DataFrame()\n output['B_44_hat'] = ikeda.calculate_B44()\n output['B_W0_hat'] = float(ikeda.calculate_B_W0())\n output['B_W_hat'] = float(ikeda.calculate_B_W())\n output['B_F_hat'] = ikeda.calculate_B_F()\n output['B_E_hat'] = ikeda.calculate_B_E()\n output['B_BK_hat'] = ikeda.calculate_B_BK()\n output['B_L_hat'] = float(ikeda.calculate_B_L())\n output['Bw_div_Bw0'] = float(ikeda.calculate_Bw_div_Bw0())\n return output\n```\n\n\n```python\n#df_rolldecays=df_rolldecays.loc[[21337,21338,21340,]].copy()\ndf_rolldecays=df_rolldecays.loc[[21338,21340,]].copy()\n```\n\n\n```python\nresources={\n 21338 : {\n 'scores_indata_path':'../models/KVLCC2_speed.IN',\n 'scores_outdata_path':'../data/interim/KVLCC2_speed.out',\n 'roll_decay_model':'../models/KVLCC2_0_speed.pkl',\n },\n 21340 : {\n 'scores_indata_path':'../models/KVLCC2_speed.IN',\n 'scores_outdata_path':'../data/interim/KVLCC2_speed.out',\n 'roll_decay_model':'../models/KVLCC2_speed.pkl',\n }\n}\n```\n\n\n```python\ng=9.81\nrho=1000\n\nphi_as = np.deg2rad(np.linspace(0,10,30))\nresults = pd.DataFrame()\n\nfor id, row in df_rolldecays.iterrows():\n run = db.session.query(Run).get(int(row.name))\n run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n scale_factor = run.model.scale_factor\n \n resource = resources[id]\n \n ## Load ScoresII results\n indata = Indata()\n indata.open(indataPath='../models/KVLCC2_speed.IN')\n output_file = OutputFile(filePath='../data/interim/KVLCC2_speed.out')\n \n ## Compare with model test\n model = joblib.load(resource['roll_decay_model'])\n estimator = model['estimator']\n \n ## Non. Lin. linear equivalent damping\n GM = run.loading_condition.gm/scale_factor\n volume = run.loading_condition.Volume/(scale_factor**3)\n GM = run.loading_condition.gm/scale_factor\n beam = run.ship.beam/scale_factor\n\n meta_data = {\n 'Volume':volume,\n 'GM':GM,\n 'rho':rho,\n 'g':g,\n }\n parameters = estimator.result_for_database(meta_data = meta_data)\n B_e = lambdas.B_e_lambda_cubic(B_1=parameters['B_1'], B_2=parameters['B_2'], B_3=parameters['B_3'], \n omega0=parameters['omega0'], phi_a=phi_as)\n B_e_hat = lambdas.B_hat_lambda(B=B_e, Disp=volume, beam=beam, g=g, rho=rho)\n\n ## Run Ikeda\n w = parameters['omega0']\n scale_factor=run.model.scale_factor\n V = row.ship_speed*1.852/3.6/np.sqrt(scale_factor)\n \n if not run.ship.BKL:\n BKL=0\n else:\n BKL=run.ship.BKL/scale_factor\n \n if not run.ship.BKB:\n BKB = 0\n else:\n BKB=run.ship.BKB/scale_factor\n \n kg = run.loading_condition.kg/scale_factor\n \n fi_as = np.deg2rad(10)\n \n BKL_ = BKL*np.ones(len(phi_as))\n BKB_ = BKB*np.ones(len(phi_as))\n \n ikeda = IkedaR.load_scoresII(V=V, w=w, fi_a=phi_as, indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL_, BKB=BKB_, kg=kg)\n \n #R = 0.15*run.ship.beam/scale_factor # Just guessing...\n #ikeda.R = R\n \n df_ikeda = calculate_ikeda(ikeda=ikeda)\n df_ikeda['phi_as']=phi_as\n df_ikeda.set_index('phi_as',inplace=True)\n df_ikeda['phi_as_deg']=np.rad2deg(phi_as)\n df_ikeda['B_e_hat_model_test']=B_e_hat\n df_ikeda['B_e_hat_model_test']=df_ikeda['B_e_hat_model_test'].astype('float')\n df_ikeda['id']=id\n results=results.append(df_ikeda)\n \n```\n\n c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n df_.units = units\n c:\\python36-64\\lib\\re.py:212: FutureWarning: split() requires a non-empty pattern match.\n return _compile(pattern, flags).split(string, maxsplit)\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:283: RuntimeWarning: divide by zero encountered in true_divide\n Cf = 1.328*sqrt(2*pi*visc/(3.22*r_f**2*fi_a**2*w))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:586: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:184: RuntimeWarning: invalid value encountered in true_divide\n CD = 22.5 * bBK / (pi * l * fi_a * f) + 2.4;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:190: RuntimeWarning: divide by zero encountered in true_divide\n So = (0.3 * pi * l * fi_a * f / bBK + 1.95) * bBK;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:190: RuntimeWarning: invalid value encountered in true_divide\n So = (0.3 * pi * l * fi_a * f / bBK + 1.95) * bBK;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:190: RuntimeWarning: invalid value encountered in multiply\n So = (0.3 * pi * l * fi_a * f / bBK + 1.95) * bBK;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:210: RuntimeWarning: invalid value encountered in true_divide\n Cp_minus = -22.5 * bBK / (pi * l * fi_a * f) - 1.2;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:223: RuntimeWarning: invalid value encountered in true_divide\n B44BK_L = 2 * LBK * l1 / (fi_a * w); #\n c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n df_.units = units\n c:\\python36-64\\lib\\re.py:212: FutureWarning: split() requires a non-empty pattern match.\n return _compile(pattern, flags).split(string, maxsplit)\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:283: RuntimeWarning: divide by zero encountered in true_divide\n Cf = 1.328*sqrt(2*pi*visc/(3.22*r_f**2*fi_a**2*w))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:586: RuntimeWarning: invalid value encountered in sqrt\n gamma=sqrt(pi)*f3*(rmax+2*M/H*sqrt(B0**2*A0**2))/((2*Ts*(1-OG/Ts)*sqrt(H0_prim*sigma_prim)))\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:184: RuntimeWarning: invalid value encountered in true_divide\n CD = 22.5 * bBK / (pi * l * fi_a * f) + 2.4;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:190: RuntimeWarning: divide by zero encountered in true_divide\n So = (0.3 * pi * l * fi_a * f / bBK + 1.95) * bBK;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:190: RuntimeWarning: invalid value encountered in true_divide\n So = (0.3 * pi * l * fi_a * f / bBK + 1.95) * bBK;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:190: RuntimeWarning: invalid value encountered in multiply\n So = (0.3 * pi * l * fi_a * f / bBK + 1.95) * bBK;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:210: RuntimeWarning: invalid value encountered in true_divide\n Cp_minus = -22.5 * bBK / (pi * l * fi_a * f) - 1.2;\n c:\\dev\\rolldecay-estimators\\rolldecayestimators\\ikeda_speed.py:223: RuntimeWarning: invalid value encountered in true_divide\n B44BK_L = 2 * LBK * l1 / (fi_a * w); #\n\n\n\n\n\n```python\nymax = np.max([df_ikeda['B_44_hat'].max(),df_ikeda['B_e_hat_model_test'].max()])\nfor id,df_ikeda in results.groupby(by='id'):\n fig,ax=plt.subplots()\n interesting_ = ['B_L_hat','B_W_hat','B_F_hat','B_E_hat',]\n df_ikeda.plot.area(x='phi_as_deg', y=interesting_, ax=ax)\n \n df_ikeda.plot(x='phi_as_deg',y='B_e_hat_model_test', label='cubic model', ax=ax)\n \n resource = resources[id]\n model = joblib.load(resource['roll_decay_model'])\n estimator = model['estimator']\n X_amplitudes=estimator.X_amplitudes.copy()\n X_amplitudes['phi_a_deg'] = np.rad2deg(X_amplitudes['phi_a'])\n result_for_database = estimator.result_for_database(meta_data=meta_data)\n omega0=result_for_database['omega0']\n A_44=result_for_database['A_44']\n X_amplitudes['B']=X_amplitudes['B_n']*2*omega0*A_44/2\n \n X_amplitudes['B_hat'] = lambdas.B_hat_lambda(B=X_amplitudes['B'], Disp=volume, beam=beam, g=g, rho=rho)\n X_amplitudes.plot(x='phi_a_deg', y='B_hat', style='k.', label='model test', ax=ax)\n \n ax.legend()\n ax.set_xlabel('$\\phi_a$ [deg] (Roll amplitude)')\n ax.set_ylabel('$\\hat{B_e}$ [-] (Nonlin. linear equivalent damping)');\n \n s = df_rolldecays.loc[id]\n title='Ship speed: %0.1f [kts]' % s.ship_speed\n ax.set_title(title) \n ax.set_ylim(0,ymax)\n \n figure_name = 'KVLCC2_B_e_%0.1f' % s.ship_speed\n save_fig(fig, name=figure_name)\n \n```\n\n## Time \n\n\n```python\ndef residual(x,df, omega0):\n \"\"\"\n Residual function for least square fit\n \"\"\"\n \n B_1 = x[0]\n B_2 = x[1]\n B_3 = x[2]\n \n phi_a = df.index\n B_e_pred = lambdas.B_e_lambda_cubic(B_1=B_1, B_2=B_2, B_3=B_3, omega0=omega0, phi_a=phi_a)\n B_e_true = df['B_44'] \n error = B_e_true-B_e_pred\n \n return error\n \n```\n\n\n```python\nfor id,df_ikeda in results.groupby(by='id'):\n \n ## Convert to dimensional damping [Nm/s]\n df_ikeda['B_44'] = lambdas.B_from_hat_lambda(B_44_hat=df_ikeda['B_44_hat'], Disp=volume, beam=beam, g=g, rho=rho)\n \n ## Load the cubic model\n resource = resources[id]\n model = joblib.load(resource['roll_decay_model'])\n estimator = model['estimator']\n result_for_database = estimator.result_for_database(meta_data=meta_data)\n omega0=result_for_database['omega0']\n A_44=result_for_database['A_44']\n \n ## Use least square fit of B_44 as a function of phi_a to determine B_1, B_2 and B_3:\n x0 = [result_for_database['B_1'],\n result_for_database['B_2'],\n result_for_database['B_3'],\n ]\n kwargs = {\n 'df':df_ikeda,\n 'omega0':omega0,\n }\n\n result = least_squares(fun=residual, x0=x0, kwargs=kwargs, method='lm')\n assert result.success\n \n ## Feed the results into a cubic model:\n parameters = {\n 'B_1A':result.x[0]/A_44,\n 'B_2A':result.x[1]/A_44,\n 'B_3A':result.x[2]/A_44,\n 'C_1A':estimator.parameters['C_1A'],\n 'C_3A':estimator.parameters['C_3A'],\n 'C_5A':estimator.parameters['C_5A'],\n }\n\n model_ikeda = EstimatorCubic.load(**parameters, X=estimator.X)\n \n ## Plotting:\n fig,ax=plt.subplots()\n model_ikeda.plot_fit(label='ikeda', ax=ax)\n s = df_rolldecays.loc[id]\n title='Ship speed: %0.1f [kts]' % s.ship_speed\n ax.set_title(title) \n\n fig,ax=plt.subplots()\n model_ikeda.plot_damping(label='ikeda', ax=ax)\n model['estimator'].plot_damping(label='cubic model', include_model_test=False, ax=ax)\n ax.set_title(title) \n \n fig,ax=plt.subplots()\n model_ikeda.plot_error(ax=ax)\n ax.set_title(title) \n \n```\n\n\n```python\nprint(run.project.project_path)\n```\n\n \\\\sspa.local\\gbg\\projekt\\2017\\40178362-HHI-121-(ML-106)-Improved-analysis-of-tes\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "e1c9596761659ee00be2340ee10a7d81bc73f21c", "size": 621383, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/04.3_KVLCC2_Ikedas_model_tests.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "notebooks/04.3_KVLCC2_Ikedas_model_tests.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "notebooks/04.3_KVLCC2_Ikedas_model_tests.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 518.683639399, "max_line_length": 133672, "alphanum_fraction": 0.9300157874, "converted": true, "num_tokens": 8179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.1602660323277607, "lm_q1q2_score": 0.07637952976412402}} {"text": "# Theoretical Foundations of Buffer Stock Saving\n\n\n\n

Generator: BufferStockTheory-make/notebooks_byname

\n\n

For 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\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnamedatetimemonthyeardate_of_birthoutcome_typeoutcome_subtypeanimal_typesex_upon_outcomeage_upon_outcomebreedcolor
0A808320Kyha2019-11-14T15:37:00.0002019-11-14T15:37:00.0002017-11-07T00:00:00.000Rto-AdoptNaNDogSpayed Female2 yearsGerman Shepherd MixSable
1A781697Pookie2019-11-14T15:33:00.0002019-11-14T15:33:00.0002017-10-05T00:00:00.000AdoptionNaNDogSpayed Female2 yearsCairn TerrierWhite/Brown
2A808382NaN2019-11-14T14:57:00.0002019-11-14T14:57:00.0002014-11-08T00:00:00.000TransferPartnerCatIntact Male5 yearsDomestic ShorthairOrange Tabby
3A806701*Emerald2019-11-14T14:41:00.0002019-11-14T14:41:00.0002019-09-02T00:00:00.000AdoptionFosterCatNeutered Male2 monthsDomestic ShorthairBlue Tabby/White
4A804553*Wendy2019-11-14T14:36:00.0002019-11-14T14:36:00.0002019-08-09T00:00:00.000AdoptionFosterCatSpayed Female3 monthsDomestic ShorthairCalico
\n
\n\n\n\n\n```python\nadoption.shape\n```\n\n\n\n\n (100000, 12)\n\n\n\nThe target in this project will be to predict whether or not an animal will be adopted or not (transferred to another shelter or, sadly, euthanized) so that perhaps animal shelters, though overwhelmed, can give some extra love or use unique methods to get those animals that may not have the best odds forever homes.\n\n\n```python\nadoption['outcome_type'].value_counts(dropna=False)\n```\n\n\n\n\n Adoption 44390\n Transfer 29861\n Return to Owner 17510\n Euthanasia 6294\n Died 969\n Rto-Adopt 508\n Disposal 387\n Missing 61\n Relocate 17\n NaN 3\n Name: outcome_type, dtype: int64\n\n\n\n\n```python\n# this might be a feature that can create leakage, will come back to it.\nadoption['outcome_subtype'].value_counts(dropna=False)\n```\n\n\n\n\n NaN 54837\n Partner 24943\n Foster 7953\n Rabies Risk 2789\n SCRP 2636\n Suffering 2503\n Snr 2279\n In Kennel 508\n Aggressive 358\n Offsite 281\n Medical 254\n In Foster 243\n At Vet 171\n Behavior 82\n Enroute 65\n Underage 29\n Court/Investigation 21\n In Surgery 19\n Possible Theft 15\n Field 8\n Barn 4\n Customer S 1\n Prc 1\n Name: outcome_subtype, dtype: int64\n\n\n\n# Classification or Regression?\n\nThere are 9 classes of outcomes but for this project I'd like to focus on the animals that were adopted or not. There are a large number of animals that were returned to owners but that would just be due to them getting out etc but they do have a home so I will not include those in my project. \"Rto-adopt\" or return to owner adoption will also be included with \"return to owner.\"\n\nFor animals that were adopted I will consider that to be: \n-adoption \n-rto-adopt (return to owner through adoption) \n\n\nI will combine the following for not adopted: \n-transfer \n-euthanasia \n-relocate \n-missing (animals that went missing from the shelter--still unsuccessful in getting them homes) \n\"Died\" and \"disposal\" are animals that may have died while at the shelter or were brought in that needed to be properly disposed of so I will not include these either as they may have been very ill when brought in.\n\n# How is the target distributed?\n## Are the classes imbalanced?\n\n\n```python\nadoption['outcome_type'].value_counts(normalize=True)\n```\n\n\n\n\n Adoption 0.443913\n Transfer 0.298619\n Return to Owner 0.175105\n Euthanasia 0.062942\n Died 0.009690\n Rto-Adopt 0.005080\n Disposal 0.003870\n Missing 0.000610\n Relocate 0.000170\n Name: outcome_type, dtype: float64\n\n\n\nwill need to drop the rows where the outcome type are the ones listed above to be excluded: \n-Return to owner \n-Rto-adopt \n-Died \n-Disposal\n\n\n\n```python\n# adoption updated to drop the outcomes we are excluding:\nadoption_upd = adoption[~adoption['outcome_type'].isin(['Return to Owner', \n 'Rto-Adopt', \n 'Died', \n 'Disposal'])]\n```\n\n\n```python\nadoption_upd['outcome_type'].value_counts(dropna=False)\n```\n\n\n\n\n Adoption 44390\n Transfer 29861\n Euthanasia 6294\n Missing 61\n Relocate 17\n NaN 3\n Name: outcome_type, dtype: int64\n\n\n\n\n```python\n# am going to drop all animals except cats and dogs, 2 of the unknown\n# outcome types are dogs and 1 also has a lot of other missing info so\n# will drop these rows.\nadoption_upd = adoption_upd.dropna(subset = ['outcome_type'])\n\n```\n\n\n```python\n# need to redefine classes as binary. Adoption as 'adopted' and \n# the rest as 'not adopted'.\ndef new_status(outcome):\n if outcome == 'Transfer' or outcome == 'Euthanasia' or outcome == 'Missing' or outcome == 'Relocate':\n return 'Not adopted'\n else:\n return 'Adopted'\n\n```\n\n\n```python\nadoption_upd = adoption_upd.copy()\nadoption_upd['new_outcome_type'] = adoption_upd['outcome_type'].apply(new_status)\n```\n\n\n```python\nadoption_upd['new_outcome_type'].value_counts(normalize=True)\n```\n\n\n\n\n Adopted 0.550587\n Not adopted 0.449413\n Name: new_outcome_type, dtype: float64\n\n\n\nThe classes now are combined into a binary classification and the classes are not imbalanced.\n\n\n```python\n# drop the original 'Outcome_Type' column:\nadoption_upd = adoption_upd.drop(columns='outcome_type')\n```\n\n# Choose Observations\n\nAs mentioned above, since the focus of my project is predicting if animals that are in need of forever homes will be adopted or not, I have already excluded the following observations from my model: \n-Return to Owner \n-Rto-Adopt \n-Died \n-Disposal \n\nThere are 3 missing values for the outcome ,so we can try to look at the outcome subtype to see if we can determine what happened to them but the remaining animals have been categorized into 'adopted' or 'not adopted.'\n\n# How to Split Data:\n\n\n```python\nadoption_upd.dtypes\n```\n\n\n\n\n animal_id object\n name object\n datetime object\n monthyear object\n date_of_birth object\n outcome_subtype object\n animal_type object\n sex_upon_outcome object\n age_upon_outcome object\n breed object\n color object\n new_outcome_type object\n dtype: object\n\n\n\n\n```python\nadoption_upd['datetime'] = pd.to_datetime(adoption_upd['datetime'], infer_datetime_format=True)\n```\n\n\n```python\nadoption_upd['datetime'].dt.year.value_counts()\n```\n\n\n\n\n 2015 14792\n 2019 14373\n 2016 14119\n 2017 14058\n 2018 13361\n 2014 9920\n Name: datetime, dtype: int64\n\n\n\nThe description of the data set said that Austin is becoming a more pet-friendly city so there may be more animals going in and out of shelters in the more recent data vs the earlier data. I will therefore split the data based on time with the most recent data being the test set and then create a test and validation set with the remaining data. \n\ntest = adoption_upd[(adoption_upd['datetime'].dt.year == 2019)] \nval = adoption_upd[(adoption_upd['datetime'].dt.year == 2018)] \ntrain = adoption_upd[(adoption_upd['datetime'].dt.year < 2018)]\n\n\n```python\n# how big to make test set? 2019:\n# 14292 observations\n```\n\n# Evaluation Metrics\n\nsince the classes aren't imbalanced I can use accuracy but will also explore the precision and recall for this problem.\n\nprecision positive: correctly predict all the animals that were adopted. \n\n\\begin{align}\nprecision = \\frac{accurately \\ predicted \\ adopted}{total\\ predicted \\ adopted}\n\\end{align}\n\n\nrecall positive: of all the animals that were adopted, how many were we able to identify?\n\\begin{align}\nrecall = \\frac{accurately \\ predicted \\ adopted}{actually \\ adopted}\n\\end{align}\n\n\n# Begin to clean data and feature selection\n\n\n```python\nadoption_upd.isnull().sum()\n```\n\n\n\n\n animal_id 0\n name 30056\n datetime 0\n monthyear 0\n date_of_birth 0\n outcome_subtype 36351\n animal_type 0\n sex_upon_outcome 2\n age_upon_outcome 24\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n\n```python\n# the name column has a lot of missing values, will change NaN's to Unknown\nadoption_upd['name'].fillna(\"Unknown\", inplace = True) \n```\n\n\n```python\n# the outcome subtype is missing 36353 values, almost half of all of our \n# data, since we will know all of the outcome types and this may cause \n# leakage into the test set because certain outcomes can be deduced from \n# the outcome subtype, I will drop that entire column.\n\nadoption_upd = adoption_upd.drop(columns='outcome_subtype')\nadoption_upd.shape\n\n```\n\n\n\n\n (80623, 11)\n\n\n\n\n```python\n# the sex_upon_outcome column has 2 missing values but noticed an 'unknown'\n# value so check to see if that's common:\nadoption_upd['sex_upon_outcome'].value_counts()\n# will one hot encode this column.\n```\n\n\n\n\n Neutered Male 27561\n Spayed Female 26019\n Intact Female 10098\n Intact Male 9372\n Unknown 7571\n Name: sex_upon_outcome, dtype: int64\n\n\n\n\n```python\n# age_upon_outcome has 25 missing values but date_of_birth has none, lets\n# look at how many times 'unknown' shows up in the data:\nadoption_upd.isin(['Unknown']).sum()\n# the name already has 18 unknowns, so will stick to changing NaN's to unknown.\n```\n\n\n\n\n animal_id 0\n name 30074\n datetime 0\n monthyear 0\n date_of_birth 0\n animal_type 0\n sex_upon_outcome 7571\n age_upon_outcome 0\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n\n```python\n# to see if 'Other is a common entry as well'\nadoption_upd.isin(['Other']).sum()\n```\n\n\n\n\n animal_id 0\n name 0\n datetime 0\n monthyear 0\n date_of_birth 0\n animal_type 4450\n sex_upon_outcome 0\n age_upon_outcome 0\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n\n```python\n# to see what kind of animals come in to the shelter\nadoption_upd['animal_type'].value_counts()\n```\n\n\n\n\n Dog 39758\n Cat 35974\n Other 4450\n Bird 432\n Livestock 9\n Name: animal_type, dtype: int64\n\n\n\n\n```python\n# initially thinking of only using cats and dogs.\nadoption_upd = adoption_upd[~adoption_upd['animal_type'].isin(['Bird', \n 'Other', \n 'Livestock'])]\n```\n\n\n```python\n# check for missing values now:\nadoption_upd.isnull().sum()\n```\n\n\n\n\n animal_id 0\n name 0\n datetime 0\n monthyear 0\n date_of_birth 0\n animal_type 0\n sex_upon_outcome 2\n age_upon_outcome 8\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n\n```python\nadoption_upd['date_of_birth'] = pd.to_datetime(adoption_upd['date_of_birth'], infer_datetime_format=True)\n```\n\n\n```python\nadoption_upd.loc[adoption_upd['age_upon_outcome'].isnull()]\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 \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
animal_idnamedatetimemonthyeardate_of_birthanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_type
59A808636Unknown2019-11-13 13:46:002019-11-13T13:46:00.0002004-11-11CatIntact FemaleNaNSiameseSeal PointNot adopted
96A808702Keepers2019-11-12 15:20:002019-11-12T15:20:00.0002009-11-12DogNeutered MaleNaNGolden RetrieverGoldNot adopted
131A808649Unknown2019-11-11 17:49:002019-11-11T17:49:00.0002019-10-11CatIntact MaleNaNDomestic ShorthairBrown TabbyNot adopted
132A738697Boots2019-11-11 17:48:002019-11-11T17:48:00.0002007-11-17DogNaNNaNMiniature Schnauzer MixBlackNot adopted
161A808626Unknown2019-11-11 13:57:002019-11-11T13:57:00.0002019-09-11CatIntact FemaleNaNDomestic ShorthairBrown TabbyNot adopted
214A808466Unknown2019-11-10 09:35:002019-11-10T09:35:00.0002019-09-09CatIntact MaleNaNDomestic ShorthairBrown/BlackNot adopted
347A808352Unknown2019-11-07 16:15:002019-11-07T16:15:00.0002011-11-07DogIntact MaleNaNDachshund MixTanNot adopted
6649A752967Gray2019-07-24 11:42:002019-07-24T11:42:00.0002015-06-29DogNaNNaNPit Bull MixBlue/WhiteNot adopted
\n
\n\n\n\n\n```python\n# 2 of the rows that are missing the age are also missing the sex so I will\n# drop those:\nadoption_upd = adoption_upd.dropna(subset = ['sex_upon_outcome'])\n```\n\n\n```python\n# since there are no missing or unknown values for DOB which still seems strange \n# especially for stray animals that were found but maybe they approximated. We can \n# create a column where we subtract 2019 from the born on year to get the age and see \n# if there are a lot of differences.\n\nnow = pd.Timestamp('now')\n# first, get DOB year column and DOB month columns:\nadoption_upd['DOB_month'] = adoption_upd['date_of_birth'].dt.month\n# now, subtract current year from DOB year:\nadoption_upd['DOB_year'] = now.year - adoption_upd['date_of_birth'].dt.year\n# now turn DOB_year into months by multiplying by 12\nadoption_upd['DOB_year'] = adoption_upd['DOB_year'] * 12\n# add DOB_year which is now in months to DOB month and divide by 12 to get years\nadoption_upd['calculated_age'] = adoption_upd['DOB_year'] + adoption_upd['DOB_month']\ndef calculate_age(age):\n if age >= 12:\n return(f'{age // 12} years')\n else:\n return(f'{age} months') \nadoption_upd['calculated_age'] = adoption_upd['calculated_age'].apply(calculate_age)\n# fill NaN's in age upon outcome column with calculated age\nadoption_upd['age_upon_outcome'].fillna(adoption_upd['calculated_age'], inplace=True)\n# drop DOB month, DOB year, calculated age:\nadoption_upd.drop(columns =['DOB_month', 'DOB_year', 'calculated_age'], inplace=True)\n```\n\n\n```python\nadoption_upd.isnull().sum()\n# no more missing values!\n```\n\n\n\n\n animal_id 0\n name 0\n datetime 0\n monthyear 0\n date_of_birth 0\n animal_type 0\n sex_upon_outcome 0\n age_upon_outcome 0\n breed 0\n color 0\n new_outcome_type 0\n dtype: int64\n\n\n\n\n```python\nadoption_upd.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnamedatetimemonthyeardate_of_birthanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_type
1A781697Pookie2019-11-14 15:33:002019-11-14T15:33:00.0002017-10-05DogSpayed Female2 yearsCairn TerrierWhite/BrownAdopted
2A808382Unknown2019-11-14 14:57:002019-11-14T14:57:00.0002014-11-08CatIntact Male5 yearsDomestic ShorthairOrange TabbyNot adopted
3A806701*Emerald2019-11-14 14:41:002019-11-14T14:41:00.0002019-09-02CatNeutered Male2 monthsDomestic ShorthairBlue Tabby/WhiteAdopted
4A804553*Wendy2019-11-14 14:36:002019-11-14T14:36:00.0002019-08-09CatSpayed Female3 monthsDomestic ShorthairCalicoAdopted
5A804552*Tinkerbell2019-11-14 14:35:002019-11-14T14:35:00.0002019-08-09CatSpayed Female3 monthsDomestic ShorthairCalicoAdopted
\n
\n\n\n\n\n```python\n# looking at redundant columns, date of birth can be dropped since the ages are all accounted for.\n# also datetime and monthyear are the same, I will get rid of datetime for now.\nadoption_upd.drop(columns=['date_of_birth'], inplace=True)\n```\n\n\n```python\n# going to create a new column for the season the animal came into the shelter to see if certain\n# seasons have higher adoption rates:\nadoption_upd['monthyear'] = pd.to_datetime(adoption_upd['monthyear'], infer_datetime_format=True)\nadoption_upd['month_arrived'] = adoption_upd['monthyear'].dt.month\nadoption_upd.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnamedatetimemonthyearanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_typemonth_arrived
1A781697Pookie2019-11-14 15:33:002019-11-14 15:33:00DogSpayed Female2 yearsCairn TerrierWhite/BrownAdopted11
2A808382Unknown2019-11-14 14:57:002019-11-14 14:57:00CatIntact Male5 yearsDomestic ShorthairOrange TabbyNot adopted11
3A806701*Emerald2019-11-14 14:41:002019-11-14 14:41:00CatNeutered Male2 monthsDomestic ShorthairBlue Tabby/WhiteAdopted11
4A804553*Wendy2019-11-14 14:36:002019-11-14 14:36:00CatSpayed Female3 monthsDomestic ShorthairCalicoAdopted11
5A804552*Tinkerbell2019-11-14 14:35:002019-11-14 14:35:00CatSpayed Female3 monthsDomestic ShorthairCalicoAdopted11
\n
\n\n\n\n\n```python\ndef season(arrival_month):\n if arrival_month == 1 or arrival_month == 2 or arrival_month == 3:\n return 'Winter'\n if arrival_month == 3 or arrival_month == 4 or arrival_month ==5:\n return 'Spring'\n if arrival_month == 6 or arrival_month == 7 or arrival_month ==8:\n return 'Summer'\n if arrival_month == 9 or arrival_month == 10 or arrival_month ==11:\n return 'Fall'\nadoption_upd['season_arrived'] = adoption_upd['month_arrived'].apply(season)\n```\n\n\n```python\n# want to change the datetime column to year only since we have month_arrived now:\nadoption_upd['year_arrived'] = adoption_upd['datetime'].dt.year\n```\n\n\n```python\n# going to drop datetime and monthyear now:\nadoption_upd.drop(columns=['datetime', 'monthyear'], inplace=True)\n```\n\n\n```python\nadoption_upd.head(10)\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 \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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnameanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_typemonth_arrivedseason_arrivedyear_arrived
1A781697PookieDogSpayed Female2 yearsCairn TerrierWhite/BrownAdopted11Fall2019
2A808382UnknownCatIntact Male5 yearsDomestic ShorthairOrange TabbyNot adopted11Fall2019
3A806701*EmeraldCatNeutered Male2 monthsDomestic ShorthairBlue Tabby/WhiteAdopted11Fall2019
4A804553*WendyCatSpayed Female3 monthsDomestic ShorthairCalicoAdopted11Fall2019
5A804552*TinkerbellCatSpayed Female3 monthsDomestic ShorthairCalicoAdopted11Fall2019
6A808132DarylCatNeutered Male5 yearsDomestic ShorthairBrown Tabby/WhiteAdopted11Fall2019
7A805655*FezzikCatNeutered Male2 monthsDomestic ShorthairOrange TabbyAdopted11Fall2019
9A808526JugezDogSpayed Female13 yearsShih TzuBrown/CreamNot adopted11Fall2019
10A787448WatermelonDogSpayed Female3 yearsLabrador Retriever MixBrown Tiger/WhiteAdopted11Fall2019
11A808522UnknownCatIntact Female4 yearsDomestic ShorthairBrown TabbyNot adopted11Fall2019
\n
\n\n\n\n\n```python\n# how many different breeds are there:\nadoption_upd['breed'].value_counts()\n# 2042...very high cardinality\n```\n\n\n\n\n Domestic Shorthair Mix 26063\n Pit Bull Mix 4720\n Labrador Retriever Mix 4372\n Chihuahua Shorthair Mix 3974\n Domestic Shorthair 3566\n Domestic Medium Hair Mix 2548\n German Shepherd Mix 1816\n Domestic Longhair Mix 1184\n Siamese Mix 1019\n Australian Cattle Dog Mix 969\n Dachshund Mix 625\n Border Collie Mix 594\n Boxer Mix 572\n Domestic Medium Hair 478\n Miniature Poodle Mix 453\n Catahoula Mix 432\n Labrador Retriever 403\n Staffordshire Mix 401\n Chihuahua Shorthair 401\n Pit Bull 384\n Australian Shepherd Mix 381\n Great Pyrenees Mix 367\n Pointer Mix 367\n Rat Terrier Mix 364\n Beagle Mix 358\n German Shepherd 348\n Yorkshire Terrier Mix 346\n Siberian Husky Mix 344\n Jack Russell Terrier Mix 338\n Cairn Terrier Mix 335\n ... \n West Highland/Lhasa Apso 1\n Vizsla/Greyhound 1\n Pembroke Welsh Corgi/Collie Smooth 1\n Whippet/Catahoula 1\n Yorkshire Terrier/Dachshund Longhair 1\n Staffordshire/Border Collie 1\n French Bulldog/Chihuahua Shorthair 1\n Dachshund Longhair/Cairn Terrier 1\n Standard Poodle/Whippet 1\n Bluetick Hound/Great Pyrenees 1\n Labrador Retriever/Collie Rough 1\n Pbgv/Pit Bull 1\n English Bulldog/Boxer 1\n Chinese Sharpei/Chow Chow 1\n Domestic Shorthair/Manx 1\n Tibetan Spaniel/Dachshund Longhair 1\n Tibetan Spaniel 1\n Collie Rough/Chow Chow 1\n Vizsla/Dachshund 1\n Snowshoe/Ragdoll 1\n Jack Russell Terrier/Australian Shepherd 1\n Golden Retriever/Akita 1\n Chinese Crested/Papillon 1\n Labrador Retriever/English Springer Spaniel 1\n English Bulldog/Mastiff 1\n Rhod Ridgeback/Pointer 1\n Cocker Spaniel/Dachshund Longhair 1\n Akita/Pit Bull 1\n Chihuahua Shorthair/Cavalier Span 1\n Black Mouth Cur/Belgian Malinois 1\n Name: breed, Length: 1867, dtype: int64\n\n\n\n\n```python\n# create subsets for dogs and cats:\ndogs = adoption_upd[adoption_upd.animal_type=='Dog']\ncats = adoption_upd[adoption_upd.animal_type=='Cat']\n```\n\n\n```python\n# Reduce cardinality for breed feature ...\ndogs =dogs.copy()\n# Get a list of the top 75 breeds\ntop75 = dogs['breed'].value_counts()[:75].index\n# Breeds that are NOT in the top 100,\n# replace the breed with 'OTHER'\ndogs.loc[~dogs['breed'].isin(top75), 'breed'] = 'OTHER'\ndogs['breed'].value_counts()\n```\n\n\n\n\n OTHER 9368\n Pit Bull Mix 4720\n Labrador Retriever Mix 4372\n Chihuahua Shorthair Mix 3974\n German Shepherd Mix 1816\n Australian Cattle Dog Mix 969\n Dachshund Mix 625\n Border Collie Mix 594\n Boxer Mix 572\n Miniature Poodle Mix 453\n Catahoula Mix 432\n Labrador Retriever 403\n Chihuahua Shorthair 401\n Staffordshire Mix 401\n Pit Bull 384\n Australian Shepherd Mix 381\n Great Pyrenees Mix 367\n Pointer Mix 367\n Rat Terrier Mix 364\n Beagle Mix 358\n German Shepherd 348\n Yorkshire Terrier Mix 346\n Siberian Husky Mix 344\n Jack Russell Terrier Mix 338\n Cairn Terrier Mix 335\n Chihuahua Longhair Mix 329\n Miniature Schnauzer Mix 315\n Plott Hound Mix 300\n Anatol Shepherd Mix 298\n Black Mouth Cur Mix 267\n ... \n Golden Retriever Mix 122\n Queensland Heeler Mix 120\n Maltese Mix 120\n Dachshund 97\n Shih Tzu 95\n Black/Tan Hound Mix 90\n Labrador Retriever/Border Collie 88\n Manchester Terrier Mix 88\n Cardigan Welsh Corgi Mix 88\n Lhasa Apso Mix 88\n Basset Hound Mix 87\n Doberman Pinsch Mix 87\n Boxer 83\n Chow Chow Mix 83\n Pit Bull/Labrador Retriever 83\n Collie Smooth Mix 79\n Labrador Retriever/Great Pyrenees 79\n Dachshund Longhair Mix 78\n Cocker Spaniel Mix 78\n Rottweiler 76\n Dachshund Wirehair Mix 72\n Labrador Retriever/Australian Cattle Dog 69\n Pug Mix 69\n Mastiff Mix 68\n Pomeranian Mix 68\n Great Pyrenees 67\n Cairn Terrier 66\n Border Collie/Labrador Retriever 66\n Flat Coat Retriever Mix 66\n Chinese Sharpei Mix 66\n Name: breed, Length: 76, dtype: int64\n\n\n\n\n```python\n# Reduce cardinality for breed feature ...cats don't have as many\n# breeds so will only use top 30\ncats =cats.copy()\n# Get a list of the top 30 breeds\ntop30 = cats['breed'].value_counts()[:30].index\n# Breeds that are NOT in the top 30,\n# replace the breed with 'OTHER'\ncats.loc[~cats['breed'].isin(top30), 'breed'] = 'OTHER'\ncats['breed'].value_counts()\n```\n\n\n\n\n Domestic Shorthair Mix 26063\n Domestic Shorthair 3566\n Domestic Medium Hair Mix 2548\n Domestic Longhair Mix 1184\n Siamese Mix 1019\n Domestic Medium Hair 478\n American Shorthair Mix 201\n Snowshoe Mix 143\n Siamese 130\n OTHER 125\n Domestic Longhair 103\n Maine Coon Mix 81\n Manx Mix 75\n Russian Blue Mix 46\n Ragdoll Mix 34\n American Shorthair 29\n Himalayan Mix 27\n Persian Mix 16\n Balinese Mix 14\n American Curl Shorthair Mix 12\n Japanese Bobtail Mix 9\n Persian 9\n Russian Blue 8\n Tonkinese Mix 8\n Turkish Van Mix 7\n Siamese/Domestic Shorthair 7\n Manx 7\n Himalayan 7\n Cymric Mix 6\n Abyssinian 6\n Snowshoe 6\n Name: breed, dtype: int64\n\n\n\n\n```python\n# concatenate the cats and dogs subsets, matches shape of adoption_upd\nadoption_final = pd.concat([dogs, cats])\nadoption_final.shape\n```\n\n\n\n\n (75730, 11)\n\n\n\n\n```python\n# lets do something similar to color:\nadoption_final['color'].value_counts()\n```\n\n\n\n\n Black/White 8297\n Black 6815\n Brown Tabby 5511\n Brown Tabby/White 2809\n Orange Tabby 2642\n White 2320\n Tan/White 2258\n Brown/White 2151\n Blue/White 2113\n White/Black 2067\n Tan 1869\n Tortie 1664\n Calico 1636\n Brown 1620\n Tricolor 1612\n Blue 1540\n Black/Tan 1514\n Blue Tabby 1381\n Black/Brown 1377\n White/Brown 1302\n Orange Tabby/White 1289\n Brown Brindle/White 1196\n White/Tan 1106\n Torbie 1035\n Brown/Black 1025\n Red 748\n Red/White 704\n Blue Tabby/White 675\n Tan/Black 675\n Brown Brindle 657\n ... \n Brown/Liver 1\n Gray/Blue Merle 1\n Tricolor/Orange 1\n Blue Smoke/Gray 1\n Tricolor/Red Tick 1\n White/Liver Tick 1\n Red Tick/Tricolor 1\n Black Tabby/Black 1\n Red/Brown Brindle 1\n Calico/Orange Tabby 1\n Brown Brindle/Blue 1\n Lynx Point/Blue 1\n Gold/Yellow 1\n Gray Tabby/Orange 1\n Lilac Point/Gray 1\n Red/Silver 1\n White/Yellow Brindle 1\n Blue/Calico 1\n Tortie/Tortie 1\n Red Merle/Black 1\n Buff/Yellow 1\n Black Smoke/Black Tiger 1\n Brown Tabby/Black Brindle 1\n Fawn/Chocolate 1\n Brown Merle/Chocolate 1\n Cream Tabby/Cream Tabby 1\n Orange/Orange Tabby 1\n Red/Red Merle 1\n Orange Tabby/Tortie Point 1\n Gray/Buff 1\n Name: color, Length: 477, dtype: int64\n\n\n\n\n```python\nadoption_final = adoption_final.copy()\n# Get a list of the top 75 colors\ntop75 = adoption_final['color'].value_counts()[:75].index\n# colors that are NOT in the top 75,\n# replace the color with 'OTHER'\nadoption_final.loc[~adoption_final['color'].isin(top75), 'color'] = 'OTHER'\n```\n\n\n```python\nadoption_final.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnameanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_typemonth_arrivedseason_arrivedyear_arrived
1A781697PookieDogSpayed Female2 yearsCairn TerrierWhite/BrownAdopted11Fall2019
9A808526JugezDogSpayed Female13 yearsShih TzuOTHERNot adopted11Fall2019
10A787448WatermelonDogSpayed Female3 yearsLabrador Retriever MixOTHERAdopted11Fall2019
17A808589LolaDogSpayed Female5 yearsOTHERBrown BrindleNot adopted11Fall2019
18A808590CheyenneDogSpayed Female7 yearsAustralian Shepherd MixBrown/WhiteNot adopted11Fall2019
\n
\n\n\n\n\n```python\n# # change animal type to numerical:\n# # 1 for dog, 2 for cat\n# def change_type(animal):\n# if animal == 'dog':\n# return 1\n# else:\n# return 2\n\n```\n\n\n```python\n# adoption_final['animal_type'] = adoption_final['animal_type'].apply(change_type).astype(int)\n```\n\n\n```python\nadoption_final['sex_upon_outcome'].value_counts()\n```\n\n\n\n\n Neutered Male 27406\n Spayed Female 25892\n Intact Female 9822\n Intact Male 8973\n Unknown 3637\n Name: sex_upon_outcome, dtype: int64\n\n\n\n\n```python\n# do the same thing with sex_upon_outcome:\ndef change_sex(animal):\n if animal == 'Neutered Male':\n return 1\n if animal == 'Spayed Female':\n return 2\n if animal == 'Intact Male':\n return 3\n if animal == 'Intact Female':\n return 4\n if animal == 'Unknown':\n return 5\nadoption_final['sex_upon_outcome'] = adoption_final['sex_upon_outcome'].apply(change_sex).astype(int)\n```\n\n\n```python\n#need to bin ages:\nadoption_final['age_upon_outcome'].value_counts()\n```\n\n\n\n\n 1 year 12232\n 2 months 11998\n 2 years 9739\n 3 months 4480\n 1 month 4321\n 3 years 3684\n 4 months 2890\n 4 years 2126\n 5 years 2050\n 5 months 1979\n 6 months 1818\n 3 weeks 1756\n 2 weeks 1664\n 8 months 1321\n 6 years 1302\n 8 years 1191\n 4 weeks 1180\n 10 months 1158\n 7 years 1064\n 7 months 1000\n 10 years 955\n 9 months 794\n 1 weeks 656\n 9 years 582\n 1 week 547\n 12 years 466\n 11 months 461\n 11 years 315\n 2 days 270\n 3 days 262\n 13 years 251\n 1 day 184\n 6 days 182\n 4 days 157\n 14 years 156\n 15 years 137\n 5 days 108\n 0 years 103\n 5 weeks 92\n 16 years 39\n 17 years 28\n 18 years 15\n 19 years 8\n 20 years 7\n -1 years 1\n 22 years 1\n Name: age_upon_outcome, dtype: int64\n\n\n\n\n```python\n# This is difficult because of the age units, there are days, weeks, months\n# and years. Best way I could think of it is to bin the ages that are under 1 year\n# and then do the rest of the data in years since that's the majority and it's numerical data.\n\ndef bin_ages(age):\n if age == '11 months' or age == '12 months' or age == '1 year':\n return '1 years'\n if age == '8 months' or age == '9 months' or age == '10 months':\n return '.75 years'\n if age == '6 months' or age == '7 months' or age =='5 months' or age == '4 months':\n return '.5 years'\n if age == '1 month' or age == '3 weeks' or age == '2 weeks' or age == '4 weeks' or age == '1 weeks' or age == '1 week' or age == '2 days' or age == '3 days' or age == '1 day' or age == '6 days' or age == '4 days' or age == '5 days' or age == '0 years' or age == '5 weeks' or age == '2 months' or age == '3 months' or age == '2 month' or age == '-1 years':\n return '.25 years'\n else:\n return age \nadoption_final['age_upon_outcome'] = adoption_final['age_upon_outcome'].apply(bin_ages)\n```\n\n\n```python\nadoption_final['age_upon_outcome'].value_counts()\n```\n\n\n\n\n .25 years 27961\n 1 years 12693\n 2 years 9739\n .5 years 7687\n 3 years 3684\n .75 years 3273\n 4 years 2126\n 5 years 2050\n 6 years 1302\n 8 years 1191\n 7 years 1064\n 10 years 955\n 9 years 582\n 12 years 466\n 11 years 315\n 13 years 251\n 14 years 156\n 15 years 137\n 16 years 39\n 17 years 28\n 18 years 15\n 19 years 8\n 20 years 7\n 22 years 1\n Name: age_upon_outcome, dtype: int64\n\n\n\n\n```python\n# now for the rest of the ages, need to strip the 'years' from the values:\n# also going to drop the row that says -1 because not sure what that means.\ndef age_to_int(age):\n return float(age.strip('years'))\n\nadoption_final['age_upon_outcome'] = adoption_final['age_upon_outcome'].apply(age_to_int)\n```\n\n\n```python\nadoption_final.dtypes\n```\n\n\n\n\n animal_id object\n name object\n animal_type object\n sex_upon_outcome int64\n age_upon_outcome float64\n breed object\n color object\n new_outcome_type object\n month_arrived int64\n season_arrived object\n year_arrived int64\n dtype: object\n\n\n\n\n```python\nadoption_final.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnameanimal_typesex_upon_outcomeage_upon_outcomebreedcolornew_outcome_typemonth_arrivedseason_arrivedyear_arrived
1A781697PookieDog22.0Cairn TerrierWhite/BrownAdopted11Fall2019
9A808526JugezDog213.0Shih TzuOTHERNot adopted11Fall2019
10A787448WatermelonDog23.0Labrador Retriever MixOTHERAdopted11Fall2019
17A808589LolaDog25.0OTHERBrown BrindleNot adopted11Fall2019
18A808590CheyenneDog27.0Australian Shepherd MixBrown/WhiteNot adopted11Fall2019
\n
\n\n\n\n\n```python\n# going to make a copy without the age upon outcome column since it has high cardinality and isn't numeric:\nadoption_use = adoption_final.drop(columns=['age_upon_outcome'])\n```\n\n\n```python\nadoption_use.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
animal_idnameanimal_typesex_upon_outcomebreedcolornew_outcome_typemonth_arrivedseason_arrivedyear_arrived
1A781697PookieDog2Cairn TerrierWhite/BrownAdopted11Fall2019
9A808526JugezDog2Shih TzuOTHERNot adopted11Fall2019
10A787448WatermelonDog2Labrador Retriever MixOTHERAdopted11Fall2019
17A808589LolaDog2OTHERBrown BrindleNot adopted11Fall2019
18A808590CheyenneDog2Australian Shepherd MixBrown/WhiteNot adopted11Fall2019
\n
\n\n\n\nThink I'm ready to start fitting models, may need to come back to features:\n\n\n```python\n# split data into train, val, test\nadoption_use['year_arrived'].value_counts()\n```\n\n\n\n\n 2015 13964\n 2019 13644\n 2016 13141\n 2017 13035\n 2018 12513\n 2014 9433\n Name: year_arrived, dtype: int64\n\n\n\n\n```python\ntest = adoption_use[(adoption_use['year_arrived'] == 2019)] \nval = adoption_use[(adoption_use['year_arrived']== 2018)] \ntrain = adoption_upd[(adoption_upd['year_arrived'] < 2018)]\n```\n\n\n```python\ntest.shape, val.shape, train.shape\n```\n\n\n\n\n ((13644, 10), (12513, 10), (49573, 11))\n\n\n\n\n```python\n# %matplotlib inline\n# import matplotlib.pyplot as plt\n# import seaborn as sns\n\n# for col in adoption_upd.columns:\n# if adoption_upd[col].nunique() < 10:\n# try:\n# sns.catplot(x=col, y='new_outcome_type', data=adoption_upd, kind='bar', color='grey')\n# plt.show()\n# except:\n# pass\n```\n\n\n```python\n# numeric = train.select_dtypes('number')\n# def change_type(animal):\n# if animal == 'Adopted':\n# return 1\n# else:\n# return 2\n# train['new_outcome_type'] = train['new_outcome_type'].apply(change_type)\n# for col in sorted(numeric.columns):\n# sns.lmplot(x=col, y='new_outcome_type', data=train, scatter_kws=dict(alpha=0.05))\n# plt.show()\n```\n\n\n```python\ntrain.dtypes\n```\n\n\n\n\n animal_id object\n name object\n animal_type object\n sex_upon_outcome object\n age_upon_outcome object\n breed object\n color object\n new_outcome_type object\n month_arrived int64\n season_arrived object\n year_arrived int64\n dtype: object\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "80c3c35104f9e61b9ad28b3c10bd7705dc7104e0", "size": 100004, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "module1/LS_DS_231_assignment (3).ipynb", "max_stars_repo_name": "mljarman/DS-Unit-2-Applied-Modeling", "max_stars_repo_head_hexsha": "de878dab12cf4deac01fd1881a9fc1414ac6285c", "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": "module1/LS_DS_231_assignment (3).ipynb", "max_issues_repo_name": "mljarman/DS-Unit-2-Applied-Modeling", "max_issues_repo_head_hexsha": "de878dab12cf4deac01fd1881a9fc1414ac6285c", "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": "module1/LS_DS_231_assignment (3).ipynb", "max_forks_repo_name": "mljarman/DS-Unit-2-Applied-Modeling", "max_forks_repo_head_hexsha": "de878dab12cf4deac01fd1881a9fc1414ac6285c", "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": 33.71679029, "max_line_length": 393, "alphanum_fraction": 0.4204431823, "converted": true, "num_tokens": 16405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.22270013882530887, "lm_q1q2_score": 0.07607047004520918}} {"text": "```python\n#format the book\n%matplotlib inline\nfrom __future__ import division, print_function\nimport sys;sys.path.insert(0,'..')\nfrom book_format import load_style;load_style('..')\n```\n\n\n\n\n\n\n\n\n\n\n# Computing and plotting PDFs of discrete data\n\nSo let's investigate how to compute and plot probability distributions.\n\n\nFirst, let's make some data according to a normal distribution. We use `numpy.random.normal` for this. The parameters are not well named. `loc` is the mean of the distribution, and `scale` is the standard deviation. We can call this function to create an arbitrary number of data points that are distributed according to that mean and std.\n\n\n```python\nimport numpy as np\nimport numpy.random as random\n\nmean = 3\nstd = 2\n\ndata = random.normal(loc=mean, scale=std, size=50000)\nprint(len(data))\nprint(data.mean())\nprint(data.std())\n```\n\n 50000\n 2.99685400941\n 1.99912142836\n\n\nAs you can see from the print statements we got 5000 points that have a mean very close to 3, and a standard deviation close to 2.\n\nWe can plot this Gaussian by using `scipy.stats.norm` to create a frozen function that we will then use to compute the pdf (probability distribution function) of the Gaussian.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n\ndef plot_normal(xs, mean, std, **kwargs):\n norm = stats.norm(mean, std)\n plt.plot(xs, norm.pdf(xs), **kwargs)\n\nxs = np.linspace(-5, 15, num=200)\nplot_normal(xs, mean, std, color='k')\n```\n\nBut we really want to plot the PDF of the discrete data, not the idealized function.\n\nThere are a couple of ways of doing that. First, we can take advantage of `matplotlib`'s `hist` method, which computes a histogram of a collection of data. Normally `hist` computes the number of points that fall in a bin, like so:\n\n\n```python\nplt.hist(data, bins=200)\nplt.show()\n```\n\nthat is not very useful to us - we want the PDF, not bin counts. Fortunately `hist` includes a `density` parameter which will plot the PDF for us.\n\n\n```python\nplt.hist(data, bins=200, normed=True)\nplt.show()\n```\n\nI may not want bars, so I can specify the `histtype` as 'step' to get a line.\n\n\n```python\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nplt.show()\n```\n\nTo be sure it is working, let's also plot the idealized Gaussian in black.\n\n\n```python\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nnorm = stats.norm(mean, std)\nplt.plot(xs, norm.pdf(xs), color='k', lw=2)\nplt.show()\n```\n\nThere is another way to get the approximate distribution of a set of data. There is a technique called *kernel density estimate* that uses a kernel to estimate the probability distribution of a set of data. NumPy implements it with the function `gaussian_kde`. Do not be mislead by the name - Gaussian refers to the type of kernel used in the computation. This works for any distribution, not just Gaussians. In this section we have a Gaussian distribution, but soon we will not, and this same function will work.\n\n\n```python\nkde = stats.gaussian_kde(data)\n\nxs = np.linspace(-5, 15, num=200)\nplt.plot(xs, kde(xs))\nplt.show()\n```\n\n## Monte Carlo Simulations\n\n\nWe (well I) want to do this sort of thing because I want to use monte carlo simulations to compute distributions. It is easy to compute Gaussians when they pass through linear functions, but difficult to impossible to compute them analytically when passed through nonlinear functions. Techniques like particle filtering handle this by taking a large sample of points, passing them through a nonlinear function, and then computing statistics on the transformed points. Let's do that.\n\nWe will start with the linear function $f(x) = 2x + 12$ just to prove to ourselves that the code is working. I will alter the mean and std of the data we are working with to help ensure the numbers that are output are unique It is easy to be fooled, for example, if the formula multipies x by 2, the mean is 2, and the std is 2. If the output of something is 4, is that due to the multication factor, the mean, the std, or a bug? It's hard to tell. \n\n\n```python\ndef f(x):\n return 2*x + 12\n\nmean = 1.\nstd = 1.4\ndata = random.normal(loc=mean, scale=std, size=50000)\n\nd_t = f(data) # transform data through f(x)\n\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\n\nplt.ylim(0, .35)\nplt.show()\nprint('mean = {:.2f}'.format(d_t.mean()))\nprint('std = {:.2f}'.format(d_t.std()))\n```\n\nThis is what we expected. The input is the Gaussian $\\mathcal{N}(\\mu=1, \\sigma=1.4)$, and the function is $f(x) = 2x+1$. Therefore we expect the mean to be shifted to $f(\\mu) = 2*1+12=14$. We can see from the plot and the print statement that this is what happened. \n\nBefore I go on, can you explain what happened to the standard deviation? You may have thought that the new $\\sigma$ should be passed through $f(x)$ like so $2(1.4) + 12=14.81$. But that is not correct - the standard deviation is only affected by the multiplicative factor, not the shift. If you think about that for a moment you will see it makes sense. We multiply our samples by 2, so they are twice as spread out as before. Standard deviation is a measure of how spread out things are, so it should also double. It doesn't matter if we then shift that distribution 12 places, or 12 million for that matter - the spread is still twice the input data.\n\n\n\n## Nonlinear Functions\n\nNow that we believe in our code, lets try it with nonlinear functions.\n\n\n```python\ndef f2(x):\n return (np.cos((1.5*x + 2.1))) * np.sin(0.3*x) - 1.6*x\n\nd_t = f2(data)\nplt.subplot(121)\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\n\nplt.subplot(122)\nkde = stats.gaussian_kde(d_t)\nxs = np.linspace(-10, 10, 200)\nplt.plot(xs, kde(xs), 'k')\nplot_normal(xs, d_t.mean(), d_t.std(), color='g', lw=3)\nplt.show()\nprint('mean = {:.2f}'.format(d_t.mean()))\nprint('std = {:.2f}'.format(d_t.std()))\n```\n\nHere I passed the data through the nonlinear function $f(x) = \\cos(1.5x+2.1)\\sin(\\frac{x}{3}) - 1.6x$. That function is quite close to linear, but we can see how much it alters the pdf of the sampled data. \n\nThere is a lot of computation going on behind the scenes to transform 50,000 points and then compute their PDF. The Extended Kalman Filter (EKF) gets around this by linearizing the function at the mean and then passing the Gaussian through the linear equation. We saw above how easy it is to pass a Gaussian through a linear function. So lets try that.\n\nWe can linearize this by taking the derivative of the function at x. We can use sympy to get the derivative. \n\n\n```python\nimport sympy\nx = sympy.symbols('x')\nf = sympy.cos(1.5*x+2.1) * sympy.sin(x/3) - 1.6*x\ndfx = sympy.diff(f, x)\ndfx\n```\n\n\n\n\n -1.5*sin(x/3)*sin(1.5*x + 2.1) + cos(x/3)*cos(1.5*x + 2.1)/3 - 1.6\n\n\n\nWe can now compute the slope of the function by evaluating the derivative at the mean.\n\n\n```python\nm = dfx.subs(x, mean)\nm\n```\n\n\n\n\n -1.66528051815545\n\n\n\nThe equation of a line is $y=mx+b$, so the new standard deviation should be $~1.67$ times the input std. We can compute the new mean by passing it through the original function because the linearized function is just the slope of f(x) evaluated at the mean. The slope is a tangent that touches the function at $x$, so both will return the same result. So, let's plot this and compare it to the results from the monte carlo simulation.\n\n\n```python\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\nplot_normal(xs, f2(mean), abs(float(m)*std), color='k', lw=3, label='EKF')\nplot_normal(xs, d_t.mean(), d_t.std(), color='r', lw=3, label='MC')\nplt.legend()\nplt.show()\n```\n\nWe can see from this that the estimate from the EKF (in red) is not exact, but it is not a bad approximation either. \n", "meta": {"hexsha": "e366c0b735455dbcc8cda564259012166dd5309d", "size": 164262, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_stars_repo_name": "simonkamronn/Kalman-and-Bayesian-Filters-in-Python", "max_stars_repo_head_hexsha": "5240944dd45415909228c233ddfb7f3c19e51189", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-02T01:28:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-02T01:28:52.000Z", "max_issues_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_issues_repo_name": "simonkamronn/Kalman-and-Bayesian-Filters-in-Python", "max_issues_repo_head_hexsha": "5240944dd45415909228c233ddfb7f3c19e51189", "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": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_forks_repo_name": "simonkamronn/Kalman-and-Bayesian-Filters-in-Python", "max_forks_repo_head_hexsha": "5240944dd45415909228c233ddfb7f3c19e51189", "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": 216.418972332, "max_line_length": 24212, "alphanum_fraction": 0.8894814382, "converted": true, "num_tokens": 3523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.20946968133032523, "lm_q1q2_score": 0.07603104381291546}} {"text": "\n\n**Submitted by**: \n\n[Ray], [Zhu], [LinkedIn](https://www.linkedin.com/in/jiasheng-ray-zhu-845241177/), \nMajoring in [Political Economy with Economics Concentration]\nClass of [2022]\nDuke Kunshan University\n\n\n---\n\n\n\n*Disclaimer: Submissions to Problem Set 1 for COMPSCI/ECON 206 Computational Microeconomics, 2022 Spring Term (Seven Week - Second) instructed by [Prof. Luyao Zhang](http://scholars.duke.edu/person/luyao.zhang) at Duke Kunshan University.*\n\n**Resources:**\n\n* Colab Instructions: https://colab.research.google.com/\n* Markdown Guide: https://www.markdownguide.org\n* Latex Math wiki: https://en.wikibooks.org/wiki/LaTeX/Mathematics\n\n\n* OER: https://ie.pubpub.org/pub/gpd9nks0/release/2\n\n\n\n\n\n---\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Part I: Game Theory Concepts (6 points)\n\n**Note:**\n\n*if you can't find definitions in the second computer science textbook, you can also refer to the algorithmic game theory textbook for substitutions.*\n\n## 1. Normal Form Game\n\n### 1.1. What defines a normal form game? Find answers in “A Course in Game Theory by Prof. Ariel Rubinstein and M. Osborne. ([Download](https://arielrubinstein.tau.ac.il/books.html)) \n\nRefer to Textbook: [Osborne, Martin J. and Ariel Rubinstein](https://arielrubinstein.tau.ac.il/books.html). 1994. A Course in Game Theory. (Chapter 1, Page 9)\n\nIn this part we study a model of strategic interaction known as a strategic game, or, in the terminology of von Neumann and Morgenstern (1944), a “game in normal form”. This model specifies for each player a set of possible actions and a preference ordering over the set of possible action profiles.\n\n### 1.2. What defines a normal form game? Find answers in “Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations” by Prof. Yoav Shoham and Kevin Leyton-Brown. ([Download](http://www.masfoundations.org/download.html))\n\nRefer to Textbook: [Noam and Nisan.](https://www.cs.cmu.edu/~sandholm/cs15-892F13/algorithmic-game-theory.pdf) 2007. Algorithmic Game Theory (Page 182)\n\nA multiplayer game consists of $n$ players, each with a finite set of pure strategies or actions available to them, along with a specification of the payoffs to each player. Throughout the chapter, we use $a_{i}$ to denote the action chosen by player $i$. For simplicity we will assume a binary action space, so $a_{i} \\in\\{0,1\\}$. (The generalization of the results examined here to the multiaction setting is straightforward.) The payoffs to player $i$ are given by a table or matrix $M_{i}$, indexed by the joint action $\\vec{a} \\in\\{0,1\\}^{n}$. The value $M_{i}(\\vec{a})$, which we assume without loss of generality to lie in the interval $[0,1]$, is the payoff to player $i$ resulting from the joint action $\\vec{a}$. Multiplayer games described in this way are referred to as normal form games.\n\n## 2. Static Game with Complete Information and Nash Equilibrium\n\n### 2.1. What defines Nash Equilibrium? Find answers in “A Course in Game Theory by Prof. Ariel Rubinstein and M. Osborne. ([Download](https://arielrubinstein.tau.ac.il/books.html)) \n\nRefer to Textbook: [Osborne, Martin J. and Ariel Rubinstein](https://arielrubinstein.tau.ac.il/books.html). 1994. A Course in Game Theory. (Chapter 2, Page 14, DEFINITION 14.1)\n\n**Definition of Nash equilibrium**\n\nA Nash Equilibrium of a strategic game $\\langle{N}, {A_{i}},(\\succeq_{i})\\rangle$ is a profile $a^{*}\\in{A}$ of actions with the property that for every player $i\\in {N}$, we have:\n$$(a^{*}_{-i},a^{*}_{i}) \\succeq_{i}(a^{*}_{-i},a_{i}), \\forall \\in {A_{i}}.$$\nAnd, a strategic game $\\langle{N}, {A_{i}},(\\succeq_{i})\\rangle$ consist of:\n* a finite set ${N}$ as the set of players\n* for each player $i\\in{N}$, a nonempty set $A_{i}$ as the set of actions available to player $i$\n* for each player $i\\in{N}$, a preference relation $\\succeq_{i}$ on ${A}=\\times_{j\\in {N}}{A}_{j}$\n\n### 2.2. What defines Nash Equilibrium? Find answers in “Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations” by Prof. Yoav Shoham and Kevin Leyton-Brown. ([Download](http://www.masfoundations.org/download.html))\n\nRefer to Textbook: [Shoham, Yoav, and Kevin Leyton-Brown](http://www.masfoundations.org/download.html). 2008. Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations. Cambridge: Cambridge University Press. (Chapter 3, Page 62, Definition 3.3.4)\n\n**Definition of Nash equilibrium**\n\nNash Equilibrium A strategy profile $s^{*}=(s_{1}^{*},...,s_{n}^{*})\\in S$ is a \\textbf{Nash Equilibrium} of a normal for game $({N}, {A}, \\mu)$ if, $\\forall$ agents $i$, $s_{i}^{*}$ is a best response to $s_{-i}^{*}$:\n\n$$\\mu_{i}(s_{i}^{*},s_{-i}^{*}) \\geq \\mu_{i}(s_{i},s_{-i}^{*}), \\forall -i.$$\nAnd a normal game $({N}, {A}, \\mu)$ consist of:\n* ${N}$, a finite set of $n$ players, indexed by $i$\n* ${A} ={A_{1}}\\times ...{A_{n}}$, where ${A_{i}}$ is a finite set of actions available to player $i$. Each vector $a=(a_{1},...,a_{n})\\in A$ is called an action profile; the set of mixed strategy for player $i$ is $S_{i}=\\prod(A_{i})$, where for any set $X$, $\\prod(X)$ denotes the set of all probability distributions over $X$\n* $\\mu = (\\mu_{1},...,\\mu_{n})$ where $\\mu_{i}: {A} \\mapsto \\mathbb{R} $\n\n## 3.Bayesian Game and Perfect Bayesian Nash Equilibrium\n\n### 3.1. How to define Bayesian Game and Bayesian Nash Equilibrium? Find answers in “A Course in Game Theory by Prof. Ariel Rubinstein and M. Osborne. ([Download](https://arielrubinstein.tau.ac.il/books.html)) \n\nRefer to Textbook: [Osborne, Martin J. and Ariel Rubinstein](https://arielrubinstein.tau.ac.il/books.html). 1994. A Course in Game Theory. (Chapter 2, Page 25-26, DEFINITION 14.1)\n\nDEFINITION 25.1 A Bayesian game consists of\n- a finite set $N$ (the set of players)\n- a finite set $\\Omega$ (the set of states)\nand for each player $i \\in N$\n- a set $A_{i}$ (the set of actions available to player $i$ )\n- a finite set $T_{i}$ (the set of signals that may be observed by player $i$ ) and a function $\\tau_{i}: \\Omega \\rightarrow T_{i}$ (the signal function of player $i$ )\n- a probability measure $p_{i}$ on $\\Omega$ (the prior belief of player $i$ ) for which $p_{i}\\left(\\tau_{i}^{-1}\\left(t_{i}\\right)\\right)>0$ for all $t_{i} \\in T_{i}$\n- a preference relation $\\succsim_{i}$ on the set of probability measures over $A \\times \\Omega$ (the preference relation of player $i$ ), where $A=\\times_{j \\in N} A_{j}$.\n\nDefinition $26.1$ A Nash equilibrium of a Bayesian game $\\langle N$, $\\left.\\Omega,\\left(A_{i}\\right),\\left(T_{i}\\right),\\left(\\tau_{i}\\right),\\left(p_{i}\\right),\\left(\\succsim_{i}\\right)\\right\\rangle$ is a Nash equilibrium of the strategic game defined as follows.\n- The set of players is the set of all pairs $\\left(i, t_{i}\\right)$ for $i \\in N$ and $t_{i} \\in T_{i}$.\n- The set of actions of each player $\\left(i, t_{i}\\right)$ is $A_{i}$.\n- The preference ordering $\\succsim_{\\left(i, t_{i}\\right)}^{*}$ of each player $\\left(i, t_{i}\\right)$ is defined by $a^{*} \\succsim_{\\left(i, t_{i}\\right)}^{*} b^{*}$ if and only if $L_{i}\\left(a^{*}, t_{i}\\right) \\succsim_{i} L_{i}\\left(b^{*}, t_{i}\\right)$,\nwhere $L_{i}\\left(a^{*}, t_{i}\\right)$ is the lottery over $A \\times \\Omega$ that assigns probability $p_{i}(\\omega) / p_{i}\\left(\\tau_{i}^{-1}\\left(t_{i}\\right)\\right)$ to $\\left(\\left(a^{*}\\left(j, \\tau_{j}(\\omega)\\right)\\right)_{j \\in N}, \\omega\\right)$ if $\\omega \\in \\tau_{i}^{-1}\\left(t_{i}\\right)$, zero otherwise.\n\n### 3.2. How to define Bayesian Game and Beyesian Nash Equilibrium? Find answers in “Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations” by Prof. Yoav Shoham and Kevin Leyton-Brown. ([Download](http://www.masfoundations.org/download.html))\n\nRefer to Textbook: [Shoham, Yoav, and Kevin Leyton-Brown](http://www.masfoundations.org/download.html). 2008. Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations. Cambridge: Cambridge University Press. (Chapter 6, Page 167-170, Definition 6.3.2 & 6.3.7)\n\nDefinition 6.3.2 (Bayesian game: types) A Bayesian game is a tuple $(N, A, \\Theta, p, u)$ where:\n- $N$ is a set of agents;\n- $A=A_{1} \\times \\cdots \\times A_{n}$, where $A_{i}$ is the set of actions available to player $i$;\n- $\\Theta=\\Theta_{1} \\times \\ldots \\times \\Theta_{n}$, where $\\Theta_{i}$ is the type space of player $i$;\n- $p: \\Theta \\mapsto[0,1]$ is a common prior over types; and\n- $u=\\left(u_{1}, \\ldots, u_{n}\\right)$, where $u_{i}: A \\times \\Theta \\mapsto \\mathbb{R}$ is the utility function for player $i$.\nThe assumption is that all of the above is common knowledge among the players, and that each agent knows his own type. This definition can seem mysterious, because the notion of type can be rather opaque. In general, the type of agent encapsulates all the information possessed by the agent that is not common knowledge. This is often quite simple (e.g., the agent's knowledge of his private payoff function), but can also include his beliefs about other agents' payoffs, about their beliefs about his own payoff, and any other higher-order beliefs.\n\nWe can get further insight into the notion of a type by relating it to the formulation at the beginning of this section. Consider again the Bayesian game in Figure 6.7. For each of the agents we have two types, corresponding to his two information sets. Denote player 1's actions as $\\mathrm{U}$ and D, player 2's actions as $\\mathrm{L}$ and R. Call the types of the first agent $\\theta_{1,1}$ and $\\theta_{1,2}$, and those of the second agent $\\theta_{2,1}$ and $\\theta_{2,2}$. The joint distribution on these types is as follows: $p\\left(\\theta_{1,1}, \\theta_{2,1}\\right)=.3$, $p\\left(\\theta_{1,1}, \\theta_{2,2}\\right)=.1, p\\left(\\theta_{1,2}, \\theta_{2,1}\\right)=.2, p\\left(\\theta_{1,2}, \\theta_{2,2}\\right)=.4$. The conditional probabilities for the first player are $p\\left(\\theta_{2,1} \\mid \\theta_{1,1}\\right)=3 / 4, p\\left(\\theta_{2,2} \\mid \\theta_{1,1}\\right)=1 / 4$, $p\\left(\\theta_{2,1} \\mid \\theta_{1,2}\\right)=1 / 3$, and $p\\left(\\theta_{2,2} \\mid \\theta_{1,2}\\right)=2 / 3$.\n\n\n\nDefinition 6.3.7 (Bayes-Nash equilibrium) A Bayes-Nash equilibrium is a mixedstrategy profile s that satisfies $\\forall i \\quad s_{i} \\in B R_{i}\\left(s_{-i}\\right)$.\n\nThis is exactly the definition we gave for the Nash equilibrium in Definition 3.3.4: each agent plays a best response to the strategies of the other players. The difference from Nash equilibrium, of course, is that the definition of Bayes-Nash equilibrium is built on top of the Bayesian game definitions of best response and expected utility. Observe that we would not be able to define equilibrium in this way if an agent's strategies were not defined for every possible type. In order for a given agent $i$ to play a best response to the other agents $-i, i$ must know what strategy each agent would play for each of his possible types. Without this information, it would be impossible to evaluate the term $E U_{i}\\left(s_{i}^{\\prime}, s_{-i}\\right)$ in Equation (6.7).\n\n## 4. Extensive Form Game\n\n### 4.1. How to define extensive form game? Find answers in “A Course in Game Theory by Prof. Ariel Rubinstein and M. Osborne. ([Download](https://arielrubinstein.tau.ac.il/books.html)) \n\nRefer to Textbook: [Osborne, Martin J. and Ariel Rubinstein](https://arielrubinstein.tau.ac.il/books.html). 1994. A Course in Game Theory. (Chapter 6, Page 89, DEFINITION 6.1.1)\n\nAn extensive game is a detailed description of the sequential structure of the decision problems encountered by the players in a strategic situation.\n\n### 4.2. How to define extensive form game? Find answers in “Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations” by Prof. Yoav Shoham and Kevin Leyton-Brown. ([Download](http://www.masfoundations.org/download.html))\n\nRefer to Textbook: [Noam and Nisan.](https://www.cs.cmu.edu/~sandholm/cs15-892F13/algorithmic-game-theory.pdf) 2007. Algorithmic Game Theory. (Page 53)\n\nExtensive games are game trees, with information sets that model imperfect information of the players.\n\n## 5. Subgame Perfect Nash Equilibrium\n\n### 5.1 How to define Subgame Perfect Nash Equilibrium (SPNE)? Find answers in “A Course in Game Theory by Prof. Ariel Rubinstein and M. Osborne. ([Download](https://arielrubinstein.tau.ac.il/books.html)) \n\nRefer to Textbook: [Osborne, Martin J. and Ariel Rubinstein](https://arielrubinstein.tau.ac.il/books.html). 1994. A Course in Game Theory. (Chapter 6, Page 97, DEFINITION 97.2)\n\nA subgame perfect equilibrium of an extensive game with perfect information $\\Gamma=\\left\\langle N, H, P,\\left(\\succsim_{i}\\right)\\right\\rangle$ is a strategy profile $s^{*}$ such that for every player $i \\in N$ and every nonterminal history $h \\in H \\backslash Z$ for which $P(h)=i$ we have\n$$\n\\left.O_{h}\\left(\\left.s_{-i}^{*}\\right|_{h},\\left.s_{i}^{*}\\right|_{h}\\right) \\succsim_{i}\\right|_{h} O_{h}\\left(\\left.s_{-i}^{*}\\right|_{h}, s_{i}\\right)\n$$\nfor every strategy $s_{i}$ of player $i$ in the subgame $\\Gamma(h)$.\nEquivalently, we can define a subgame perfect equilibrium to be a strategy profile $s^{*}$ in $\\Gamma$ for which for any history $h$ the strategy profile $\\left.s^{*}\\right|_{h}$ is a Nash equilibrium of the subgame $\\Gamma(h)$.\n\nThe notion of subgame perfect equilibrium eliminates Nash equilibria in which the players' threats are not credible. For example, in the game in Figure $96.2$ the only subgame perfect equilibrium is $(A, R)$ and in the game in Figure $91.1$ the only subgame perfect equilibria are $((2,0), y y y)$ and $((1,1)$, nyy $)$.\n\n\n### 5.2 How to define Subgame Perfect Nash Equilibrium (SPNE)? Find answers in “Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations” by Prof. Yoav Shoham and Kevin Leyton-Brown. ([Download](http://www.masfoundations.org/download.html))\n\nRefer to Textbook: [Shoham, Yoav, and Kevin Leyton-Brown](http://www.masfoundations.org/download.html). 2008. Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations. Cambridge: Cambridge University Press. (Chapter 5, Page 123, Definition 5.1.5)\n\nDefinition 5.1.5 (Subgame-perfect equilibrium) The subgame-perfect equilibria $(S P E)$ of a game $G$ are all strategy profiles s such that for any subgame $G^{\\prime}$ of $G$, the restriction of s to $G^{\\prime}$ is a Nash equilibrium of $G^{\\prime}$.\n\n\n## 6. Perfect Bayesian Equilibrium\n\n### 6.1 How to define Perfect Bayesian Equilibrium (PBE)? Find answers in “A Course in Game Theory by Prof. Ariel Rubinstein and M. Osborne. ([Download](https://arielrubinstein.tau.ac.il/books.html)) \n\nRefer to Textbook: [Osborne, Martin J. and Ariel Rubinstein](https://arielrubinstein.tau.ac.il/books.html). 1994. A Course in Game Theory. (Chapter 12, Page 232-233, DEFINITION 232.1)\n\nLet $\\left\\langle\\Gamma,\\left(\\Theta_{i}\\right),\\left(p_{i}\\right),\\left(u_{i}\\right)\\right\\rangle$ be a Bayesian extensive game with observable actions, where $\\Gamma=\\langle N, H, P\\rangle$. A pair $\\left(\\left(\\sigma_{i}\\right),\\left(\\mu_{i}\\right)\\right)=$ $\\left(\\left(\\sigma_{i}\\left(\\theta_{i}\\right)\\right)_{i \\in N, \\theta_{i} \\in \\Theta_{i}},\\left(\\mu_{i}(h)\\right)_{i \\in N, h \\in H \\backslash Z}\\right)$, where $\\sigma_{i}\\left(\\theta_{i}\\right)$ is a behavioral strategy of player $i$ in $\\Gamma$ and $\\mu_{i}(h)$ is a probability measure on $\\Theta_{i}$, is a perfect Bayesian equilibrium of the game if the following conditions are satisfied.\n\n- Sequential rationality: For every nonterminal history $h \\in H \\backslash Z$, every player $i \\in P(h)$, and every $\\theta_{i} \\in \\Theta_{i}$ the probability measure $O\\left(\\sigma_{-i}, \\sigma_{i}\\left(\\theta_{i}\\right), \\mu_{-i} \\mid h\\right)$ is at least good for type $\\theta_{i}$ as $O\\left(\\sigma_{-i}, s_{i}, \\mu_{-i} \\mid h\\right)$ for any strategy $s_{i}$ of player $i$ in $\\Gamma$.\n- Correct initial beliefs: $\\mu_{i}(\\varnothing)=p_{i}$ for each $i \\in N$.\n- Action-determined beliefs: If $i \\notin P(h)$ and $a \\in A(h)$ then $\\mu_{i}(h, a)=$ $\\mu_{i}(h)$; if $i \\in P(h), a \\in A(h), a^{\\prime} \\in A(h)$, and $a_{i}=a_{i}^{\\prime}$ then $\\mu_{i}(h, a)=$ $\\mu_{i}\\left(h, a^{\\prime}\\right)$.\n- Bayesian updating: If $i \\in P(h)$ and $a_{i}$ is in the support of $\\sigma_{i}\\left(\\theta_{i}\\right)(h)$ for some $\\theta_{i}$ in the support of $\\mu_{i}(h)$ then for any $\\theta_{i}^{\\prime} \\in \\Theta_{i}$ we have\n$$\n\\mu_{i}(h, a)\\left(\\theta_{i}^{\\prime}\\right)=\\frac{\\sigma_{i}\\left(\\theta_{i}^{\\prime}\\right)(h)\\left(a_{i}\\right) \\cdot \\mu_{i}(h)\\left(\\theta_{i}^{\\prime}\\right)}{\\sum_{\\theta_{i} \\in \\Theta_{i}} \\sigma_{i}\\left(\\theta_{i}\\right)(h)\\left(a_{i}\\right) \\cdot \\mu_{i}(h)\\left(\\theta_{i}\\right)} .\n$$\n\n### 6.2 How to define Perfect Bayesian Equilibrium (PBE)? Find answers in “Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations” by Prof. Yoav Shoham and Kevin Leyton-Brown. ([Download](http://www.masfoundations.org/download.html))\n\nRefer to Textbook: [Shoham, Yoav, and Kevin Leyton-Brown](http://www.masfoundations.org/download.html). 2008. Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations. Cambridge: Cambridge University Press. (Chapter 5, Page 144, Definition 5.2.10)\n\nDefinition 5.2.10 (Sequential equilibrium) A strategy profile $s$ is a sequential equilibrium of an extensive-form game $G$ if there exist probability distributions $\\mu(h)$ for each information set $h$ in $G$, such that the following two conditions hold:\n1. $(s, \\mu)=\\lim _{m \\rightarrow \\infty}\\left(s^{m}, \\mu^{m}\\right)$ for some sequence $\\left(s^{1}, \\mu^{1}\\right),\\left(s^{2}, \\mu^{2}\\right), \\ldots$, where $s^{m}$ is fully mixed, and $\\mu^{m}$ is consistent with $s^{m}$ (in fact, since $s^{m}$ is fully mixed, $\\mu^{m}$ is uniquely determined by $\\left.s^{m}\\right)$; and\n2. For any information set $h$ belonging to agent $i$, and any alternative strategy $s_{i}^{\\prime}$ of $i$, we have that\n$$\nu_{i}(s \\mid h, \\mu(h)) \\geq u_{i}\\left(\\left(s^{\\prime}, s_{-i}\\right) \\mid h, \\mu(h)\\right)\n$$\nAnalogous to subgame-perfect equilibria in games of perfect information, sequential equilibria are guaranteed to always exist.\n\n# Part II: Computational Issues (1 points)\n\n### Brieftly read Algorithmic Game Theory e-book Chapter 1 and 2. ([URL](https://drive.google.com/file/d/1qbWzkgKbej9KTRcOOK7a57LEU83lRpfY/view?usp=sharing)) Answer the following questions:\n\n\n### RQ1: What is the computational issues of the Nash Equilibrium?\n\n\n1. No Nash equilibria: Even though mixed-strategy Nash equilibrium exists for a game with a finite number of players and a finite number of actions, a game with an infinite number of players, or a game with a finite number of players with an infinite strategy set may not have Nash equilibria[(Noam Nisan 2007, 13)](https://www.cs.cmu.edu/~sandholm/cs15-892F13/algorithmic-game-theory.pdf). This reminds me of the intermediate microeconomic class. When we tried to find the optimal solutions for a given utility function and choice set, even though in most cases they have mathematical optimal solutions, we should be careful about some special cases, such as the boundary solutions. While we are appreciating theoretical models, we should also be cautious about how it interacts with and informs about the real world.\n\n2. Multiple Nash equilibria: Even though in many cases Nash equilibria could be computed, it is not strange that for some games there exist mutiple Nash Equilibria and we cannot explicitly tell which equilibria to be selected. In the case of multiple Nash equilibria, the solutions are less useful and directional in predicting players' decision-making and behaviors. As a result, it is even harder for players to know which equilibrium they are supposed to coordinate on [(Noam Nisan 2007, 12)](https://www.cs.cmu.edu/~sandholm/cs15-892F13/algorithmic-game-theory.pdf). This also reminds me of the models in intermediate microeconomic class. When either the choice set or the utility function is not convex, there might exist mutiple solutions and we have to look at them case by case.\n\n### RQ2: What is the complexity of finding Nash Equilibrium?\n\nIn the case of a two-player game, applying the Lemke–Howson algorithm, we are able to compute a Nash Equilibrium in exponential time at worst. NP completeness, the “standard” way of establishing intractability of individual problems, is not appropriate because Nash (1951) proved that Nash equilibria always exist. The problem of finding a Nash equilibrium is PPAD-complete even for two-player games in standard form[(Noam Nisan 2007, 16)](https://www.cs.cmu.edu/~sandholm/cs15-892F13/algorithmic-game-theory.pdf). The correlated equilibrium is a computationally benign generalization of the intractable Nash equilibrium. We can find in polynomial time a correlated equilibrium for any game by linear programming techniques [(Noam Nisan 2007, 47)](https://www.cs.cmu.edu/~sandholm/cs15-892F13/algorithmic-game-theory.pdf).\n\n* [NP completeness](https://www.britannica.com/science/NP-complete-problem)\n> A problem is called NP (nondeterministic polynomial) if its solution can be guessed and verified in polynomial time; nondeterministic means that no particular rule is followed to make the guess. If a problem is NP and all other NP problems are polynomial-time reducible to it, the problem is NP-complete.\n\n* [PPAD](https://en.wikipedia.org/wiki/PPAD_(complexity))\n>In computer science, PPAD (\"Polynomial Parity Arguments on Directed graphs\") is a complexity class introduced by Christos Papadimitriou in 1994.\n\n# Part III: Case Studies (8 points)\n\n## 1.NashPy\n\n### 1.1. What types of games and solution concepts can NashPy deal with?\n\nNashpy is a python library for the computation of equilibria of 2 player strategic games.\n\n[(Knight 2021)](https://github.com/drvinceknight/Nashpy)\n\n### 1.2. Apply NashPy to solve a solution concept on a specific game (your own choices) different from the case studies in the OER\n\nRock Paper Scissors is a hand game originating from China, usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. \n\nA simultaneous, zero-sum game, it has three possible outcomes: a draw, a win or a loss. A player who decides to play rock will beat another player who has chosen scissors (\"rock crushes scissors\" or \"breaks scissors\" or sometimes \"blunts scissors\"), but will lose to one who has played paper (\"paper covers rock\"); a play of paper will lose to a play of scissors (\"scissors cuts paper\"). If both players choose the same shape, the game is tied and is usually immediately replayed to break the tie. The type of game originated in China and spread with increased contact with East Asia, while developing different variants in signs over time.\n\n[(“Rock Paper Scissors” 2020)](https://en.wikipedia.org/wiki/Rock_paper_scissors)\n\n\n```python\n# install the tools you will use later\n!pip install --upgrade setuptools\n!pip install --upgrade pip\n!pip install quantecon\n```\n\n Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (62.1.0)\n \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n \u001b[0mRequirement already satisfied: pip in /usr/local/lib/python3.7/dist-packages (22.0.4)\n \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n \u001b[0mRequirement already satisfied: quantecon in /usr/local/lib/python3.7/dist-packages (0.5.3)\n Requirement already satisfied: scipy>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from quantecon) (1.4.1)\n Requirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from quantecon) (0.51.2)\n Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from quantecon) (1.7.1)\n Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from quantecon) (1.21.5)\n Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from quantecon) (2.23.0)\n Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba->quantecon) (62.1.0)\n Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->quantecon) (0.34.0)\n Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->quantecon) (2021.10.8)\n Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->quantecon) (3.0.4)\n Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->quantecon) (1.24.3)\n Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->quantecon) (2.10)\n Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->quantecon) (1.2.1)\n \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n \u001b[0m\n\n\n```python\n!which python\n```\n\n /usr/local/bin/python\n\n\n\n```python\n!pip3 install nashpy --use-deprecated=backtrack-on-build-failures\n```\n\n \u001b[33mDEPRECATION: Backtracking on build failures can mask issues related to how a package generates metadata or builds a wheel. This flag will be removed in pip 22.2. A possible replacement is avoiding known-bad versions by explicitly telling pip to ignore them (either directly as requirements, or via a constraints file). Discussion can be found at https://github.com/pypa/pip/issues/10655\u001b[0m\u001b[33m\n \u001b[0mCollecting nashpy\n Using cached nashpy-0.0.22.tar.gz (11 kB)\n \u001b[1;31merror\u001b[0m: \u001b[1msubprocess-exited-with-error\u001b[0m\n \n \u001b[31m×\u001b[0m \u001b[32mpython setup.py egg_info\u001b[0m did not run successfully.\n \u001b[31m│\u001b[0m exit code: \u001b[1;36m1\u001b[0m\n \u001b[31m╰─>\u001b[0m See above for output.\n \n \u001b[1;35mnote\u001b[0m: This error originates from a subprocess, and is likely not a problem with pip.\n Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25herror\n \u001b[33mWARNING: Discarding https://files.pythonhosted.org/packages/93/1c/9005c6a0a3a3b183b5b216cc02cef14bb080fd3ee8733a1006fbcd81fffc/nashpy-0.0.22.tar.gz#sha256=9378fd492f01163ac01a7384dd94f7ffa3ce40e31fe2a08844a2e34576b3d8db (from https://pypi.org/simple/nashpy/) due to build failure: metadata generation failed\u001b[0m\u001b[33m\n \u001b[0m Downloading nashpy-0.0.21.tar.gz (11 kB)\n Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n Requirement already satisfied: numpy>=1.12.1 in /usr/local/lib/python3.7/dist-packages (from nashpy) (1.21.5)\n Requirement already satisfied: scipy>=0.19.0 in /usr/local/lib/python3.7/dist-packages (from nashpy) (1.4.1)\n Building wheels for collected packages: nashpy\n Building wheel for nashpy (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for nashpy: filename=nashpy-0.0.21-py3-none-any.whl size=15279 sha256=d6a0755aa742f535a94d26247d80a704995b49b6d60c73263a5ffc51c4fa3cb7\n Stored in directory: /root/.cache/pip/wheels/02/08/62/cf4fa931e0a317d180936b266169a57f4bb4eb801465bbe8a1\n Successfully built nashpy\n Installing collected packages: nashpy\n Successfully installed nashpy-0.0.21\n \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n \u001b[0m\n\n\n```python\nimport nashpy as nash\nimport numpy as np\n\n# Creater the game with the payoff matrix\n\nA = np.array([[0, 0, 1],\n [1, 0, 0],\n [0, 1, 0]]) # A is the row player (in this case, prisoner)\n\nB = np.array([[0, 1, 0],\n [0, 0, 1],\n [1, 0, 0]]) # B is the column player\n```\n\n\n```python\n# Form the game\ngame2 = nash.Game(A,B)\ngame2\n```\n\n\n\n\n Bi matrix game with payoff matrices:\n \n Row player:\n [[0 0 1]\n [1 0 0]\n [0 1 0]]\n \n Column player:\n [[0 1 0]\n [0 0 1]\n [1 0 0]]\n\n\n\n\n```python\n# Find the Nash Equilibrium with Support Enumeration\nequilibria = game2.support_enumeration()\nfor eq in equilibria:\n print(eq)\n```\n\n (array([0.33333333, 0.33333333, 0.33333333]), array([0.33333333, 0.33333333, 0.33333333]))\n\n\nThe results are consistent with the facts and are explainable. This game has a mixed Nash equilibrium. In this equilibium, both players play the mixed strategy that puts equal probabilities on all three actions. In short words, they play rock, paper, or scissors with the equal frequency (probability).\n\n## 2. QuantEcon\n\n### 2.1. What types of games and soution concepts can QuantEcon deal with?\n\nQuantEcon is the open source code for economic modeling. It can deal with normal form game with more than 2 players and solve for the Nash Equilibrium. \nThere are several algorithms implemented to compute Nash equilibria:\n\n* Brute force\n> Find all pure-action Nash equilibria of an N-player game (if any).\n* Sequential best response\n> Find one pure-action Nash equilibrium of an N-player game (if any).\n* Support enumeration\n> Find all mixed-action Nash equilibria of a two-player nondegenerate game.\n* Vertex enumeration\n> Find all mixed-action Nash equilibria of a two-player nondegenerate game.\n* Lemke-Howson\n> Find one mixed-action Nash equilibrium of a two-player game.\n* McLennan-Tourky\n> Find one mixed-action Nash equilibrium of an N-player game.\n\nQuantEcon is also developing Julia code that implements an algorithm for computing equilibrium values (e.g. subgame perfect equilibria) and associated equilibrium strategy profiles for repeated games with N players and finite actions.\n\n[(Sargent and Stachurski 2021)](https://quantecon.org/notebooks/)\n\n### 2.2. Apply QuantEcon to solve a solution concept on a specific game (your own choices) different from the case studies in the OER\n\nRock Paper Scissors is a hand game originating from China, usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. \n\nA simultaneous, zero-sum game, it has three possible outcomes: a draw, a win or a loss. A player who decides to play rock will beat another player who has chosen scissors (\"rock crushes scissors\" or \"breaks scissors\" or sometimes \"blunts scissors\"), but will lose to one who has played paper (\"paper covers rock\"); a play of paper will lose to a play of scissors (\"scissors cuts paper\"). If both players choose the same shape, the game is tied and is usually immediately replayed to break the tie. The type of game originated in China and spread with increased contact with East Asia, while developing different variants in signs over time.\n\n[(“Rock Paper Scissors” 2020)](https://en.wikipedia.org/wiki/Rock_paper_scissors)\n\n\n```python\n# import the QuantEcon package\nimport quantecon.game_theory as gt\nimport numpy as np\n\n# The first way to form the game: by the payoff matrix\nprisoner_dilemma_matrix = np.array([[[0, 0], [0, 1], [1, 0]],\n [[1, 0], [0, 0], [0, 1]],\n [[0, 1], [1, 0], [0, 0]]])\n\ng_PD = gt.NormalFormGame(prisoner_dilemma_matrix)\nprint(g_PD)\n```\n\n\n```python\n# Finding the Nash equilibrium: pure_nash_brute\n\nNE = gt.pure_nash_brute(g_PD)\nprint(NE)\n```\n\n\n```python\n# Finding the Nash equilibrium: support_enumeration\n\nNE = gt.support_enumeration(g_PD)\nprint(NE)\n```\n\n\n```python\nNE = gt.vertex_enumeration(g_PD)\nprint(NE)\n```\n\nThe results are consistent with the facts and are explainable. The game of Rock-Paper-Scissors doesn't have pure Nash equilibrium. Imagine you are playing rock all the time, once the other player figures out your strategy and he/she can win by always playing paper. However, this game has a unique mixed Nash equilibrium. In this equilibium, both players play the mixed strategy that puts equal probabilities on all three actions. In short words, they play rock, paper, or scissors with the equal frequency (probability).\n\n## 3. Game Theory Explorer\n\n### 3.1. What types of games and soution concepts can Game Theory Explorer deal with?\n\nGame theory explorer is a web interface to gambit useful for teaching. An extensive or strategic-form game can be created and nicely displayed with a graphical user interface in a web browser. State-of-the-art algorithms then compute one or all Nash equilibria of the game.\n\n[(Savani and von Stengel 2014)](https://gte.csc.liv.ac.uk/index/)\n\n### 3.2. Apply Game Theory Explorer to solve a solution concept on a specific game (your own choices) different from the case studies in the OER\n\nRock Paper Scissors is a hand game originating from China, usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. \n\nA simultaneous, zero-sum game, it has three possible outcomes: a draw, a win or a loss. A player who decides to play rock will beat another player who has chosen scissors (\"rock crushes scissors\" or \"breaks scissors\" or sometimes \"blunts scissors\"), but will lose to one who has played paper (\"paper covers rock\"); a play of paper will lose to a play of scissors (\"scissors cuts paper\"). If both players choose the same shape, the game is tied and is usually immediately replayed to break the tie. The type of game originated in China and spread with increased contact with East Asia, while developing different variants in signs over time.\n\n[(“Rock Paper Scissors” 2020)](https://en.wikipedia.org/wiki/Rock_paper_scissors)\n\n(1) General Matrix\n\n\n\n(2) Strategic Form\n\n\n\n(3)Extensive Form\n\n\n\nThe results are consistent with the facts and are explainable. The game of Rock-Paper-Scissors doesn't have pure Nash equilibrium. Imagine you are playing rock all the time, once the other player figures out your strategy and he/she can win by always playing paper. However, this game has a unique mixed Nash equilibrium. In this equilibium, both players play the mixed strategy that puts equal probabilities on all three actions. In short words, they play rock, paper, or scissors with the equal frequency (probability).\n\n## 4. Gambit\n\n### 4.1. What types of games and solution concepts can Gambit deal with?\n\nGambit is a library of game theory software and tools for the construction and analysis of finite extensive and strategic noncooperative games. Gambit supports building game trees, finding all equilibria of a two-player game, computing equilibria in games with three or more players, and doing statistical game theory. It is more powerful and includes more various games than QuantEcon.\n\n[(McKelvey, McLennan, and Turocy 2016)]( http://www.gambit-project.org)\n\n\n\n### 4.2. Apply Gambit to solve a solution concept on a specific game (your own choices) different from the case studies in the OER\n\n**Poker Game - Description**\n\nThe game begins with each player being dealt two cards which are hidden from the other player.\nA round of betting takes place, where there are four actions available to the players: check, bet, call, raise. A player can check or bet if no amount has yet been made in the current round of betting and a player can call (match the amount bet by the opponent) or raise (bet an additional amount on top of opponent’s bet) if the opponent bets. After the initial round of betting (pre-flop), the first three community cards (visible to both players) come out (flop). Another round of betting proceeds before the fourth card comes out and likewise before the fifth and final card. After all cards are out, there is one last round of betting before the players’ hands are compared (showdown). The complexity of poker arises from inferring probabilities through the many rounds of betting and making decisions that consider events in the future.\n\n[(Li 2018)](https://math.mit.edu/~apost/courses/18.204_2018/Jingyu_Li_paper.pdf)\n\n\n\nGambit can show various games in several forms, including the graphical form. The poker game's rule is not that complex, but with the help of Gambit, it is easier and clearer to analyze the decision tree and unfold the strategies. Besides, Gambit users can change the color to adjust the plot accordingly.\n\n# 5. Mesa [optional]\n\n## 5.1. What types of games and solution concepts can Mesa deal with?\n\nIt allows users to quickly create agent-based models using built-in core components (such as spatial grids and agent schedulers) or customized implementations; visualize them using a browser-based interface; and analyze their results using Python’s data analysis tools.\nAgent-based models are computer simulations involving multiple entities (the agents) acting and interacting with one another based on their programmed behavior. Agents can be used to represent living cells, animals, individual humans, even entire organizations or abstract entities. Sometimes, we may have an understanding of how the individual components of a system behave, and want to see what system-level behaviors and effects emerge from their interaction. Other times, we may have a good idea of how the system overall behaves, and want to figure out what individual behaviors explain it. Or we may want to see how to get agents to cooperate or compete most effectively. Or we may just want to build a cool toy with colorful little dots moving around. \n\n[(Thomson 2020)](https://mesa.readthedocs.io/en/latest/index.html)\n\n# References\n\nNoam Nisan. 2007. Algorithmic Game Theory. Cambridge ; New York: Cambridge University Press.\n\nOsborne, Martin J, and Ariel Rubinstein. 1994. A Course in Game Theory. Cambridge, Mass.: Mit Press.\n\nYoav Shoham, and Kevin Leyton-Brown. 2009. Multiagent Systems : Algorithmic, Game-Theoretic, and Logical Foundations. Cambridge ; New York: Cambridge University Press.\n\nKazil, Jackie, Masad, David, Crooks, and Andrew. 2013. “Mesa: Agent-Based Modeling in Python 3+.” GitHub. 2013. https://github.com/projectmesa/mesa.Knight.\n\nVincent. 2021. “Nashpy: A Python Library for the Computation of Equilibria of 2 Player Strategic Games, Version 0.0.28.” GitHub. May 4, 2021. https://github.com/drvinceknight/Nashpy.McKelvey.\n\nRichard, Andrew McLennan, and Theodore Turocy. n.d. “Gambit: Software Tools for Game Theory, Version 16.0.1.” Www.gambit-Project.org. http://www.gambit-project.org/.Sargent.\n\nThomas, and John Stachurski. 2021. “Quantitative Economics (Python), Version 0.5.1.” QuantEcon. 2021. https://quantecon.org/quantecon-py/.Savani.\n\nRahul, and Bernhard von Stengel. 2014. “Game Theory Explorer: Software for the Applied Game Theorist.” Computational Management Science 12 (1): 5–33. https://doi.org/10.1007/s10287-014-0206-x.\n\nLi, Jingyu. 2018. “Exploitability and Game Theory Optimal Play in Poker.” Boletín de Matemáticas 0 (0): 1. https://math.mit.edu/~apost/courses/18.204_2018/\n\nJingyu_Li_paper.pdf.“Rock Paper Scissors.” 2020. Wikipedia. August 21, 2020. https://en.wikipedia.org/wiki/Rock_paper_scissors.\n\n\n```python\n\n```\n", "meta": {"hexsha": "c4951569b1bd65609257f4f626b8345a76b8516a", "size": 520082, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ray_CS_Econ_206_Computational_Microeconomics_[Code_Assignment_2].ipynb", "max_stars_repo_name": "Ray88888888/CS-ECON-206", "max_stars_repo_head_hexsha": "73f47a939c0372b3ff9754da471456b4b6194077", "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": "Ray_CS_Econ_206_Computational_Microeconomics_[Code_Assignment_2].ipynb", "max_issues_repo_name": "Ray88888888/CS-ECON-206", "max_issues_repo_head_hexsha": "73f47a939c0372b3ff9754da471456b4b6194077", "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": "Ray_CS_Econ_206_Computational_Microeconomics_[Code_Assignment_2].ipynb", "max_forks_repo_name": "Ray88888888/CS-ECON-206", "max_forks_repo_head_hexsha": "73f47a939c0372b3ff9754da471456b4b6194077", "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": 431.9617940199, "max_line_length": 201746, "alphanum_fraction": 0.9267211709, "converted": true, "num_tokens": 11002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.1847675061589216, "lm_q1q2_score": 0.07595993006285422}} {"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\n\nToggle cell visibility here.\n\n\n## Costruire un osservatore per il sistema massa-molla-smorzatore\n\nQuesto esempio mostra come sviluppare un osservatore per il sistema massa-molla-smorzatore. Le equazioni scritte in forma di stato (vedi l'esempio [Analisi modale del sistema Massa-Molla-Smorzatore](SS-08-Analisi_modale_Massa-Molla-Smorzatore.ipynb) per maggiori dettagli) sono:\n\n\\begin{cases}\n\\begin{bmatrix}\n\\dot{x_1} \\\\\n\\dot{x_2}\n\\end{bmatrix}=\\underbrace{\\begin{bmatrix}\n0 && 1 \\\\\n-\\frac{k}{m} && -\\frac{c}{m}\n\\end{bmatrix}}_{A}\\begin{bmatrix}\nx_1 \\\\\nx_2\n\\end{bmatrix}+\\underbrace{\\begin{bmatrix}\n0 \\\\\n\\frac{1}{m}\n\\end{bmatrix}}_{B}u \\\\\ny = \\underbrace{\\begin{bmatrix}1&0\\end{bmatrix}}_{C}\\begin{bmatrix}\nx_1 \\\\\nx_2\n\\end{bmatrix}\n\\end{cases}\ncon $m=1\\,$kg, $k=2\\,$N/m e $c=1\\,$Ns/m. Gli autovalori corrispondenti sono $\\lambda_{1,2} = -\\frac{c}{2m} \\pm \\frac{\\sqrt{c^2 - 4km}}{2m} = -\\frac{1}{2} \\pm i\\frac{\\sqrt{7}}{2}$.\n\nLa matrice di osservabilità ha rango pieno ed è uguale a:\n$$\n\\begin{bmatrix}C\\\\CA\\end{bmatrix} = \\begin{bmatrix}1&0\\\\0&1\\end{bmatrix},\n$$\nquindi il sistema è osservabile ed è possibile sviluppare un osservatore dello stato. Per avere una convergenza della stima in un tempo ragionevole, è conveniente impostare la dinamica dell'errore in modo che sia più rapida, o almeno 10 volte, rispetto alla dinamica del sistema. Gli autovalori scelti sono $\\lambda_{\\text{err} 1,2}=-10\\sqrt{\\left(\\frac{1}{2}\\right)^2+\\left(\\frac{\\sqrt{7}}{2}\\right)^2}=-10\\sqrt{2}$.\n\nLa struttura dell'osservatore è:\n\n$$\n\\dot{\\hat{\\textbf{x}}}=A\\hat{\\textbf{x}}+B\\textbf{u}+L\\textbf{y},\n$$\n\ncon la matrice $L$ definita come $L = \\begin{bmatrix}l_1&l_2\\end{bmatrix}^T$. I valori necessari per avere la giusta convergenza (di $\\dot{\\textbf{e}}=(A-LC)\\textbf{e}$) sono quindi:\n\n\\begin{cases}\nl_1 = -c/m + 20\\sqrt{2} = -1+20\\sqrt{2}\\\\\nl_2 = \\frac{c^2}{m^2} - 20\\sqrt{2}\\frac{c}{m} - \\frac{k}{m} + 200 = 197-20\\sqrt{2}\n\\end{cases}\n\nottenuti imponendo $\\text{det}(\\lambda I_{2\\text{x}2}-A+LC) = \\left(\\lambda+10\\sqrt{2}\\right)^2$.\n\n### Come utilizzare questo notebook?\nL'osservatore sviluppato è simulato di seguito e l'interfaccia interattiva consente di modificare tutti i valori e visualizzare i relativi cambiamenti nel comportamento.\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 1; -2 -1')\nB = numpy.matrix('0; 1')\nC = numpy.matrix('1 0')\nX0 = numpy.matrix('2; 2')\nL = numpy.matrix([[-1+20*numpy.sqrt(2)],[197-20*numpy.sqrt(2)]])\nsol1 = numpy.linalg.eig(A)\n\nAw = matrixWidget(2,2)\nAw.setM(A)\nBw = matrixWidget(2,1)\nBw.setM(B)\nCw = matrixWidget(1,2)\nCw.setM(C)\nX0w = matrixWidget(2,1)\nX0w.setM(X0)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-10*numpy.sqrt(2)])) \neig2o.setM(numpy.matrix([[-10*numpy.sqrt(2)],[0]]))\n```\n\n\n```python\n# Interactive widgets\n\nm = widgets.FloatSlider(\n value=1,\n min=0.1,\n max=10.0,\n step=0.1,\n description='m [kg]:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.1f',\n)\nk = widgets.FloatSlider(\n value=2,\n min=0,\n max=10.0,\n step=0.1,\n description='k [N/m]:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.1f',\n)\nc = widgets.FloatSlider(\n value=1,\n min=0,\n max=10.0,\n step=0.1,\n description='c [Ns/m]:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.1f',\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='input u:',\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.0,\n max=1,\n step=0.05,\n description='Periodo: ',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.2f',\n)\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= [('Imposta L','Set L'), ('Imposta gli autovalori','Set the eigenvalues')],\n value= 'Set L',\n description='',\n disabled=False\n)\n\n# Define the number of complex eigenvalues for the observer\nselo = widgets.Dropdown(\n options= [('0 autovalori complessi','0 complex eigenvalues'), ('2 autovalori complessi','2 complex eigenvalues')],\n value= '0 complex eigenvalues',\n description='Autovalori:',\n disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n options=[('impulso','impulse'), ('gradino','step'), ('sinusoide','sinusoid'), ('onda quadra','square wave')],\n value='impulse',\n description='Input:',\n disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(selo):\n if selo == '0 complex eigenvalues':\n eig1o.children[0].children[0].disabled = False\n eig2o.children[1].children[0].disabled = True\n eigo = 0\n if selo == '2 complex eigenvalues':\n eig1o.children[0].children[0].disabled = True\n eig2o.children[1].children[0].disabled = False\n eigo = 2\n return eigo\n\ndef method_choice(selm):\n if selm == 'Set L':\n method = 1\n selo.disabled = True\n if selm == 'Set the eigenvalues':\n method = 2\n selo.disabled = False\n return method\n```\n\n\n```python\ndef main_callback(m, k, c, X0w, L, eig1o, eig2o, u, period, selm, selo, selu, DW):\n A = numpy.matrix([[0,1],[-k/m,-c/m]])\n eigo = eigen_choice(selo)\n method = method_choice(selm)\n \n if method == 1:\n sol = numpy.linalg.eig(A-L*C)\n if method == 2:\n if eigo == 0:\n L = control.acker(A.T, C.T, [eig1o[0,0], eig2o[0,0]]).T\n Lw.setM(L) \n if eigo == 2:\n L = control.acker(A.T, C.T, [numpy.complex(eig2o[0,0],eig2o[1,0]), \n numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n Lw.setM(L)\n sol = numpy.linalg.eig(A-L*C)\n print('Gli autovalori del sistema sono:',round(sol1[0][0],4),'e',round(sol1[0][1],4)) \n print('Gli autovalori dell\\'osservatore sono:',round(sol[0][0],4),'e',round(sol[0][1],4))\n \n sys = sss(A,B,C,0)\n syso = sss(A-L*C, numpy.concatenate((B,L),axis=1), numpy.eye(2), numpy.zeros(4).reshape((2,2)))\n T = numpy.linspace(0, 6, 1000)\n \n if selu == 'impulse': #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 T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0]])\n if selu == 'step':\n U = [u for t in range(0,len(T))]\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0]])\n if selu == 'sinusoid':\n U = u*numpy.sin(2*numpy.pi/period*T)\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0]])\n if selu == 'square wave':\n U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0]])\n \n fig = plt.figure(num='Simulation', figsize=(16,10))\n \n fig.add_subplot(211)\n plt.ylabel('Posizione vs Posizione stimata (uscita del sistema)')\n plt.plot(T,xout[0])\n plt.plot(T,xouto[0])\n plt.xlabel('t [s]')\n plt.legend(['Reale','Stimata'])\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 plt.ylabel('Velocità vs Velocità stimata')\n plt.plot(T,xout[1])\n plt.plot(T,xouto[1])\n plt.xlabel('t [s]')\n plt.legend(['Reale','Stimata'])\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([m, \n k, \n c]),\n widgets.HBox([selm, \n selo, \n selu]),\n widgets.Label(' ',border=3),\n widgets.HBox([widgets.Label('L:',border=3), Lw, \n widgets.Label(' ',border=3),\n widgets.Label(' ',border=3),\n widgets.Label('Autovalori:',border=3), \n eig1o, \n eig2o,\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])])\nout = widgets.interactive_output(main_callback, {'m':m, 'k':k, 'c':c, 'X0w':X0w, 'L':Lw, 'eig1o':eig1o, 'eig2o':eig2o, \n 'u':u, 'period':period, 'selm':selm, 'selo':selo, '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=(FloatSlider(value=1.0, continuous_update=False, description='m [kg]:', max=10.0,…\n\n", "meta": {"hexsha": "d262213c3d64af477e9b433ae0831107395957f1", "size": 21005, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/04/SS-28-Osservatore_per_il_sistema_Massa-Molla-Smorzatore.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_it/examples/04/SS-28-Osservatore_per_il_sistema_Massa-Molla-Smorzatore.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_it/examples/04/SS-28-Osservatore_per_il_sistema_Massa-Molla-Smorzatore.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": 37.3754448399, "max_line_length": 437, "alphanum_fraction": 0.4822661271, "converted": true, "num_tokens": 4250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.22000709974589316, "lm_q1q2_score": 0.07592560977046213}} {"text": "# Experimental design and pattern estimation\nThis week's lab will be about the basics of pattern analysis of (f)MRI data. We assume that you've worked through the two Nilearn tutorials already. \n\nFunctional MRI data are most often stored as 4D data, with 3 spatial dimensions ($X$, $Y$, and $Z$) and 1 temporal dimension ($T$). But most pattern analyses assume that data are formatted in 2D: trials ($N$) by patterns (often a subset of $X$, $Y$, and $Z$). Where did the time dimension ($T$) go? And how do we \"extract\" the patterns of the $N$ trials? In this lab, we'll take a look at various methods to estimate patterns from fMRI time series. Because these methods often depend on your experimental design (and your research question, of course), the first part of this lab will discuss some experimental design considerations. After this more theoretical part, we'll dive into how to estimate patterns from fMRI data.\n\n**What you'll learn**: At the end of this tutorial, you ...\n\n* Understand the most important experimental design factors for pattern analyses;\n* Understand and are able to implement different pattern estimation techniques\n\n**Estimated time needed to complete**: 8-12 hours\n\n\n```python\n# We need to limit the amount of threads numpy can use, otherwise\n# it tends to hog all the CPUs available when using Nilearn\nimport os\nos.environ['MKL_NUM_THREADS'] = '1'\nos.environ['OPENBLAS_NUM_THREADS'] = '1'\nimport numpy as np\n```\n\n## Experimental design\nBefore you can do any fancy machine learning or representational similarity analysis (or any other pattern analysis), there are several decisions you need to make and steps to take in terms of study design, (pre)processing, and structuring your data. Roughly, there are three steps to take:\n\n1. Design your study in a way that's appropriate to answer your question through a pattern analysis; this, of course, needs to be done *before* data acquisition!\n2. Estimate/extract your patterns from the (functional) MRI data;\n3. Structure and preprocess your data appropriately for pattern analyses;\n\nWhile we won't go into all the design factors that make for an *efficient* pattern analysis (see [this article](http://www.sciencedirect.com/science/article/pii/S105381191400768X) for a good review), we will now discuss/demonstrate some design considerations and how they impact the rest of the MVPA pipeline.\n\n### Within-subject vs. between-subject analyses\nAs always, your experimental design depends on your specific research question. If, for example, you're trying to predict schizophrenia patients from healthy controls based on structural MRI, your experimental design is going to be different than when you, for example, are comparing fMRI activity patterns in the amygdala between trials targeted to induce different emotions. Crucially, with *design* we mean the factors that you as a researcher control: e.g., which schizophrenia patients and healthy control to scan in the former example and which emotion trials to present at what time. These two examples indicate that experimental design considerations are quite different when you are trying to model a factor that varies *between subjects* (the schizophrenia vs. healthy control example) versus a factor that varies *within subjects* (the emotion trials example).\n\n
\nToDo/ToThink (1.5 points): before continuing, let's practice a bit. For the three articles below, determine whether they used a within-subject or between-subject design.
\n\n
    \n
  1. https://www.nature.com/articles/nn1444 (machine learning based)
  2. \n
  3. http://www.jneurosci.org/content/33/47/18597.short (RSA based)
  4. \n
  5. https://www.sciencedirect.com/science/article/pii/S1053811913000074 (machine learning based)
  6. \n
\n\nAssign either 'within' or 'between' to the variables corresponding to the studies above (i.e., study_1, study_2, study_3).\n\n
\n\n\n```python\n''' Implement the ToDo here. '''\nstudy_1 = '' # fill in 'within' or 'between'\nstudy_2 = '' # fill in 'within' or 'between'\nstudy_3 = '' # fill in 'within' or 'between'\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. ''' \nfor this_study in [study_1, study_2, study_3]:\n if not this_study: # if empty string\n raise ValueError(\"You haven't filled in anything!\")\n else:\n if this_study not in ['within', 'between']:\n raise ValueError(\"Fill in either 'within' or 'between'!\")\n \nprint(\"Your answer will be graded by hidden tests.\")\n```\n\nNote that, while we think it is a useful way to think about different types of studies, it is possible to use \"hybrid\" designs and analyses. For example, you could compare patterns from a particular condition (within-subject) across different participants (between-subject). This is, to our knowledge, not very common though, so we won't discuss it here.\n\n
\nToThink (1 point)
\nSuppose a researcher wants to implement a decoding analysis in which he/she aims to predict schizophrenia (vs. healthy control) from gray-matter density patterns in the orbitofrontal cortex. Is this an example of a within-subject or between-subject pattern analysis? Can it be either one? Why (not)? \n
\n\nYOUR ANSWER HERE\n\nThat said, let's talk about something that is not only important for univariate MRI analyses, but also for pattern-based multivariate MRI analyses: confounds.\n\n### Confounds\nFor most task-based MRI analyses, we try to relate features from our experiment (stimuli, responses, participant characteristics; let's call these $\\mathbf{S}$) to brain features (this is not restricted to \"activity patterns\"; let's call these $\\mathbf{R}$\\*). Ideally, we have designed our experiment that any association between our experimental factor of interest ($\\mathbf{S}$) and brain data ($\\mathbf{R}$) can *only* be due to our experimental factor, not something else. \n\nIf another factor besides our experimental factor of interest can explain this association, this \"other factor\" may be a *confound* (let's call this $\\mathbf{C}$). If we care to conclude anything about our experimental factor of interest and its relation to our brain data, we should try to minimize any confounding factors in our design. \n\n---\n\\* Note that the notation for experimental variables ($\\mathbf{S}$) and brain features ($\\mathbf{R}$) is different from what we used in the previous course, in which we used $\\mathbf{X}$ for experimental variables and $\\mathbf{y}$ for brain signals. We did this to conform to the convention to use $\\mathbf{X}$ for the set of independent variables and $\\mathbf{y}$ for dependent variables. In some pattern analyses (such as RSA), however, this independent/dependent variable distintion does not really apply, so that's why we'll stick to the more generic $\\mathbf{R}$ (for brain features) and $\\mathbf{S}$ (for experimental features) terms.\n\n
\n Note: In some situations, you may only be interested in maximizing your explanatory/predictive power; in that case, you could argue that confounds are not a problem. The article by Hebart & Baker (2018) provides an excellent overview of this issue.\n
\n\nStatistically speaking, you should design your experiment in such a way that there are no associations (correlations) between $\\mathbf{R}$ and $\\mathbf{C}$, such that any association between $\\mathbf{S}$ and $\\mathbf{R}$ can *only* be due to $\\mathbf{R}$. Note that this is not trivial, because this presumes that you (1) know which factors might confound your study and (2) if you know these factors, that they are measured properly ([Westfall & Yarkoni, 2016)](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0152719)).\n\nMinimizing confounds in between-subject studies is notably harder than in within-subject designs, especially when dealing with clinical populations that are hard to acquire, because it is simply easier to experimentally control within-subject factors (especially when they are stimulus- rather than response-based). There are ways to deal with confounds post-hoc, but ideally you prevent confounds in the first place. For an overview of confounds in (multivariate/decoding) neuroimaging analyses and a proposed post-hoc correction method, see [this article](https://www.sciencedirect.com/science/article/pii/S1053811918319463) (apologies for the shameless self-promotion) and [this follow-up article](https://www.biorxiv.org/content/10.1101/2020.08.17.255034v1.abstract).\n\nIn sum, as with *any* (neuroimaging) analysis, a good experimental design is one that minimizes the possibilities of confounds, i.e., associations between factors that are not of interest ($\\mathbf{C}$) and experimental factors that *are* of interest ($\\mathbf{S}$).\n\n
\n ToThink (0 points): Suppose that you are interested in the neural correlates of ADHD. You want to compare multivariate resting-state fMRI networks between ADHD patients and healthy controls. What is the experimental factor ($\\mathbf{S}$)? And can you think of a factor that, when unaccounted for, presents a major confound ($\\mathbf{C}$) in this study/analysis? \n
\n\n
\n ToThink (1 point): Suppose that you're interested in the neural representation of \"cognitive effort\". You think of an experimental design in which you show participants either easy arithmetic problems, which involve only single-digit addition/subtraction (e.g., $2+5-4$) or hard(er) arithmetic problems, which involve two-digit addition/subtraction and multiplication (e.g., $12\\times4-2\\times11$), for which they have to respond whether the solution is odd (press left) or even (press right) as fast as possible. You then compare patterns during the between easy and hard trials. What is the experimental factor of interest ($\\mathbf{S}$) here? And what are possible confounds ($\\mathbf{C}$) in this design? Name at least two. (Note: this is a separate hypothetical experimental from the previous ToThink.)\n
\n\nYOUR ANSWER HERE\n\n### What makes up a \"pattern\"?\nSo far, we talked a lot about \"patterns\", but what do we mean with that term? There are different options with regard to *what you choose as your unit of measurement* that makes up your pattern. The far majority of pattern analyses in functional MRI use patterns of *activity estimates*, i.e., the same unit of measurement — relative (de)activation — as is common in standard mass-univariate analyses. For example, decoding object category (e.g., images of faces vs. images of houses) from fMRI activity patterns in inferotemporal cortex is an example of a pattern analysis that uses *activity estimates* as its unit of measurement. \n\nHowever, you are definitely not limited to using *activity estimates* for your patterns. For example, you could apply pattern analyses to structural data (e.g., patterns of voxelwise gray-matter volume values, like in [voxel-based morphometry](https://en.wikipedia.org/wiki/Voxel-based_morphometry)) or to functional connectivity data (e.g., patterns of time series correlations between voxels, or even topological properties of brain networks). (In fact, the connectivity examples from the Nilearn tutorial represents a way to estimate these connectivity features, which can be used in pattern analyses.) In short, pattern analyses can be applied to patterns composed of *any* type of measurement or metric!\n\nNow, let's get a little more technical. Usually, as mentioned in the beginning, pattern analyses represent the data as a 2D array of brain patterns. Let's call this $\\mathbf{R}$. The rows of $\\mathbf{R}$ represent different instances of patterns (sometimes called \"samples\" or \"observations\") and the columns represent different brain features (e.g., voxels; sometimes simply called \"features\"). Note that we thus lose all spatial information by \"flattening\" our patterns into 1D rows!\n\nLet's call the number of samples $N$ and the number of brain features $K$. We can thus represent $\\mathbf{R}$ as a $N\\times K$ matrix (2D array):\n\n\\begin{align}\n\\mathbf{R} = \n\\begin{bmatrix}\n R_{1,1} & R_{1,2} & R_{1,3} & \\dots & R_{1,K}\\\\\n R_{2,1} & R_{1,2} & R_{1,3} & \\dots & R_{2,K}\\\\\n R_{3,1} & R_{1,2} & R_{1,3} & \\dots & R_{3,K}\\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots\\\\ \n R_{N,1} & R_{1,2} & R_{1,3} & \\dots & R_{N,K}\\\\\n\\end{bmatrix}\n\\end{align}\n\nAs discussed before, the values themselves (e.g., $R_{1,1}$, $R_{1,2}$, $R_{3,6}$) represent whatever you chose for your patterns (fMRI activity, connectivity estimates, VBM, etc.). What is represented by the rows (samples/observations) of $\\mathbf{R}$ depends on your study design: in between-subject studies, these are usually participants, while in within-subject studies, these samples represent trials (or averages of trials or sometimes runs). The columns of $\\mathbf{R}$ represent the different (brain) features in your pattern; for example, these may be different voxels (or sensors/magnetometers in EEG/MEG), vertices (when working with cortical surfaces), edges in functional brain networks, etc. etc. \n\nLet's make it a little bit more concrete. We'll make up some random data below that represents a typical data array in pattern analyses:\n\n\n```python\nimport numpy as np\nN = 100 # e.g. trials\nK = 250 # e.g. voxels\n\nR = np.random.normal(0, 1, size=(N, K))\nR\n```\n\nLet's visualize this:\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.figure(figsize=(12, 4))\nplt.imshow(R, aspect='auto')\nplt.xlabel('Brain features', fontsize=15)\nplt.ylabel('Samples', fontsize=15)\nplt.title(r'$\\mathbf{R}_{N\\times K}$', fontsize=20)\ncbar = plt.colorbar()\ncbar.set_label('Feature value', fontsize=13, rotation=270, labelpad=10)\nplt.show()\n```\n\n
\n ToDo (1 point): Extract the pattern of the 42nd trial and store it in a variable called trial42. Then, extract the values of 187th brain feature across all trials and store it in a variable called feat187. Lastly, extract feature value of the 60th trial and the 221nd feature and store it in a variable called t60_f221. Remember: Python uses zero-based indexing (first value in an array is indexed by 0)!\n
\n\n\n```python\n''' Implement the ToDo here.'''\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom niedu.tests.nipa.week_1 import test_R_indexing\ntest_R_indexing(R, trial42, feat187, t60_f221)\n```\n\nAlright, to practice a little bit more. We included whole-brain VBM data for 20 subjects in the `vbm/` subfolder:\n\n\n```python\nimport os\nsorted(os.listdir('vbm'))\n```\n\nThe VBM data represents spatially normalized (to MNI152, 2mm), whole-brain voxelwise gray matter volume estimates (read more about VBM [here](https://en.wikipedia.org/wiki/Voxel-based_morphometry)).\n\nLet's inspect the data from a single subject:\n\n\n```python\nimport os\nimport nibabel as nib\nfrom nilearn import plotting\n\nsub_01_vbm_path = os.path.join('vbm', 'sub-01.nii.gz')\nsub_01_vbm = nib.load(sub_01_vbm_path)\nprint(\"Shape of Nifti file: \", sub_01_vbm.shape)\n\n# Let's plot it as well\nplotting.plot_anat(sub_01_vbm)\nplt.show()\n```\n\nAs you can see, the VBM data is a 3D array of shape 91 ($X$) $\\times$ 109 ($Y$) $\\times$ 91 ($Z$) (representing voxels). These are the spatial dimensions associated with the standard MNI152 (2 mm) template provided by FSL. As VBM is structural (not functional!) data, there is no time dimension ($T$).\n\nNow, suppose that we want to do a pattern analysis on the data of all 20 subjects. We should then create a 2D array of shape 20 (subjects) $\\times\\ K$ (number of voxels, i.e., $91 \\times 109 \\times 91$). To do so, we need to create a loop over all files, load them in, \"flatten\" the data, and ultimately stack them into a 2D array. \n\nBefore you'll implement this as part of the next ToDo, we will show you a neat Python function called `glob`, which allows you to simply find files using \"[wildcards](https://en.wikipedia.org/wiki/Wildcard_character)\":\n\n\n```python\nfrom glob import glob\n```\n\nIt works as follows:\n\n```\nlist_of_files = glob('path/with/subdirectories/*/*.nii.gz')\n```\n\nImportantly, the string you pass to `glob` can contain one or more wildcard characters (such as `?` or `*`). Also, *the returned list is not sorted*! Let's try to get all our VBM subject data into a list using this function:\n\n\n```python\n# Let's define a \"search string\"; we'll use the os.path.join function\n# to make sure this works both on Linux/Mac and Windows\nsearch_str = os.path.join('vbm', 'sub-*.nii.gz')\nvbm_files = glob(search_str)\n\n# this is also possible: vbm_files = glob(os.path.join('vbm', 'sub-*.nii.gz'))\n\n# Let's print the returned list\nprint(vbm_files)\n```\n\nAs you can see, *the list is not alphabetically sorted*, so let's fix that with the `sorted` function:\n\n\n```python\nvbm_files = sorted(vbm_files)\nprint(vbm_files)\n# Note that we could have done that with a single statement\n# vbm_files = sorted(glob(os.path.join('vbm', 'sub-*.nii.gz')))\n# But also remember: shorter code is not always better!\n```\n\n
\n ToDo (2 points): Create a 2D array with the vertically stacked subject-specific (flattened) VBM patterns, in which the first subject should be the first row. You may want to pre-allocate this array before starting your loop (using, e.g., np.zeros). Also, the enumerate function may be useful when writing your loop. Try to google how to flatten an N-dimensional array into a single vector. Store the final 2D array in a variable named R_vbm.\n
\n\n\n```python\n''' Implement the ToDo here. '''\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom niedu.tests.nipa.week_1 import test_R_vbm_loop\ntest_R_vbm_loop(R_vbm)\n```\n\n
\n Tip: While it is a good exercise to load in the data yourself, you can also easily load in and concatenate a set of Nifti files using Nilearn's concat_imgs function (which returns a 4D Nifti1Image, with the different patterns as the fourth dimension). You'd still have to reorganize this data into a 2D array, though.\n
\n\n\n```python\n# Run this cell after you're done with the ToDo\n# This will remove the all numpy arrays from memory,\n# clearing up RAM for the next sections\n%reset -f array\n```\n\n### Patterns as \"points in space\"\nBefore we continue with the topic of pattern estimation, there is one idea that we'd like to introduce: thinking of patterns as points (i.e., coordinates) in space. Thinking of patterns this way is helpful to understanding both machine learning based analyses and representational similarity analysis. While for some, this idea might sound trivial, we believe it's worth going over anyway. Now, let's make this idea more concrete. \n\nSuppose we have estimated fMRI activity patterns for 20 trials (rows of $\\mathbf{R}$). Now, we will also assume that those patterns consist of only two features (e.g., voxels; columns of $\\mathbf{R}$), because this will make visualizing patterns as points in space easier than when we choose a larger number of features.\n\nAlright, let's simulate and visualize the data (as a 2D array):\n\n\n```python\nK = 2 # features (voxels)\nN = 20 # samples (trials)\n\nR = np.random.multivariate_normal(np.zeros(K), np.eye(K), size=N)\n\nprint(\"Shape of R:\", R.shape)\n\n# Plot 2D array as heatmap\nfig, ax = plt.subplots(figsize=(2, 10))\nmapp = ax.imshow(R)\ncbar = fig.colorbar(mapp, pad=0.1)\ncbar.set_label('Feature value', fontsize=13, rotation=270, labelpad=15)\nax.set_yticks(np.arange(N))\nax.set_xticks(np.arange(K))\nax.set_title(r\"$\\mathbf{R}$\", fontsize=20)\nax.set_xlabel('Voxels', fontsize=15)\nax.set_ylabel('Trials', fontsize=15)\nplt.show()\n```\n\nNow, we mentioned that each pattern (row of $\\mathbf{R}$, i.e., $\\mathbf{R}_{i}$) can be interpreted as a point in 2D space. With space, here, we mean a space where each feature (e.g., voxel; column of $\\mathbf{R}$, i.e., $\\mathbf{R}_{j}$) represents a separate axis. In our simulated data, we have two features (e.g., voxel 1 and voxel 2), so our space will have two axes:\n\n\n```python\nplt.figure(figsize=(5, 5))\nplt.title(\"A two-dimensional space\", fontsize=15)\nplt.grid()\nplt.xlim(-3, 3)\nplt.ylim(-3, 3)\nplt.xlabel('Activity voxel 1', fontsize=13)\nplt.ylabel('Activity voxel 2', fontsize=13)\nplt.show()\n```\n\nWithin this space, each of our patterns (samples) represents a point. The values of each pattern represent the *coordinates* of its location in this space. For example, the coordinates of the first pattern are:\n\n\n```python\nprint(R[0, :])\n```\n\nAs such, we can plot this pattern as a point in space:\n\n\n```python\nplt.figure(figsize=(5, 5))\nplt.title(\"A two-dimensional space\", fontsize=15)\nplt.grid()\n\n# We use the \"scatter\" function to plot this point, but\n# we could also have used plt.plot(R[0, 0], R[0, 1], marker='o')\nplt.scatter(R[0, 0], R[0, 1], marker='o', s=75)\nplt.axhline(0, c='k')\nplt.axvline(0, c='k')\nplt.xlabel('Activity voxel 1', fontsize=13)\nplt.ylabel('Activity voxel 2', fontsize=13)\n\nplt.xlim(-3, 3)\nplt.ylim(-3, 3)\nplt.show()\n```\n\nIf we do this for all patterns, we get an ordinary scatter plot of the data:\n\n\n```python\nplt.figure(figsize=(5, 5))\nplt.title(\"A two-dimensional space\", fontsize=15)\nplt.grid()\n\n# We use the \"scatter\" function to plot this point, but\n# we could also have used plt.plot(R[0, 0], R[0, 1], marker='o')\nplt.axhline(0, c='k')\nplt.axvline(0, c='k')\nplt.scatter(R[:, 0], R[:, 1], marker='o', s=75, zorder=3)\nplt.xlabel('Activity voxel 1', fontsize=13)\nplt.ylabel('Activity voxel 2', fontsize=13)\n\nplt.xlim(-3, 3)\nplt.ylim(-3, 3)\nplt.show()\n```\n\nIt is important to realize that both perspectives — as a 2D array and as a set of points in $K$-dimensional space — represents the same data! Practically, pattern analysis algorithms usually expect the data as a 2D array, but (in our experience) the operations and mechanisms implemented by those algorithms are easiest to explain and to understand from the \"points in space\" perspective.\n\nYou might think, \"but how does this work for data with more than two features?\" Well, the idea of patterns as points in space remains the same: each feature represents a new dimension (or \"axis\"). For three features, this means that a pattern represents a point in 3D (X, Y, Z) space; for four features, a pattern represents a point in 4D space (like a point moving in 3D space) ... but what about a pattern with 14 features? Or 500? Actually, this is impossible to visualize or even make sense of mentally. As the famous artificial intelligence researcher Geoffrey Hinton put it:\n\n> \"To deal with ... a 14 dimensional space, visualize a 3D space and say 'fourteen' very loudly. Everyone does it.\" (Geoffrey Hinton)\n\nThe important thing to understand, though, is that most operations, computations, and algorithms that deal with patterns do not care about whether your data is 2D (two features) or 14D (fourteen features) — we just have to trust the mathematicians that whatever we do on 2D data will generalize to $K$-dimensional data :-)\n\nThat said, people still try to visualize >2D data using *dimensionality reduction* techniques. These techniques try to project data to a lower-dimensional space. For example, you can transform a dataset with 500 features (i.e., a 500-dimensional dataset) to a 2D dimensional dataset using techniques such as principal component analysis (PCA), Multidimensional Scaling (MDS), and t-SNE. For example, PCA tries to a subset of uncorrelated lower-dimensional features (e.g., 2) from linear combinations of high-dimensional features (e.g., 4) that still represent as much variance of the high-dimensional components as possible. We'll show you an example below using an implementation of PCA from the machine learning library [scikit-learn](https://scikit-learn.org/stable/), which we'll use extensively in next week's lab:\n\n\n```python\nfrom sklearn.decomposition import PCA\n\n# Let's create a dataset with 100 samples and 4 features\nR4D = np.random.normal(0, 1, size=(100, 4))\nprint(\"Shape R4D:\", R4D.shape)\n\n# We'll instantiate a PCA object that will\n# transform our data into 2 components\npca = PCA(n_components=2)\n\n# Fit and transform the data from 4D to 2D\nR2D = pca.fit_transform(R4D)\nprint(\"Shape R2D:\", R2D.shape)\n\n# Plot the result\nplt.figure(figsize=(5, 5))\nplt.scatter(R2D[:, 0], R2D[:, 1], marker='o', s=75, zorder=3)\nplt.axhline(0, c='k')\nplt.axvline(0, c='k')\nplt.xlabel('PCA component 1', fontsize=13)\nplt.ylabel('PCA component 2', fontsize=13)\nplt.grid()\nplt.xlim(-4, 4)\nplt.ylim(-4, 4)\nplt.show()\n```\n\n
\n ToDo (optional): As discussed, PCA is a specific dimensionality reduction technique that uses linear combinations of features to project the data to a lower-dimensional space with fewer \"components\". Linear combinations are simply weighted sums of high-dimensional features. In a 4D dimensional space that is project to 2D, PCA component 1 might be computed as $\\mathbf{R}_{j=1}\\theta_{1}+\\mathbf{R}_{j=2}\\theta_{2}+\\mathbf{R}_{j=3}\\theta_{3}+\\mathbf{R}_{j=4}\\theta_{4}$, where $R_{j=1}$ represents the 4th feature of $\\mathbf{R}$ and $\\theta_{1}$ represents the weight for the 4th feature.\n \nThe weights of the fitted PCA model can be accessed by, confusingly, pca.components_ (shape: $K_{lower} \\times K_{higher}$. Using these weights, can you recompute the lower-dimensional features from the higher-dimensional features yourself? Try to plot it like the figure above and check whether it matches.\n
\n\n\n```python\n''' Implement the (optional) ToDo here. '''\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\nNote that dimensionality reduction is often used for visualization, but it can also be used as a preprocessing step in pattern analyses. We'll take a look this in more detail next week.\n\nAlright, back to the topic of pattern extraction/estimation. You saw that preparing VBM data for (between-subject) pattern analyses is actually quite straightforward, but unfortunately, preparing functional MRI data for pattern analysis is a little more complicated. The reason is that we are dealing with time series in which different trials ($N$) are \"embedded\". The next section discusses different methods to \"extract\" (estimate) these trial-wise patterns.\n\n## Estimating patterns\nAs we mentioned before, we should prepare our data as an $N$ (samples) $\\times$ $K$ (features) array. With fMRI data, our data is formatted as a $X \\times Y \\times Z \\times T$ array; we can flatten the $X$, $Y$, and $Z$ dimensions, but we still have to find a way to \"extract\" patterns for our $N$ trials from the time series (i.e., the $T$ dimension). \n\n### Important side note: single trials vs. (runwise) average trials\nIn this section, we often assume that our \"samples\" refer to different *trials*, i.e., single instances of a stimulus or response (or another experimentally-related factor). This is, however, not the only option. Sometimes, researchers choose to treat multiple repetitions of a trial as a single sample or multiple trials within a condition as a single sample. For example, suppose you design a simple passive-viewing experiment with images belonging two one of three conditions: faces, houses, and chairs. Each condition has ten exemplars (face1, face2, ..., face10, house1, house2, ..., house10, chair1, chair2, ... , chair10) and each exemplar/item is repeated six times. So, in total there are 3 (condition) $\\times$ 10 (examplars) $\\times$ 6 (repetitions) = 180 trials. Because you don't want to bore the participant to death, you split the 180 trials into two runs (90 each).\n \nNow, there are different ways to define your samples. One is to treat every single trial as a sample (so you'll have a 180 samples). Another way is to treat each exemplar as a sample. If you do so, you'll have to \"pool\" the pattern estimates across all 6 repetitions (so you'll have $10 \\times 3 = 30$ samples). And yet another way is to treat each condition as a sample, so you'll have to pool the pattern estimates across all 6 repetitions and 10 exemplars per condition (so you'll end up with only 3 samples). Lastly, with respect to the latter two approaches, you may choose to only average repetitions and/or exemplars *within* runs. So, for two runs, you end up with either $10 \\times 3 \\times 2 = 60$ samples (when averaging across repetitions only) or $3 \\times 2 = 6$ samples (when averaging across examplars and repetitions).\n\nWhether you should perform your pattern analysis on the trial, examplar, or condition level, and whether you should estimate these patterns across runs or within runs, depends on your research question and analysis technique. For example, if you want to decode exemplars from each other, you obviously should not average across exemplars. Also, some experiments may not have different exemplars per condition (or do not have categorical conditions at all). With respect to the importance of analysis technique: when applying machine learning analyses to fMRI data, people often prefer to split their trials across many (short) runs and — if using a categorical design — prefer to estimate a single pattern per run. This is because samples across runs are not temporally autocorrelated, which is an important assumption in machine learning based analyses. Lastly, for any pattern analysis, averaging across different trials will increase the signal-to-noise ratio (SNR) for any sample (because you average out noise), but will decrease the statistical power of the analysis (because you have fewer samples). \n\nLong story short: whatever you treat as a sample — single trials, (runwise) exemplars or (runwise) conditions — depends on your design, research question, and analysis technique. In the rest of the tutorial, we will usually refer to samples as \"trials\", as this scenario is easiest to simulate and visualize, but remember that this term may equally well refer to (runwise) exemplar-average or condition-average patterns.\n\n---\n\nTo make the issue of estimating patterns from time series a little more concrete, let's simulate some signals. We'll assume that we have a very simple experiment with two conditions (A, B) with ten trials each (interleaved, i.e., ABABAB...AB), a trial duration of 1 second, spaced evenly within a single run of 200 seconds (with a TR of 2 seconds, so 100 timepoints). Note that you are not necessarily limited to discrete categorical designs for all pattern analyses! While for machine learning-based methods (topic of week 2) it is common to have a design with a single categorical feature of interest (or some times a single continuous one), representional similarity analyses (topic of week 3) are often applied to data with more \"rich\" designs (i.e., designs that include many, often continuously varying, factors of interest). Also, using twenty trials is probably way too few for any pattern analysis, but it'll make the examples (and visualizations) in this section easier to understand. \n\nAlright, let's get to it.\n\n\n```python\nTR = 2\nN = 20 # 2 x 10 trials\nT = 200 # duration in seconds\n\n# t_pad is a little baseline at the \n# start and end of the run\nt_pad = 10\n\nonsets = np.linspace(t_pad, T - t_pad, N, endpoint=False)\ndurations = np.ones(onsets.size)\nconditions = ['A', 'B'] * (N // 2)\n\nprint(\"Onsets:\", onsets, end='\\n\\n')\nprint(\"Conditions:\", conditions)\n```\n\nWe'll use the `simulate_signal` function used in the introductory course to simulate the data. This function is like a GLM in reverse: it assumes that a signal ($R$) is generated as a linear combination between (HRF-convolved) experimental features ($\\mathbf{S}$) weighted by some parameters ( $\\beta$ ) plus some additive noise ($\\epsilon$), and simulates the signal accordingly (you can check out the function by running `simulate_signal??` in a new code cell). \n\nBecause we simulate the signal, we can use \"ground-truth\" activation parameters ( $\\beta$ ). In this simulation, we'll determine that the signal responds more strongly to trials of condition A ($\\beta = 0.8$) than trials of condition B ($\\beta = 0.2$) in *even* voxels (voxel 0, 2, etc.) and vice versa for *odd* voxels (voxel 1, 3, etc.):\n\n\n```python\nparams_even = np.array([0.8, 0.2])\nparams_odd = 1 - params_even\n```\n\n
\n ToThink (0 points): Given these simulation parameters, how do you think that the corresponding $N\\times K$ pattern array ($\\mathbf{R}$) would roughly look like visually (assuming an efficient pattern estimation method)?\n
\n\nAlright, We simulate some data for, let's say, four voxels ($K = 4$). (Again, you'll usually perform pattern analyses on many more voxels.) \n\n\n```python\nfrom niedu.utils.nii import simulate_signal\nK = 4\n\nts = []\nfor i in range(K):\n\n # Google \"Python modulo\" to figure out\n # what the line below does!\n is_even = (i % 2) == 0\n \n sig, _ = simulate_signal(\n onsets,\n conditions,\n duration=T,\n plot=False,\n std_noise=0.25,\n params_canon=params_even if is_even else params_odd\n )\n\n ts.append(sig[:, np.newaxis])\n\n# ts = timeseries\nts = np.hstack(ts)\nprint(\"Shape of simulated signals: \", ts.shape)\n```\n\nAnd let's plot these voxels. We'll show the trial onsets as arrows (red = condition A, orange = condition B):\n\n\n```python\nimport seaborn as sns\n\nfig, axes = plt.subplots(ncols=K, sharex=True, sharey=True, figsize=(10, 12))\nt = np.arange(ts.shape[0])\n\nfor i, ax in enumerate(axes.flatten()):\n # Plot signal\n ax.plot(ts[:, i], t, marker='o', ms=4, c='tab:blue')\n # Plot trial onsets (as arrows)\n for ii, to in enumerate(onsets):\n color = 'tab:red' if ii % 2 == 0 else 'tab:orange'\n ax.arrow(-1.5, to / TR, dy=0, dx=0.5, color=color, head_width=0.75, head_length=0.25)\n\n ax.set_xlim(-1.5, 2)\n ax.set_ylim(0, ts.shape[0])\n ax.grid(b=True)\n ax.set_title(f'Voxel {i+1}', fontsize=15)\n ax.invert_yaxis()\n if i == 0:\n ax.set_ylabel(\"Time (volumes)\", fontsize=20)\n \n# Common axis labels\nfig.text(0.425, -.03, \"Activation (A.U.)\", fontsize=20)\nfig.tight_layout()\nsns.despine()\nplt.show()\n```\n\n
\n Tip: Matplotlib is a very flexible plotting package, but arguably at the expense of how fast you can implement something. Seaborn is a great package (build on top of Matplotlib) that offers some neat functionality that makes your life easier when plotting in Python. For example, we used the despine function to remove the top and right spines to make our plot a little nicer. In this course, we'll mostly use Matplotlib, but we just wanted to make you aware of this awesome package.\n
\n\nAlright, now we can start discussing methods for pattern estimation! Unfortunately, as pattern analyses are relatively new, there no concensus yet about the \"best\" method for pattern estimation. In fact, there exist many different methods, which we can roughly divided into two types:\n\n1. Timepoint-based method (for lack of a better name) and\n2. GLM-based methods\n\nWe'll discuss both of them, but spend a little more time on the latter set of methods as they are more complicated (and are more popular).\n\n### Timepoint-based methods\nTimepoint-based methods \"extract\" patterns by simply using a single timepoint (e.g., 6 seconds after stimulus presentation) or (an average of) multiple timepoints (e.g., 4, 6, and 8 seconds after stimulus presentation). \n\nBelow, we visualize how a single-timepoint method would look like (assuming that we'd want to extract the timepoint 6 seconds after stimulus presentation, i.e., around the assumed peak of the BOLD response). The stars represent the values that we would extract (red when condition A, orange when condition B). Note, we only plot the first 60 volumes.\n\n\n```python\nfig, axes = plt.subplots(ncols=4, sharex=True, sharey=True, figsize=(10, 12))\nt_fmri = np.linspace(0, T, ts.shape[0], endpoint=False)\nt = np.arange(ts.shape[0])\n\nfor i, ax in enumerate(axes.flatten()):\n # Plot signal\n ax.plot(ts[:, i], t, marker='o', ms=4, c='tab:blue')\n # Plot trial onsets (as arrows)\n for ii, to in enumerate(onsets):\n plus6 = np.interp(to+6, t_fmri, ts[:, i])\n color = 'tab:red' if ii % 2 == 0 else 'tab:orange'\n ax.arrow(-1.5, to / TR, dy=0, dx=0.5, color=color, head_width=0.75, head_length=0.25)\n ax.plot([plus6, plus6], [(to+6) / TR, (to+6) / TR], marker='*', ms=15, c=color)\n \n ax.set_xlim(-1.5, 2)\n ax.set_ylim(0, ts.shape[0] // 2)\n ax.grid(b=True)\n ax.set_title(f'Voxel {i+1}', fontsize=15)\n ax.invert_yaxis()\n if i == 0:\n ax.set_ylabel(\"Time (volumes)\", fontsize=20)\n\n# Common axis labels\nfig.text(0.425, -.03, \"Activation (A.U.)\", fontsize=20)\nfig.tight_layout()\nsns.despine()\nplt.show()\n```\n\nNow, extracting these timepoints 6 seconds after stimulus presentation is easy when this timepoint is a multiple of the scan's TR (here: 2 seconds). For example, to extract the value for the first trial (onset: 10 seconds), we simply take the 8th value in our timeseries, because $(10 + 6) / 2 = 8$. But what if our trial onset + 6 seconds is *not* a multiple of the TR, such as with trial 2 (onset: 19 seconds)? Well, we can interpolate this value! We will use the same function for this operation as we did for slice-timing correction (from the previous course): `interp1d` from the `scipy.interpolate` module.\n\nTo refresh your memory: this function takes the timepoints associated with the values (or \"frame_times\" in Nilearn lingo) and the values itself to generate a new object which we'll later use to do the actual (linear) interpolation. First, let's define the timepoints:\n\n\n```python\nt_fmri = np.linspace(0, T, ts.shape[0], endpoint=False)\n```\n\n
\n ToDo (1 point): The above timepoints assume that all data was acquired at the onset of the volume acquisition ($t=0$, $t=2$, etc.). Suppose that we actually slice-time corrected our data to the middle slice, i.e., the 18th slice (out of 36 slices) — create a new array (using np.linspace with timepoints that reflect these slice-time corrected acquisition onsets) and store it in a variable named t_fmri_middle_slice.\n
\n\n\n```python\n''' Implement your ToDo here. '''\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom niedu.tests.nipa.week_1 import test_frame_times_stc\ntest_frame_times_stc(TR, T, ts.shape[0], t_fmri_middle_slice)\n```\n\nFor now, let's assume that all data was actually acquired at the start of the volume ($t=0$, $t=2$, etc.). We can \"initialize\" our interpolator by giving it both the timepoints (`t_fmri`) and the data (`ts`). Note that `ts` is not a single time series, but a 2D array with time series for four voxels (across different columns). By specifying `axis=0`, we tell `interp1d` that the first axis represents the axis that we want to interpolate later:\n\n\n```python\nfrom scipy.interpolate import interp1d\ninterpolator = interp1d(t_fmri, ts, axis=0)\n```\n\nNow, we can give the `interpolator` object any set of timepoints and it will return the linearly interpolated values associated with these timepoints for all four voxels. Let's do this for our trial onsets plus six seconds:\n\n\n```python\nonsets_plus_6 = onsets + 6\nR_plus6 = interpolator(onsets_plus_6)\nprint(\"Shape extracted pattern:\", R_plus6.shape)\n\nfig, ax = plt.subplots(figsize=(2, 10))\nmapp = ax.imshow(R_plus6)\ncbar = fig.colorbar(mapp)\ncbar.set_label('Feature value', fontsize=13, rotation=270, labelpad=15)\nax.set_yticks(np.arange(N))\nax.set_xticks(np.arange(K))\nax.set_title(r\"$\\mathbf{R}$\", fontsize=20)\nax.set_xlabel('Voxels', fontsize=15)\nax.set_ylabel('Trials', fontsize=15)\nplt.show()\n```\n\nYay, we have extracted our first pattern! Does it look like what you expected given the known mean amplitude of the trials from the two conditions ($\\beta_{\\mathrm{A,even}} = 0.8, \\beta_{\\mathrm{B,even}} = 0.2$ and vice versa for odd voxels)?\n\n
\n ToDo (3 points): An alternative to the single-timepoint method is to extract, per trial, the average activity within a particular time window, for example 5-7 seconds post-stimulus. One way to do this is by perform interpolation in steps of (for example) 0.1 within the 5-7 post-stimulus time window (i.e., $5.0, 5.1, 5.2, \\dots , 6.8, 6.9, 7.0$) and subsequently averaging these values, per trial, into a single activity estimate. Below, we defined these different steps (t_post_stimulus) for you already. Use the interpolator object to extract the timepoints for these different post-stimulus times relative to our onsets (onsets variable) from our data (ts variable). Store the extracted patterns in a new variable called R_av.\n \nNote: this is a relatively difficult ToDo! Consider skipping it if it takes too long.\n
\n\n\n```python\n''' Implement your ToDo here. '''\nt_post_stimulus = np.linspace(5, 7, 21, endpoint=True)\nprint(t_post_stimulus)\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom niedu.tests.nipa.week_1 import test_average_extraction\ntest_average_extraction(onsets, ts, t_post_stimulus, interpolator, R_av)\n```\n\nThese timepoint-based methods are relatively simple to implement and computationally efficient. Another variation that you might see in the literature is that extracted (averages of) timepoints are baseline-subtracted ($\\mathbf{R}_{i} - \\mathrm{baseline}_{i}$) or baseline-normalized ($\\frac{\\mathbf{R}_{i}}{\\mathrm{baseline}_{i}}$), where the baseline is usually chosen to be at the stimulus onset or a small window before the stimulus onset. This technique is, as far as we know, not very popular, so we won't discuss it any further in this lab.\n\n### GLM-based methods\nOne big disadvantage of timepoint-based methods is that it cannot disentangle activity due to different sources (such as trials that are close in time), which is a major problem for fast (event-related) designs. For example, if you present a trial at $t=10$ and another at $t=12$ and subsequently extract the pattern six seconds post-stimulus (at $t=18$ for the second trial), then the activity estimate for the second trial is definitely going to contain activity due to the first trial because of the sluggishness of the HRF. \n\nAs such, nowadays GLM-based pattern estimation techniques, which *can* disentangle the contribution of different sources, are more popular than timepoint-based methods. (Although, technically, you can use timepoint-based methods using the GLM with FIR-based designs, but that's beyond the scope of this course.) Again, there are multiple flavors of GLM-based pattern estimation, of which we'll discuss the two most popular ones.\n\n#### Least-squares all (LSA)\nThe most straightforward GLM-based pattern estimation technique is to fit a single GLM with a design matrix that contains one or more regressors for each sample that you want to estimate (in addition to any confound regressors). The estimated parameters ($\\hat{\\beta}$) corresponding to our samples from this GLM — representing the relative (de)activation of each voxel for each trial — will then represent our patterns! \n\nThis technique is often reffered to as \"least-squares all\" (LSA). Note that, as explained before, a sample can refer to either a single trial, a set of repetitions of a particuar exemplar, or even a single condition. For now, we'll assume that samples refer to single trials. Often, each sample is modelled by a single (canonical) HRF-convolved regressor (but you could also use more than one regressor, e.g., using a basis set with temporal/dispersion derivatives or a FIR-based basis set), so we'll focus on this approach.\n\nLet's go back to our simulated data. We have a single run containing 20 trials, so ultimately our design matrix should contain twenty columns: one for every trial. We can use the `make_first_level_design_matrix` function from Nilearn to create the design matrix. Importantly, we should make sure to give a separate and unique \"trial_type\" values for all our trials. If we don't do this (e.g., set trial type to the trial condition: \"A\" or \"B\"), then Nilearn won't create separate regressors for our trials.\n\n\n```python\nimport pandas as pd\nfrom nilearn.glm.first_level import make_first_level_design_matrix\n\n# We have to create a dataframe with onsets/durations/trial_types\n# No need for modulation!\nevents_sim = pd.DataFrame(onsets, columns=['onset'])\nevents_sim.loc[:, 'duration'] = 1\nevents_sim.loc[:, 'trial_type'] = ['trial_' + str(i).zfill(2) for i in range(1, N+1)]\n\n# lsa_dm = least squares all design matrix\nlsa_dm = make_first_level_design_matrix(\n frame_times=t_fmri, # we defined this earlier for interpolation!\n events=events_sim,\n hrf_model='glover',\n drift_model=None # assume data is already high-pass filtered\n)\n\n# Check out the created design matrix\n# Note that the index represents the frame times\nlsa_dm\n```\n\nNote that the design matrix contains 21 regressors: 20 trialwise regressors and an intercept (the last column). Let's also plot it using Nilearn:\n\n\n```python\nfrom nilearn.plotting import plot_design_matrix\nplot_design_matrix(lsa_dm);\n```\n\nAnd, while we're at it, plot it as time series (rather than a heatmap):\n\n\n```python\nfig, ax = plt.subplots(figsize=(12, 12))\nfor i in range(lsa_dm.shape[1]):\n ax.plot(i + lsa_dm.iloc[:, i], np.arange(ts.shape[0]))\n\nax.set_title(\"LSA design matrix\", fontsize=20)\nax.set_ylim(0, lsa_dm.shape[0]-1)\nax.set_xlabel('')\nax.set_xticks(np.arange(N+1))\nax.set_xticklabels(['trial ' + str(i+1) for i in range(N)] + ['icept'], rotation=-90)\nax.invert_yaxis()\nax.grid()\nax.set_ylabel(\"Time (volumes)\", fontsize=15)\nplt.show()\n```\n\n
\n ToDo/ToThink (2 points): One \"problem\" with LSA-type design matrices, especially in fast event-related designs, is that they are not very statistically efficient, i.e., they lead to relatively high variance estimates of your parameters ($\\hat{\\beta}$), mainly due to relatively high predictor variance. Because we used a fixed inter-trial interval (here: 9 seconds), the correlation between \"adjacent\" trials are (approximately) the same.
\n \nCompute the correlation between, for example, the predictors associated with trial 1 and trial 2, using the pearsonr function imported below, and store it in a variable named corr_t1t2 (1 point). Then, try to think of a way to improve the efficiency of this particular LSA design and write it down in the cell below the test cell.\n
\n\n\n```python\n''' Implement your ToDO here. '''\n# For more info about the `pearsonr` function, check\n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html\n# Want a challenge? Try to compute the correlation from scratch!\nfrom scipy.stats import pearsonr\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the ToDo above. '''\nfrom niedu.tests.nipa.week_1 import test_t1t2_corr\ntest_t1t2_corr(lsa_dm, corr_t1t2)\n```\n\nYOUR ANSWER HERE\n\nAlright, let's actually fit the model! When dealing with real fMRI data, we'd use Nilearn to fit our GLM, but for now, we'll just use our own implementation of an (OLS) GLM. Note that we can actually fit a *single* GLM for all voxels at the same time by using `ts` (a $T \\times K$ matrix) as our dependent variable due to the magic of linear algebra. In other words, we can run $K$ OLS models at once!\n\n\n```python\n# Let's use 'X', because it's shorter\nX = lsa_dm.values\n\n# Note we can fit our GLM for all K voxels at \n# the same time! As such, betas is not a vector,\n# but an n_regressor x k_voxel matrix!\nbeta_hat_all = np.linalg.inv(X.T @ X) @ X.T @ ts\nprint(\"Shape beta_hat_all:\", beta_hat_all.shape)\n\n# Ah, the beta for the intercept is still in there\n# Let's remove it\nbeta_icept = beta_hat_all[-1, :]\nbeta_hat = beta_hat_all[:-1, :]\nprint(\"Shape beta_hat (intercept removed):\", beta_hat.shape)\n```\n\nAlright, let's visualize the estimated parameters ($\\hat{\\beta}$). We'll do this by plotting the scaled regressors (i.e., $X_{j}\\hat{\\beta}_{j}$) on top of the original signal. Each differently colored line represents a different regressor (so a different trial):\n\n\n```python\nfig, axes = plt.subplots(ncols=4, sharex=True, sharey=True, figsize=(10, 12))\nt = np.arange(ts.shape[0])\n\nfor i, ax in enumerate(axes.flatten()):\n # Plot signal\n ax.plot(ts[:, i], t, marker='o', ms=4, lw=0.5, c='tab:blue')\n # Plot trial onsets (as arrows)\n for ii, to in enumerate(onsets):\n color = 'tab:red' if ii % 2 == 0 else 'tab:orange'\n ax.arrow(-1.5, to / TR, dy=0, dx=0.5, color=color, head_width=0.75, head_length=0.25)\n\n # Compute x*beta for icept only \n scaled_icept = lsa_dm.iloc[:, -1].values * beta_icept[i]\n for ii in range(N):\n this_x = lsa_dm.iloc[:, ii].values\n # Compute x*beta for this particular trial (ii)\n xb = scaled_icept + this_x * beta_hat[ii, i]\n ax.plot(xb, t, lw=2)\n\n ax.set_xlim(-1.5, 2)\n ax.set_ylim(0, ts.shape[0] // 2)\n ax.grid(b=True)\n ax.set_title(f'Voxel {i+1}', fontsize=15)\n ax.invert_yaxis()\n if i == 0:\n ax.set_ylabel(\"Time (volumes)\", fontsize=20)\n\n# Common axis labels\nfig.text(0.425, -.03, \"Activation (A.U.)\", fontsize=20)\nfig.tight_layout()\nsns.despine()\nplt.show()\n```\n\nUltimately, though, the estimated GLM parameters are just another way to estimate our pattern array ($\\mathbf{R}$) — this time, we just estimated it using a different method (GLM-based) than before (timepoint-based). Therefore, let's visualize this array as we did with the other methods:\n\n\n```python\nfig, ax = plt.subplots(figsize=(2, 10))\nmapp = ax.imshow(beta_hat)\ncbar = fig.colorbar(mapp)\ncbar.set_label(r'$\\hat{\\beta}$', fontsize=25, rotation=0, labelpad=10)\nax.set_yticks(np.arange(N))\nax.set_xticks(np.arange(K))\nax.set_title(r\"$\\mathbf{R}$\", fontsize=20)\nax.set_xlabel('Voxels', fontsize=15)\nax.set_ylabel('Trials', fontsize=15)\nplt.show()\n```\n\n
\n ToDo (optional, 0 points): It would be nice to visualize the patterns, but this is very hard because we have four dimenions (because we have four voxels)!

PCA to the rescue! Run PCA on the estimated patterns (beta_hat) and store the PCA-transformed array (shape: $20 \\times 2$) in a variable named beta_hat_2d. Then, try to plot the first two components as a scatterplot. Make it even nicer by plotting the trials from condition A as red points and trials from condition B als orange points. \n
\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\nfrom niedu.tests.nipa.week_1 import test_pca_beta_hat\ntest_pca_beta_hat(beta_hat, beta_hat_2d)\n```\n\n#### Noise normalization\nOne often used preprocessing step for pattern analyses (using GLM-estimation methods) is to use \"noise normalization\" on the estimated patterns. There are two flavours: \"univariate\" and \"multivariate\" noise normalization. In univariate noise normalization, the estimated parameters ($\\hat{\\beta}$) are divided (normalized) by the standard deviation of the estimated parameters — which you might recognize as the formula for $t$-values (for a contrast against baseline)!\n\n\\begin{align}\nt_{c\\hat{\\beta}} = \\frac{c\\hat{\\beta}}{\\sqrt{\\hat{\\sigma}^{2}c(X^{T}X)^{-1}c^{T}}}\n\\end{align}\n\nwhere $\\hat{\\sigma}^{2}$ is the estimate of the error variance (sum of squared errors divided by the degrees of freedom) and $c(X^{T}X)^{-1}c^{T}$ is the \"design variance\". Sometimes people disregard the design variance and the degrees of freedom (DF) and instead only use the standard deviation of the noise: \n\n\\begin{align}\nt_{c\\hat{\\beta}} \\approx \\frac{c\\hat{\\beta}}{\\sqrt{\\sum (y_{i} - X_{i}\\hat{\\beta})^{2}}}\n\\end{align}\n\n
\n ToThink (1 point): When experiments use a fixed ISI (in the context of single-trial GLMs), the omission of the design variance in univariate noise normalization is warranted. Explain why.\n
\n\nYOUR ANSWER HERE\n\nEither way, this univariate noise normalization is a way to \"down-weigh\" the uncertain (noisy) parameter estimates. Although this type of univariate noise normalization seems to lead to better results in both decoding and RSA analyses (e.g., [Misaki et al., 2010](https://www.ncbi.nlm.nih.gov/pubmed/20580933)), the jury is still out on this issue.\n\nMultivariate noise normalization will be discussed in week 3 (RSA), so let's focus for now on the implementation of univariate noise normalization using the approximate method (which disregards design variance). To compute the standard deviation of the noise ($\\sqrt{\\sum (y_{i} - X_{i}\\hat{\\beta})^{2}}$), we first need to compute the noise, i.e., the unexplained variance ($y - X\\hat{\\beta}$) also known as the residuals:\n\n\n```python\nresiduals = ts - X @ beta_hat_all\nprint(\"Shape residuals:\", residuals.shape)\n```\n\nSo, for each voxel ($K=4$), we have a timeseries ($T=100$) with unexplained variance (\"noise\"). Now, to get the standard deviation across all voxels, we can do the following:\n\n\n```python\nstd_noise = np.std(residuals, axis=0)\nprint(\"Shape noise std:\", std_noise.shape)\n```\n\nTo do the actual normalization step, we simply divide the columns of the pattern matrix (`beta_hat`, which we estimated before) by the estimated noise standard deviation:\n\n\n```python\n# unn = univariate noise normalization\n# Note that we don't have to do this for each trial (row) separately\n# due to Numpy broadcasting!\nR_unn = beta_hat / std_noise\nprint(\"Shape R_unn:\", R_unn.shape)\n```\n\nAnd let's visualize it:\n\n\n```python\nfig, ax = plt.subplots(figsize=(2, 10))\nmapp = ax.imshow(R_unn)\ncbar = fig.colorbar(mapp)\ncbar.set_label(r'$t$', fontsize=25, rotation=0, labelpad=10)\nax.set_yticks(np.arange(N))\nax.set_xticks(np.arange(K))\nax.set_title(r\"$\\mathbf{R}_{unn}$\", fontsize=20)\nax.set_xlabel('Voxels', fontsize=15)\nax.set_ylabel('Trials', fontsize=15)\nplt.show()\n```\n\n
\n ToThink (1 point): In fact, univariate noise normalization didn't really change the pattern matrix much. Why do you think this is the case for our simulation data? Hint: check out the parameters for the simulation.\n
\n\nYOUR ANSWER HERE\n\n#### LSA on real data\nAlright, enough with all that fake data — let's work with some real data! We'll use the face perception task data from the *NI-edu* dataset, which we briefly mentioned in the fMRI-introduction course.\n\nIn the face perception task, participants were presented with images of faces (from the publicly available [Face Research Lab London Set](https://figshare.com/articles/Face_Research_Lab_London_Set/5047666)). In total, frontal face images from 40 different people (\"identities\") were used, which were either without expression (\"neutral\") or were smiling. Each face image (from in total 80 faces, i.e., 40 identities $\\times$ 2, neutral/smiling) was shown, per participant, 6 times across the 12 runs (3 times per session). \n\n
\n Mini ToThink (0 points): Why do you think we show the same image multiple times?\n
\n\nIdentities were counterbalanced in terms of biological sex (male vs. female) and ethnicity (Caucasian vs. East-Asian vs. Black). The Face Research Lab London Set also contains the age of the people in the stimulus dataset and (average) attractiveness ratings for all faces from an independent set of raters. In addition, we also had our own participants rate the faces on perceived attractiveness, dominance, and trustworthiness after each session (rating each face, on each dimension, four times in total for robustness). The stimuli were chosen such that we have many different attributes that we could use to model brain responses (e.g., identity, expression, ethnicity, age, average attractiveness, and subjective/personal perceived attractiveness/dominance/trustworthiness).\n\nIn this paradigm, stimuli were presented for 1.25 seconds and had a fixed interstimulus interval (ISI) of 3.75 seconds. While sub-optimal for univariate \"detection-based\" analyses, we used a fixed ISI — rather than jittered — to make sure it can also be used for \"single-trial\" multivariate analyses. Each run contained 40 stimulus presentations. To keep the participants attentive, a random selection of 5 stimuli (out of 40) were followed by a rating on either perceived attractiveness, dominance, or trustworthiness using a button-box with eight buttons (four per hand) lasting 2.5 seconds. After the rating, a regular ISI of 3.75 seconds followed. See the figure below for a visualization of the paradigm.\n\n\n\nFirst, let's set up all the data that we need for our LSA model. Let's see where our data is located:\n\n\n```python\nimport os\ndata_dir = os.path.join(os.path.expanduser('~'), 'NI-edu-data')\n\nprint(\"Downloading Fmriprep data (+- 175MB) ...\\n\")\n!aws s3 sync --no-sign-request s3://openneuro.org/ds003965 {data_dir} --exclude \"*\" --include \"sub-03/ses-1/func/*task-face*run-1*events.tsv\"\n!aws s3 sync --no-sign-request s3://openneuro.org/ds003965 {data_dir} --exclude \"*\" --include \"derivatives/fmriprep/sub-03/ses-1/func/*task-face*run-1*space-T1w*bold.nii.gz\"\n!aws s3 sync --no-sign-request s3://openneuro.org/ds003965 {data_dir} --exclude \"*\" --include \"derivatives/fmriprep/sub-03/ses-1/func/*task-face*run-1*space-T1w*mask.nii.gz\"\n!aws s3 sync --no-sign-request s3://openneuro.org/ds003965 {data_dir} --exclude \"*\" --include \"derivatives/fmriprep/sub-03/ses-1/func/*task-face*run-1*confounds_timeseries.tsv\"\nprint(\"\\nDone!\")\n```\n\nAs you can see, it contains both \"raw\" (not-preprocessed) subject data (e.g., sub-03) and derivatives, which include Fmriprep-preprocessed data:\n\n\n```python\nfprep_sub03 = os.path.join(data_dir, 'derivatives', 'fmriprep', 'sub-03')\nprint(\"Contents derivatives/fmriprep/sub-03:\", os.listdir(fprep_sub03))\n```\n\nThere is preprocessed anatomical data and session-specific functional data:\n\n\n```python\nfprep_sub03_ses1_func = os.path.join(fprep_sub03, 'ses-1', 'func')\ncontents = sorted(os.listdir(fprep_sub03_ses1_func))\nprint(\"Contents ses-1/func:\", '\\n'.join(contents))\n```\n\nThat's a lot of data! Importantly, we will only use the \"face\" data (\"task-face\") in T1 space (\"space-T1w\"), meaning that this dat has not been normalized to a common template (unlike the \"task-MNI152NLin2009cAsym\" data). Here, we'll only analyze the first run (\"run-1\") data. Let's define the functional data, the associated functional brain mask (a binary image indicating which voxels are brain and which are not), and the file with timepoint-by-timepoint confounds (such as motion parameters):\n\n\n```python\nfunc = os.path.join(fprep_sub03_ses1_func, 'sub-03_ses-1_task-face_run-1_space-T1w_desc-preproc_bold.nii.gz')\n\n# Notice this neat little trick: we use the string method \"replace\" to define\n# the functional brain mask\nfunc_mask = func.replace('desc-preproc_bold', 'desc-brain_mask')\n\nconfs = os.path.join(fprep_sub03_ses1_func, 'sub-03_ses-1_task-face_run-1_desc-confounds_timeseries.tsv')\nconfs_df = pd.read_csv(confs, sep='\\t')\nconfs_df\n```\n\nFinally, we need the events-file with onsets, durations, and trial-types for this particular run:\n\n\n```python\nevents = os.path.join(data_dir, 'sub-03', 'ses-1', 'func', 'sub-03_ses-1_task-face_run-1_events.tsv')\nevents_df = pd.read_csv(events, sep='\\t')\nevents_df = events_df.query(\"trial_type != 'rating' and trial_type != 'response'\") # don't need this\n\n# Oops, Nilearn doesn't accept trial_type values that start with a number, so\n# let's prepend 'tt_' to it!\nevents_df['trial_type'] = 'tt_' + events_df['trial_type']\n```\n\nNow, it's up to you to use this data to fit an LSA model!\n\n
\n ToDo (2 points): in this first ToDo, you define your events and the confounds you want to include.
\n \n1. Remove all columns except \"onset\", \"duration\", and \"trial_type\". You should end up with a DataFrame with 40 rows and 3 columns. You can check this with the .shape attribute of the DataFrame. (Note that, technically, you could model the reponse and rating-related events as well! For now, we'll exclude them.) Name this filtered DataFrame events_df_filt.\n \n2. You also need to select specific columns from the confounds DataFrame, as we don't want to include all confounds! For now, include only the motion parameters (trans_x, trans_y, trans_z, rot_x, rot_y, rot_z). You should end up with a confounds DataFrame with 342 rows and 6 columns. Name this filtered DataFrame confs_df_filt.\n
\n\n\n```python\n''' Implement your ToDo here. '''\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nassert(events_df_filt.shape == (40, 3))\nassert(events_df_filt.columns.tolist() == ['onset', 'duration', 'trial_type'])\nassert(confs_df_filt.shape == (confs_df.shape[0], 6))\nassert(all('trans' in col or 'rot' in col for col in confs_df_filt.columns))\nprint(\"Well done!\")\n```\n\n
\n ToDo (2 points): in this Todo, you'll fit your model! Define a FirstLevelModel object, name this flm_todo and make sure you do the following:
\n \n1. Set the correct TR (this is 0.7)\n2. Set the slice time reference to 0.5\n3. Set the mask image to the one we defined before\n4. Use a \"glover\" HRF\n5. Use a \"cosine\" drift model with a cutoff of 0.01 Hz\n6. Do not apply any smoothing\n7. Set minimize_memory to true\n8. Use an \"ols\" noise model\n\nThen, fit your model using the functional data (func), filtered confounds, and filtered events we defined before. \n
\n\n\n```python\n''' Implement your ToDo here. '''\n# Ignore the DeprecationWarning!\nfrom nilearn.glm.first_level import FirstLevelModel\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n\"\"\" Tests the above ToDo. \"\"\"\nfrom niedu.tests.nipa.week_1 import test_lsa_flm\ntest_lsa_flm(flm_todo, func_mask, func, events_df_filt, confs_df_filt)\n```\n\n
\n ToDo (2 points): in this Todo, you'll run the single-trial contrasts (\"against baseline\"). To do so, write a for-loop in which you call the compute_contrast method every iteration with a new contrast definition for a new trial. Make sure to output the \"betas\" (by using output_type='effect_size').\n \nNote that the compute_contrast method returns the \"unmasked\" results (i.e., from all voxels). Make sure that, for each trial, you mask the results using the func_mask variable and the apply_mask function from Nilearn. Save these masked results (which should be patterns of 66298 voxels) for each trial. After the loop, stack all results in a 2D array with the different trials in different rows and the (flattened) voxels in columns. This array should be of shape 40 (trials) by 65643 (nr. of masked voxels). The variable name of this array should be R_todo.\n
\n\n\n```python\n''' Implement your ToDo here. '''\nfrom nilearn.masking import apply_mask\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom niedu.tests.nipa.week_1 import test_lsa_R\ntest_lsa_R(R_todo, events_df_filt, flm_todo, func_mask)\n```\n\n
\n Disclaimer: In this ToDo, we asked you not to spatially smooth the data. This is often recommended for pattern analyses, as they arguably use information that is encoded in finely distributed patterns. However, several studies have shown that smoothing may sometimes benefit pattern analyses (e.g., Hendriks et al., 2017). In general, in line with the matched filter theorem, we recommend smoothing your data with a kernel equal to how finegrained you think your experimental feature is encoded in the brain patterns.\n
\n\n## Dealing with trial correlations\nWhen working with single-trial experimental designs (such as the LSA designs discussed previously), one often occurring problem is correlation between trial predictors and their resulting estimates. Trial correlations in such designs occur when the inter-stimulus interval (ISI) is sufficiently short such that trial predictors overlap and thus correlate. This, in turn, leads to relatively unstable (high-variance) pattern estimates and, as we will see later in this section, trial patterns that correlate with each other (which is sometimes called [pattern drift](https://www.biorxiv.org/content/10.1101/032391v2)).\n\nThis is also the case in our data from the NI-edu dataset. In the \"face\" task, stimuli were presented for 1.25 seconds, followed by a 3.75 ISI, which causes a slightly positive correlation between a given trial ($i$) and the next trial ($i + 1$) and a slightly negative correlation between the trial after that ($i + 2$). We'll show this below by visualizing the correlation matrix of the design matrix: \n\n\n```python\ndm_todo = pd.read_csv('dm_todo.tsv', sep='\\t')\ndm_todo = dm_todo.iloc[:, :40]\nfig, ax = plt.subplots(figsize=(8, 8))\n\n# Slightly exaggerate by setting the limits to (-.3, .3)\nmapp = ax.imshow(dm_todo.corr(), vmin=-0.3, vmax=0.3)\n\n# Some styling\nax.set_xticks(range(dm_todo.shape[1]))\nax.set_xticklabels(dm_todo.columns, rotation=90)\nax.set_yticks(range(dm_todo.shape[1]))\nax.set_yticklabels(dm_todo.columns)\ncbar = plt.colorbar(mapp, shrink=0.825)\ncbar.ax.set_ylabel('Correlation', fontsize=15, rotation=-90)\n\nplt.show()\n```\n\n
\n ToThink (1 point): Explain why trials (at index $i$) correlate slightly negatively with the the second trial coming after it (at index $i + 2$). Hint: try to plot it!\n
\n\nYOUR ANSWER HERE\n\nThe trial-by-trial correlation structure in the design leads to a trial-by-trial correlation structure in the estimated patterns as well (as explained by [Soch et al., 2020](https://www.sciencedirect.com/science/article/pii/S1053811919310407)). We show this below by computing and visualizing the $N \\times N$ correlation matrix of the patterns:\n\n\n```python\n# Load in R_todo if you didn't manage to do the\n# previous ToDo\nR_todo = np.load('R_todo.npy')\n\n# Compute the NxN correlation matrix\nR_corr = np.corrcoef(R_todo)\n\nfig, ax = plt.subplots(figsize=(8, 8))\nmapp = ax.imshow(R_corr, vmin=-1, vmax=1)\n\n# Some styling\nax.set_xticks(range(dm_todo.shape[1]))\nax.set_xticklabels(dm_todo.columns, rotation=90)\nax.set_yticks(range(dm_todo.shape[1]))\nax.set_yticklabels(dm_todo.columns)\ncbar = plt.colorbar(mapp, shrink=0.825)\ncbar.ax.set_ylabel('Correlation', fontsize=15, rotation=-90)\n\nplt.show()\n```\n\nThis correlation structure across trials poses a problem for representational similarity analysis (the topic of week 3) especially. Although this issue is still debated and far from solved, in this section we highlight two possible solutions to this problem: least-squares separate designs and temporal \"uncorrelation\".\n\n### Least-squares separate (LSS)\nThe least-squares separate LSS) design is a slight modifcation of the LSA design ([Mumford et al., 2014](https://www.sciencedirect.com/science/article/pii/S105381191400768X)). In LSS, you fit a separate model per trial. Each model contains one regressor for the trial that you want to estimate and, for each condition in your experimental design (in case of a categorical design), another regressor containing all other trials. \n\nSo, suppose you have a run with 30 trials across 3 conditions (A, B, and C); using an LSS approach, you'd fit 30 different models, each containing four regressors (one for the single trial, one for all (other) trials of condition A, one for all (other) trials of condition B, and one for all (other) trials of condition C). The apparent upside of this is that it strongly reduces the collinearity of trials close in time, which in turn makes the trial parameters more efficient to estimate.\n\n
\n ToThink (1 point): Suppose my experiment contains 90 stimuli which all belong to their own condition (i.e., there are 90 conditions). Explain why LSS provides no improvement over LSA in this case.\n
\n\nYOUR ANSWER HERE\n\nWe'll show this for our example data. It's a bit complicated (and not necessarily the best/fastest/clearest way), but the comments will explain what it's doing. Essentially, what we're doing, for each trial, is to extract that regressor for a standard LSA design and, for each condition, create a single regressor by summing all single-trial regressors from that condition together.\n\n\n```python\n# First, well make a standard LSA design matrix\nlsa_dm = make_first_level_design_matrix(\n frame_times=t_fmri, # we defined this earlier for interpolation!\n events=events_sim,\n hrf_model='glover',\n drift_model=None # assume data is already high-pass filtered\n)\n\n# Then, we will loop across trials, making a single GLM\nlss_dms = [] # we'll store the design matrices here\n\n# Do not include last column, the intercept, in the loop\nfor i, col in enumerate(lsa_dm.columns[:-1]): \n # Extract the single-trial predictor\n single_trial_reg = lsa_dm.loc[:, col]\n\n # Now, we need to create a predictor per condition\n # (one for A, one for B). We'll store these in \"other_regs\"\n other_regs = []\n\n # Loop across unique conditions (\"A\" and \"B\")\n for con in np.unique(conditions):\n # Which columns belong to the current condition?\n idx = con == np.array(conditions)\n \n # Make sure NOT to include the trial we're currently estimating!\n idx[i] = False\n \n # Also, exclude the intercept (last column)\n idx = np.append(idx, False)\n \n # Now, extract all N-1 regressors\n con_regs = lsa_dm.loc[:, idx]\n \n # And sum them together!\n # This creates a single predictor for the current\n # condition\n con_reg_all = con_regs.sum(axis=1)\n \n # Save for later\n other_regs.append(con_reg_all)\n\n # Concatenate the condition regressors (one of A, one for B)\n other_regs = pd.concat(other_regs, axis=1)\n \n # Concatenate the single-trial regressor and two condition regressors\n this_dm = pd.concat((single_trial_reg, other_regs), axis=1)\n\n # Add back an intercept!\n this_dm.loc[:, 'intercept'] = 1\n \n # Give it sensible column names\n this_dm.columns = ['trial_to_estimate'] + list(set(conditions)) + ['intercept']\n\n # Save for alter\n lss_dms.append(this_dm)\n\nprint(\"We have created %i design matrices!\" % len(lss_dms))\n```\n\nAlright, now let's check out the first five design matrices, which should estimate the first five trials and contain 4 regressors each (one for the single trial, two for the separate conditions, and one for the intercept):\n\n\n```python\nfig, axes = plt.subplots(ncols=5, figsize=(15, 10))\nfor i, ax in enumerate(axes.flatten()):\n plot_design_matrix(lss_dms[i], ax=ax)\n ax.set_title(\"Design for trial %i\" % (i+1), fontsize=20)\n\nplt.tight_layout()\nplt.show()\n```\n\n
\n ToDo (optional; 1 bonus point): Can you implement an LSS approach to estimate our patterns on the real data? You can reuse the flm_todo you created earlier; the only thing you need to change each time is the design matrix. Because we have 40 trials, you need to fit 40 different models (which takes a while). Note that our experimental design does not necessarily have discrete categories, so your LSS design matrices should only have 3 columns: one for the trial to estimate, one for all other trials, and one for the intercept. After fitting each model, compute the trial-against-baseline contrast for the single trial and save the parameter (\"beta\") map. Then, after the loop, create the same pattern matrix as the previous ToDo, which should also have the same shape, but name it this time R_todo_lss. Note, this is a very hard ToDo if you're not very familiar with Python, but a great way to test your programming skills :-)\n
\n\n\n```python\n''' Implement your ToDo here. Note that we already created the LSA design matrix for you. '''\nfunc_img = nib.load(func)\nn_vol = func_img.shape[-1]\nlsa_dm = make_first_level_design_matrix(\n frame_times=np.linspace(0, n_vol * 0.7, num=n_vol, endpoint=False),\n events=events_df_filt,\n drift_model=None\n)\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom niedu.tests.nipa.week_1 import test_lss\ntest_lss(R_todo_lss, func, flm_todo, lsa_dm, confs_df_filt)\n```\n\n
\n Tip: Programming your own pattern estimation pipeline allows you to be very flexible and is a great way to practice your programming skills, but if you want a more \"pre-packaged\" tool, I recommend the nibetaseries package. The package's name is derived from a specific analysis technique called \"beta-series correlation\", which is a type of analysis that allows for resting-state like connectivity analyses of task-based fMRI data (which we won't discuss in this course). For this technique, you need to estimate single-trial activity patterns — just like we need to do for pattern analyses! I've used this package to estimate patterns for pattern analysis and I highly recommend it!\n
\n\n### Temporal uncorrelation\nAnother method to deal with trial-by-trial correlations is the \"uncorrelation\" method by [Soch and colleagues (2020)](https://www.sciencedirect.com/science/article/pii/S1053811919310407). As opposed to the LSS method, the uncorrelation approach takes care of the correlation structure in the data in a post-hoc manner. It does so, in essence, by \"removing\" the correlations in the data that are due to the correlations in the design in a way that is similar to what prewhitening does in generalized least squares.\n\nFormally, the \"uncorrelated\" patterns ($R_{\\mathrm{unc}}$) are estimated by (matrix) multiplying the square root ($^{\\frac{1}{2}}$) of covariance matrix of the LSA design matrix ($X^{T}X$) with the patterns ($R$):\n\n\\begin{align}\nR_{\\mathrm{unc}} = (X^{T}X)^{\\frac{1}{2}}R\n\\end{align}\n\nHere, $(X^{T}X)^{\\frac{1}{2}}$ represents the \"whitening\" matrix which uncorrelates the patterns. Let's implement this in code. Note that we can use the `sqrtm` function from the `scipy.linalg` package to take the square root of a matrix:\n\n\n```python\nfrom scipy.linalg import sqrtm\n\n# Design matrix\nX = dm_todo.to_numpy()\nR_unc = sqrtm(X.T @ X) @ R_todo\n```\n\nThis uncorrelation technique is something we'll see again in week 3 when we'll talk about multivariate noise normalization!\n\nAlright, that was it for this lab! We have covered the basics of experimental design and pattern estimation techniques for fMRI data. Note that there are many other (more advanced) things related to pattern estimation that we haven't discussed, such as standardization of patterns, multivariate noise normalization, [hyperalignment](https://www.sciencedirect.com/science/article/pii/S0896627311007811), etc. etc. Some of these topics will be discussed in week 2 (decoding) or week 3 (RSA).\n", "meta": {"hexsha": "d810e9c1ff6fb2830bfb692af5877582ba01a544", "size": 109507, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NI-edu/fMRI-pattern-analysis/week_1/design_and_pattern_estimation.ipynb", "max_stars_repo_name": "Neuroimaging-UvA/NI-edu", "max_stars_repo_head_hexsha": "c21874ab59b2c7f48658f603fc849d4d6597f5e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-08-16T09:09:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T03:02:50.000Z", "max_issues_repo_path": "NI-edu/fMRI-pattern-analysis/week_1/design_and_pattern_estimation.ipynb", "max_issues_repo_name": "Neuroimaging-UvA/NI-edu", "max_issues_repo_head_hexsha": "c21874ab59b2c7f48658f603fc849d4d6597f5e3", "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": "NI-edu/fMRI-pattern-analysis/week_1/design_and_pattern_estimation.ipynb", "max_forks_repo_name": "Neuroimaging-UvA/NI-edu", "max_forks_repo_head_hexsha": "c21874ab59b2c7f48658f603fc849d4d6597f5e3", "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": 43.1809936909, "max_line_length": 1128, "alphanum_fraction": 0.6348543929, "converted": true, "num_tokens": 19502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250462027098473, "lm_q2_score": 0.17781087601343812, "lm_q1q2_score": 0.07512591665010881}} {"text": "```pyspark\nfrom IPython.display import Image\nImage(url='http://python.org/images/python-logo.gif')\n\n```\n\n\n\n\n\n\n\n\n# IPython notebook\n\n\n\n```pyspark\nImage(url='http://ipython.org/_static/IPy_header.png')\n```\n\n\n\n\n\n\n\n\n\n```pyspark\nImage(url='http://jupyter.org/images/jupyter-sq-text.svg', width=300, height=300)\n```\n\n\n\n\n\n\n\n\n# Jupyter\nIPython will continue to exist as a Python kernel for Jupyter, but the notebook and other language-agnostic parts of IPython will move to new projects under the Jupyter name. IPython 3.0 will be the last monolithic release of IPython.\n\n- Let's continue to call this IPython for now\n\n# IPython\n- interactive shell\n- browser-based notebook (this)\n- 'Kernel'\n- great support for visualization library (eg. matplotlib)\n- built on pyzmq, tornado\n\n## IPython notebook\n### Notebook == browser-based REPL\nIPython Notebook is a web-based interactive computational environment for creating IPython notebooks. An IPython notebook is a JSON document containing an ordered list of input/output cells which can contain code, text, mathematics, plots and rich media.\n\n## matplotlib\nmatplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc, with just a few lines of code, with familiar MATLAB APIs.\n\n```py\nplt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)\nplt.yticks(y_pos, people)\nplt.xlabel('Performance')\nplt.title('How fast do you want to go today?')\nplt.show()\n```\n\n## PySpark\nSpark on Python, this serves as the Kernel, integrating with IPython\n- Each notebook spins up a new instance of the Kernal (ie. PySpark running as the Spark Driver)\n\n## Environment\n\n- CentOS 6.5\n- CDH 5.3.0 cluster\n- Spark\n- PySpark [(YARN client mode)](http://spark.apache.org/docs/latest/running-on-yarn.html)\n- matplotlib and other packages installed\n\n\n# Maxwell's Equations\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\ \\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{align}\n\n\n```Python\n# Markdown code block\nif not full:\n print 'eat more!'\n```\n\n\n```pyspark\nimport matplotlib\nmatplotlib.__version__\n```\n\n\n\n\n '1.4.3'\n\n\n\n# Spark\n\n\n```pyspark\nprint sys.version\nprint sc.version\n\n```\n\n\n VBox()\n\n\n Starting Spark application\n\n\n\n\n
IDYARN Application IDKindStateSpark UIDriver logCurrent session?
2application_1571347151292_0003pysparkidleLinkLink
\n\n\n\n FloatProgress(value=0.0, bar_style='info', description='Progress:', layout=Layout(height='25px', width='50%'),…\n\n\n SparkSession available as 'spark'.\n\n\n\n FloatProgress(value=0.0, bar_style='info', description='Progress:', layout=Layout(height='25px', width='50%'),…\n\n\n Missing parentheses in call to 'print'. Did you mean print(sys.version)? (, line 1)\n File \"\", line 1\n print sys.version\n ^\n SyntaxError: Missing parentheses in call to 'print'. Did you mean print(sys.version)?\n \n\n\n\n```pyspark\nlines = sc.parallelize(['This is Bezos Jeff, not Jeff Bezos. Its fun to have fun,','but you have to know how.']) \nwordcounts = lines.map( lambda x: x.replace(',',' ').replace('.',' ').replace('-',' ').lower()) \\\n .flatMap(lambda x: x.split()) \\\n .map(lambda x: (x, 1)) \\\n .reduceByKey(lambda x,y:x+y) \\\n .map(lambda x:(x[1],x[0])) \\\n .sortByKey(False) \nwordcounts.take(10)\n\n```\n\n\n VBox()\n\n\n\n FloatProgress(value=0.0, bar_style='info', description='Progress:', layout=Layout(height='25px', width='50%'),…\n\n\n [(2, 'bezos'), (2, 'have'), (2, 'to'), (2, 'jeff'), (2, 'fun'), (1, 'but'), (1, 'you'), (1, 'how'), (1, 'this'), (1, 'is')]\n\n\n```pyspark\npagecounts = sc.textFile('/user/fcheung/pagecounts') # HDFS\npagecounts.take(10)\n```\n\n\n VBox()\n\n\n\n FloatProgress(value=0.0, bar_style='info', description='Progress:', layout=Layout(height='25px', width='50%'),…\n\n\n An error occurred while calling o154.partitions.\n : org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: hdfs://ip-10-0-1-35.ec2.internal:8020/user/fcheung/pagecounts\n \tat org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:260)\n \tat org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:208)\n \tat org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:288)\n \tat org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:204)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:253)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:251)\n \tat scala.Option.getOrElse(Option.scala:121)\n \tat org.apache.spark.rdd.RDD.partitions(RDD.scala:251)\n \tat org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:49)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:253)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:251)\n \tat scala.Option.getOrElse(Option.scala:121)\n \tat org.apache.spark.rdd.RDD.partitions(RDD.scala:251)\n \tat org.apache.spark.api.java.JavaRDDLike$class.partitions(JavaRDDLike.scala:61)\n \tat org.apache.spark.api.java.AbstractJavaRDDLike.partitions(JavaRDDLike.scala:45)\n \tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n \tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n \tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n \tat java.lang.reflect.Method.invoke(Method.java:498)\n \tat py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)\n \tat py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)\n \tat py4j.Gateway.invoke(Gateway.java:282)\n \tat py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)\n \tat py4j.commands.CallCommand.execute(CallCommand.java:79)\n \tat py4j.GatewayConnection.run(GatewayConnection.java:238)\n \tat java.lang.Thread.run(Thread.java:748)\n \n Traceback (most recent call last):\n File \"/usr/lib/spark/python/lib/pyspark.zip/pyspark/rdd.py\", line 1327, in take\n totalParts = self.getNumPartitions()\n File \"/usr/lib/spark/python/lib/pyspark.zip/pyspark/rdd.py\", line 391, in getNumPartitions\n return self._jrdd.partitions().size()\n File \"/usr/lib/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py\", line 1257, in __call__\n answer, self.gateway_client, self.target_id, self.name)\n File \"/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py\", line 63, in deco\n return f(*a, **kw)\n File \"/usr/lib/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py\", line 328, in get_return_value\n format(target_id, \".\", name), value)\n py4j.protocol.Py4JJavaError: An error occurred while calling o154.partitions.\n : org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: hdfs://ip-10-0-1-35.ec2.internal:8020/user/fcheung/pagecounts\n \tat org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:260)\n \tat org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:208)\n \tat org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:288)\n \tat org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:204)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:253)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:251)\n \tat scala.Option.getOrElse(Option.scala:121)\n \tat org.apache.spark.rdd.RDD.partitions(RDD.scala:251)\n \tat org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:49)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:253)\n \tat org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:251)\n \tat scala.Option.getOrElse(Option.scala:121)\n \tat org.apache.spark.rdd.RDD.partitions(RDD.scala:251)\n \tat org.apache.spark.api.java.JavaRDDLike$class.partitions(JavaRDDLike.scala:61)\n \tat org.apache.spark.api.java.AbstractJavaRDDLike.partitions(JavaRDDLike.scala:45)\n \tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n \tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n \tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n \tat java.lang.reflect.Method.invoke(Method.java:498)\n \tat py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)\n \tat py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)\n \tat py4j.Gateway.invoke(Gateway.java:282)\n \tat py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)\n \tat py4j.commands.CallCommand.execute(CallCommand.java:79)\n \tat py4j.GatewayConnection.run(GatewayConnection.java:238)\n \tat java.lang.Thread.run(Thread.java:748)\n \n \n\n\n\n```pyspark\nenPages = pagecounts.filter(lambda x: x.split(\" \")[1] == \"en\")\nenPages.map(lambda x: x.split(\" \")).map(lambda x: (x[2], int(x[3]))).reduceByKey(lambda x, y: x + y, 40).filter(lambda x: x[1] > 200000).map(lambda x: (x[1], x[0])).collect()\n# This runs in the cluster\n```\n\n\n\n\n [(451126, u'Main_Page'), (1066734, u'404_error/'), (468159, u'Special:Search')]\n\n\n\n# To be or not to be\n\n\n```pyspark\nwords = sc.textFile('/user/fcheung/hamlet.txt')\nwords.take(5)\n```\n\n\n\n\n [u'', u'1604', u'', u'', u'THE TRAGEDY OF HAMLET, PRINCE OF DENMARK']\n\n\n\n\n```pyspark\nimport re\nhamlet = words.flatMap(lambda line: re.split('\\W+', line.lower().strip()))\nhamlet.take(5)\n```\n\n\n\n\n [u'', u'1604', u'', u'', u'the']\n\n\n\n\n```pyspark\ntmp = hamlet.filter(lambda x: len(x) > 2 )\nprint tmp.take(5)\n```\n\n [u'1604', u'the', u'tragedy', u'hamlet', u'prince']\n\n\n\n```pyspark\ntmp = tmp.map(lambda word: (word, 1))\ntmp.take(5)\n```\n\n\n\n\n [(u'1604', 1), (u'the', 1), (u'tragedy', 1), (u'hamlet', 1), (u'prince', 1)]\n\n\n\n\n```pyspark\ntmp = tmp.reduceByKey(lambda a, b: a + b)\ntmp.take(5)\n \n```\n\n\n\n\n [(u'pardon', 9),\n (u'nunnery', 5),\n (u'lunacies', 1),\n (u'needful', 1),\n (u'foul', 12)]\n\n\n\n\n```pyspark\ntmp = tmp.map(lambda x: (x[1], x[0])).sortByKey(False)\ntmp.take(20)\n```\n\n\n\n\n [(1091, u'the'),\n (969, u'and'),\n (558, u'you'),\n (405, u'that'),\n (358, u'ham'),\n (315, u'not'),\n (304, u'his'),\n (300, u'this'),\n (278, u'with'),\n (274, u'but'),\n (252, u'for'),\n (242, u'your'),\n (226, u'lord'),\n (219, u'what'),\n (203, u'king'),\n (197, u'him'),\n (183, u'have'),\n (173, u'will'),\n (132, u'are'),\n (125, u'all')]\n\n\n\n\n```pyspark\ntmp = tmp.map(lambda x: (x[1], x[0]))\ntmp.take(20)\n```\n\n\n\n\n [(u'the', 1091),\n (u'and', 969),\n (u'you', 558),\n (u'that', 405),\n (u'ham', 358),\n (u'not', 315),\n (u'his', 304),\n (u'this', 300),\n (u'with', 278),\n (u'but', 274),\n (u'for', 252),\n (u'your', 242),\n (u'lord', 226),\n (u'what', 219),\n (u'king', 203),\n (u'him', 197),\n (u'have', 183),\n (u'will', 173),\n (u'are', 132),\n (u'all', 125)]\n\n\n\n\n```pyspark\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\ndef plot(words):\n values = map(lambda x: x[1], words)\n labels = map(lambda x: x[0], words)\n plt.barh(range(len(values)), values, color='grey')\n plt.yticks(range(len(values)), labels)\n plt.show()\n```\n\n\n```pyspark\nplot(tmp.take(15))\n```\n\n# Word vector\nWord2Vec computes distributed vector representation of words. Distributed vector representation is showed to be useful in many natural language processing applications such as named entity recognition, disambiguation, parsing, tagging and machine translation.\nhttps://code.google.com/p/word2vec/\n\nSpark implements the Skip-gram approach. With Skip-gram we want to predict a window of words given a single word.\n\nIt was recently shown that the word vectors capture many linguistic regularities, for example vector operations vector('Paris') - vector('France') + vector('Italy') results in a vector that is very close to vector('Rome'), and vector('king') - vector('man') + vector('woman') is close to vector('queen') [3, 1].\n\n\n## Data set\nWikipedia dump http://mattmahoney.net/dc/textdata \n`grep -o -E '\\w+(\\W+\\w+){0,15}' text8 > text8_lines` \nthen randomly sampled to ~200k lines\n\n\n\n\n```pyspark\nfrom pyspark.mllib.feature import Word2Vec\n\ntextpath = '/user/fcheung/text8_linessmall'\ninp = sc.textFile(textpath).map(lambda row: row.split(\" \"))\n\nword2vec = Word2Vec()\nmodel = word2vec.fit(inp)\n\n# This takes a while....\n```\n\n\n```pyspark\nsynonyms = model.findSynonyms('car', 40)\n\nfor word, cosine_distance in synonyms:\n print \"{}: {}\".format(word, cosine_distance)\n\n```\n\n driver: 0.717452287674\n accident: 0.540586173534\n pilot: 0.534710288048\n cable: 0.533736109734\n flying: 0.524660527706\n marlin: 0.52224111557\n slim: 0.515641212463\n revolver: 0.512815892696\n launched: 0.512356519699\n serie: 0.511943757534\n racing: 0.507736027241\n geoff: 0.507051408291\n mickey: 0.502854526043\n engined: 0.496125161648\n miniaturized: 0.495229810476\n harrier: 0.49293076992\n mclaren: 0.490967661142\n rf: 0.48476678133\n fighter: 0.482738018036\n passenger: 0.480480760336\n bomb: 0.476699143648\n mctaggart: 0.474561154842\n chase: 0.473450392485\n race: 0.472357422113\n crash: 0.472341090441\n kirby: 0.472037523985\n drunken: 0.471260607243\n window: 0.470358043909\n raf: 0.470099359751\n button: 0.466545432806\n factory: 0.46252438426\n killer: 0.462217181921\n shot: 0.461643457413\n trainer: 0.459573149681\n jockey: 0.456390231848\n runner: 0.454748958349\n mario: 0.454734921455\n lane: 0.453607857227\n singh: 0.453275740147\n debuts: 0.451825499535\n\n\n\n```pyspark\nvalues = map(lambda x: x[1], synonyms)\nlabels = map(lambda x: x[0], synonyms)\nplt.barh(range(len(values)), values, color='blue')\nplt.yticks(range(len(values)), labels)\nplt.show()\n\n```\n\n\n```pyspark\nfrom wordcloud import WordCloud, STOPWORDS\n\nwords = \" \".join([x[0] for x in synonyms for times in range(0, int(x[1]*10))])\n \nwordcloud = WordCloud(font_path='/home/fcheung/CabinSketch-Bold.ttf',\n stopwords=STOPWORDS,\n background_color='white',\n width=1800,\n height=1400\n ).generate(words)\n \nplt.imshow(wordcloud)\nplt.axis('off')\nplt.show()\n```\n\n#### wordcloud package uses PIL/Image\n\n\n\n```pyspark\n\n```\n", "meta": {"hexsha": "07543e776391353a842bbc123cc30d691cb21159", "size": 163740, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPython_notebook/IPythonPySpark.ipynb", "max_stars_repo_name": "bezosjeff/spark-notebook-examples", "max_stars_repo_head_hexsha": "69ddf849618b39ab0779edeb36b608d013d1847c", "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": "IPython_notebook/IPythonPySpark.ipynb", "max_issues_repo_name": "bezosjeff/spark-notebook-examples", "max_issues_repo_head_hexsha": "69ddf849618b39ab0779edeb36b608d013d1847c", "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": "IPython_notebook/IPythonPySpark.ipynb", "max_forks_repo_name": "bezosjeff/spark-notebook-examples", "max_forks_repo_head_hexsha": "69ddf849618b39ab0779edeb36b608d013d1847c", "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": 168.6302780639, "max_line_length": 106406, "alphanum_fraction": 0.8852021497, "converted": true, "num_tokens": 4488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.20434190962774396, "lm_q1q2_score": 0.0749096495981546}} {"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# QAOA: Max-Cut\n\n\n \n \n \n \n
\n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\nIn this tutorial, we implement the quantum approximate optimization algorithm (QAOA) for determining the Max-Cut of the Bristlecone processor's hardware graph (with random edge weights). To do so, we will:\n\n1. Define a random set of weights over the hardware graph.\n2. Construct a QAOA circuit using Cirq.\n3. Calculate the expected value of the QAOA cost function.\n4. Create an outer loop optimization to minimize the cost function.\n5. Compare cuts found from QAOA with random cuts.\n\n\n```\ntry:\n import cirq\nexcept ImportError:\n print(\"installing cirq...\")\n !pip install --quiet cirq\n print(\"installed cirq.\")\n```\n\n## 1. Defining a random set of weights over the hardware graph\nIn order to make the problem easily embeddable on a quantum device, we will look at the problem of Max-Cut on the same graph that the device's qubit connectivity defines, but with random valued edge weights.\n\n\n```\nimport cirq\nimport sympy\nimport numpy as np\nimport matplotlib.pyplot as plt\nworking_device = cirq.google.Bristlecone\nprint(working_device)\n```\n\n (0, 5)────(0, 6)\n │ │\n │ │\n (1, 4)───(1, 5)────(1, 6)────(1, 7)\n │ │ │ │\n │ │ │ │\n (2, 3)───(2, 4)───(2, 5)────(2, 6)────(2, 7)───(2, 8)\n │ │ │ │ │ │\n │ │ │ │ │ │\n (3, 2)───(3, 3)───(3, 4)───(3, 5)────(3, 6)────(3, 7)───(3, 8)───(3, 9)\n │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │\n (4, 1)───(4, 2)───(4, 3)───(4, 4)───(4, 5)────(4, 6)────(4, 7)───(4, 8)───(4, 9)───(4, 10)\n │ │ │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │ │ │\n (5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4)───(5, 5)────(5, 6)────(5, 7)───(5, 8)───(5, 9)───(5, 10)───(5, 11)\n │ │ │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │ │ │\n (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5)────(6, 6)────(6, 7)───(6, 8)───(6, 9)───(6, 10)\n │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │\n (7, 2)───(7, 3)───(7, 4)───(7, 5)────(7, 6)────(7, 7)───(7, 8)───(7, 9)\n │ │ │ │ │ │\n │ │ │ │ │ │\n (8, 3)───(8, 4)───(8, 5)────(8, 6)────(8, 7)───(8, 8)\n │ │ │ │\n │ │ │ │\n (9, 4)───(9, 5)────(9, 6)────(9, 7)\n │ │\n │ │\n (10, 5)───(10, 6)\n\n\nSince a circuit covering the entire Bristlecone device cannot be easily simulated, a small subset of the device graph will be used instead.\n\n\n```\nimport networkx as nx\n\n# Set the seed to determine the problem instance.\nnp.random.seed(seed=11)\n\n# Identify working qubits from the device.\ndevice_qubits = working_device.qubits\nworking_qubits = sorted(device_qubits)[:12]\n\n# Populate a networkx graph with working_qubits as nodes.\nworking_graph = nx.Graph()\nfor qubit in working_qubits:\n working_graph.add_node(qubit)\n\n# Pair up all neighbors with random weights in working_graph.\nfor qubit in working_qubits:\n for neighbor in working_device.neighbors_of(qubit):\n if neighbor in working_graph:\n # Generate a randomly weighted edge between them. Here the weighting\n # is a random 2 decimal floating point between 0 and 5.\n working_graph.add_edge(\n qubit, neighbor, weight=np.random.randint(0, 500) / 100\n )\n\nnx.draw_circular(working_graph, node_size=1000, with_labels=True)\nplt.show()\n```\n\n## 2. Construct the QAOA circuit\nNow that we have created a Max-Cut problem graph, it's time to generate the QAOA circuit following [Farhi et al.](https://arxiv.org/abs/1411.4028). For simplicity $p = 1$ is chosen.\n\n\n```\nfrom cirq.contrib.svg import SVGCircuit\n\n# Symbols for the rotation angles in the QAOA circuit.\nalpha = sympy.Symbol('alpha')\nbeta = sympy.Symbol('beta')\n\nqaoa_circuit = cirq.Circuit(\n # Prepare uniform superposition on working_qubits == working_graph.nodes\n cirq.H.on_each(working_graph.nodes()),\n\n # Do ZZ operations between neighbors u, v in the graph. Here, u is a qubit,\n # v is its neighboring qubit, and w is the weight between these qubits.\n (cirq.ZZ(u, v) ** (alpha * w['weight']) for (u, v, w) in working_graph.edges(data=True)),\n\n # Apply X operations along all nodes of the graph. Again working_graph's\n # nodes are the working_qubits. Note here we use a moment\n # which will force all of the gates into the same line.\n cirq.Moment(cirq.X(qubit) ** beta for qubit in working_graph.nodes()),\n \n # All relevant things can be computed in the computational basis.\n (cirq.measure(qubit) for qubit in working_graph.nodes()),\n)\nSVGCircuit(qaoa_circuit)\n```\n\n findfont: Font family ['Arial'] not found. Falling back to DejaVu Sans.\n\n\n\n\n\n \n\n \n\n\n\n## 3. Calculating the expected value of the QAOA cost Hamiltonian\nNow that we have created a parameterized QAOA circuit, we need a way to calculate expectation values of the cost Hamiltonian. For Max-Cut, the cost Hamiltonian is\n\n$$\n H_C = \\frac{1}{2} \\sum_{\\langle i, j\\rangle} w_{ij} (1 - Z_i Z_j )\n$$\n\nwhere $\\langle i, j \\rangle$ denotes neighboring qubits, $w_{ij}$ is the weight of edge $ij$, and $Z$ is the usual Pauli-$Z$ matrix. The expectation value of this cost Hamiltonian is $\\langle \\alpha, \\beta | H_C | \\alpha, \\beta \\rangle$ where $|\\alpha, \\beta\\rangle$ is the quantum state prepared by our `qaoa_circuit`. This is the cost function we need to estimate.\n\n> Pauli-$Z$ has eigenvalues $\\pm 1$. If qubits $i$ and $j$ are in the same eigenspace, then $\\langle Z_i Z_j \\rangle = 1$ and so $\\frac{1}{2} w_{ij} \\langle 1 - Z_i Z_j \\rangle = 0$. In the Max-Cut language, this means that edge $ij$ does not contribute to the cost. If qubits $i$ and $j$ are in the opposite eigenspace, then $\\langle Z_i Z_j \\rangle = -1$ and so $\\frac{1}{2} w_{ij} \\langle 1 - Z_i Z_j \\rangle = w_{ij}$. In the Max-Cut language, this means that edge $ij$ contributes its weight $w_{ij}$ to the cost. \n\nTo estimate the cost function, we need to estimate the (weighted) sum of all $ZZ$ pairs in the graph. Since these terms are diagonal in the same basis (namely, the computational basis), they can measured simultaneously. Given a set of measurements (samples), the function below estimates the cost function.\n\n> *Note*: We say \"estimate the cost\" instead of \"compute the cost\" since we are sampling from the circuit. This is how the cost would be evaluated when running QAOA on a real quantum processor.\n\n\n```\ndef estimate_cost(graph, samples):\n \"\"\"Estimate the cost function of the QAOA on the given graph using the\n provided computational basis bitstrings.\"\"\"\n cost_value = 0.0\n\n # Loop over edge pairs and compute contribution.\n for u, v, w in graph.edges(data=True):\n u_samples = samples[str(u)]\n v_samples = samples[str(v)]\n\n # Determine if it was a +1 or -1 eigenvalue.\n u_signs = (-1)**u_samples\n v_signs = (-1)**v_samples\n term_signs = u_signs * v_signs\n\n # Add scaled term to total cost.\n term_val = np.mean(term_signs) * w['weight']\n cost_value += term_val\n\n return -cost_value\n```\n\nNow we can sample from the `qaoa_circuit` and use `estimate_expectation` to calculate the expectation value of the cost function for the circuit. Below, we use arbitrary values for $\\alpha$ and $\\beta$.\n\n\n```\nalpha_value = np.pi / 4\nbeta_value = np.pi / 2\nsim = cirq.Simulator()\n\nsample_results = sim.sample(\n qaoa_circuit, \n params={alpha: alpha_value, beta: beta_value}, \n repetitions=20_000\n)\nprint(f'Alpha = {round(alpha_value, 3)} Beta = {round(beta_value, 3)}')\nprint(f'Estimated cost: {estimate_cost(working_graph, sample_results)}')\n```\n\n Alpha = 0.785 Beta = 1.571\n Estimated cost: -0.22279300000000013\n\n\n## 4. Outer loop optimization\nNow that we can compute the cost function, we want to find the optimal cost. There are lots of different techniques to choose optimal parameters for the `qaoa_circuit`. Since there are only two parameters here ($\\alpha$ and $\\beta$), we can keep things simple and sweep over incremental pairings using `np.linspace` and track the minimum value found along the way.\n\n\n```\n# Set the grid size = number of points in the interval [0, 2π).\ngrid_size = 5\n\nexp_values = np.empty((grid_size, grid_size))\npar_values = np.empty((grid_size, grid_size, 2))\n\nfor i, alpha_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)):\n for j, beta_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)):\n samples = sim.sample(\n qaoa_circuit,\n params={alpha: alpha_value, beta: beta_value},\n repetitions=20000\n )\n exp_values[i][j] = estimate_cost(working_graph, samples)\n par_values[i][j] = alpha_value, beta_value\n```\n\nWe can now visualize the cost as a function of $\\alpha$ and $\\beta$.\n\n\n```\nplt.title('Heatmap of QAOA Cost Function Value')\nplt.xlabel(r'$\\alpha$')\nplt.ylabel(r'$\\beta$')\nplt.imshow(exp_values);\n```\n\nThis heatmap is coarse because we selected a small `grid_size`. To see more detail in the heatmap, one can increase the `grid_size`. \n\n## 5. Compare cuts\n\nWe now compare the optimal cut found by QAOA to a randomly selected cut. The helper function draws the `working_graph` and colors nodes in different sets different colors. Additionally, we print out the cost function for the given cut.\n\n\n```\ndef output_cut(S_partition):\n \"\"\"Plot and output the graph cut information.\"\"\"\n\n # Generate the colors.\n coloring = []\n for node in working_graph:\n if node in S_partition:\n coloring.append('blue')\n else:\n coloring.append('red')\n\n # Get the weights\n edges = working_graph.edges(data=True)\n weights = [w['weight'] for (u,v, w) in edges]\n\n nx.draw_circular(\n working_graph,\n node_color=coloring,\n node_size=1000,\n with_labels=True,\n width=weights)\n plt.show()\n size = nx.cut_size(working_graph, S_partition, weight='weight')\n print(f'Cut size: {size}')\n```\n\nAs an example, we can test this function with all nodes in the same set, for which the cut size should be zero.\n\n\n```\n# Test with the empty S and all nodes placed in T.\noutput_cut([])\n```\n\nTo get cuts using the QAOA we will first need to extract the best control parameters found during the sweep:\n\n\n```\nbest_exp_index = np.unravel_index(np.argmax(exp_values), exp_values.shape)\nbest_parameters = par_values[best_exp_index]\nprint(f'Best control parameters: {best_parameters}')\n```\n\n Best control parameters: [3.14159265 6.28318531]\n\n\nEach bitstring can be seen as a candidate cut in the graph. The qubits that measured 0 correspond to that qubit being in one cut partition and a qubit that measured to 1 corresponds to that qubit being in the other cut partition. Now that we've found good parameters for the `qaoa_circuit`, we can just sample some bistrings, iterate over them and pick the one that gives the best cut:\n\n\n```\n# Number of candidate cuts to sample.\nnum_cuts = 100\ncandidate_cuts = sim.sample(\n qaoa_circuit,\n params={alpha: best_parameters[0], beta: best_parameters[1]},\n repetitions=num_cuts\n)\n\n# Variables to store best cut partitions and cut size.\nbest_qaoa_S_partition = set()\nbest_qaoa_T_partition = set()\nbest_qaoa_cut_size = -np.inf\n\n# Analyze each candidate cut.\nfor i in range(num_cuts):\n candidate = candidate_cuts.iloc[i]\n one_qubits = set(candidate[candidate==1].index)\n S_partition = set()\n T_partition = set()\n for node in working_graph:\n if str(node) in one_qubits:\n # If a one was measured add node to S partition.\n S_partition.add(node)\n else:\n # Otherwise a zero was measured so add to T partition.\n T_partition.add(node)\n\n cut_size = nx.cut_size(\n working_graph, S_partition, T_partition, weight='weight')\n \n # If you found a better cut update best_qaoa_cut variables.\n if cut_size > best_qaoa_cut_size:\n best_qaoa_cut_size = cut_size\n best_qaoa_S_partition = S_partition\n best_qaoa_T_partition = T_partition\n```\n\nThe QAOA is known to do just a little better better than random guessing for Max-Cut on 3-regular graphs at `p=1`. You can use very similar logic to the code above, but now instead of relying on the QAOA to decied your `S_partition` and `T_partition` you can just pick then randomly:\n\n\n```\nimport random\n\nbest_random_S_partition = set()\nbest_random_T_partition = set()\nbest_random_cut_size = -9999\n\n# Randomly build candidate sets.\nfor i in range(num_cuts):\n S_partition = set()\n T_partition = set()\n for node in working_graph:\n if random.random() > 0.5:\n # If we flip heads add to S.\n S_partition.add(node)\n else:\n # Otherwise add to T.\n T_partition.add(node)\n\n cut_size = nx.cut_size(\n working_graph, S_partition, T_partition, weight='weight')\n \n # If you found a better cut update best_random_cut variables.\n if cut_size > best_random_cut_size:\n best_random_cut_size = cut_size\n best_random_S_partition = S_partition\n best_random_T_partition = T_partition\n```\n\n\n```\nprint('-----QAOA-----')\noutput_cut(best_qaoa_S_partition)\n\nprint('\\n\\n-----RANDOM-----')\noutput_cut(best_random_S_partition)\n```\n\nFor this problem instance, one should see that $p = 1$ QAOA performs better, on average, than randomly guessing.\n", "meta": {"hexsha": "c1c2673b740b77e964dfab491d6f6d592ef35b2b", "size": 225388, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/qaoa.ipynb", "max_stars_repo_name": "alex-treebeard/Cirq", "max_stars_repo_head_hexsha": "10594c0edf7a4c26d5d21f985c6dc391197d3075", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-05T19:47:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T19:47:55.000Z", "max_issues_repo_path": "docs/tutorials/qaoa.ipynb", "max_issues_repo_name": "rohitvuppala/Cirq", "max_issues_repo_head_hexsha": "0ff2894e053e4ce3bb1b54e9b9de1cc4345d10b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-01-11T10:35:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T19:17:02.000Z", "max_forks_repo_path": "docs/tutorials/qaoa.ipynb", "max_forks_repo_name": "rohitvuppala/Cirq", "max_forks_repo_head_hexsha": "0ff2894e053e4ce3bb1b54e9b9de1cc4345d10b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-30T21:50:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T21:50:00.000Z", "avg_line_length": 301.320855615, "max_line_length": 42228, "alphanum_fraction": 0.8792482297, "converted": true, "num_tokens": 4191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.1755380649971796, "lm_q1q2_score": 0.07483566998122564}} {"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 8\n\n## Transformada de Laplace de una integral de convolución\n\nQueremos obtener:\n\n$$\n\\mathcal{L} \\left\\{ \\int_{-\\tau}^0 G(\\theta) x(\\tau + \\theta) d\\theta \\right\\}\n$$\n\nPodemos definir la integral de convolución para dos funciones continuas $f(t)$ y $g(t)$, tales que la convolución $(f*g)(t)$ es de la forma:\n\n$$\n(f*g)(t) = \\int_0^t f(t - \\tau) g(\\tau) d\\tau\n$$\n\ny la transformada de Laplace de esta integral de convolución es:\n\n$$\n\\mathcal{L} \\left\\{ (f*g)(t) \\right\\} = F(s)G(s)\n$$\n\npor lo que nos interesa poner nuestra integral original de manera que sea una integral de convolución.\n\nPodemos ver que al aplicar el cambio de variable $\\delta = \\theta + \\tau$, cuando $\\theta$ variaba de $-\\tau \\to 0$, $\\delta$ variará de $0 \\to \\tau$ y el diferencial $d\\theta$ es equivalente a $d\\delta$, por lo que nuestra integral quedará:\n\n$$\n\\mathcal{L} \\left\\{ \\int_{0}^{\\tau} G(\\delta - \\tau) x(\\tau + \\delta - \\tau) d\\delta \\right\\} = \\mathcal{L} \\left\\{ \\int_{0}^{\\tau} G(\\delta - \\tau) x(\\delta) d\\delta \\right\\}\n$$\n\ny etsa integral ya es de la forma de la integral de convolución, por lo que podemos escribirla como:\n\n$$\n\\mathcal{L} \\left\\{ (G*x)(t) \\right\\} = G(s) x(s)\n$$\n\n## Diseño de un controlador predictivo para un sistema con retardo en la entrada\n\nDado el sistema con retardo en la entrada:\n\n$$\n\\dot{x}(t) = A x(t) + B u(t - h)\n$$\n\n$$\ny(t) = C x(t)\n$$\n\nEmpezaremos creando un modelo sin retardo para el diseño del controlador predictor de Smith. Si logramos diseñar un controlador $C(s)$ que estabilice de manera aceptable al sistema sin retardos, podremos diseñar otro $\\tilde{C}(s)$ que tenga el mismo comportamiento agregado el efecto del retardo.\n\n\n\nen donde $\\tilde{C}(s)$ será de la forma:\n\n\n\nes decir:\n\n$$\n\\tilde{C}(s) = \\frac{C(s)}{1 + C(s) \\hat{G}(s) \\left( 1 - e^{-sh} \\right)}\n$$\n\nen donde $\\hat{G}(s)$ es la parte de la función de transferencia del sistema que no incluye al retardo. Por lo que nuestra primera tarea es encontrar la función de transferencia para nuestro sistema sin el efecto del retardo.\n\nConsideremos pues el sistema\n\n$$\n\\dot{x}(t) = A x(t) + B u(t)\n$$\n\n$$\ny(t) = C x(t)\n$$\n\npara el cual la función de transferencia se puede obtener por la siguiente ecuación:\n\n$$\n\\hat{G}(s) = C \\left( sI - A \\right)^{-1} B\n$$\n\ncabe mencionar que la función de transferencia para el sistema con retardo es:\n\n$$\nG(s) = C \\left( sI - A \\right)^{-1} B e^{-sh}\n$$\n\npor lo que en efecto $\\hat{G}(s)$ es la parte de la función de transferencia del sistema sin el efecto del retardo:\n\n$$\nG(s) = \\hat{G}(s) e^{-sh}\n$$\n\n\n```python\n# Se importan las librerias para calculo simbolico\nfrom IPython.display import display\n\nfrom sympy import var, simplify, collect, expand, solve, sin, cos, Matrix, eye, diff, Function, expand_power_base\nfrom sympy.physics.mechanics import mlatex, mechanics_printing\nmechanics_printing()\n```\n\n\n```python\n%matplotlib inline\nfrom matplotlib.pyplot import plot, style, figure, legend\nstyle.use(\"ggplot\")\n```\n\n\n```python\nfrom control import tf, step, pade, acker, ss, feedback\nfrom numpy import linspace, matrix, eye\n```\n\n\n```python\nvar(\"s\")\n```\n\nEmpezaremos con el sistema $A_1 = \\begin{pmatrix} 0 & 1 \\\\ 0 & 0 \\end{pmatrix}$, $B_1 = \\begin{pmatrix} 0 \\\\ 1 \\end{pmatrix}$, $C_1 = \\begin{pmatrix} 1 & 0 \\end{pmatrix}$ y $h = 1$.\n\n\n```python\nA1 = Matrix([[0, 1], [0, 0]])\nB1 = Matrix([[0], [1]])\nC1 = Matrix([[1, 0]])\n\nG1 = (C1*(s*eye(2) - A1).inv()*B1)[0]\nG1\n```\n\n\n```python\nt = linspace(0, 10, 100)\nt.max()\n```\n\nPodemos notar que la función de transferencia de este sistema es:\n\n$$\nG(s) = \\frac{1}{s^2}\n$$\n\n\n```python\n# Convertimos las matrices simbolicas en matrices de tipo numerico\nA1 = matrix(A1.tolist(), dtype=float)\nB1 = matrix(B1.tolist(), dtype=float)\nC1 = matrix(C1.tolist(), dtype=float)\n```\n\nPara obtener dos polos en $-1$ podemos usar la función ```acker()``` para obtener las ganancias de nuestro controlador PD, el cual utilizaremos para estabilizar nuestro sistema.\n\n\n```python\nk1 = acker(A1, B1, (-1, -1))\nk1\n```\n\n\n\n\n matrix([[ 1., 2.]])\n\n\n\nDefinimos una función que calculará todos los controladores que deseamos, segun la ecuación que ya dimos:\n\n$$\n\\tilde{C}(s) = \\frac{C(s)}{1 + C(s) \\hat{G}(s) \\left( 1 - e^{-sh} \\right)}\n$$\n\nAl final gráfica la respuesta del sistema con y sin efecto del retardo, asi como con y sin controlador.\n\n\n```python\ndef smith_predictor(A, B, C, D, k, tau=1, t=(0, 10)):\n '''Predictor de Smith\n \n Esta función toma los arreglos A, B, C, D de un sistema con retardo en la entrada\n y crea un controlador PD con los valores de k = [kp, kd] que estabiliza al sistema\n sin retardos. Ademas crea un controlador que estabiliza al sistema con retardo,\n dada la condición de que este sistema sea estable, y grafica la salida de los\n con y sin realimentación y con y sin retardo tau del tiempo t0 al tiempo t1\n especificados en t = (t0, t1).\n \n Ejemplo\n -------\n >>> A1 = [[0, 1], [0, 0]]\n >>> B1 = [[0], [1]]\n >>> C1 = [[1, 0]]\n >>> D1 = 0\n >>> tau1 = 1\n >>> t = (0, 10)\n >>> smith_predictor(A1, B1, C1, D1, [1, 2], tau, t)\n '''\n from control import ss, tf, pade, step, feedback\n from numpy import linspace\n from matplotlib.pyplot import figure, plot, legend\n \n kp, kd = k\n ts = linspace(t[0], t[1], 1000)\n \n sis = ss(A, B, C, D)\n cont = tf([kd, kp], [0, 1])\n \n num, den = pade(T=tau, n=10)\n delay = tf(num, den)\n \n delcont = ((1 - delay)*sis)\n \n y, t1 = step(sis, ts)\n yd, td = step(sis*delay, ts)\n ycont, tcont = step((cont*sis).feedback(), ts)\n ycontdel, tcontdel = step(feedback(feedback(cont, delcont)*sis), ts)\n \n f = figure(figsize=(10, 6))\n\n p1, = plot(td, yd)\n p2, = plot(t1, y)\n p3, = plot(tcont, ycont)\n p4, = plot(tcontdel, ycontdel)\n\n ax = f.gca()\n ax.set_xlim(t[0] - 0.1, t[1])\n ax.set_ylim(-0.10*ycont.max(), 1.1*ycont.max())\n\n ax.set_ylabel(r\"$y(t)$\", fontsize=20)\n ax.set_xlabel(r\"$t$\", fontsize=20)\n\n legend([p1, p2, p3, p4],\n [r\"$G(s)$\",\n r\"$\\hat{G}(s)$\",\n r\"$\\hat{G}_F(s)$\",\n r\"$G_F(s)$\"], loc=4, fontsize=16);\n```\n\nPor lo que si le damos nuestro sistema con las ganancias deseadas, asi como el tiempo para el que nos interesa, y el retardo, tendremos:\n\n\n```python\nsmith_predictor(A1, B1, C1, 0, k=[3, 3], t=(0, 7), tau=1)\n```\n\nAhora definimos el sistema $A_2 = \\begin{pmatrix} 0 & 1 \\\\ -1 & 0 \\end{pmatrix}$, $B_2 = \\begin{pmatrix} 0 \\\\ 1 \\end{pmatrix}$, $C_2 = \\begin{pmatrix} 1 & 0 \\end{pmatrix}$ y $h = 1$.\n\n\n```python\nA2 = Matrix([[0, 1], [-1, 0]])\nB2 = Matrix([[0], [1]])\nC2 = Matrix([[1, 0]])\n\nG2 = (C2*(s*eye(2) - A2).inv()*B2)[0]\nG2\n```\n\nPor lo que la función de transferencia de este sistema es:\n\n$$\nG(s) = \\frac{1}{s^2 + 1}\n$$\n\n\n```python\n# Convertimos las matrices simbolicas en matrices de tipo numerico\nA2 = matrix(A2.tolist(), dtype=float)\nB2 = matrix(B2.tolist(), dtype=float)\nC2 = matrix(C2.tolist(), dtype=float)\n```\n\nPara obtener dos polos en $-1$ podemos usar la función ```acker()``` para obtener las ganancias de nuestro controlador PD.\n\n\n```python\nk2 = acker(A2, B2, (-1, -1))\nk2\n```\n\n\n\n\n matrix([[ 0., 2.]])\n\n\n\nY la respuesta del sistema es:\n\n\n```python\nsmith_predictor(A2, B2, C2, 0, k=[3, 3], t=(0, 8))\n```\n\nPuedes acceder a este notebook a traves de la página\n\nhttp://bit.ly/1wiwlpl\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/1wiwlpl\")\nimg.save(\"codigos/codigo8.jpg\")\n```\n", "meta": {"hexsha": "23939d712247a5b95139ee38d3f22af1316b8ba7", "size": 108519, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPythonNotebooks/Sistemas con retardo en la entrada/Tarea 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/Tarea 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/Tarea 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": 149.6813793103, "max_line_length": 48136, "alphanum_fraction": 0.8693316378, "converted": true, "num_tokens": 3292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.29098086006635987, "lm_q1q2_score": 0.07473319374649616}} {"text": "

Dinámica

\n

Capítulo 3: Cinemática y Cinética de partículas

\n

Movimiento parabólico

\n

2021/02

\n

MEDELLÍN - COLOMBIA

\n\n\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***Docente:*** Carlos Alberto Álvarez Henao, I.C. D.Sc.\n\n***e-mail:*** carlosalvarezh@gmail.com\n\n***skype:*** carlos.alberto.alvarez.henao\n\n***Linkedin:*** https://www.linkedin.com/in/carlosalvarez5/\n\n***github:*** https://github.com/carlosalvarezh/Dinamica\n\n***Herramienta:*** [Jupyter](http://jupyter.org/)\n\n***Kernel:*** Python 3.9\n\n\n***\n\n

Tabla de Contenidos

\n\n\n

\n \n

\n\n
Fuente: Wikipedia
\n\n## Movimiento parabólico\n\n### Introducción\n\nEl [movimiento parabólico](https://en.wikipedia.org/wiki/Projectile_motion) es el realizado por cualquier objeto cuya trayectoria describe una [parábola](https://en.wikipedia.org/wiki/Parabola), y que corresponde con la trayectoria ideal de un proyectil que se mueve en un medio que no ofrece resistencia al avance y que esté sujeto a un campo gravitatorio uniforme. El movimiento parabólico es un ejemplo de un movimiento realizado por un objeto en dos dimensiones o sobre un plano. Puede considerarse como la combinación de dos movimientos que son un [movimiento rectilíneo uniforme](https://es.wikipedia.org/wiki/Movimiento_rectil%C3%ADneo_uniforme), en la dirección horizontal ($\\longleftrightarrow$), y un [movimiento rectilíneo uniformemente acelerado](https://es.wikipedia.org/wiki/Movimiento_rectil%C3%ADneo_uniformemente_acelerado) en la dirección vertical ($\\updownarrow$).\n\n### Análisis cinemático\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\n\n
\n\n\n\n

Un 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***Solución analítica:***\n\n- ***Sistema de coordenadas*** Se establece el origen en el punto $A$, donde comienza la trayectoria de la partícula (saco). Se observa que la velocidad inicial del saco presenta dos componentes, donde $v_{Ax}=12m/s$ y $v_{Ay}=0$. La acelaración en todo el recorrido, entre $A$ y $B$, es de $a_y=-9.81 m/s^2$. También se observa que se cumple que $v_{Bx}=v_{Ax}=12m/s$ (por qué?). Con lo anterior, las tres incógnitas restantes son $v_{By}$, $R$, y el tiempo de vuelo $t_{AB}$.\n\n\n- ***Movimiento vertical $\\left(+\\uparrow \\right)$:*** Del enunciado, se conoce la distancia vertical $A-B$, que será $y_B=6m$\n\n$$y_B=y_A+v_{Ay}t_{AB}+\\frac{1}{2}a_ct_{AB}^2$$\n\nreemplazando valores se tiene\n\n$$0=6m+0 \\times t_{AB}+\\frac{1}{2}(-9.81m/s^2)t_{AB}^2$$\n\n$$t_{AB}=1.11 s$$\n\nUna vez calculado el tiempo, la distancia horizontal, $R$ se determina así:\n\n\n- ***Movimiento horizontal $\\left(\\underrightarrow{+}\\right)$:***\n\n$$x_B=x_A+v_{Ax}t_{AB}$$\n$$R=0+12m/s(1.11s)$$\n$$R=13.3m$$\n\n\n***Solución computacional:***\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sympy import *\nimport seaborn as sns\n\nt,R = symbols('t R')\ninit_printing(use_latex='mathjax')\n```\n\n\n```python\n# condiciones iniciales\nx0 = 0 # coordenada xA\ny0 = 6 # coordenada yA\nv0x = 12 # Veloc en A en la dirección x\nv0y = 0 # Veloc en A en la dirección y\ny = 0 # Altura final \nac = -9.81 # aceleración debida a la gravedad\n```\n\n\n```python\n# Ecuación del movimiento vertical\nyd2 = Eq(y, y0 + v0y * t + ac * t**2 / 2)\nyd2\n```\n\n\n```python\n# Resolviendo para t\ntiempo = solve(yd2,t)\nprint(\"El tiempo de caída de cada saco es de {0:6.4f} s\".format(tiempo[1]))\n```\n\n\n```python\ntiempo\n```\n\n\n```python\nxd2 = Eq(R, x0 + v0x * tiempo[0])\nxd2\n```\n\n\n```python\n# Ecuación del movimiento horizontal\nR = float(x0 + v0x * tiempo[0])\nprint(\"La distancia a la que caerá cada saco es de {0:6.4f} m\".format(R))\n```\n\n\n```python\n# Graficando\nt = np.linspace(0,np.around(float(tiempo[1]), decimals = 4),100)\n\nx = x0 + v0x * t\ny = y0 + v0y * t + ac * t**2 / 2\n\nplt.plot(x,y);\nplt.xlabel(\"x(m)\")\nplt.ylabel(\"y(m)\")\nplt.grid(True)\n```\n\n## Movimiento curvilíneo: Componentes normal y tangencial\n\n### Introducción\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\n\n
\n\n\n\n

Cuando 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- ***Sistema de coordenadas:***\n\nSe establece el origen de los ejes $n-t$ en el punto fijo $A$ de la trayectoria.\n\n\n- ***Velocidad:***\n\nComo se definió, la velocidad será siempre tangente a la trayectoria. Como $y = \\frac{1}{20}x^2$, su derivada es $\\frac{dy}{dx}=\\frac{1}{10}x$, reemplazando cuando $x=10m$, $\\frac{dy}{dx}=1$. Por lo tanto, en $A$, $\\boldsymbol{v}$ forma un ángulo $\\theta=\\tan^{-1}(1)=45^{\\circ}$ con el eje $x$. Con esto, la velocidad en $A$ es \n\n$$v_A=6m/s \\quad 45^{\\circ}\\measuredangle$$\n\n\n- ***Aceleración:***\n\nReemplazando las [Ecs. 3.7 y 3.8](#Ec3_7) en la [Ec. 3.6](#Ec3_6) para determinar la aceleración, se llega a:\n\n$$\\boldsymbol{a}=\\dot{v}\\boldsymbol{u}_t+\\frac{v^2}{\\rho}\\boldsymbol{u}_n$$\n\nDe esta ecuación se desconoce el radio de curvatura $\\rho$ de la trayectoria en el punto $A(10,5)$. Empleando la [Ec. 3.10](#Ec3.10) y reemplazando el valor de la coordenada:\n\n$$\\rho=\\frac{\\left[1 + (dy/dx)^2\\right]^{3/2}}{|d^2y/dx^2|}=\\left. \\frac{\\left[1 + (x/10)^2\\right]^{3/2}}{|1/10|} \\right|_{x=10m}=28.28m$$\n\n\nCon lo anterior, la dirección de la aceleración está dada por\n\n$$\n\\begin{align*}\n\\boldsymbol{a} & = \\dot{v} \\boldsymbol{u}_t + \\frac{v^2}{\\rho} \\boldsymbol{u}_n \\\\\n & = 2 \\boldsymbol{u}_t + \\frac{(6m/s)^2}{28.28m} \\boldsymbol{u}_n \\\\\n & = (2 \\boldsymbol{u}_t + 1.273 \\boldsymbol{u}_n) m/s^2\n\\end{align*}\n$$\n\ny cada una de las componentes se representan en la siguiente figura.\n\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$\\color{red}{\\textbf{Actividad para ser realizada por el estudiante:}}$\n\n
    \n
  • Realizar computacionalmente los otros ejemplos del capítulo que aparecen en el libro de Hibbeler, sección 12.7, ejemplos 12-15 y 12-16 (pags. 58 y 59).
  • \n\n\n
  • También se invita a que desarrollen al menos un ejercicio de los problemas fundamentales (pag. 60), y ejercicios de los problemas (pags. 61 - 67), dividiendolos en tres partes: dos ejercicios del tercio inferior, dos del tercio medio y dos del tercio superior, tanto analíticamente (\"a mano\") como computacionalmente.
  • \n
\n
\n\n## Movimiento curvilíneo: Componentes cilíndricos\n\n### Introducción\n\nEn ciertos problemas cuyo movimiento de la partícula describe una trayectoria curva, la descripción de dicho movimiento se describe de mejor forma (más simple) empleando un [sistema de coordenadas cilíndricas](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system). Si el movimiento se limita a un plano se emplea un [sistema de coordenadas polares](https://en.wikipedia.org/wiki/Polar_coordinate_system).\n\n### Coordenadas polares\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\n\n
\n\n\n\n

Debido 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- ***Sistema de coordenadas:***\nEsta trayectoria es muy rara, y matemáticamente se expresa mejor por medio de coordenadas polares, como se hace aquí, en lugar de coordenadas rectangulares. También, como $\\dot{theta}$ y $\\ddot{\\theta}$ deben determinarse, entonces las coordenadas $r$, $\\theta$ no son una opción obvia.\n\n- ***Velocidad y aceleración:***\n\nEmpleando la regla de la cadena para determinar las derivadas de $r$ y $\\theta$:\n\n\\begin{equation*}\n\\begin{split}\nr&=0.5(1-\\cos\\theta) \\\\\n\\dot{r}&=0.5(\\sin\\theta)\\dot{\\theta}\\\\\n\\ddot{r}&=0.5(\\cos\\theta)\\dot{\\theta}(\\dot{\\theta})+0.5(\\sin\\theta)\\ddot{\\theta}\n\\end{split}\n\\end{equation*}\n\nevaluando cuando $\\theta=180^{\\circ}$, se tiene\n\n$$r=1 pie \\quad\\quad \\dot{r}=0\\quad\\quad\\ddot{r}=-0.5\\dot{\\theta}^2$$\n\ncomo $v=4 pie/s$, utilizando la ecuación [(3.16)](#Ec3_16) para determinar $\\dot{\\theta}$ se tiene\n\n\\begin{equation*}\n\\begin{split}\nv&=\\sqrt{(\\dot{r})^2+(r\\dot{\\theta})^2} \\\\\n4&=\\sqrt{(0)^2+(1\\dot{\\theta})^2}\\\\\n\\dot{\\theta}&=4rad/s \n\\end{split}\n\\end{equation*}\n\nAhora calculando $\\ddot{\\theta}$, empleando la ecuacion [3.21](#Ec3_21)\n\n\\begin{equation*}\n\\begin{split}\na&=\\sqrt{(\\ddot{r}-r\\dot{\\theta}^2)^2+(r\\ddot{\\theta}+2\\dot{r}\\dot{\\theta})^2} \\\\\n30&=\\sqrt{[-0.5(4)^2-1(4)^2]^2+[1\\ddot{\\theta}+2(0)(4)]^2}\\\\\n(30)^2&=(-24)^2+\\ddot{\\theta}^2 \\\\\n\\ddot{\\theta}&=18rad/s^2\n\\end{split}\n\\end{equation*}\n\n- ***Solución computacional:***\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sympy import *\nfrom sympy.physics.mechanics import dynamicsymbols, init_vprinting\n\ntheta = dynamicsymbols(r'\\theta')\nt = Symbol('t')\n\ninit_vprinting()\n```\n\nGraficando primero la funcion cardioide\n\n\n```python\nphi = np.linspace(0, 2*np.pi, 1000)\n\nr = 0.5 * (1 - np.cos(phi))\nplt.polar(phi, r, 'r')\nplt.show()\n\n```\n\nAhora obtenemos los valores de $\\dot{r}$ y $\\ddot{r}$\n\n\n```python\nr = 0.5 * (1 - cos(theta))\nrdot = diff(r, t)\nrdot\n```\n\n\n```python\nrddot = diff(rdot, t)\nrddot\n```\n\nEvaluando los anteriores resultados cuando $\\theta=180^{\\circ}$\n\n\n```python\nrN = r.subs(theta, 180 * pi / 180)\nrN\n```\n\n\n```python\nrdotN = rdot.subs(theta, 180 * pi / 180)\nrdotN\n```\n\n\n```python\nrddotN = rddot.subs(theta, 180 * pi / 180)\nrddotN\n```\n\nAhora vamos a determinar el valor numérico para $\\dot{\\theta}$, cuando $v=4pie/s$\n\n\n```python\nthetadot = N(Eq(4, sqrt(rdotN**2 + (rN * theta)**2)))\nthetadot\n```\n\n\n```python\nthetadot = solve(thetadot,theta)\nthetadot\n```\n", "meta": {"hexsha": "c08b12771e76e6239d49dfb71ef825bb6d135975", "size": 55957, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "C03_CinematicaCineticaParticulas_MovParabolico.ipynb", "max_stars_repo_name": "carlosalvarezh/Dinamica", "max_stars_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "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": "C03_CinematicaCineticaParticulas_MovParabolico.ipynb", "max_issues_repo_name": "carlosalvarezh/Dinamica", "max_issues_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "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": "C03_CinematicaCineticaParticulas_MovParabolico.ipynb", "max_forks_repo_name": "carlosalvarezh/Dinamica", "max_forks_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-28T18:47:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T18:47:37.000Z", "avg_line_length": 38.9401530967, "max_line_length": 4297, "alphanum_fraction": 0.586986436, "converted": true, "num_tokens": 12380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.16667540054859167, "lm_q1q2_score": 0.07425881370894859}} {"text": "# Focal Loss for Dense Object Detection\n\n\nFollow [Andrew Ng's](https://www.youtube.com/watch?v=733m6qBH-jI&list=PLoROMvodv4rOABXSygHTsbvUz4G_YQhOb&index=9&t=0s) suggested strategy of multiple passes over a paper. Namely:\n\n\n1. Title, Abstract and Figures\n2. Intro/Conclusion and Skim the rest (Skipping related work)\n3. Read All Remaining Sections (however Skip the maths)\n4. Read Everything (but skip the parts that don't make sense)\n\nAfter some background reading (medium posts, blog posts, other papers, youtube videos from [cs231 2016](https://www.youtube.com/watch?v=GxZrEKZfW2o&t=3s) [cs231 2017](https://www.youtube.com/watch?v=nDPWywWRIRo&t=3909s)), I have made notes below following each pass.\n\n## Title, Abstract and Figures\n\n### Title\nFocal Loss for Dense Object Detection\nComments: \n\nWhat is `Focal Loss`? A new type of loss function called focal loss is introduced in this paper.\n\nWhat is `Dense Object Detection`? Dense object detection is looking for objects in the same image over many densely covered spatial positions, scales and aspect ratios - it is one stage detection approach. \n\n### Abstract\n\n**Comments**\n\nObject detection is a task of finding bounding boxes for zero of more instances of predefined classes on an image. The bounding box is a rectangle that locates and bounds the instance of a class. A solution which does this is called an object detector.\n\nHere is an example:\n\n\n\nThere are two classes of object detection algorithm that are state of the art on competing metrics - namely:\n\n1. Dense object detection performs at the state of the art level of performance, as measured by an accuracy metric: average precision (area under precision recall curve - for different classification thresholds).\n\n\n\n2. Sparse object detection performs at the state of the art level of performance, as measured by speed of prediction on test cases, for a respectable level but not excellent of performance of accuracy on the average precision metric.\n\n\n\n```\nAside: The dense object detection approach is for one stage learning models - those that do proposal, classification, and localization in one shot - such as OverFeat, SSD or YOLO - many (dense) blind possibly overlapping candidate boxes are made and fitted over a grid.\n\nThe sparse object detection approach is a two step approach - where first regions that may contain an object are proposed and then these boxes are put through a classifier - some examples being R-CNN, Fast R-CNN, Faster R-CNN and Mask R-CNN.\n```\n\nThe first approach produces excellent results. However, the second approach provides a \n\n> In contrast, one-stage detectors that are applied\nover a regular, dense sampling of possible object locations\nhave the potential to be faster and simpler, but have trailed\nthe accuracy of two-stage detectors thus far.\n\n`Question: Simpler in what sense? Still very difficult to interpret or understand a sparse object detection model.`\n\nThe authors suggest that the paper identifies the reason for poor performance on sparse object detection. They claim that they are able to pinpoint the blame on *extremely unbalanced data* (no objects >> objects) occurring at training time. That is to say, dense detectors suffer from many more examples of no objects in boxes over an image than examples of boxes with images.\n\nThey have a way to address this imbalance. They notice that no object *boxes* are assigned much lower cost $-log(Pr($no object | box$))$ than $-log(Pr($class j | box$))$ - the probability of class (object) $j$ the classes of objects when they occur in boxes.\n\nEffectively, they are noticing an artifact that the probabilities of no object are more peaked than they should be and the probabilities of the object classes are flatter than they should be. \n\n`Idea: Could what the authors do be translated into applying a regularization or prior to make the optimizer prefer models with flatter no-object probability and more peaky object probabilities. Could we explicitly set the Bayesian prior to achieve the same result`\n\nThe authors view their algorithm as having a *focal loss* which focuses (by having a higher cost) on harder examples (examples with objects present - those with lower probabilities) and having less focus on easy negatives (examples with no object and higher probability - the no object class). They believe this alleviates the problem of the detector being overwhelmed by the imbalanced data, so that learning can still take place. \n\nTo see how well their loss does for dense objects detectors, the authors present a network they dub RetinaNet. Their results show that with the *focal loss* RetinaNet is as fast as the popular one stage detectors, and yet have accuracy (as measures by average precision) as good as the state of the art two stage detectors.\n\n### Figures\n\n#### Figure 1\n\nA graph showing how the proposed novel loss function - focal loss - has the desired properties of increasing cost for low probability values and reducing cost for high probability values. A hyperparameter $\\gamma$ is shown over a range of values. \n\nNote that the proposed loss function is pinned at the extremes of 0 loss for predicting with probability 1 the ground truth and shoots off to infinity asymptote as the probability of predicting the ground truth goes to 0.\n\n#### Figure 2\n\nThis is a plot of Speed vs accuracy (Average Precision) for RetinaNet with base feature extractor network as ResNet100 or ResNet50 compared to other popular competitive algorithms. It shows that RetinaNet is forms an upper enveloper over the other methods and so is superior in speed and accuracy vs the popular algorithms - with one exception. YOLOv2 is faster, but at a much lower accuracy than RetinaNet. \n\n#### Figure 3\nOutline of RetinaNet. The backbone of the network is a Feature Pyramid Network (FPN) - which allows the network to work at various scales. FPN receives inputs from a ConvNet Feature Extractor, and it is connected to two heads: a classifier for the anchor boxes, a regressor to fine tune the anchor boxes to get estimates for the bounding box - the ground truth boxes and IoU metric is used for this. The authors claim that this design is simple enough to allow the focal loss to show it's power.\n\n```\nQuestion: If the network as well as the loss function are being changed - then doesn't this make it hard to ensure the changes are orthogonal and not interfering and impacting the results?\n```\n\n#### Figure 4\n\nThis graph shows the q-q plot or CDF of normalized loss against the CDF of sample, for each of foreground(object) and background (no object) examples from the ResNet-101 predictions, at different values of gamma for Focal Loss (including Cross Entropy Loss).\n\nThis graph is used to identify that the loss on \n\n\n```\nnormalized loss: I guess this is the normalized cost function\nCDF to CDF - p-p plot.\n```\n\nActually, reading the section for this figure - I don't get this section well - there is the dataset, the model, some normalization of loss, splits into unbalanced foreground and background labels, quite a lot that needs to be teased out. I will come back to this on the third or fourth pass.\n\n\n#### Figure 5\n\nThis graph and the following two are used to show that a similar function to the Focal Loss (FL), $FL^*$ (which depends on a $\\beta$ as well as $\\gamma$ parameter) is close to FL. \n\n```\nThere is no proper rigorous analysis, but empirical results and plots - is this good enough?\n```\n\n\n#### Figure 6\n\nFigure 6 show the derivatives are similar in nature and magnitude for FL and $FL^*$.\n\n#### Figure 7\n\nThis shows the effective variations of the parameters $\\beta$ and $\\gamma$ such that the loss function has desired behavior. It also shows less desirable loss functions in light black lines vs the better loss functions in heavier blue lines.\n\n\n## Introduction and Conclusion\n\n### 1. Introduction\n\nThe benchmark data set for researchers working on the object detection task is MS COCO (or COCO).\n\nThe reference metric is AP (Average Precision).\n\n```\nNeed to find references and blog posts on AP\n```\n\nState Of The Art (SOTA) object detectors on the AP (average precision) metric are all from a family of sparse object detectors that rely on two stage (proposal then classification+localization) technologies. \n\nAlthough their performance is to be applauded (still not good enough for many production applications) these two stage detectors are quite slow - as measured in Frames Per Second, FPS.\n\nA promising direction has been the development of one stage detectors, they run one order of magnitude faster (7 FPS for `Faster R-CNN` two stage detector vs 21 FPS for `YOLO Fast` using VGG-16 as a CNN feature extractor). However the performance of one stage detectors has lagged significantly (73.2 - `Faster R-CNN` vs 66.4 `YOLO Fast` AP).\n\nThis paper introduces a few technologies that demonstrate a one stage detector with comparable speed to SOTA one stage detectors for speed and comparable AP as SOTA two stage detectors - what they call an upper envelope of performance. The authors assert that the main driver of this improved performance is their new loss function - which combats extremely imbalanced foreground/background data in one stage detectors. (The authors believe extremely imbalanced foreground/background data this to be the impediment to better one stage detector performance).\n\nAlthough two stage detectors also see class imbalance, it is less severe and can be remedied by:\n\n- sampling heuristics (fixing the imbalance ratio by sampling)\n- online hard example mining (OHEM is a technique applied inside a minibatch to only select *high loss function* examples from the minibatch forward pass and use them in the backward pass)\n\nImbalance is less of an issue for two stage detectors because the first stage proposals are chosen as very likely to have foreground objects - most two stage detectors only present 1-2k proposal regions. \n\nOne shot detectors need to deal with orders of magnitude more locations that can be overlapping densely covered with many aspect ratios. As a consequence imbalances of 1000 to 1 are normal in background/foreground object classes. At training time this imbalance dominates the loss function, enough that effective learning for the foreground object classes doesn't happen. \n\nStrategies like sampling and OHEM can help but are not as efficient because the training algorithm still concentrates weight changing efforts on the easily classified background examples - there are so many more background examples due to the imbalance.\n\nTypically treatment for this imbalance is to use:\n\n- bootstrapping the dataset to create a distribution of parameters and averaging the resultant probabilities.\n\n- hard example mining (produce many data augmented examples possibly via crops/reflections of mis-classifications from prior training -foregrounds predicted as backgrounds - so that algorithm becomes better at learning these mappings.)\n\n\nThe authors believe their novel loss function alleviates the imbalance problem - by down-weighting easy examples and up-weighting hard examples. The exact form of the loss function is not important - the authors show that similar functions work.\n\nTo show how good the focal loss function is, the authors produced a one stage learning algorithm with many state of the art innovations (FPN backbone, ResNet) - called RetinaNet. It's performance of 5 FPS and very good AP of 39.1 - by comparison YOLOv2 achieves 21.2 AP, with undocumented speed.\n\n### 6. Conclusion\n\nThe authors reiterate that the problem with one stage detector AP performance has been extreme background/foreground class imbalance. \n\nThey present a modulating term applied to the cross entropy loss to create a new focal loss function. They believe this is a high quality solution as it results a better detector. The authors are pleased with a new one stage detector network trained using this focal loss, one that is better on speed and accuracy metrics.\n\n\n## All Remaining Section (except the Mathematics)\n\n### 2. Related Work\n\n**Classic Object Detectors**\n\nThere have some old school object detectors, starting around 2001, including:\n\n**Viola-Jones** was the first set of algorithms to produce useful results for object detection - applied to face recognition. Essentially taking rectangles and matching them to eyes, cheeks, nose and mouth, features are extracted. Then a boosting algorithm of the adaBoost variety is applied to these features to detect faces. **LeCun's** seminal paper proposed sliding windows to detect characters. **Histogram of Oriented Gradients** of integral channels produced good results for pedestrian detection - essentially finding edges in images, again powered by sliding windows. With the onset of Deep Learning, these fell behind in SOTA performance. \n\n**Two Stage Detectors** have been suggested by some of the authors of this paper. They have pioneered innovations and improvements in this space. The main idea is to propose a smaller number of regions (relative to sliding windows) where the propasal step is done so each region has a high probability of having a foreground object class. Then a feature extractor CNN is used to get features and then a classifier and located at most one object class in each region proposal. \n\nThe first iteration of the methodology R-CNN using a fixed method - they used selective search algorithm was used for the region proposal, CNN feature extractor run on this and then SVMs used classify objects, and regression head to get the bounding boxes. However, this was slow.\n\nLater this improved by using the faster R-CNN algorithm. This would move things around a little and change the SVM. An image is processed by a CNN feature extractor, then the region proposal takes place, then this is fed into a CNN which outputs two heads - a classifier using a fully connected layer and a bounding box regression, both of which take the CNN as input.\n\nThis was still too slow for many applications. So, Faster R-CNN algorithm was proposed. With this algorithm, the region proposal step is also trained using a CNN, using a IoU criteria to train region finding - taking input from a CNN feature extractor network that is pre-trained. Then the rest follows as before for the fast R-CNN algorithm.\n\nThere have been several extensions since then to the same basic idea - first classify/set regions likely to have foreground objects, then classify and regress bounding boxes on them.\n\n**One Stage Detectors**\n\nOne stage detectors are all from the dense object detector family. They propose several orders of magnitude more regions - using anchors has been a key insight. Then they finesse the bounding boxes around these anchors and classify the object contained. Among those that have been suggested are:\n\n- OverFeat\n- SSD\n- YOLO\n\nThey all are highly performant on speed, but lag accuracy materially compared to two stage detectors.\n\nRetinaNet is a one stage detector taken from this family of dense detectors using FPN for the scaling to boost performance. It achieves higher accuracy and maintains speed by having the novel loss function - focal loss. \n\n**Class Imbalance**\n\nThe one stage detectors suffer from extreme imbalance, $~10^5$ regions. This poses two problems:\n\n- overwhelming the cost function at training time with easy negative (background) classifications \n- inefficient estimation as most regions produce no signal\n\n\nHard negative mining has been the traditional solution. Other more complex re-sampling strategies can be used.\n\nThe central theme of this paper, focal loss is shown to be good at dealing with such imbalance.\n\n**Robust Estimation**\n\nRobust Loss functions have been used to down-weight or reduce the influence of outliers - outliers being determined by their frequency in the data. This paper instead focuses on down-weighting or reducing the impact of easy examples - even if they are the majority of the imbalanced data. \n\n### 3. Focal Loss\n\nTraditional cross entropy loss is given in equation 1. It is the average number of bits needed to learn the outcome of a random draw from the true distribution. One can also think of it as a measure how different the true distribution q is from the distribution being used p.\n\nOne hot data vectors are used as instances to compute the cross entropy for data against a model distribution. Then this averaged cross entropy function is the cost function which is usually run through an optimization algorithm (often from the gradient descent family of optimizers) to find the best parameters that minimize the cost.\n\nBy minimizing the cross entropy function, we can get a best fit. This also reduces the NLL of MLEs for classifiers.\n\n#### 3.1 Balanced Cross Entropy\n\nAlthough the above is a good strategy, the reality is that sometimes we come across imbalanced data in classification tasks. For example our current case of dense object detection. What this imbalance does is make it very difficult for gradient descent algorithms to find a good local optima. The reason is that the class(es) with the highest frequency contribute so much more to the loss function, that they dominate the loss function and the other examples are not concentrated on enough by the loss function optimizer.\n\nUsually re-sampling strategies are run to artificially add more examples of the lower/least frequency classes. This can be done through:\n\n- over-sampling the lower frequency classes\n- under-sampling the higher frequency classes\n- setting a weight hyper-parameter to increase the contribution of the lower frequency classes and/or reduce the contribution of the higher frequency classes.\n\nEquation (3) lists the expression for the last of these strategies - in a compacted form.\n\n#### 3.2 Focal Loss Definition\n\nThe tunable focal loss equation is introduced in equations 4 (one parameter) and 5 (two parameter). Somewhat strange, but at training time an approximation to this is used.\n\nThe authors outline how the focal loss has the desired property of reducing the loss of misclassifying high probability classes (such as background) and increasing the loss of misclassifying more complicated examples.\n\n#### 3.3 Class Imbalance and Model Initialization\n\nWith extreme class imbalance of around $10^3-10^6$ to 1, the usual parameter initialization strategy for binary classification leads to unstable training early on for focal loss. The authors suggest instead giving initial conditions that corresponds to 0.01 probability for the foreground (lower frequency) class. They even call this a prior - which it doesn't feel like in a Bayesian sense - but given that neural networks can have many local optima - perhaps it is like a Bayesian prior, in that it impacts the parameter choices and final probability estimates.\n\n#### 3.4 Class Imbalance and Two Stage Detectors\n\nClass imbalance is less of an issue for two stage detectors because of the proposal layer, that filters for likely regions. There are still 1000-2000 proposal locations usually. Of these, again many will not have a foreground object. However, the regions are proposed to be much more likely to have a foreground object. This helps reduce the class imbalance. Secondly at training time, the minibatches are constructed to have reasonable ratios of classes - say 1:3, effectively re-sampling within the minibatches.\n\nThe authors note this is like re-weighting the terms of the loss function with a $\\alpha$ weight hyperparameter.\n\nBy contrast the focal loss function works at a different level of abstraction.\n\n```\nIt would have been interesting to see how focal loss does with two stage detectors.\n```\n\n### 4. RetinaNet Detector\n\n**Feature Pyramid Network**\nGiven a single image input resolution, it is normal that some objects are at very different scales to others. In that case, performance can be improved by having classification go through a range of scales. A Feature Pyramid Network is a collection of layers that achieves this. It works as follows:\n\n- lateral connections are made from the convolutional layers to each scale layer of the pyramid.\n\n- top down connections feed into the scale layers through the convolutions.\n\n- the scale layers connect to their own classification and box sub networks. \n\nThese then feed into the final set of classification and bounding box predictions.\n\nScale layer $P_l$ reduces input resolution by by a factor $2^l$.\n\n**Anchors**\n\nDefault boxes, or anchors are spaced out across the image data. They then assign to a K hot vector of classifications and probabilities and the bounding box regression. These anchors are presented at the various scales corresponding to the FPNs.\n\n**Classification Subnets**\n\nThis head predicts the classification probability for each of the classes for each anchor box.\n\n**Box Regression Subnet**\n\nThis finesses the anchors box to get the bounding box for each object in the anchor box.\n\n#### 4.1 Inference and Training\n\n**Inference**\n\nThis is a FCN with two heads per bounding box, a classification head and a bounding box regression head. The architecture includes the backbone FPN and a CNN extractor.\n\nTo improve speed of training, after some threshold only the top 1000 detected objects are used to continue training on. Non-max suppression is used when at a threshold of 0.5 to keep only the most promising predictions.\n\n**Focal Loss**\n\nThe authors found in their hyperparameter tuning that focal loss with $\\gamma = 2$, $\\alpha = 0.25$, worked best. They suggest reducing $\\alpha$ as $\\gamma$ is increased.\n\n**Initialization**\n\nThe hidden layers were initialized with the usual bias being 0 and small variance ($\\sigma=0.01$) random gaussian noise.\n\nFor the final layer of the classification head, the bias parameter is set as the inverse logit of 0.01. \n\n**Optimization**\n\nminibatch (16 images) stochastic gradient descent using GPUs is used to train RetinaNet for 90000 iterations and decaying learning parameter. Focal loss is used for the classification part and L1 loss for the bounding box regression. They trained for around 35 hours.\n\n\n### 5. Experiments\n\nTraining is done on 40k images with some randomized selection from the dataset. The test-dev set is found for data where no public labels are given and the test-dev features are tested and predicted on using an evaluation server.\n\n#### 5.1 Training Dense Detection\n\n**Network Initialization**\nIf the usual initialization techniques are used, the network diverges. However, the earlier outlined strategy of using the prior probs of 0.01 and inverse logit to get bias parameters of the final layer of the network, make it converge to good AP values. This is all for the cross entropy loss.\n\n**Balanced Cross Entropy**\n\nWeighted or balanced cross entropy loss with $\\alpha=0.9$ gives the best results.\n\n**Focal Loss**\nThe hyperparameter search worked as explained above. The table shows a range of values used.\n\n**Analysis of the Focal Loss**\n\nThis section is important as it shows that the FL reduces the loss for all but the most extreme negative background examples contribute to the FL over the dataset. That is, the majority of background easy classifications do not contribute very much to the loss function.\n\nI feel some other kind of chart could be used to indicate this - maybe plotting the cumulative loss function cumulatively against the probability estimate of the foreground and background classes.\n\n**Online Hard Example Mining**\n\nOHEM discards the easy examples and has the loss function optimized on the hard examples that were misclassified - this happens inside the gradient descent algorithm where examples are included or discarded. Note that focal loss still keeps the easy examples, but reduces their effect on the loss function. \n\nThe authors note that the AP was higher (better) for focal loss by 3.6 points than OHEM.\n\n**Hinge Loss**\n\nLin et al. tried to train with hinge loss - setting loss to zero after a certain threshold, but it didn't work producing unstable results that didn't converge. \n\n#### 5.2 Model Architecture Design\n\n**Anchor Density**\nHow high a density to have for for the anchors and possibly having the same anchor locations for different tall and wide boxes is not an exact science, but impacts performance a great deal for one stage detectors. The authors find that after a certain density, increasing the number and spread of anchors doesn't help performance.\n\n**Speed Vs Accuracy**\n\nFaster networks need smaller backbone networks. The speed accuracy tradeoff is show in the figures. it shows an upper envelope of better accuracy and faster speed compared to most models that are at the SOTA. \n\n\n### 5.3 Comparison to State of the Art\n\nThe authors reiterate their faster and more accurate model over a range of backbone networks. They show exact numbers.\n\n\n## Everything Else\n\n### Mathematics\n\n#### Equation 1\n\nUnder this binary regime either $y=1$ or $y=-1$ are the two classes.\n\n$$\n\\begin{equation}\n CE(p,y) = \\left \\{\n \\begin{aligned}\n &-\\log(p), && \\text{if}\\ y=1 \\\\\n &-\\log(1-p), && \\text{if}\\ y=-1 \n \\end{aligned} \\right.\n\\end{equation} \n$$\n\nThis is the equation for cross entropy loss for a binary classifier - it is the average number of bits needed under assumed probability distribution $p$ to identify an event drawn using the true distribution of $y$.\n\nThis is the natural loss function for binary classification and nicely links to MLE estimation/NLL cost function.\n\n#### Equation 2a\n\n$$\n\\begin{equation}\n p_t \\left \\{\n \\begin{aligned}\n & p, && \\text{if}\\ y=1 \\\\\n & 1-p, && \\text{if}\\ y=-1 \n \\end{aligned} \\right.\n\\end{equation} \n$$\n\nThis equation is a little odd because, there is no index or variable $t$ being referenced by the subscript. It might have been better to replace that with something $\\tilde{p} = \\tilde{p}(p,y)$, to keep a relation with p and indicate that it is transform of $p$ and $y$.\n\nOne way that it makes sense to keep the subscript t notation is if we were looking at multiclass classification. In that case,\n\n$$\n\\begin{equation}\n p_t \\left \\{\n \\begin{aligned}\n & p(y_t), && \\text{if}\\ y=y_t \\\\\n & 1-p(y_t), && \\text{if}\\ y \\neq y_t \n \\end{aligned} \\right.\n\\end{equation} \n$$\n\nHowever, even then this is messy notation.\n\n#### Equation 2a\n\nFrom the equation above we can rewrite $CE(p, y) = CE(p_t) = − log(p_t)$, keeping the same odd subscript $t$ notation.\n\n#### Equation 3\n\n$CE(p_t) = -\\alpha_t log(p_t)$\n\nThis is an equation made to put weight ($\\alpha_t \\in [0,1]$) to increase or decrease the cost of different outcomes. It's making adjustments (unnatural from some perspectives) to the cross entropy loss function.\n\nThis is a well known practice for dealing with imbalanced data.\n\nIn fact, note that this can be expressed as:\n\n$CE(p_t) = - log(p_t^{\\alpha_t})$\n\nNow if we have $y_0 = 1$ and $y_1 = -1$ (so $t=0$ or $t=1$) for the binary case, then in order to be consistent probability distributions in this representation we need:\n\n$(1-p_0)^{\\alpha_1} + p_0^{\\alpha_0} = 1$\n\nThis follows because $p_1 = 1 - p_0$.\n\nwhich we can write as saying that $\\alpha_0$ is free to be any value in [0,1], but that the following must hold - for probability consistency:\n\n${\\alpha_1} = \\frac{1- p_0^{\\alpha_0}}{log(1-p_0)}$\n\nWith a similar constraint existing if we extend to multiclass classification. \n\nThe effect is to increase the probability $p_0$ and decrease the probability $p_1$ with a functional form that does not depend on the weights or features of the network. If we assigned foreground images to the label $y_0=1$, then it makes sense to upweight the class with fewer examples.\n\nIf this modification was acting on the weights, then it would be called a regularizer, or a flat Bayesian prior. But since it is at the level of the loss function we don't call it that but the effect is similar.\n\n\nOf course one downside is that we need to use hyperparameter tuning to find the best value of the loss function weight parameter.\n\n#### Equation 4\n\nThe central topic of this paper is the tunable focal loss, given by the equation:\n\n$FL(p_t) = −(1 − p_t)^{\\gamma} log(p_t)$\n\nfor $\\gamma \\geq 0$. \n\nThe authors find that in practice the exact choice of gamma does not affect much the accuracy. They suggest $\\gamma \\in [2,5]$ for good tuning results based on their experiments.\n\nLet's do our analysis of this function via Taylor series. Using $log(x) \\approx (x-1) - (1/2)(x-1)^2$ for small enough x, well then:\n\n$FL(p_t) \\approx −(1 − p_t)^{\\gamma} ((p_t-1) - ^2)$\n\n$ = −(1 − p_t)^{\\gamma} ((p_t-1) - (1/2)(p_t^2- 2*p_t + 1))$\n\n$ = −(1 − p_t)^{\\gamma} (1/2)(p_t-1)(3 - p_t)$\n\n$ = (1/2)(1 − p_t)^{\\gamma + 1 }(3 - p_t)$\n\nThere is no real insight to be had from this expansion, but it might have been useful.\n\n\nThis $FL$ function is still pinned at 0 and infinity for perfect and worst fit to the one hot vector of actual observation y to distribution estimated via $p_t$. What it does however, is to lower the loss for good estimations ($p_t$ close to y) and increase the loss for bad estimation ($p_t$ far from $y$). \n\nIn effect, the focal loss is applying a modulating factor to the cross entropy loss. This might be seen as a kind of flat Bayesian prior, or regularizer to encourage the kind of fit that does well for imbalanced data. Only this flattening is not at the level of the weights, but higher up in the model, acting at the loss function level.\n\n```\nThere is something not satisfying that the true probabilities cannot be estimated well due to imbalanced data, so much so that we need to resort to modifying the cross entropy loss function using heuristics. \n\nThe hope would be to have methods which deal with imbalance at a lower level, at the parameter or architecture level. The reason I believe this to be important is that the cross entropy function is well understood with connections to maximum likelihood estimation. To introduce extra parameters - some of which might be better pushed down the network parameter estimation level feels wrong.\n\nHowever, since focal loss produces state of the art results we should applaud it's contribution to the field. It also is specifically used for data imbalance - where other strategies have failed to get solutions efficiently. Also, it is not post processing the estimated probabilities - but directly optimizing them, albeit in a novel way.\n\nPerhaps it is time to consider others families of loss functions.\n```\n#### Equation 5\n\nIn practice the authors suggest that a weight factor applied to the modulated loss function produces good results. So one could express focal loss as:\n\n$FL(p_t) = -\\alpha_t (1 − p_t)^{\\gamma} log(p_t)$\n\nNow with two tunable parameters.\n\n```\nLet's see what happens if we try to express the probability model implied by this loss - for the binary case:\n```\nSay, we set:\n\n$$ \\phi_t = -\\alpha_t (1 − p_t)^{\\gamma} log(p_t)$$\n\nThen:\n\n$$ exp(- \\frac{\\phi_t}{\\alpha_t} (1 − p_t)^{-\\gamma}) = p_t$$\n\nreplacing the ratio $\\frac{\\phi_t}{\\alpha_t} = \\Gamma_t$\n\n$$ exp( - \\Gamma_t (1 − p_t)^{-\\gamma}) = p_t $$\n\n```\nSo as we are optimizing the loss function, we are restricting the solution to be on a level set with the form above. I wonder if constrained optimization could be used, maybe not relevant\n```\n\n#### Equation 6\n\nThis and the following two equations are in the appendix and are supposed to show that there is a easier to optimize function that is very similar to the focal loss described earlier.\n \n$x_t = yx$\n\nIt really isn't clear what x is supposed to represent. It may just be that for any scalar $x$, we denote by $x_t$ the product of $y$ and $x$. We are told that $y \\in {-1,1}$ is the ground truth label. I initially thought $x$ was a reference to the features $x$, but that doesn't seem to be the case. We are also told that \n\n$p_t = \\sigma(x_t)$\n\nis compatible with equation 2. There isn't an explicit definition of $\\sigma(\\cdot)$. I had thought that it might be the sigmoid function. However matching up the earlier definition from equation 2\n\n$$\n\\begin{equation}\n p_t \\left \\{\n \\begin{aligned}\n & p, && \\text{if}\\ y=1 \\\\\n & 1-p, && \\text{if}\\ y=-1 \n \\end{aligned} \\right.\n\\end{equation} \n$$\n\nit's hard to tell. So, let's investigate:\n\n$p_t = \\sigma(x_t) = \\sigma(yx)$ is to be $p$ if $y=1$ and $1-p$ if $y=-1$.\n\nAgain, it's difficult to be sure. So what we'll do it look further ahead at equation 9. From this, we can see that the differential equation can be evaluated only if $\\sigma(\\cdot)$ is the sigmoid function. It would have been nice if the authors had made this explicit.\n\n\n#### Equation 7\n\n$p_t^{∗} = \\sigma(\\gamma x_t + \\beta)$\n\n#### Equation 8\n\n$FL∗ = − \\frac{log(p_t^{∗})}{\\gamma}$\n\nThe authors assert that $FL^{*}$ for the settings of $\\gamma=2$ and $\\beta=1$ is very close to FL and computationally easier. The show graphs where the function is similar within a good range.\n\n```\nQuestion: As neural networks are excellent function approximators, I'm inclined to wonder why they couldn't just approximate these specific transformations. Perhaps the extra help is needed because of the overwhelming imbalance. \n```\n\n#### Equation 9\n\n$\\frac{dCE}{dx} = y(p_t − 1)$\n\nThis equation only works if $\\sigma(\\cdot)$ is the sigmoid function. We'll do the arithmetic here:\n\n$CE = -log(p_t) = -log(\\sigma(x_t)) = -log(\\sigma(yx))$\n\n$\\frac{dCE}{dx} = -[\\sigma(yx)]^{-1} * \\frac{d[\\sigma(yx)]}{dx}$\n\n$ = -[\\sigma(yx)]^{-1} * \\sigma(yx) * [1- \\sigma(yx)] y$\n\n$= y(p_t − 1)$\n\n\n\nThe reason for giving this and the following two equations seems to be to allow parameter updates via gradient descent when training. In addition, they serve to demonstrate the closeness of $FL$ to $FL^*$, particularly with reference to the figures with the chosen values of the tuning parameters.\n\n#### Equation 10\n\n$\\frac{dF}{dx} = y(1 − p_t)^\\gamma (\\gamma p_t log(p_t) + p_t − 1)$\n\n#### Equation 11\n\n$\\frac{dFL^{∗}}{dx} = y(p_t^{*} − 1)$\n\n\n### Tables\n#### Table 1\n#### Table 2\n#### Table 3\n\n### Appendix\n#### Appendix A\n#### Appendix B\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "dd9f07115bb3d1b1caacdf5e0dd09a53cc161e0e", "size": 40514, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "papers/focal_loss_for_dense_object_detection_review.ipynb", "max_stars_repo_name": "project-delphi/object-detector", "max_stars_repo_head_hexsha": "0caf4f8c676f433286e99425baa2ad7c8350f711", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-06-16T22:44:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T17:11:27.000Z", "max_issues_repo_path": "papers/focal_loss_for_dense_object_detection_review.ipynb", "max_issues_repo_name": "project-delphi/object-detector", "max_issues_repo_head_hexsha": "0caf4f8c676f433286e99425baa2ad7c8350f711", "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": "papers/focal_loss_for_dense_object_detection_review.ipynb", "max_forks_repo_name": "project-delphi/object-detector", "max_forks_repo_head_hexsha": "0caf4f8c676f433286e99425baa2ad7c8350f711", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-23T17:11:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T17:11:41.000Z", "avg_line_length": 62.0428790199, "max_line_length": 659, "alphanum_fraction": 0.6749025028, "converted": true, "num_tokens": 7619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339458, "lm_q2_score": 0.21206879439743004, "lm_q1q2_score": 0.07393675352279873}} {"text": "# Chap_07_Nochapter\n## Comparison of Forward and Futures Contracts\nskipped...\n## Hedging\nskipped, still here though. ***Hedging***: *eliminate some or all of the risks*. We can hedge with **futures**, or even ***perfect hedge***, that if there's a future contract that trades:\n\n- exactly the asset we want to hedge\n- with the exact maturity we want to hedge\n\nOtherwise, ***asset mismatch*** or ***maturity mismatch***. Then, the solution is **cross-hedging**.\n\n## Cross-Hedging\nalso skipped, presented here though. Let \n$\n% color\n% Aquamarine, black, blue, brown, cyan, darkgray, gray, green, lightgray, lime, magenta, olive, orange, pink, purple, red, teal, violet, white, yellow\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\plim}{plim}\n\\newcommand{\\ffrac}{\\displaystyle \\frac}\n\\newcommand{\\d}[1]{\\displaystyle{#1}}\n\\newcommand{\\space}{\\text{ }}\n\\newcommand{\\bspace}{\\;\\;\\;\\;}\n\\newcommand{\\bbspace}{\\;\\;\\;\\;\\;\\;\\;\\;}\n\\newcommand{\\QQQ}{\\boxed{?\\:}}\n\\newcommand{\\void}{\\left.\\right.}\n\\newcommand{\\Tran}[1]{{#1}^{\\mathrm{T}}}\n\\newcommand{\\CB}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\SB}[1]{\\left[ #1 \\right]}\n\\newcommand{\\P}[1]{\\left( #1 \\right)}\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\n\\newcommand{\\norm}[1]{\\left\\| #1 \\right\\|}\n\\newcommand{\\given}[1]{\\left. #1 \\right|}\n\\newcommand{\\using}[1]{\\stackrel{\\mathrm{#1}}{=}}\n\\newcommand{\\asim}{\\overset{\\text{a}}{\\sim}}\n\\newcommand{\\RR}{\\mathbb{R}}\n\\newcommand{\\EE}{\\mathbb{E}}\n\\newcommand{\\II}{\\mathbb{I}}\n\\newcommand{\\NN}{\\mathbb{N}}\n\\newcommand{\\ZZ}{\\mathbb{Z}}\n\\newcommand{\\QQ}{\\mathbb{Q}}\n\\newcommand{\\PP}{\\mathbb{P}}\n\\newcommand{\\AcA}{\\mathcal{A}}\n\\newcommand{\\FcF}{\\mathcal{F}}\n\\newcommand{\\AsA}{\\mathscr{A}}\n\\newcommand{\\FsF}{\\mathscr{F}}\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\I}[1]{\\mathrm{I}\\left( #1 \\right)}\n\\newcommand{\\N}[1]{\\mathcal{N}\\left( #1 \\right)}\n\\newcommand{\\Exp}[1]{\\mathrm{E}\\left[ #1 \\right]}\n\\newcommand{\\Var}[1]{\\mathrm{Var}\\left[ #1 \\right]}\n\\newcommand{\\Avar}[1]{\\mathrm{Avar}\\left[ #1 \\right]}\n\\newcommand{\\Cov}[1]{\\mathrm{Cov}\\left( #1 \\right)}\n\\newcommand{\\Corr}[1]{\\mathrm{Corr}\\left( #1 \\right)}\n\\newcommand{\\ExpH}{\\mathrm{E}}\n\\newcommand{\\VarH}{\\mathrm{Var}}\n\\newcommand{\\AVarH}{\\mathrm{Avar}}\n\\newcommand{\\CovH}{\\mathrm{Cov}}\n\\newcommand{\\CorrH}{\\mathrm{Corr}}\n\\newcommand{\\ow}{\\text{otherwise}}\n\\newcommand{\\wp}{\\text{with probability }}\n\\newcommand{\\FSD}{\\text{FSD}}\n\\newcommand{\\SSD}{\\text{SSD}} S_T^\\P1$ be the **spot price** of the asset at which the hedger has to deliver at time $T$; and $F_2\\P{t,U}$ be the **futures price** at time $t$ of the contract maturing at time $U$ on the asset $S^\\P2$, which will be used for **hedging**.\n\nThe hedger takes a *long position* in $\\delta$ units of the futures $F_2\\P{t,U}$. Here $\\delta$ is called the ***hedge ratio***. After hedging, we have the ***risk exposure*** $H$:\n\n$$H = S_t^\\P1 - S_T^\\P1 + \\delta\\P{F_2\\P{T,U} - F_2\\P{t,U}}$$\n\n- $S_t^\\P1 - S_T^\\P1$: the change in the value of the asset to be delivered at time $T$\n- $\\delta\\P{F_2\\P{T,U} - F_2\\P{t,U}}$: the payoff of holding the *long position* in the futures contract between $t$ and $T$.\n\nIdeally, $H=0$, meaning the perfect hedge.\n## Optimal $\\delta$\nskipped, interesting though.\n\n## Delta Neutral Strategy\nRisk exposure $H$ per one call option is $H = c\\P{0} - c\\P{T} +y\\P{S_T-S_0}$. Here the ***delta hedging*** means: *to hedge your position by holding the stock with the number of shares equal to the option's delta*.\n\nUnder the **single-period binomial tree** model, $H = x-xe^{rT}$, and with more periods, we can hedge dynamically. Then the **continuous-time** model, we define the ***Delta***:\n\n$$\\Delta_c \\equiv \\ffrac{\\partial c\\P{t,S_t}}{\\partial S_t}$$\n\nCommonly, an option written on an underlying asset $S$ is most sensitive to the changes in the value of $S$. Hence, the largest part of the risk comes from the price movements of asset $S$.\n\nAnd the **first order approximation** for $c$:\n\n$$c\\P{t,S_t} \\approx c\\P{0,S_t} + \\Delta_c\\P{S_t-S_0}$$\n\nThen the ***Delta*** of a portfolio: *the change in the value of the portfolio divided by the change in the value of the underlying asset*.\n\nAnd the position with a **Delta** of $0$ is called ***delta neutral***, meaning that the portfolio doesn't change if the price of the underlying asset changes.\n\n**e.g.**\n\nWe are short $c\\P{t,S_t}$ and we want to hedge the associated risk with respect to the movements of $S_t$ by holding a position in $S_t$. We should find the number of shares of $S_t$ we should hold, namely $y$, in the complete portfolio $\\Pi$ in order to make $\\Delta_\\Pi = 0$:\n\n$$\\Delta_\\Pi = -\\Delta_c + y \\times 1 = 0 \\Rightarrow y = \\Delta_c$$\n***\n\nA portfolio is called ***long*** (***short***) ***Delta*** if its **Delta** is positive, $\\Delta_\\Pi > 0$ (negative with $\\Delta_\\Pi < 0$), in which case its value will *increase* (*decrease*) if the value of $S_t$ increases, all other variables being constant.\n\n***Static Hedging***: The hedge is set up initially and *never adjusted*. That's exactly what we do under the **single-period binomial model**, where a perfect replication of a payoff $c\\P{T,S_T}$ is achieved by holding exactly $\\Delta_c$ shares of the underlying at the initial time. All the risk is eliminated keeping the portfolio **Delta-Neutral** under this model. This result is not necessarily true in other models. However in practice, $S_t$ changes frequently thus to neutralize the **Delta**, we need to adjust the number of shares of $S_t$ held in the portfolio. We called this the ***dynamic hedging*** strategy.\n\nAnd for the **perfect hedge**, rebalancing must take *continuously*. This requires that the model and its parameters are exactly correct.\n\n## Delta under the Black-Scholes Model\nThe **Black-Scholes-Mertion equation** is derived by setting up a **delta-neutral position** (*short* $1$ option and *long* $\\Delta_c$ shares of the stock) and arguing that the return on the position should be the *risk-free interest rate*.\n\nFor the European call option, BS equation gives\n\n$$c\\P{t,S_t} = S_t\\N{d_1} - Ke^{-r\\P{T-t}}\\N{d_2}\\\\\nd_{1,2} = \\ffrac{1}{\\sigma\\sqrt{T-t}}\\P{\\log\\ffrac{S_t}{K}+\\P{r\\pm\\ffrac{\\sigma^2}{2}}\\P{T-t}}$$\n\nand we have $\\Delta_c = \\N{d_1}$ and then using the put-call parity we have $\\Delta_p = \\N{d_1} -1$. What's more\n\n- $\\Delta_c > 0$: the **replicating** portfolio of the call, never goes short in the stock\n- $\\Delta_c < 1$: holding one share or more of the stock is *more than enough* to **hedge** the call option payoff.\n- $\\Delta_p < 0$: the **replicating** portfolio, of the put, never goes long in the stock\n- $\\Delta_p > -1$: holding one share or more of the stock is *more than enough* to **hedge** the put option payoff.\n\n## Option Sensitivities\n*Partial derivatives* of the portfolio value with respect to parameters are called ***Greeks***. The five standard **Greeks** for a *portfolio* with value $V$ are\n\n$$\\begin{array}{c|ccccc}\\hline\n\\text{name} & \\text{Delta} & \\text{Theta} & \\text{Gamma} & \\text{Vega} & \\text{Rho}\\\\ \\hline\n\\text{expression} & \\Delta = \\ffrac{\\partial V}{\\partial S_t} & \\Theta = \\ffrac{\\partial V}{\\partial t} & \\Gamma = \\ffrac{\\partial^2 V}{\\partial S_t^2} & {\\large\\nu} = \\ffrac{\\partial V}{\\partial \\sigma} & {\\large\\rho} = \\ffrac{\\partial r}{\\partial S_t}\\\\\\hline\n\\end{array}$$\n\n### $\\Theta$, derivative with respect to time\n**Theta** is sometimes referred to as the ***time decay*** of the portfolio.\n\n$$\\begin{align}\n\\Theta_c &= S_t\\mathcal{N}'\\P{d_1}\\ffrac{\\partial d_1}{\\partial t} - rKe^{-r\\P{T-t}}\\N{d_2}-Ke^{-r\\P{T-t}}\\mathcal N'\\P{d_2}\\ffrac{\\partial d_2}{\\partial t}\\\\\n\\Theta_p &= rKe^{-r\\P{T-t}}\\N{-d_2}-Ke^{-r\\P{T-t}}\\mathcal N'\\P{-d_2}\\ffrac{\\partial d_2}{\\partial t} + S_t\\mathcal{N}'\\P{-d_1}\\ffrac{\\partial d_1}{\\partial t} \n\\end{align}$$\n\nand using the facts that $S_t\\mathcal{N}'\\P{\\pm d_1} = Ke^{-r\\P{T-t}}\\mathcal{N}'\\P{\\pm d_2}$ and $\\ffrac{\\partial d_1}{\\partial t} = \\ffrac{\\partial d_2}{\\partial t} - \\ffrac{\\sigma}{2\\sqrt{T-t}}$ we have\n\n$$\\begin{align}\n\\Theta_c &= - \\ffrac{\\sigma}{2\\sqrt{T-t}}S_t\\mathcal{N}'\\P{d_1} - rKe^{-r\\P{T-t}}\\N{d_2}\\\\\n\\Theta_p &= - \\ffrac{\\sigma}{2\\sqrt{T-t}}S_t\\mathcal{N}'\\P{d_1} + rKe^{-r\\P{T-t}}\\N{-d_2}\n\\end{align}$$\n\nUsually $\\Theta$ is negative, since option tends to be less valuable.\n\n### $\\Gamma$, second order derivative with respect to asset price\nIf the *absolute value* of $\\Gamma$ is large, $\\Delta$ would be highly sensitive to the price of the underlying asset, meaning that adjustments to keep a portfolio **delta neutral** need to be made relatively frequently. \n\nAnd since $\\Delta_c = \\N{d_1}$ and $\\Delta_p = \\N{d_1}-1$, we have, for European call/put\n\n$$\\Gamma = \\ffrac{\\partial \\N{d_1}}{\\partial S_t} = \\mathcal{N}'\\P{d_1} \\ffrac{1}{\\sigma\\sqrt{T-t}}\\ffrac{1}{S_t}>0$$\n\nUp to this point, we can already draw two very useful conclusions.\n\n### Approximation\nUsing **Taylor Expansion**:\n\n$$\\begin{align}\nV\\P{t+\\Delta t,S_{t+\\Delta t}} &= V\\P{t,S_t} + \\Delta t \\ffrac{\\partial V\\P{t,S_t}}{\\partial t} + O\\P{\\P{\\Delta t}\n^2} + \\P{S_{t+\\Delta t} - S_t}\\ffrac{\\partial V\\P{t,S_t}}{\\partial S_t} \\\\\n&\\bspace + \\ffrac{1}{2}\\P{S_{t+\\Delta t} - S_t}^2 \\ffrac{\\partial^2 V\\P{t,S_t}}{\\partial S_t\\partial S_t}+\\cdots\\\\\n&\\approx V\\P{t,S_t} + \\color{brown}{\\Theta}\\Delta t + \\color{brown}{\\Delta} \\P{S_{t+\\Delta t} - S_t} + \\ffrac{1}{2}\\color{brown}{\\Gamma} \\P{S_{t+\\Delta t} - S_t}^2\n\\end{align}$$\n\nFurther, if the portolio is **Delta Neutral**, then\n\n$$V\\P{t+\\Delta t,S_{t+\\Delta t}} \\approx V\\P{t,S_t} + \\color{brown}{\\Theta}\\Delta t + \\ffrac{1}{2}\\color{brown}{\\Gamma} \\P{S_{t+\\Delta t} - S_t}^2$$\n\n### Reaching Gamma Neutral\nSuppose a **Delta Neutral** portfolio has $\\Gamma$ as its **Gamma**, and another traded opion has **Gamma** equal to $\\Gamma_T$. If the number of traded options added to the portfolio is $w_T$, gamma of the new portfolio is $w_T \\Gamma_T + \\Gamma$ and thus buying $w_T = -\\ffrac{\\Gamma}{\\Gamma_T}$ would lead to **Gamma Neutral**. \n\nHowever this changes the $\\Delta$ of the portfolio, we need to trade more shares to neutralize our $\\Delta$ after that.\n\n**e.g.**\n\nSuppose that a portfolio is **Delta Neutral** and has a $\\Gamma$ of $-3000$. The $\\Delta_c$ and $\\Gamma_c$ of a particular traded call option are $0.62$ and $1.50$, respectively. How to make the portfolio **Delta Neutral** and **Gamma Neutral**?\n\n> The portfolio can be made **Gamma Neutral** by including in the portfolio a *long position* of $-\\ffrac{\\Gamma}{\\Gamma_c} = -\\ffrac{-3000}{1.5} = 2000$ call option. However, the **Delta** of the portfolio will then change fram $0$ to $\\Delta_v = 2000\\times 0.62 = 1240$. Thus, $1240$ units of the underlying asset must be *sold* from the portfolio to keep it **Delta Neutral**.\n***\n\n***delta hedging error***: when the stock price moves from $S_{1}$ to $S_{2}$ the option price moves from $C_1$ to $C_2$, while **delta hedging** assumes that it moves to $C_2'$. The difference between $C_2$ and $C_2'$ is the **delta hedging error**.\n\n- **Delta neutrality** provides protection against *relatively small* stock price moves between rebalancing.\n- **Gamma neutrality** provides protection against *larger* movements in this stock price between hedge rebalancing.\n\n### $\\large\\nu$, derivative with respect to volatility\n\nFor a European call or put option, **Vega** is given by\n\n$$\\begin{align}{\\large{\\nu}} &= S_t \\mathcal N'\\P{d_1}\\ffrac{\\partial d_1}{\\partial \\sigma} - Ke^{-r\\P{T-t}}\\mathcal N'\\P{d_2}\\ffrac{\\partial d_2}{\\partial \\sigma}\\\\\n&= S_t \\mathcal N'\\P{d_1}\\ffrac{\\partial d_1}{\\partial \\sigma} - S_t \\mathcal N'\\P{d_1}\\P{\\ffrac{\\partial d_1}{\\partial \\sigma} - \\sqrt{T-t}}\\\\\n&= S_t \\sqrt{T-t} \\mathcal N'\\P{d_1}>0\n\\end{align}$$\n\nThus, both the European call and put prices *increase with increasing volatility*. And this doesn't violate our intuition. Higher volatility lead to a higher chance that the option may end up either **deeper in-the-money** or **deep out-of-the-money**, while there's no extra peanlty for the option to be deeper out-of-the-money but the payoff increases when the option expires deeper in the money.\n\n### $\\large\\rho$, derivative with respect to interest rate\n\n$$\\begin{align}\n{\\large\\rho}_c &= S_t \\mathcal N'\\P{d_1}\\ffrac{\\partial d_1}{\\partial r} + K\\P{T-t}e^{-r\\P{T-t}}\\N{d_2} - Ke^{-r\\P{T-t}}\\mathcal N'\\P{d_2}\\ffrac{\\partial d_2}{\\partial r}\\\\\n&= K\\P{T-t}e^{-r\\P{T-t}}\\N{d_2} + S_t \\mathcal N'\\P{d_1}\\ffrac{\\partial d_1}{\\partial \\sigma} - S_t \\mathcal N'\\P{d_1}\\P{\\ffrac{\\partial d_1}{\\partial \\sigma} - 0}\\\\\n&= K\\P{T-t}e^{-r\\P{T-t}}\\N{d_2} > 0\\\\\n{\\large\\rho}_p &= -K\\P{T-t}e^{-r\\P{T-t}} \\N{-d_2} < 0\n\\end{align}$$\n\nA *higher interest* rate lowers the present value of the cost of exercising the European call option at expiration (the effect is similar to the *lowering of the strike price*), in turn this increases the call price. Reverse effect holds for the put option price.\n\n***\n", "meta": {"hexsha": "9c67770a061e8ad1b925ba34d1f154168fb7d395", "size": 16681, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FinMath/Models and Pricing of Financial Derivatives/Chap_07_Anonymous.ipynb", "max_stars_repo_name": "XavierOwen/Notes", "max_stars_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-27T10:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T03:11:58.000Z", "max_issues_repo_path": "FinMath/Models and Pricing of Financial Derivatives/Chap_07_Anonymous.ipynb", "max_issues_repo_name": "XavierOwen/Notes", "max_issues_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "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": "FinMath/Models and Pricing of Financial Derivatives/Chap_07_Anonymous.ipynb", "max_forks_repo_name": "XavierOwen/Notes", "max_forks_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:57:23.000Z", "avg_line_length": 57.7197231834, "max_line_length": 635, "alphanum_fraction": 0.5807205803, "converted": true, "num_tokens": 4244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268346176374815, "lm_q2_score": 0.15610489351941398, "lm_q1q2_score": 0.0737882014670179}} {"text": "```python\n#format the book\n%matplotlib inline\nfrom __future__ import division, print_function\nimport sys;sys.path.insert(0,'..')\nfrom book_format import load_style;load_style('..')\n```\n\n\n\n\n\n\n\n\n\n\n# Computing and plotting PDFs of discrete data\n\nSo let's investigate how to compute and plot probability distributions.\n\n\nFirst, let's make some data according to a normal distribution. We use `numpy.random.normal` for this. The parameters are not well named. `loc` is the mean of the distribution, and `scale` is the standard deviation. We can call this function to create an arbitrary number of data points that are distributed according to that mean and std.\n\n\n```python\nimport numpy as np\nimport numpy.random as random\n\nmean = 3\nstd = 2\n\ndata = random.normal(loc=mean, scale=std, size=50000)\nprint(len(data))\nprint(data.mean())\nprint(data.std())\n```\n\n 50000\n 3.00621596517\n 1.99696435477\n\n\nAs you can see from the print statements we got 5000 points that have a mean very close to 3, and a standard deviation close to 2.\n\nWe can plot this Gaussian by using `scipy.stats.norm` to create a frozen function that we will then use to compute the pdf (probability distribution function) of the Gaussian.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n\ndef plot_normal(xs, mean, std, **kwargs):\n norm = stats.norm(mean, std)\n plt.plot(xs, norm.pdf(xs), **kwargs)\n\nxs = np.linspace(-5, 15, num=200)\nplot_normal(xs, mean, std, color='k')\n```\n\nBut we really want to plot the PDF of the discrete data, not the idealized function.\n\nThere are a couple of ways of doing that. First, we can take advantage of `matplotlib`'s `hist` method, which computes a histogram of a collection of data. Normally `hist` computes the number of points that fall in a bin, like so:\n\n\n```python\nplt.hist(data, bins=200)\nplt.show()\n```\n\nthat is not very useful to us - we want the PDF, not bin counts. Fortunately `hist` includes a `density` parameter which will plot the PDF for us.\n\n\n```python\nplt.hist(data, bins=200, normed=True)\nplt.show()\n```\n\nI may not want bars, so I can specify the `histtype` as 'step' to get a line.\n\n\n```python\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nplt.show()\n```\n\nTo be sure it is working, let's also plot the idealized Gaussian in black.\n\n\n```python\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nnorm = stats.norm(mean, std)\nplt.plot(xs, norm.pdf(xs), color='k', lw=2)\nplt.show()\n```\n\nThere is another way to get the approximate distribution of a set of data. There is a technique called *kernel density estimate* that uses a kernel to estimate the probability distribution of a set of data. NumPy implements it with the function `gaussian_kde`. Do not be mislead by the name - Gaussian refers to the type of kernel used in the computation. This works for any distribution, not just Gaussians. In this section we have a Gaussian distribution, but soon we will not, and this same function will work.\n\n\n```python\nkde = stats.gaussian_kde(data)\n\nxs = np.linspace(-5, 15, num=200)\nplt.plot(xs, kde(xs))\nplt.show()\n```\n\n## Monte Carlo Simulations\n\n\nWe (well I) want to do this sort of thing because I want to use monte carlo simulations to compute distributions. It is easy to compute Gaussians when they pass through linear functions, but difficult to impossible to compute them analytically when passed through nonlinear functions. Techniques like particle filtering handle this by taking a large sample of points, passing them through a nonlinear function, and then computing statistics on the transformed points. Let's do that.\n\nWe will start with the linear function $f(x) = 2x + 12$ just to prove to ourselves that the code is working. I will alter the mean and std of the data we are working with to help ensure the numbers that are output are unique It is easy to be fooled, for example, if the formula multipies x by 2, the mean is 2, and the std is 2. If the output of something is 4, is that due to the multication factor, the mean, the std, or a bug? It's hard to tell. \n\n\n```python\ndef f(x):\n return 2*x + 12\n\nmean = 1.\nstd = 1.4\ndata = random.normal(loc=mean, scale=std, size=50000)\n\nd_t = f(data) # transform data through f(x)\n\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\n\nplt.ylim(0, .35)\nplt.show()\nprint('mean = {:.2f}'.format(d_t.mean()))\nprint('std = {:.2f}'.format(d_t.std()))\n```\n\nThis is what we expected. The input is the Gaussian $\\mathcal{N}(\\mu=1, \\sigma=1.4)$, and the function is $f(x) = 2x+1$. Therefore we expect the mean to be shifted to $f(\\mu) = 2*1+12=14$. We can see from the plot and the print statement that this is what happened. \n\nBefore I go on, can you explain what happened to the standard deviation? You may have thought that the new $\\sigma$ should be passed through $f(x)$ like so $2(1.4) + 12=14.81$. But that is not correct - the standard deviation is only affected by the multiplicative factor, not the shift. If you think about that for a moment you will see it makes sense. We multiply our samples by 2, so they are twice as spread out as before. Standard deviation is a measure of how spread out things are, so it should also double. It doesn't matter if we then shift that distribution 12 places, or 12 million for that matter - the spread is still twice the input data.\n\n\n\n## Nonlinear Functions\n\nNow that we believe in our code, lets try it with nonlinear functions.\n\n\n```python\ndef f2(x):\n return (np.cos((1.5*x + 2.1))) * np.sin(0.3*x) - 1.6*x\n\nd_t = f2(data)\nplt.subplot(121)\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\n\nplt.subplot(122)\nkde = stats.gaussian_kde(d_t)\nxs = np.linspace(-10, 10, 200)\nplt.plot(xs, kde(xs), 'k')\nplot_normal(xs, d_t.mean(), d_t.std(), color='g', lw=3)\nplt.show()\nprint('mean = {:.2f}'.format(d_t.mean()))\nprint('std = {:.2f}'.format(d_t.std()))\n```\n\nHere I passed the data through the nonlinear function $f(x) = \\cos(1.5x+2.1)\\sin(\\frac{x}{3}) - 1.6x$. That function is quite close to linear, but we can see how much it alters the pdf of the sampled data. \n\nThere is a lot of computation going on behind the scenes to transform 50,000 points and then compute their PDF. The Extended Kalman Filter (EKF) gets around this by linearizing the function at the mean and then passing the Gaussian through the linear equation. We saw above how easy it is to pass a Gaussian through a linear function. So lets try that.\n\nWe can linearize this by taking the derivative of the function at x. We can use sympy to get the derivative. \n\n\n```python\nimport sympy\nx = sympy.symbols('x')\nf = sympy.cos(1.5*x+2.1) * sympy.sin(x/3) - 1.6*x\ndfx = sympy.diff(f, x)\ndfx\n```\n\n\n\n\n -1.5*sin(x/3)*sin(1.5*x + 2.1) + cos(x/3)*cos(1.5*x + 2.1)/3 - 1.6\n\n\n\nWe can now compute the slope of the function by evaluating the derivative at the mean.\n\n\n```python\nm = dfx.subs(x, mean)\nm\n```\n\n\n\n\n -1.66528051815545\n\n\n\nThe equation of a line is $y=mx+b$, so the new standard deviation should be $~1.67$ times the input std. We can compute the new mean by passing it through the original function because the linearized function is just the slope of f(x) evaluated at the mean. The slope is a tangent that touches the function at $x$, so both will return the same result. So, let's plot this and compare it to the results from the monte carlo simulation.\n\n\n```python\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\nplot_normal(xs, f2(mean), abs(float(m)*std), color='k', lw=3, label='EKF')\nplot_normal(xs, d_t.mean(), d_t.std(), color='r', lw=3, label='MC')\nplt.legend()\nplt.show()\n```\n\nWe can see from this that the estimate from the EKF (in red) is not exact, but it is not a bad approximation either. \n", "meta": {"hexsha": "ba159565e7e16535a1984639af97a6a0ff693886", "size": 162737, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_stars_repo_name": "horaceheaven/Kalman-and-Bayesian-Filters-in-Python", "max_stars_repo_head_hexsha": "3639394a1218ab3e22e2c9929648d78586e52fe9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-11-20T02:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T23:06:59.000Z", "max_issues_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_issues_repo_name": "gokhanettin/Kalman-and-Bayesian-Filters-in-Python", "max_issues_repo_head_hexsha": "55d73b21de01ee4278cef1ab5b32405917f96287", "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": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_forks_repo_name": "gokhanettin/Kalman-and-Bayesian-Filters-in-Python", "max_forks_repo_head_hexsha": "55d73b21de01ee4278cef1ab5b32405917f96287", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-30T05:28:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T07:08:42.000Z", "avg_line_length": 205.9962025316, "max_line_length": 22622, "alphanum_fraction": 0.8850292189, "converted": true, "num_tokens": 3971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.17106119801750536, "lm_q1q2_score": 0.07358152327240777}} {"text": "「TransformerとTorchTextを用いたsequence-to-sequenceモデルの学習」\n===============================================================\n【原題】Sequence-to-Sequence Modeling with nn.Transformer and TorchText\n\n【元URL】https://pytorch.org/tutorials/beginner/transformer_tutorial.html\n\n【翻訳】電通国際情報サービスISID AIトランスフォーメーションセンター 御手洗 拓真\n\n【日付】2020年10月13日\n\n【チュトーリアル概要】\n\n本チュートリアルでは、Attention機構を備えたTransformerモジュールを使用したsequence-to-sequenceモデルの実装手法と訓練方法を解説します。\n\nWikiText2から取得した文章において、文章=単語系列(sequence)を入力し、その次に来るであろう単語を予測するsequence-to-sequenceモデルを構築します。\n\n
\n\n---\n\n\n\n\n本ノートブックは、[nn.Transformer](https://pytorch.org/docs/master/nn.html?highlight=nn%20transformer#torch.nn.Transformer)モジュールを使用した、sequence-to-sequenceモデル学習の解説チュートリアルです。\n\nPyTorch 1.2 以降では、論文 [Attention is All You Need](https://arxiv.org/pdf/1706.03762.pdf)を基に実装された、標準的なTransformerのモジュールが用意されています。\n\n
\n\nTransformerモデルは、これまでのモデル(日本語訳注:RNN系)と比べてより並列化が容易であると同時に、多くのsequence-to-sequenceのタスクにおいて、より優れた結果が得られることが実証されています。\n\n\n\n\n`nn.Transformer`モジュールは、Attensionメカニズム(最近、\r\n[nn.MultiheadAttention](https://pytorch.org/docs/master/nn.html?highlight=multiheadattention#torch.nn.MultiheadAttention)として実装された別のモジュール)に完全に依存しています。このAttensionメカニズムにより、入力と出力の間の大域的な依存関係を捉えることができます。\r\n\r\n`nn.Transformer`モジュールは、単一でも使用しやすいように、高度にモジュール化されており、簡単に、`nn.Transformer`モジュールをコンポーネント(本チュートリアルの[nn.TransformerEncoder](https://pytorch.org/docs/master/nn.html?highlight=nn%20transformerencoder#torch.nn.TransformerEncoder)など)に適用したり、あるいは`nn.Transformer`モジュールを使って、コンポーネントを作成したりすることができます。\r\n\r\n
\n\n\n\nモデルの定義\n----------------\n\n\n本チュートリアルでは、言語モデルタスクで`NN.TransformerEncoder`モデルを訓練します。\n\nここでの言語モデルタスク(language modeling task)とは、特定の単語(または単語のシーケンス)が、与えられた単語シーケンスの後に続けて登場する確率を当てるタスクです。\n\n\n\n\n単語(トークン)のシーケンスは、最初にモデルの埋め込み層に渡され、その後、単語の順序の情報を得るための位置エンコーディング層(詳細は次の段落)へと渡されます。\r\n\r\n\r\n`nn.TransformerEncoder`は、複数の[NN.TransformerEncoderLayer](https://pytorch.org/docs/master/nn.html?highlight=transformerencoderlayer#torch.nn.TransformerEncoderLaye)の層で構成されています。\r\n\r\n言語モデルタスクでは、入力シーケンスと共に、アテンション・マスクが必要です。\r\n\r\nなぜなら、`NN.TransformerEncoder`のSelf-Attention層では、シーケンス内でより前方に登場するトークンのみに着目することが許されているためです。\r\n\r\n※日本語訳注:RNNでも単語は前から順番に入力され、後ろの単語は通常、考慮できないので、その状態を再現しています(後方からのシーケンスを利用する場合もありますが)。\r\n\r\n普通の日常会話でも、会話最中に、会話の先の内容を事前に聞くことはできない点と同じ状況です。\r\n\r\n\n\nそこで、言語モデルタスクでは、後方の位置にある単語(トークン)は未知のトークンとして扱うため、マスクする必要があります。\r\n\r\n正解の単語を求めるために、`NN.TransformerEncoder`モデルの出力は、最終的に全結合層に送られ、その後にlog-Softmax関数で処理されます。\n\n\n```python\n# 日本語訳注:追加\n%matplotlib inline\n!pip3 install torchtext==0.4.0\n```\n\n Collecting torchtext==0.4.0\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/43/94/929d6bd236a4fb5c435982a7eb9730b78dcd8659acf328fd2ef9de85f483/torchtext-0.4.0-py3-none-any.whl (53kB)\n \u001b[K |████████████████████████████████| 61kB 8.1MB/s \n \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torchtext==0.4.0) (1.18.5)\n Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from torchtext==0.4.0) (4.41.1)\n Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from torchtext==0.4.0) (1.7.0+cu101)\n Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from torchtext==0.4.0) (2.23.0)\n Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchtext==0.4.0) (1.15.0)\n Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch->torchtext==0.4.0) (3.7.4.3)\n Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-packages (from torch->torchtext==0.4.0) (0.8)\n Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch->torchtext==0.4.0) (0.16.0)\n Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.4.0) (2020.12.5)\n Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.4.0) (3.0.4)\n Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.4.0) (1.24.3)\n Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.4.0) (2.10)\n Installing collected packages: torchtext\n Found existing installation: torchtext 0.3.1\n Uninstalling torchtext-0.3.1:\n Successfully uninstalled torchtext-0.3.1\n Successfully installed torchtext-0.4.0\n\n\n\n```python\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass TransformerModel(nn.Module):\n\n def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):\n super(TransformerModel, self).__init__()\n from torch.nn import TransformerEncoder, TransformerEncoderLayer\n self.model_type = 'Transformer'\n self.src_mask = None\n self.pos_encoder = PositionalEncoding(ninp, dropout)\n encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)\n self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n self.decoder = nn.Linear(ninp, ntoken)\n\n self.init_weights()\n\n def _generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src):\n if self.src_mask is None or self.src_mask.size(0) != src.size(0):\n device = src.device\n mask = self._generate_square_subsequent_mask(src.size(0)).to(device)\n self.src_mask = mask\n\n src = self.encoder(src) * math.sqrt(self.ninp)\n src = self.pos_encoder(src)\n output = self.transformer_encoder(src, self.src_mask)\n output = self.decoder(output)\n return output\n```\n\n`PositionalEncoding` モジュールは、シーケンス内のトークンの相対的な位置、もしくは絶対的な位置に関する情報をモデルに与えます。\n\n\n位置エンコーディング層(PositionalEncoding Layer)は、埋め込み層と同じ次元であり、位置エンコーディングの出力と、埋め込み層の出力は足し算することができます。\n\nここでは,異なる周波数のサイン波関数とコサイン波関数を使用し、位置エンコーディングを行っています。\n\n\n```python\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n```\n\nデータの読み込みとバッチ処理\n-------------------\n\n学習には`torchtext`のWikitext-2データセットを使用します。\n\nvocabオブジェクトは訓練データセットを元に構築され、トークン(単語)をテンソル形式の数値に変換するために使用されます。\n\n`batchify()` 関数は、シーケンス形式のデータ(トークンが左から右に一つずつ並んだ形)を、列が並んだ形式に変換します。変換する際には、データを``batch_size`` 変数のサイズで分割し、最後に余ったトークンは無視されます。\n\n例えば、アルファベットをシーケンス (長さ26) とし、バッチサイズを 4 とすると、アルファベットを長さ 6 の 4 つのシーケンスに分割したのが以下の例です。\n\n\\begin{align}\\begin{bmatrix}\n \\text{A} & \\text{B} & \\text{C} & \\ldots & \\text{X} & \\text{Y} & \\text{Z}\n \\end{bmatrix}\n \\Rightarrow\n \\begin{bmatrix}\n \\begin{bmatrix}\\text{A} \\\\ \\text{B} \\\\ \\text{C} \\\\ \\text{D} \\\\ \\text{E} \\\\ \\text{F}\\end{bmatrix} &\n \\begin{bmatrix}\\text{G} \\\\ \\text{H} \\\\ \\text{I} \\\\ \\text{J} \\\\ \\text{K} \\\\ \\text{L}\\end{bmatrix} &\n \\begin{bmatrix}\\text{M} \\\\ \\text{N} \\\\ \\text{O} \\\\ \\text{P} \\\\ \\text{Q} \\\\ \\text{R}\\end{bmatrix} &\n \\begin{bmatrix}\\text{S} \\\\ \\text{T} \\\\ \\text{U} \\\\ \\text{V} \\\\ \\text{W} \\\\ \\text{X}\\end{bmatrix}\n \\end{bmatrix}\\end{align}\n\n\n\n各列(=バッチ)は、モデル内では独立したものとして扱われます。そのため、例えば ``F`` と ``G`` の依存関係を学習することはできません。\r\n\r\n(日本語訳注:FとGは連続したアルファベットという依存関係がありますが、それはこの学習では考慮できないことになります)\r\n\r\n\r\nしかしながら、各バッチを独立したものとして扱うことで、より効率的なバッチ処理が可能になります。\n\n\n```python\nimport torchtext\nfrom torchtext.data.utils import get_tokenizer\nTEXT = torchtext.data.Field(tokenize=get_tokenizer(\"basic_english\"),\n init_token='',\n eos_token='',\n lower=True)\ntrain_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)\nTEXT.build_vocab(train_txt)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef batchify(data, bsz):\n data = TEXT.numericalize([data.examples[0].text])\n # データセットをbszサイズに分割した際のバッチ数を求める\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1).t().contiguous()\n return data.to(device)\n\nbatch_size = 20\neval_batch_size = 10\ntrain_data = batchify(train_txt, batch_size)\nval_data = batchify(val_txt, eval_batch_size)\ntest_data = batchify(test_txt, eval_batch_size)\n```\n\n wikitext-2-v1.zip: 100%|██████████| 4.48M/4.48M [00:00<00:00, 64.5MB/s]\n\n downloading wikitext-2-v1.zip\n extracting\n\n\n \n\n\n\n```python\n# 日本語訳注:追記(GPUの確認と訓練データの確認)\n\nprint(\"GPU環境:\", device) # GPU環境であれば、cuda と表示されます\nprint(\"訓練データのサンプル:\", train_txt.examples[0].text[:100])\n```\n\n GPU環境: cuda\n 訓練データのサンプル: ['', '=', 'valkyria', 'chronicles', 'iii', '=', '', '', 'senjō', 'no', 'valkyria', '3', '', 'chronicles', '(', 'japanese', '戦場のヴァルキュリア3', ',', 'lit', '.', 'valkyria', 'of', 'the', 'battlefield', '3', ')', ',', 'commonly', 'referred', 'to', 'as', 'valkyria', 'chronicles', 'iii', 'outside', 'japan', ',', 'is', 'a', 'tactical', 'role', '@-@', 'playing', 'video', 'game', 'developed', 'by', 'sega', 'and', 'media', '.', 'vision', 'for', 'the', 'playstation', 'portable', '.', 'released', 'in', 'january', '2011', 'in', 'japan', ',', 'it', 'is', 'the', 'third', 'game', 'in', 'the', 'valkyria', 'series', '.', '', 'the', 'same', 'fusion', 'of', 'tactical', 'and', 'real', '@-@', 'time', 'gameplay', 'as', 'its', 'predecessors', ',', 'the', 'story', 'runs', 'parallel', 'to', 'the', 'first', 'game', 'and', 'follows', 'the']\n\n\n
\n\n**入力シーケンスとTargetシーケンスを生成するための関数**\n\n``get_batch()``関数は,Transformerモデルの入力シーケンスと、Targetシーケンスを生成します。\n\nこの関数はソースデータを変数``bptt``の長さのチャンクデータに細分化します。\n\n 言語モデルのタスクでは、入力シーケンスに後続する単語がTargetとして必要となります。\n \n 例えば以下の図で、``bptt`` の値が 2 の場合、``i`` = 0 に後続する2 つの要素を取得します。\n\n
\n\n日本語訳注:bpttより2つの要素をinputに使用。\n\n下の図では、モデルへの入力(とあるタイミングで来た単語)とモデルが予測して欲しい出力(次のタイミングで来るべき単語)を表示しています。\n\n\n\n\n\n``get_batch()``関数の返り値``data``変数の 0 次元目 がチャンクの長さで、これはトランスフォーマーモデルの 次元``S``と一致していることに注意してください。\n\nまた、``data``変数の 1 次元目 はバッチサイズを示す次元数 ``N`` となっています。\n\n\n```python\nbptt = 35\ndef get_batch(source, i):\n seq_len = min(bptt, len(source) - 1 - i)\n data = source[i:i+seq_len]\n target = source[i+1:i+1+seq_len].view(-1)\n return data, target\n```\n\nインスタンスの初期化\n--------------------\n\nモデルは、以下のハイパーパラメータを使用して設定されます。vocabのサイズは、vocabオブジェクトの長さと同じです。\n\n\n```python\nntokens = len(TEXT.vocab.stoi) # the size of vocabulary\nemsize = 200 # embedding dimension\nnhid = 200 # the dimension of the feedforward network model in nn.TransformerEncoder\nnlayers = 2 # the number of nn.TransformerEncoderLayer in nn.TransformerEncoder\nnhead = 2 # the number of heads in the multiheadattention models\ndropout = 0.2 # the dropout value\nmodel = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to(device)\n```\n\nモデルの実行\n-------------\n\n\n\n\n[CrossEntropyLoss](https://pytorch.org/docs/master/nn.html?highlight=crossentropyloss#torch.nn.CrossEntropyLoss)は損失値を計算するために適用され、[SGD](https://pytorch.org/docs/master/optim.html?highlight=sgd#torch.optim.SGD)はオプティマイザとして使われる確率的勾配降下法です。\n\n初期の学習率は5.0に設定しています。\n\n\nエポック単位で学習率を調整するために[StepLR](https://pytorch.org/docs/master/optim.html?highlight=steplr#torch.optim.lr_scheduler.StepLR)__を使用します。\n\n訓練中は、勾配爆発を防ぐために、[nn.utils.clip_grad_norm](https://pytorch.org/docs/master/nn.html?highlight=nn%20utils%20clip_grad_norm#torch.nn.utils.clip_grad_norm_) 関数を用いて、全ての勾配をまとめた後、大きさをスケーリングしています。\n\n(日本語訳注:ここでのスケーリングとは、clip_grad_normで勾配が大きすぎる値は設定した上限値に変更するスケーリング操作を示します)\n\n\n```python\ncriterion = nn.CrossEntropyLoss()\nlr = 5.0 # 学習率\noptimizer = torch.optim.SGD(model.parameters(), lr=lr)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)\n\nimport time\ndef train():\n model.train() # 訓練モードに\n total_loss = 0.\n start_time = time.time()\n ntokens = len(TEXT.vocab.stoi)\n for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):\n data, targets = get_batch(train_data, i)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output.view(-1, ntokens), targets)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n total_loss += loss.item()\n log_interval = 200\n if batch % log_interval == 0 and batch > 0:\n cur_loss = total_loss / log_interval\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches | '\n 'lr {:02.2f} | ms/batch {:5.2f} | '\n 'loss {:5.2f} | ppl {:8.2f}'.format(\n epoch, batch, len(train_data) // bptt, scheduler.get_lr()[0],\n elapsed * 1000 / log_interval,\n cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\ndef evaluate(eval_model, data_source):\n eval_model.eval() # 検証モードに\n total_loss = 0.\n ntokens = len(TEXT.vocab.stoi)\n with torch.no_grad():\n for i in range(0, data_source.size(0) - 1, bptt):\n data, targets = get_batch(data_source, i)\n output = eval_model(data)\n output_flat = output.view(-1, ntokens)\n total_loss += len(data) * criterion(output_flat, targets).item()\n return total_loss / (len(data_source) - 1)\n```\n\nエポックを繰り返します。\n\nその最中に、検証データの損失がそれまでの実行のなかで最も良い(低い)場合はモデルを保存します。\n\nそして、各エポックの後に学習率を調整し小さくします。\n\n\n```python\nbest_val_loss = float(\"inf\")\nepochs = 3 # The number of epochs\nbest_model = None\n\nfor epoch in range(1, epochs + 1):\n epoch_start_time = time.time()\n train()\n val_loss = evaluate(model, val_data)\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n val_loss, math.exp(val_loss)))\n print('-' * 89)\n\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_model = model\n\n scheduler.step()\n```\n\n /usr/local/lib/python3.6/dist-packages/torch/optim/lr_scheduler.py:370: UserWarning: To get the last learning rate computed by the scheduler, please use `get_last_lr()`.\n \"please use `get_last_lr()`.\", UserWarning)\n\n\n | epoch 1 | 200/ 2981 batches | lr 5.00 | ms/batch 18.01 | loss 7.99 | ppl 2946.49\n | epoch 1 | 400/ 2981 batches | lr 5.00 | ms/batch 16.62 | loss 6.79 | ppl 890.76\n | epoch 1 | 600/ 2981 batches | lr 5.00 | ms/batch 16.79 | loss 6.37 | ppl 582.28\n | epoch 1 | 800/ 2981 batches | lr 5.00 | ms/batch 16.73 | loss 6.24 | ppl 511.11\n | epoch 1 | 1000/ 2981 batches | lr 5.00 | ms/batch 16.73 | loss 6.12 | ppl 452.94\n | epoch 1 | 1200/ 2981 batches | lr 5.00 | ms/batch 16.74 | loss 6.09 | ppl 442.13\n | epoch 1 | 1400/ 2981 batches | lr 5.00 | ms/batch 16.81 | loss 6.05 | ppl 425.44\n | epoch 1 | 1600/ 2981 batches | lr 5.00 | ms/batch 16.81 | loss 6.04 | ppl 421.63\n | epoch 1 | 1800/ 2981 batches | lr 5.00 | ms/batch 16.86 | loss 5.95 | ppl 384.24\n | epoch 1 | 2000/ 2981 batches | lr 5.00 | ms/batch 16.83 | loss 5.96 | ppl 389.04\n | epoch 1 | 2200/ 2981 batches | lr 5.00 | ms/batch 16.87 | loss 5.85 | ppl 348.46\n | epoch 1 | 2400/ 2981 batches | lr 5.00 | ms/batch 16.87 | loss 5.89 | ppl 361.68\n | epoch 1 | 2600/ 2981 batches | lr 5.00 | ms/batch 16.88 | loss 5.90 | ppl 363.64\n | epoch 1 | 2800/ 2981 batches | lr 5.00 | ms/batch 16.91 | loss 5.81 | ppl 333.02\n -----------------------------------------------------------------------------------------\n | end of epoch 1 | time: 52.96s | valid loss 5.71 | valid ppl 301.92\n -----------------------------------------------------------------------------------------\n | epoch 2 | 200/ 2981 batches | lr 4.51 | ms/batch 17.01 | loss 5.81 | ppl 332.85\n | epoch 2 | 400/ 2981 batches | lr 4.51 | ms/batch 16.95 | loss 5.78 | ppl 322.99\n | epoch 2 | 600/ 2981 batches | lr 4.51 | ms/batch 16.99 | loss 5.60 | ppl 270.27\n | epoch 2 | 800/ 2981 batches | lr 4.51 | ms/batch 16.98 | loss 5.64 | ppl 281.97\n | epoch 2 | 1000/ 2981 batches | lr 4.51 | ms/batch 17.02 | loss 5.60 | ppl 269.70\n | epoch 2 | 1200/ 2981 batches | lr 4.51 | ms/batch 17.01 | loss 5.62 | ppl 276.25\n | epoch 2 | 1400/ 2981 batches | lr 4.51 | ms/batch 17.03 | loss 5.64 | ppl 281.10\n | epoch 2 | 1600/ 2981 batches | lr 4.51 | ms/batch 17.08 | loss 5.67 | ppl 289.51\n | epoch 2 | 1800/ 2981 batches | lr 4.51 | ms/batch 17.13 | loss 5.59 | ppl 268.94\n | epoch 2 | 2000/ 2981 batches | lr 4.51 | ms/batch 17.10 | loss 5.63 | ppl 277.96\n | epoch 2 | 2200/ 2981 batches | lr 4.51 | ms/batch 17.14 | loss 5.52 | ppl 249.62\n | epoch 2 | 2400/ 2981 batches | lr 4.51 | ms/batch 17.10 | loss 5.58 | ppl 265.00\n | epoch 2 | 2600/ 2981 batches | lr 4.51 | ms/batch 17.15 | loss 5.59 | ppl 268.33\n | epoch 2 | 2800/ 2981 batches | lr 4.51 | ms/batch 17.18 | loss 5.52 | ppl 248.84\n -----------------------------------------------------------------------------------------\n | end of epoch 2 | time: 53.46s | valid loss 5.56 | valid ppl 259.92\n -----------------------------------------------------------------------------------------\n | epoch 3 | 200/ 2981 batches | lr 4.29 | ms/batch 17.25 | loss 5.55 | ppl 256.28\n | epoch 3 | 400/ 2981 batches | lr 4.29 | ms/batch 17.22 | loss 5.56 | ppl 259.06\n | epoch 3 | 600/ 2981 batches | lr 4.29 | ms/batch 17.19 | loss 5.37 | ppl 215.03\n | epoch 3 | 800/ 2981 batches | lr 4.29 | ms/batch 17.21 | loss 5.42 | ppl 226.48\n | epoch 3 | 1000/ 2981 batches | lr 4.29 | ms/batch 17.19 | loss 5.38 | ppl 217.09\n | epoch 3 | 1200/ 2981 batches | lr 4.29 | ms/batch 17.20 | loss 5.42 | ppl 225.31\n | epoch 3 | 1400/ 2981 batches | lr 4.29 | ms/batch 17.19 | loss 5.44 | ppl 230.62\n | epoch 3 | 1600/ 2981 batches | lr 4.29 | ms/batch 17.15 | loss 5.48 | ppl 239.92\n | epoch 3 | 1800/ 2981 batches | lr 4.29 | ms/batch 17.20 | loss 5.41 | ppl 222.97\n | epoch 3 | 2000/ 2981 batches | lr 4.29 | ms/batch 17.21 | loss 5.44 | ppl 231.59\n | epoch 3 | 2200/ 2981 batches | lr 4.29 | ms/batch 17.22 | loss 5.32 | ppl 204.66\n | epoch 3 | 2400/ 2981 batches | lr 4.29 | ms/batch 17.20 | loss 5.39 | ppl 219.99\n | epoch 3 | 2600/ 2981 batches | lr 4.29 | ms/batch 17.24 | loss 5.42 | ppl 226.52\n | epoch 3 | 2800/ 2981 batches | lr 4.29 | ms/batch 17.37 | loss 5.34 | ppl 209.23\n -----------------------------------------------------------------------------------------\n | end of epoch 3 | time: 53.91s | valid loss 5.54 | valid ppl 254.24\n -----------------------------------------------------------------------------------------\n\n\nテストデータセットでモデルを評価する\n-------------------------------------\n\n結果を確認するために、ベストモデルでテスト用データセットを評価してみます。\n\n\n\n\n```python\ntest_loss = evaluate(best_model, test_data)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\nprint('=' * 89)\n```\n\n =========================================================================================\n | End of training | test loss 5.45 | test ppl 232.03\n =========================================================================================\n\n", "meta": {"hexsha": "d23a3a0ddb2bb731f5a8ee162e61c85a96429a6a", "size": 173831, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebook/3_NLP/3_1_transformer_tutorial_jp.ipynb", "max_stars_repo_name": "koseimori/pytorch_tutorials_jp", "max_stars_repo_head_hexsha": "a43397d1988a6f820044bd32474a55318253b932", "max_stars_repo_licenses": ["zlib-acknowledgement"], "max_stars_count": 114, "max_stars_repo_stars_event_min_datetime": "2020-12-18T05:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:36:50.000Z", "max_issues_repo_path": "notebook/3_NLP/3_1_transformer_tutorial_jp.ipynb", "max_issues_repo_name": "koseimori/pytorch_tutorials_jp", "max_issues_repo_head_hexsha": "a43397d1988a6f820044bd32474a55318253b932", "max_issues_repo_licenses": ["zlib-acknowledgement"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-01-01T01:33:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T04:20:46.000Z", "max_forks_repo_path": "notebook/3_NLP/3_1_transformer_tutorial_jp.ipynb", "max_forks_repo_name": "koseimori/pytorch_tutorials_jp", "max_forks_repo_head_hexsha": "a43397d1988a6f820044bd32474a55318253b932", "max_forks_repo_licenses": ["zlib-acknowledgement"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2020-12-26T00:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:32:25.000Z", "avg_line_length": 225.1696891192, "max_line_length": 89154, "alphanum_fraction": 0.8510162169, "converted": true, "num_tokens": 8353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.1581743507642642, "lm_q1q2_score": 0.07353550422127196}} {"text": "```python\nfrom IPython.display import HTML\n\nHTML('''\n
''')\n```\n\n\n\n\n\n
\n\n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n\n\n\n''')\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''{% include jupyter_benchmark_table.html num=\"[4]\" revision=0 %}''')\n```\n\n\n\n\n{% include jupyter_benchmark_table.html num=\"[4]\" revision=0 %}\n\n\n\n# Benchmark Problem 4: Linear Elasticity in 3D\n\nThe linear elastic energy of a body is\n\n\\begin{equation}\nE_{\\rm elastic}=\\frac{1}{2}\\int \\sigma_{ij}\\epsilon_{ij}\\,dV=\\frac{1}{2}\\int C_{ijkl}\\epsilon_{ij}\\epsilon_{kl}\\,dV,\n\\end{equation}\n\nwhere $\\sigma_{ij}=C_{ijkl}\\epsilon_{kl}$ is the stress, $C_{ijkl}$ is the elastic tensor, and $\\epsilon_{ij}$ is the strain,\n\\begin{equation}\n\\epsilon_{ij}=\\frac{1}{2}\\left[\\frac{\\partial u_i}{\\partial x_j}+\\frac{\\partial u_j}{\\partial x_i}\\right],\n\\end{equation}\nwith $u_i$ the displacement field. The indices $i,j,k,l$ run from 1 to 3, and $x_i,\\,i=1,2,3$, are Cartesian coordinates; we are using Einstein summation convention so repeated indices are summed over.\n\nThe elastic tensor obeys symmetries $C_{ijkl}=C_{jikl}=C_{ijlk}=C_{jilk}$ and $C_{ijkl}=C_{klij}$. These symmetries imply that there are only 21 independent entries in the elastic tensor. Usually Voigt notation is used, in which the four indices $ijkl$ are replaced by two indices $IJ$. The mapping for each pair $ij$ (or $kl$) is $11\\to1$, $22\\to2$, $33\\to3$, $23\\to4$ (and $32\\to4$), $13\\to5$ (and $31\\to5$), and $12\\to6$ (and $21\\to6$). The crystal symmetry may further reduce the number of independent entries. In an orthorombic crystal, there are only nine independent entries, and they are (in Voigt notation) $C_{11}, C_{22}, C_{33}, C_{44}, C_{55}, C_{66}, C_{12}, C_{13}$, and $C_{23}$. The tensor $C_{IJ}$ thus has the form\n\n\\begin{equation}\n\\left(\n\\begin{matrix}\nC_{11} & C_{12} & C_{13} & 0 & 0 & 0\\\\\nC_{12} & C_{22} & C_{23} & 0 & 0 & 0 \\\\\nC_{13} & C_{23} & C_{33} & 0 & 0 & 0 \\\\\n0 & 0 & 0 & C_{44} & 0 & 0\\\\\n0 & 0 & 0 & 0 & C_{55} & 0\\\\\n0 & 0 & 0 & 0 & 0 & C_{66}\n\\end{matrix}\n\\right).\n\\end{equation}\n\nFor tetragonal symmetry, there are six independent entries, $C_{11}, C_{33}, C_{44}, C_{66}, C_{12}$, and $C_{13}$. \n\nAluminum silicate, Al$_2$SiO$_5$ is a crystal with orthorombic symmetry and unit cell parameters $a=7.738\\;\\unicode{x212B}$ , $b=7.857\\;\\unicode{x212B}$, and $c=5.534\\;\\unicode{x212B}$. The elastic tensor is given by $C_{11}=233.4$, $C_{22}=289.0$, $C_{33}=380.1$, $C_{44}=99.5$, $C_{55}=87.8$, $C_{66}=112.3$; $C_{11}+C_{22}-2C_{12}=233.4$, $C_{11}+C_{33}-2C_{13}=380.9$, and $C_{22}+C_{33}-2C_{23}=506.3$, all in units of GPa.\n\n(a) (Potato in space) What is the equilibrium shape of a 0.0042~$\\mu$m$^3$ volume of Al$_2$SiO$_5$ in free space (stress-free boundaries)? Take the surface energy, $\\gamma$, to be equal to 200 mJ/m$^2$. The crystalline axes $a$, $b$, and $c$ are aligned with the $x$, $y$, and $z$-axes of a Cartesian lab coordinate system.\n\nThis problem can be cast as a phase field problem, where the phase field $\\varphi\\in[0,1]$ takes the value of 1 in one phase (the \"potato\"), and a value of 0 in the other (the surrounding vacuum). Thus, the total free energy can be written\n\\begin{equation}\n{\\mathcal F}=\\int \\left[f_{\\rm elastic}+\\frac{\\kappa}{2}|\\nabla\\varphi|^2+h_0f(\\varphi)\\right]\\,dV,\n\\end{equation}\nwith the integral extended over all space,\nwhere\n$f(\\varphi)$ is a (dimensionless) double-well function\n\\begin{equation}\nf(\\varphi)=\\varphi^2\\left[\\varphi-1\\right]^2,\n\\end{equation}\nand $h_0$ has the dimension of energy per unit volume. The interface width $W$ between approximately $\\varphi=0.1$ and $\\varphi=0.9$ in this model is given by $W=2\\sqrt{2\\kappa/h_0}$, while $\\gamma=\\sqrt{\\kappa h_0/18}$, $\\kappa=1.5\\gamma W$, and $h_0=12\\gamma/W$ (ignoring modification of the phase field order parameter $\\varphi$ by the elastic interactions through the interface). Use $\\kappa=3\\times10^{-9}$~J/m, and\n$h_0=2.4\\times10^{8}$~J/m$^3$. \n\nWe use a simple interpolation of the elastic constants, \n\n\\begin{equation}\nC_{ijkl}=h(\\varphi)C_{ijkl}^{\\rm potato},%+\\left[1-h(\\varphi)\\right]C_{ijkl}^{\\rm matrix},\n\\end{equation}\n\nwhere $h(\\varphi)$ is a smooth interpolation function,\n\\begin{equation}\nh(\\varphi)=\\varphi^3\\left[6\\varphi^2-15\\varphi+10\\right],\n\\end{equation}\nthat interpolates between $h(\\varphi=0)=0$ and $h(\\varphi=1)=1$.\n\nHint: find time-evolution equations for $\\varphi$ that monotonically drive the total energy to a minimum while preserving the volume. One way to do this is to set up a Cahn-Hilliard equation for $\\varphi$.\n\n(b) (Compressed potato in space) What is the equilibrium shape of a 0.0042 $\\mu$m$^3$ volume Al$_2$SiO$_5$ with uniaxial compressive stress of 500~MPa applied in the $z$-direction? Note that the strain must go to zero far from the \"potato.\"\n\n(c) (Potato in a stew) A volume of Al$_2$SiO$_5$ is embedded coherently in a matrix of tetragonal symmetry with unit cell parameters $a_m=b_m=7.6918\\;\\unicode{x212B}$ and $c_m=5.5674\\;\\unicode{x212B}$ such that $a$ and $a_m$, $b$ and $b_m$ and $c$ and $c_m$ are pairwise aligned. The elastic tensor of the matrix is given by $C_{11}=C_{22}=269.0$, $C_{12}=177.0$, $C_{13}=146.0$, $C_{33}=480.0$, $C_{44}=124.0$, and $C_{66}=192.0$, all in units of GPa.\n\nThis problem can also be cast as a phase field problem, where now the phase field $\\varphi\\in[0,1]$ takes the value of 1 in one phase (the inclusion), and a value of 0 in the other (the matrix). The total free energy is again\n\\begin{equation}\n{\\mathcal F}=\\int \\left[f_{\\rm elastic}+\\frac{\\kappa}{2}|\\nabla\\varphi|^2+h_0f(\\varphi)\\right]\\,dV,\n\\end{equation}\nwhere \n$f(\\varphi)$ is given by above.\n\nThe interpolation of the elastic constants is now, \n\n\\begin{equation}\nC_{ijkl}=h(\\varphi)C_{ijkl}^{\\rm inclusion}+\\left[1-h(\\varphi)\\right]C_{ijkl}^{\\rm matrix},\n\\end{equation}\n\nwhere again $h(\\varphi)$ is a smooth interpolation function given above.\n\nIn the elastic energy, the relevant strain is the total strain $\\epsilon_{ij}$ minus the local misfit strain $\\epsilon^0_{ij}$, so\n\n\\begin{equation}\nf_{\\rm elastic}=\\frac{1}{2}C_{ijkl}\\left(\\epsilon_{ij}-\\epsilon^0_{ij}\\right)\\left(\\epsilon_{kl}-\\epsilon^0_{kl}\\right).\n\\end{equation}\n\nWe will use Vegard's law to determine the local misfit strain, for which we just interpolate the crystallographic misfit strain tensor, $\\epsilon^T_{ij}$:\n\n\\begin{equation}\n\\epsilon^0_{ij}=h(\\varphi)\\epsilon^T_{ij},\n\\end{equation}\n\nwhere $h(\\varphi)$ is the interpolation function, and $\\epsilon^T_{ij}$ is\n\\begin{equation}\n\\epsilon^T_{ij}=\\left(\n\\begin{matrix}\n\\frac{a-a_m}{a_m} & 0 & 0\\\\\n0 & \\frac{b-b_m}{b_m} & 0\\\\\n0& 0 & \\frac{c-c_c}{c_m}\n\\end{matrix}\n\\right).\n\\end{equation}\n\nFind the equilibrium shape of an isolated inclusion with a volume of 0.0042 $\\mu$m$^3$ for $\\kappa=3\\times10^{-9}$ J/m, and $h_0=2.4\\times10^{8}$ J/m$^3$. Use as an initial condition a prolate ellipsoid with $a=c=0.155$ $\\mu$m and $b=0.042$ $\\mu$m. Because of elastic strain energy and interfacial energy within the system, you will need to increase the intial values of the phase field variable in the matrix and the precipitate (e.g., $\\varphi$ in the precipitate $\\approx$ 1.05; $\\varphi$ in the matrix $\\approx 0.05$). Note that the strain must go to zero far from the \"potato\".\n\nFor parts (a) - (c), present a rendering of the final shape as well as the lengths of the \"potato\" along the principal axes, and also track the total free energy as function of \"time\" and plot it.\n\n", "meta": {"hexsha": "ec8792204a3264320ffca67876841e8e670d41bf", "size": 11622, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "hackathons/hackathon2/problem2.ipynb", "max_stars_repo_name": "wd15/chimad-phase-field", "max_stars_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-04-19T13:51:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T07:52:21.000Z", "max_issues_repo_path": "hackathons/hackathon2/problem2.ipynb", "max_issues_repo_name": "usnistgov/chimad-phase-field", "max_issues_repo_head_hexsha": "7f07e5ab046b917dfa32d84a68421ed94ec03a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 417, "max_issues_repo_issues_event_min_datetime": "2015-03-20T16:39:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-16T16:33:53.000Z", "max_forks_repo_path": "hackathons/hackathon2/problem2.ipynb", "max_forks_repo_name": "stvdwtt/chimad-phase-field", "max_forks_repo_head_hexsha": "cf0c0b923b7dcfd8eb5785fb778438387194920d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-03-20T21:44:06.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-05T23:39:36.000Z", "avg_line_length": 46.119047619, "max_line_length": 751, "alphanum_fraction": 0.5745998967, "converted": true, "num_tokens": 2682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.14804720179063333, "lm_q1q2_score": 0.07344530327876926}} {"text": "# Notebook contents: \n\nThis notebook contains a lecture. The code for generating plots are found at the of the notebook. Links below.\n\n- [presentation](#Session-1b:)\n- [code for plots](#Code-for-plots)\n\n# Session 11:\n## Machine learning introduction\n\n*Andreas Bjerre-Nielsen*\n\n## Taking stock\n\n*What have we learned until now?*\n- Fundamental data types, functions, containes, loops\n- Pandas: DataFrame, Series - these contain basic datatypes\n - A lot of powerful tools in methods/functions\n - E.g. groupby, join/merge\n- Scraping: API, HTML, and a lot more\n\n## Some coding advice\n\n- *How do I extract an object from my function?* \n - Print or return?\n- Solving complex problems: \n - Solve one thing at a time, start with the most essential that you can do now\n- Is joining datasets difficult? \n - Check out [the pandas documentation on merging](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html)\n - Or [the guide available from Jake Van der Plas](https://jakevdp.github.io/PythonDataScienceHandbook/03.07-merge-and-join.html)\n\n\n```python\ndef my_fct(a):\n b = a + 1\n return (b)\n \nc = my_fct(2)\nprint(c)\n```\n\n 3\n\n\n## Agenda\n\n1. [Math and stats review](#Math-review)\n1. [Why machine learing](#Why-machine-learning)\n1. [What is machine learning](#Machine-learning-overview)\n1. Classification models\n 1. [the perceptron](#The-perceptron-model)\n 1. [beyond the perceptron](#Beyond-the-perceptron)\n\n## Math review\n\nVector: 1-d dimensional array of numbers \n\\begin{align}\\boldsymbol{x}=[x_0,x_1,x_2,..]\\end{align}\n\n
\n\nMatrix: 2-d dimensional array of numbers \n\\begin{eqnarray}\\boldsymbol{X}=[\n[&x_{00}&,x_{01}&,x_{02}&,..&],\\\\\n[&x_{10}&,x_{11}&,x_{12}&,..&],\\\\\n[&x_{20}&,x_{21}&,x_{22}&,..&],\\\\\n[&... &,... &,... &,..&]]\n\\end{eqnarray}\n\n\n## Function fitting\n*What does (supervised) machine learning do?*\n\nSuppose we have some data $y$ we want to model/predict from input $x$. \n\nThe aim is to find a function $f$ such that the distance between actual values $y$ and predicted values $f(x)$ are minimized.\n\n*What are some examples?*\n\n- Linear form: $y=x\\beta$.\n- Logistic form: $y=g(x\\beta)$\n\nwhere $x^T\\beta=\\beta_0+x_1\\beta_1+x_2\\beta_2+...+x_n\\beta_n$ (vector dot product)\n\n# Why machine learning\n\n## Value of modelling \n*Why are models useful?*\n\nModels are pursued with differens aims. Suppose we have a linear model, $y=x\\beta+\\epsilon$.\n\n- Social science:\n - They teach us something about the world.\n - We want to estimate $\\hat{\\beta}$ and distribution\n- Data science:\n - To make optimal future decisions and precise predictions, i.e. $\\hat{y}$. \n\n## Model fragility (1)\n*What is a polynomial regression?*\n\n- Fitting a curve with an *n-dimenstional polynomial*\n- Can fit any \"regular\" curve ~ Taylor Series Approximation.\n\n## Model fragility (2)\n*Suppose we build models of the size of the Danish population, how do polynomial fits perform?*\n- We estimate model with data from 1769-1975.\n\n\n```python\nf_pop1\n```\n\n## Model fragility (3)\n*Which model performs best when we extend the forecasting period from 1975 to now?*\n\n\n```python\nf_pop2\n```\n\n## Model fragility (4)\n*What happens if we extend the prediction period until 2050? See the fifth order.*\n\n\n```python\nf_pop3\n```\n\n## Model fragility (5)\n*What trade off do we face in modelling?*\n\n- Making a model that is too simple and does not capture enough of data (`underfitting`)\n- Making a model with great fit on estimation data, but poor out-of-sample prediction (`overfitting`)\n\nThe goal of machine learning is to find models that minimize these two problems simultaneously.\n\n## Learning ML\n\n- During lectures copy code for see what it does - ***listen*** to me. Write own notes.\n- After lecture > understand code details\n- Learn with your group - VERY IMPORTANT!\n\n# Machine learning overview\n\n## Machine learning outline for this course \n\nML: short for machine learning\n\n- Problems: ***supervised*** vs unsupervised\n- Linear supervised ML models \n - classification and regression\n - regularization \n - **getting hands dirty with implementing solver**\n- Fundamental concepts of ML\n - overfitting, underfitting, model validation\n - model selection and hyperparameters\n- Emphasize differences and synergies between ML and statistics\n- Brief intro of non-linear models\n\n## What is machine learning\n*Can you define machine learning, i.e. ML?*\n\n- Supervised learning\n - Models designed to infer a relationship between input and **labeled** data. \n - We define the `target` as labels in data we wish to model. \n - Example: population as a function of year. \n- Unsupervised learning\n - Find patterns and relationships from **unlabeled** data. \n - This may involve clustering, dimensionality reduction and more. \n - Not part of the course.\n\n## Why machine learning \n*How might this be useful for social scientists?*\n\nSupervised machine learning is important (elaborated in Lecture 14):\n- Improve estimation by validating models (not only theory)\n- We can generate new data (impute missing)\n- Better predictive models \n- Use in hybrid models that leverage machine learning for causal estimation \n - (e.g. causal forest, neural instrumentation)\n\n## Supervised ML problems \n*How can we categorize a supervised ML model?*\n\nSuppose we have model $y=g(X\\beta)$\n\nWe distinguish by type of the `target` variable `y`:\n- **regression**: predict a numeric value\n- **classification**: distinguish between target categories (non-numeric data)\n\n## Supervised ML problems (2)\n*Which one is classification, which one is regression?*\n\n\n```python\nf_identify_question\n```\n\n## Supervised ML problems (3)\n\n\n```python\nf_identify_answer\n```\n\n## Regression models\n*What are examples of regressions models?*\n\n- Example of targets: income, life expectancy, education length (years)\n\n*What is the underlying data of the target, $y$?*\n\n- target is `continuous` \n\n## Classification models\n*What are examples of classification models?*\n\nTarget, `y`, are categories \n- Examples of target: kind of education (linguistics, math), mode of transportation\n - sometimes known as `factor` in statistics \n- (work for `str`, `bool`, `int`, `float` which are then interpreted as categories)\n\n\n## Example of supervised ML\n*Classification or regression?*\n\nWe load the titanic data. We select variables and make dummy variables from categorical. We split into target and features. \n\nTarget is: ...?\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\ntitanic = sns.load_dataset('titanic')\ncols = ['survived','class', 'sex', 'sibsp', 'age', 'alone']\ntitanic_sub = pd.get_dummies(titanic[cols].dropna(), drop_first=True).astype(np.int64) \n\nX = titanic_sub.drop('survived', axis=1)\ny = titanic_sub.survived\n```\n\n## Definitions\n\nML lingo and econometric equivalents (in italic)\n\n- `feature` vector, $\\textbf{x}_i$, i.e a row of input variables\n - = explanatory *variables* in econometrics\n- `weight` vector, $\\textbf{w}$, i.e model parameters\n - = *coefficients* in econometrics where denoted $\\beta$\n- `bias` term, $w_0$, i.e. the model intercept\n - = the *constant* variable in denoted $\\beta_0$\n \n\n# The perceptron model \n\n## The articifial neuron\n\nA real neuron maps stimulus (input) to output. \n\n[Research estimates](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5063692) there are 55–70 billion neurons in the brain.\n
\n\n\n## The articifial neuron (2)\nWe are interested in making a decision rule that takes arbitrary input and outputs either positive or negative. \n\nMathematically we define this map as $\\phi: \\mathbb{R}^p\\rightarrow\\{-1, 1\\}$.\n\n\\begin{align}\n\\phi(z_i)=\\begin{cases}\n\\hfill1, & z_i>0\\\\\n-1, & z_i\\le0\n\\end{cases}\n\\end{align}\n\n- `net-input`, $z_i = \\underset{~vector\\,form}{\\underbrace{\\boldsymbol{w}^{T}\\boldsymbol{x}_i}} = \\underset{~expanded\\,form}{\\underbrace{1\\cdot w_0+w_1x_{i,1}+...+w_kx_{i,k}}}$\n\n- `unit step function`, $\\phi$, checks if value exceeds threshold\n\n\n## The articifial neuron (3)\nQuiz: what are the input dimensions of the neuron, what is the output dimension?\n\n- Input is the p-dimensional space, $\\mathbb{R}^p$.\n- Output is binary, either $-1$ or $1$.\n\n## The articifial neuron (4)\n*The unit step function (left) and the decision boundary (right)*\n\n
\n\n\n## The articifial neuron (5)\n*When does the articial neuron work?*\n\n\nIf the two target types are linearly separable:\n\n
\n\n\n## The perceptron learning rule (1)\n*How do we estimate the model parameters?*\n\n1. initialize the weight with small random number\n1. for each training observation, i=1,..,n\n 1. compute predicted target, $\\hat{y}_i$\n 1. update weights $\\hat{w}$\n\n## The perceptron learning rule (2)\n*How do we compute the predicted target $\\hat{y}$?*\n\nWe apply a transformation on the net-input :\n- single observation, expanded notation:\n\\begin{align*}\n\\hat{y}_i= \\phi(z_i),\\quad z_i=w_0+w_1x_{i,1}+...+w_kx_{i,k}\n\\end{align*}\n\n- single observation, vector notation:\n\\begin{align*}\n\\hat{y}_i= \\phi(z_i),\\quad z_i=\\boldsymbol{w}^{T}\\boldsymbol{x}_i\n\\end{align*}\n\n\n- multiple observations, matrix notation:\n\\begin{align*}\n\\hat{\\boldsymbol{y}}= & \\phi(\\boldsymbol{z}),\\quad\\boldsymbol{z}=\\boldsymbol{X}\\boldsymbol{w}\n\\end{align*}\n\n## The perceptron learning rule (3)\n*How do we update weights?*\n\nWeights are updated as follows:\n\\begin{align*}\nw&=w+\\Delta w\\\\\n\\Delta w&=\\eta\\cdot(y_i-\\phi(z_i))\\cdot \\textbf{x}_{i}\\end{align*}\n\nwhere $\\eta$ is the learning rate, and the first order derivative is:\n\n$$\\frac{\\partial SSE}{\\partial w}=- \\textbf{X}^T\\textbf{e}$$\n\n## The perceptron learning rule (4)\n\nThe computation process\n\n
\n\n\n## Implementation in Python (1)\n*Let's set some values of input and output* \n\n\n```python\nX = np.random.normal(size=(3, 2)) # feature matrix\ny = np.array([1, -1, 1]) # target vector\nw = np.random.normal(size=(3)) # weight vector\nprint('X:\\n',X)\nprint('y:',y)\nprint('w:',w)\n```\n\n X:\n [[ 1.72431863 -2.03686152]\n [ 1.28450109 -0.40514301]\n [-0.61794548 0.80683709]]\n y: [ 1 -1 1]\n w: [1.26991801 0.53081782 1.16030887]\n\n\n## Implementation in Python (2)\n*How do we compute the errors vectorized?* \n\n\n```python\n# compute net-input \nz = w[0] + X.dot(w[1:]) # (w[0]: bias, w[1:]: other weights, X: features)\n\n# unit step-function\npositive = z>0 # compute prediction (boolean)\ny_hat = np.where(positive, 1, -1) # convert prediction\n\n# compute errors\ne = y - y_hat # compute errors\nSSE = e.T.dot(e)\n```\n\n## Implementation in Python (3)\n*How do we compute the updated weights?*\n\n\n```python\n# learning rate\neta = 0.001 \n\n# update weights \nupdate_vars = eta*X.T.dot(e) \nupdate_bias = eta*e.sum()/2\n```\n\n## Working with the perceptron (1)\nWe load the iris data.\n\n\n```python\niris = sns.load_dataset('iris').iloc[:100] # drop virginica\n\nX = iris.iloc[:, [0, 2]].values # keep petal_length and sepal_length\ny = np.where(iris.species=='setosa', 1, -1) # convert to 1, -1\n\nsns.scatterplot(iris.sepal_length, iris.petal_length, hue=iris.species)\n```\n\n## Working with the perceptron (2)\n*How do we fit the perceptron model?* [perceptron definition](#Code-from-Raschka-2017)\n\n\n```python\n# initialize the perceptron\nclf = Perceptron(n_iter=10) \n# clf: short for classifier (classification model), \n# n_iter: number of times to run through all observations\n\n# fit the perceptron (estimate the model)\n# runs 10 iterations of updating the model\nclf.fit(X,y)\n```\n\n\n\n\n \n\n\n\n## Working with the perceptron (3)\n*How can we evaluate the model??*\n\n\n```python\nprint('Number of errors: %i' % sum(clf.predict(X)!=y))\n\n# we plot the decisions\nplot_decision_regions(X,y,clf)\n```\n\n## Working with the perceptron (4)\n*How does the model performance change??*\n\n\n```python\nf,ax = plt.subplots(figsize=(12, 4))\nax.set_xticks(range(11))\nax.plot(range(1, len(clf.errors_) + 1), clf.errors_, marker='o')\nax.set_xlabel('Number of iterations')\nax.set_ylabel('Number of errors')\n```\n\n# Model validation\n\n## Model validation\n*How can we see how our model generalizes?*\n\nWe can simulate out-of-sample prediction. How?\n\n\n\n- Idea: Use some of our sample for model evaluation.\n- Implementation - divide data randomly into two subsets:\n - `training data` for estimation; \n - `test data` for evaluation.\n- Note: does not work for time series.\n\n\n\n## Model validation (2)\nWe revert to titanic, `y`: survived, `X`: everything else\n\n\n```python\nprint(titanic_sub.head(3))\n```\n\n survived sibsp age alone class_Second class_Third sex_male\n 0 0 1 22 0 0 1 1\n 1 1 1 38 0 0 0 0\n 2 1 0 26 1 0 1 0\n\n\nWe split the data into test and training samples\n\n\n```python\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=0)\n```\n\n# Beyond the perceptron\n\n## Motivation\n*What might we change about the perceptron?*\n\n1. Change from updating errors that are binary to continuous\n2. Use more than one observation a time for updating\n\n## The activation function (1)\n*What else might we use to update errors?*\n\n- The most simple is **no transformation** of the net-input, i.e. $\\phi(z_i)=z_i$.\n\n- When we change this from perceptron we call it Adaptive Linear Neuron (**Adaline**).\n\n## The activation function (2)\n*How is this different from the Perceptron?*\n\n
\n\n\n## The activation function (3)\n*Which activation functions can be used?*\n\n- Linear \n- Logistic (Sigmoid)\n- Unit step, sign\n\nSee page 450 in Python for Machine Learning.\n\n## The activation function (4)\n*How do Adaline and Logistic regression differ?*\n\n
\n\n\n## A new objective (1)\n*The update rule in perceptron seems ad hoc, is there a more general way?*\n\n- Yes, we minimize the sum of squared errors (SSE). The SSE for Adaline is:\n\\begin{align}SSE&=\\boldsymbol{e}^{T}\\boldsymbol{e}=e_1^2+..+e_n^2\\\\\\boldsymbol{e}&=\\textbf{y}-\\textbf{X}\\textbf{w}\\end{align}\n\n*Doesn't the above look strangely familiar?*\n\n- Yes, it is the same objective as OLS. The difference:\n - OLS computes the exact solution with system of equations from first order conditions.\n - We make an approximate solution.\n\n## A new objective (2)\n*So how the hell do we make the approximate solution?*\n\n- Two general classes:\n - We approximate the first order derivative ~ gradient descent (GD)\n - We approximate both first and second order derivative ~ quasi Newton \n
\n- We take gradient descent - much simpler (often faster)\n\n## A new objective (3)\n*How does a gradient descent look?*\n\nAn algorithm that finds the direction where expected differences are largest. Attempt of satisfying first order condition (FOC).\n\n
\n\n\n## A new objective (4)\n*What is the first order derivative of SSE wrt. weights in Adaline?*\n\n\\begin{align}\\frac{\\partial SSE}{\\partial w}=\\textbf{X}^T\\textbf{e},\\end{align}\n\n\n*How do we update with GD in Adaline?*\n\n - Idea: take small steps to approximate the solution.\n\n - $\\Delta w=\\eta\\textbf{X}^T\\textbf{e}=\\eta\\cdot\\textbf{X}^T(\\textbf{y}-\\hat{\\textbf{y}})$\n\n## A new objective (5)\nThe gradient descent algorithm we just learned uses the whole data.\n\n- Often known as batch gradient descent.\n\n*What might be a smart way of changing (batch) gradient descent?*\n\n- We only use a subset of the data. Two variants:\n - *stochastic gradient descent* (SGD): uses random subset of observations\n - *mini batch*: uses deterministic subset of observations (loop whole dataset)\n \n- Idea: we converge faster by computing update for subset of data\n - Note: we may need a million repetitions.\n\n## Applying logistic regression\n*How difficult is it to use `LogisticRegression`?*\n\nVery easy:\n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\n\n# estimate model on train data, evaluate on test data\nclf = LogisticRegression() # note try default values\n# solver='lbfgs'\nclf.fit(X_train, y_train) # model training\ny_hat = clf.predict(X_test)\naccuracy = (y_hat==y_test).mean() # model testing\nprint('Model accuracy is:', np.round(accuracy,3))\n```\n\n Model accuracy is: 1.0\n\n\n# The end\n[Return to agenda](#Agenda)\n\n# Code for plots\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport requests\nimport seaborn as sns\n\nplt.style.use('ggplot')\n%matplotlib inline\n\nSMALL_SIZE = 16\nMEDIUM_SIZE = 18\nBIGGER_SIZE = 20\n\nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n\nplt.rcParams['figure.figsize'] = 10, 4 # set default size of plots\n```\n\n### Population plots\n\n\n```python\n%run pop_plots.ipynb\n```\n\n### Plots of ML types\n\n\n```python\n%run ../ML_plots.ipynb\n```\n\n### Plots from book\n\n\n```python\nimport requests\nimport os\nbase_url = 'https://raw.githubusercontent.com/rasbt/python-machine-learning-book-2nd-edition/master/code/ch02/'\n\nfor filename in ('ch02.py', 'iris.data', 'iris.names.txt'):\n if not os.path.exists(filename):\n response = requests.get(base_url+filename)\n with open(filename,'wb') as f:\n f.write(response.text.encode('utf-8'))\n \nfrom ch02 import Perceptron, AdalineGD, AdalineSGD, plot_decision_regions\n```\n", "meta": {"hexsha": "b8845ac58d581bbcf5e16b5a34c37c9dd64b1bf4", "size": 584393, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "material/session_11/lecture_11.ipynb", "max_stars_repo_name": "abjer/sds2019", "max_stars_repo_head_hexsha": "35ed4c5727a24f66c4d3ce3faff0c583378c7695", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2019-07-02T00:43:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T10:21:19.000Z", "max_issues_repo_path": "material/session_11/lecture_11.ipynb", "max_issues_repo_name": "abjer/sds2019", "max_issues_repo_head_hexsha": "35ed4c5727a24f66c4d3ce3faff0c583378c7695", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2019-07-09T11:51:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-30T07:19:19.000Z", "max_forks_repo_path": "material/session_11/lecture_11.ipynb", "max_forks_repo_name": "abjer/sds2019", "max_forks_repo_head_hexsha": "35ed4c5727a24f66c4d3ce3faff0c583378c7695", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 101, "max_forks_repo_forks_event_min_datetime": "2019-07-15T09:02:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T05:14:11.000Z", "avg_line_length": 298.7694274029, "max_line_length": 77868, "alphanum_fraction": 0.9333547801, "converted": true, "num_tokens": 4875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.19436780635202988, "lm_q1q2_score": 0.07338175432554446}} {"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility here.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility here.\n\n\n## Krmiljenje horizontalnega pomika lunarne sonde\n\nTa primer prikazuje načrtovanje regulatorja za lateralno pozicijo lunarne sonde, izhajajoč iz dinamičnih enačb sistema.\n\n\n\nSistem je predstavljen na zgornji sliki; navpični spust sistema je upočasnjen z vertikalnim potiskom, ki deluje na sistem s konstantno silo $F$. Horizontalno gibanje dosežemo z rahlim nagibom sonde za kot $\\theta$; nagib povzroči lateralno silo, ki je približno enaka $F\\theta$. Nagib dosežemo z navorom $T$, ki ga povzročajo vodljive pogonske rakete (maksimalni navor znaša 500 Nm). Nagibni kot more biti znotraj intervala vrednosti $\\pm15$, da se prepreči nevarno povečanje hitrosti navpičnega spusta. Merjeni veličini sta lateralni pomik in hitrost, zračni upor zanemarimo, ostali sistemski parametri pa so prikazani v spodnji tabeli:\n\n| Parameter | Vrednost |\n|-----------|-------------------------------:|\n|$m$ | 1000 kg |\n|$J$ | 1000 kg$\\text{m}^2$ |\n|$F$ | 1500 N |\n\nCilj krmilnega sistema je regulacija horizontalnega pomika $z$ ob izpolnjevanju naslednjih zahtev:\n1. Maksimalni prenihaj znaša 30%.\n2. Čas ustalitve krajši od 15 s (dosežena vrednost izhoda naj se razlikuje od tiste v stacionarnem stanju za 5%).\n3. Kot $\\theta$ naj bo ves čas znotraj omenjenega intervala vrednosti, ki zagotavlja maksimalno lateralne spremembo v velikost 10 m.\n4. Brez odstopka v stacionarnem stanju v odzivu na koračno funkcijo.\n\nEnačbi sistema sta:\n\n\\begin{cases}\nJ\\ddot{\\theta}=T \\\\\nm\\ddot{z}=F\\theta\n\\end{cases}\nin ob upoštevanju vektorja stanj $\\textbf{x}=[x_1,x_2,x_3,x_4]^T=[z,\\dot{z},\\theta,\\dot{\\theta}]^T$ ter vhoda $u=T$, ju lahko preoblikujemo v obliko prostora stanj:\n\n\\begin{cases}\n\\dot{\\textbf{x}}=\\underbrace{\\begin{bmatrix}0&1&0&0 \\\\ 0&0&F/m&0 \\\\ 0&0&0&1 \\\\ 0&0&0&0\\end{bmatrix}}_{A}\\textbf{x}+\\underbrace{\\begin{bmatrix}0\\\\0\\\\0\\\\1/J\\end{bmatrix}}_{B}u \\\\ \\\\\n\\textbf{y}=\\underbrace{\\begin{bmatrix}1&0&0&0 \\\\ 0&1&0&0\\end{bmatrix}}_{C}\\textbf{x}.\n\\end{cases}\n\n### Načrtovanje krmilnika\nZa dosego ničelnega odstopka v stacionarnem stanju, sistem razširimo z novo spremenljivko stanj $\\dot{x_5}=y_1-y_d$, v kateri $y_1$ predstavlja izmerjeno lateralen pomik, $y_d$ pa zahtevan pomik. Razširjen sistem lahko torej zapišemo kot:\n\n\\begin{cases}\n\\dot{\\textbf{x}_a}=\\underbrace{\\begin{bmatrix}0&1&0&0&0 \\\\ 0&0&F/m&0&0 \\\\ 0&0&0&1&0 \\\\ 0&0&0&0&0 \\\\ 1&0&0&0&0 \\end{bmatrix}}_{A_a}\\textbf{x}_a+\\underbrace{\\begin{bmatrix} 0&0\\\\0&0\\\\0&0\\\\1/J&0\\\\0&-1 \\end{bmatrix}}_{B_a}\\underbrace{\\begin{bmatrix} u\\\\y_d \\end{bmatrix}}_{u_a} \\\\ \\\\\n\\textbf{y}_a=\\underbrace{\\begin{bmatrix}1&0&0&0&0\\\\0&1&0&0&0\\\\0&0&0&0&1\\end{bmatrix}}_{C_a}\\textbf{x}_a\n\\end{cases}\n\nSistem je vodljiv glede na prvi stolpec matrike $B_a$, zato lahko uporabimo metodo razporejanja polov. Z namenom ohranitve spoznavnosti sistema, je v matriki $C$ dodana vrstica, ker je novo stanje $x_5$ znano.\n\nMatrika ojačanj $K_a$, ki ustreza vsem zahtevam je:\n$$\nK_a=\\begin{bmatrix}2225.0&6244.0&13861.0&5275.0&316.0\\end{bmatrix}\n$$\nPoli matrike $(A_a-B_aK_a)$ so tako razporejeni v $-0.28$, $-2.24+2.23i$, $-2.24-2.23i$, $-0.26+0.32i$ in $-0.26-0.32i$.\n\n### Načrtovanje spoznavalnika\nSistem je spoznaven, in ker merimo tri spremenljivke stanj sistema, lahko načrtujemo poenostavljen spoznavalnik stanj (za $\\theta$ in $\\dot{\\theta}$), ki ima naslednjo strukturo:\n$$\n\\dot{\\hat{\\textbf{v}}}=(A_{11}+L_aA_{21})\\hat{\\textbf{v}}+(A_{12}+L_aA_{22}-A_{11}L_a-L_aA_{21}L_a)\\textbf{y}_a+(B_1+L_aB_2)u_a,\n$$\npri čemer velja\n$$\nT^{-1}A_aT=\\begin{bmatrix}A_{11}&A_{12} \\\\ A_{21}&A_{22}\\end{bmatrix}, \n\\quad T^{-1}B_a=\\begin{bmatrix}B_1 \\\\ B_2\\end{bmatrix}, \n\\quad \\overline{\\textbf{x}_a}=T^{-1}\\textbf{x}_a=\\begin{bmatrix}V \\\\ C\\end{bmatrix}\\textbf{x}_a, \n\\quad V=\\begin{bmatrix}0&0&1&0&0 \\\\ 0&0&0&1&0\\end{bmatrix}, \n\\quad \\hat{\\textbf{x}_a}=\\begin{bmatrix}\\hat{\\textbf{v}}-L_a\\textbf{y}_a \\\\ \\textbf{y}_a\\end{bmatrix}.\n$$\n\nIzbiro lastnih vrednosti spoznavalnika izvedemo tako, da dinamika napake ocene stanj konvergira hitreje kot pa dinamika sistema, določena z zgornjimi zahtevami. Lastni vrednosti matrike $A_{11}+L_aA_{21}$ sta $\\lambda_i=-10$rad/s, $i=1,2$ z $$ L_a=\\begin{bmatrix}0&-\\frac{40}{3}&0 \\\\ 0&-\\frac{200}{3}&0\\end{bmatrix} $$\n\n\n### Kako upravljati s tem interaktivnim primerom?\nOpazuj delovanje sistema z načrtovanim regulatorjem in direktno spreminjaj krmilnik in spoznavalnik. Simulacija se vedno začne z začetno napako spoznavalnika.\n\n\n```python\n#Preparatory Cell \n\n%matplotlib notebook\nimport control as ctrl\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\nimport matplotlib.transforms as transforms\nimport matplotlib.lines as lines\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(ctrl.StateSpace):\n def __init__(self,*args):\n #call base class init constructor\n ctrl.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# Define matrixes\n\nA = numpy.matrix('0 1 0 0; 0 0 1.5 0; 0 0 0 1; 0 0 0 0')\nB = numpy.matrix('0;0;0;0.001')\nC = numpy.matrix('1 0 0 0; 0 1 0 0')\nAa = numpy.matrix('0 1 0 0 0; 0 0 1.5 0 0; 0 0 0 1 0; 0 0 0 0 0; 1 0 0 0 0')\nBa = numpy.matrix('0 0;0 0;0 0;0.001 0;0 -1')\nCa = numpy.matrix('1 0 0 0 0; 0 1 0 0 0; 0 0 0 0 1')\nKa1 = numpy.matrix('[2225.0, 6244.0, 13861.0, 5275.0, 316.0') #318.9333 835 2012.5 2000 59.6\nTa = (numpy.matrix('0 0 1 0 0; 0 0 0 1 0; 1 0 0 0 0;0 1 0 0 0; 0 0 0 0 1'))**(-1)\nAr = Ta**(-1)*Aa*Ta\nBr = Ta**(-1)*Ba\nA11 = Ar[0:2,0:2]\nA12 = Ar[0:2,2:5]\nA21 = Ar[2:5,0:2]\nA22 = Ar[2:5,2:5]\nB1 = Br[0:2,:]\nB2 = Br[2:5,:]\nLa1 = numpy.matrix([[0, -4*10/3, 0],[0, -3/8*(-4*10/3)**2, 0]])\nX0a = numpy.matrix('0;0;0;0;0;0;0;0;0;0;0.002;0.002;0;0;0;0;0;0.002;0.002;0;0;0;0;0')\n# X0a = numpy.matrix('0;0;0;0;0')\n# V0 = numpy.matrix('0;0')\n```\n\n\n```python\n# Define matrixes widget\nKaw = matrixWidget(1,5)\nLaw = matrixWidget(2,3)\neig1 = matrixWidget(1,1)\neig2 = matrixWidget(2,1)\neig3 = matrixWidget(2,1)\neig4 = matrixWidget(1,1)\neig5 = matrixWidget(1,1)\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\n\nYdw = widgets.FloatSlider(\n value=10,\n min=0,\n max=10.0,\n step=0.1,\n description='$y_d$:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.1f',\n )\n\n# Init matrix widgets\nKaw.setM(Ka1) \nLaw.setM(La1)\n#[-0.6,-0.5-0.35j,-0.5+0.35j,-0.2-0.6j,-0.2+0.6j]\neig1.setM(numpy.matrix([-0.28]))\neig2.setM(numpy.matrix([[-2.24],[-2.23]]))\neig3.setM(numpy.matrix([[-0.26],[-0.32]])) \neig4.setM(numpy.matrix([-1])) \neig5.setM(numpy.matrix([-1])) \neig1o.setM(numpy.matrix([-10])) \neig2o.setM(numpy.matrix([[-10],[0]])) \n```\n\n\n```python\n# Support functions\n# Simulation function\ndef simulation(Aa, Baa, Ca, A11, A12, A21, A22, B1, B2, La, Ka, Ta):\n Aa, Baa, Ca = sym.Matrix(Aa), sym.Matrix(Baa), sym.Matrix(Ca)\n A11, A12, A21, A22 = sym.Matrix(A11), sym.Matrix(A12), sym.Matrix(A21), sym.Matrix(A22)\n B1, B2 = sym.Matrix(B1), sym.Matrix(B2)\n La, Ka = sym.Matrix(La), sym.Matrix(Ka)\n Ta = sym.Matrix(Ta)\n sysS = sss(Aa, Baa, Ca, sym.zeros(3,2))\n sysX = sss(Aa, Baa, sym.eye(5), sym.zeros(5,2))\n sysO1 = sss((A11+La*A21), (B1+La*B2).row_join(A12+La*A22-A11*La-La*A21*La), sym.eye(2), sym.zeros(2,5))\n sysO2 = ctrl.append(sysO1, sysS)\n sysO3 = ctrl.connect(sysO2, [[3, 3], [4, 4], [5, 5]], [1, 2, 6, 7], [1, 2, 3, 4, 5])\n sysO = sss(sysO3.A,\n sysO3.B*sym.eye(2).col_join(sym.eye(2)),\n Ta*(sym.eye(2).row_join(-La)).col_join(sym.zeros(3, 2).row_join(sym.eye(3)))*sysO3.C,\n sym.zeros(5,2))\n sysU = sss(sysO.A, sysO.B, -Ka*sysO.C, sym.zeros(1,2))\n sysT = ctrl.append(sysS, sysX, sysO, sysU)\n sysT1 = ctrl.connect(sysT, [[1, 14], [3, 14], [5, 14], [7, 14]], [2, 4, 6, 8], [i for i in range(1, 15)])\n sys = sss(sysT1.A, sysT1.B*sym.Matrix([1, 1, 1, 1]), sysT1.C, sym.zeros(14, 1))\n return sys\n\n# check functions\ndef eigen_choice(selc,selo):\n if selc == 'brez kompleksnih lastnih vrednosti':\n eig2.children[1].children[0].disabled = True\n eig3.children[1].children[0].disabled = True\n eig3.children[0].children[0].disabled = False\n eig4.children[0].children[0].disabled = False\n eig5.children[0].children[0].disabled = False\n eigc = 0\n if selc == 'dve kompleksni lastni vrednosti':\n eig2.children[1].children[0].disabled = False\n eig3.children[1].children[0].disabled = True\n eig3.children[0].children[0].disabled = True\n eig4.children[0].children[0].disabled = False\n eig5.children[0].children[0].disabled = False\n eigc = 2\n if selc == 'štiri kompleksne lastne vrednosti':\n eig2.children[1].children[0].disabled = False\n eig3.children[1].children[0].disabled = False\n eig3.children[0].children[0].disabled = False\n eig4.children[0].children[0].disabled = True\n eig5.children[0].children[0].disabled = True\n eigc = 4\n if selo == 'brez kompleksnih lastnih vrednosti':\n eig1o.children[0].children[0].disabled = False\n eig2o.children[1].children[0].disabled = True\n eigo = 0\n if selo == 'dve kompleksni lastni vrednosti':\n eig1o.children[0].children[0].disabled = True\n eig2o.children[1].children[0].disabled = False\n eigo = 2\n return (eigc, eigo)\n\ndef method_choice(selm):\n if selm == 'Nastavi Ka in La':\n method = 1\n selc.disabled = True\n selo.disabled = True\n if selm == 'Nastavi lastne vrednosti':\n method = 2\n selc.disabled = False\n selo.disabled = False\n return method\n\n# Animation functions\ndef fun_animation(index):\n global Ydw, yout, T\n yd = Ydw.value\n frame = 1\n \n linez.set_data(T[0:index*frame],yd*yout[0][0:index*frame])\n linezv.set_data(T[0:index*frame],yd*yout[1][0:index*frame])\n lined.set_data(T,[yd for i in range(0,len(T))])\n lineu.set_data(T[0:index*frame],yd*yout[13][0:index*frame])\n linelimu1.set_data(T,[500 for j in range(0,len(T))])\n linelimu2.set_data(T,[-500 for j in range(0,len(T))])\n linethetaest.set_data(T[0:index*frame],yd*yout[10][0:index*frame]*180/numpy.pi)\n linetheta.set_data(T[0:index*frame],yd*yout[5][0:index*frame]*180/numpy.pi)\n \n \n rotation_transform.clear().translate(yd*yout[0][index*frame]*numpy.cos(float(yd*yout[6][index*frame])), yd*yout[0][index*frame]*numpy.sin(float(yd*yout[6][index*frame]))).rotate(float(-yd*yout[6][index*frame]))\n \n return (linez,linezv,lined,lineu,linelimu1,linelimu2,linethetaest,linetheta)\n\ndef anim_init():\n linez.set_data([], [])\n linezv.set_data([], [])\n lined.set_data([], [])\n lineu.set_data([], [])\n linelimu1.set_data([], [])\n linelimu2.set_data([], [])\n linethetaest.set_data([], [])\n linetheta.set_data([], [])\n return (linez,linezv,lined,lineu,linelimu1,linelimu2,linethetaest,linetheta)\n\n```\n\n\n```python\n# Main cell\n# Data\nglobal yd, T, yout\nyd = 10.\nT = []\nyout = []\n\n# Figures\nfig = plt.figure(num='Simulacija krmiljenja horizontalnega pomika lunarne sonde')\nfig.set_size_inches((9.8, 6))\nfig.set_tight_layout(True)\n\nax0 = fig.add_subplot(221)\nax0.set_title('Lunarna sonda')\nax0.set_xlim(-12,12)\nax0.set_ylim(-4,4)\nax0.grid()\n# ax0.axis('off')\n\nax1 = fig.add_subplot(222)\nlinez = ax1.plot([],[])[0]\nlinezv = ax1.plot([],[])[0]\nlined = ax1.plot([],[])[0]\nax1.set_title('Lateralni pomik in hitrost')\nax1.set_xlabel('$t$ [s]')\nax1.set_ylabel('y [m], $\\dot y$ [m/s]')\nax1.set_xlim([0,17])\nax1.axvline(x=0,color='black',linewidth=0.8)\nax1.axhline(y=0,color='black',linewidth=0.8)\nax1.grid()\nax1.legend(['Lateralni pomik','Lateralna hitrost','Zahtevana vrednost'])\n\nax2 = fig.add_subplot(223)\nlineu = ax2.plot([],[])[0]\nlinelimu1 = ax2.plot([],[],'r')[0]\nlinelimu2 = ax2.plot([],[],'r')[0]\nax2.set_title('Vhodni navor T')\nax2.set_xlabel('$t$ [s]')\nax2.set_ylabel('$T$ [Nm]')\nax2.set_xlim([0,17])\nax2.axvline(x=0,color='black',linewidth=0.8)\nax2.axhline(y=0,color='black',linewidth=0.8)\nax2.grid()\nax2.legend(['T','Limit'])\n\nax3 = fig.add_subplot(224)\nlinethetaest = ax3.plot([],[])[0]\nlinetheta = ax3.plot([],[])[0]\nax3.set_title(r'$\\theta_{est}$ vs $\\theta$')\nax3.set_xlabel('$t$ [s]')\nax3.set_ylabel(r'$\\theta$ [deg]')\nax3.axvline(x=0,color='black',linewidth=0.8)\nax3.axhline(y=0,color='black',linewidth=0.8)\nax3.set_xlim([0,17])\nax3.grid()\n\n# Patches\nrotation_transform = transforms.Affine2D()\ncircle = patches.Circle((0, 0.6), fill=True, radius=0.5, ec='black', fc='gray', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nrect = patches.Rectangle((-1, -0.4), 2, 0.5, fill=True, ec='black', fc='gray', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\npoly = patches.Polygon(numpy.stack(([-0.25, -0.15, 0.15, 0.25], [-0.8, -0.4, -0.4, -0.8])).T, \n closed=True, fill=True, ec='black', fc='black', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nlleg = patches.Rectangle((-1, -1.2), 0.05, 1, angle=-15, fill=True, ec='black', fc='black', lw=1, zorder=10, \n transform=rotation_transform + ax0.transData)\nrleg = patches.Rectangle((1, -1.2), 0.05, 1, angle=15, fill=True, ec='black', fc='black', lw=1, zorder=10, \n transform=rotation_transform + ax0.transData)\nlfoot = patches.Rectangle((-1.1, -1.2), 0.2, 0.05, fill=True, ec='black', fc='black', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nrfoot = patches.Rectangle((0.9, -1.2), 0.2, 0.05, fill=True, ec='black', fc='black', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nax0.add_patch(circle)\nax0.add_patch(rect)\nax0.add_patch(poly)\nax0.add_patch(lleg)\nax0.add_patch(rleg)\nax0.add_patch(lfoot)\nax0.add_patch(rfoot)\nplt.show()\n\n# Functions\ndef main_function(Ka,La,Ydw,eig1,eig2,eig3,eig4,eig5,eig1o,eig2o,selm,selc,selo,DW):\n global T, yout, yd, Aa, Ba, A11, A21\n method = method_choice(selm)\n eigc, eigo = eigen_choice(selc,selo)\n yd = Ydw\n ax1.set_ylim([-0.1*yd,yd*1.5])\n ax2.set_ylim([-51*yd,51*yd])\n ax3.set_ylim([-15,15])\n \n if method == 1: #Setted matrix gain\n sol = numpy.linalg.eig((Aa-Ba[:,0]*Ka))\n print('Lastne vrednosti Aa so: '+str(round(sol[0][0],3))+', '+str(round(sol[0][1],3))+', '+str(round(sol[0][2],3))+', '+str(round(sol[0][3],3))+' in '+str(round(sol[0][4],3)))\n sol = numpy.linalg.eig(A11+La*A21)\n print('Lastni vrednosti A11+La*A21 sta: '+str(round(sol[0][0],3))+' in '+str(round(sol[0][1],3))) \n sys = simulation(Aa, Ba, Ca, A11, A12, A21, A22, B1, B2, La, Ka, Ta)\n T = numpy.linspace(0, 17, 100)\n T, yout = ctrl.step_response(sys, T, X0a)\n if method == 2: #Setted eigenvalues\n if eigc == 0:\n Ka = ctrl.acker(Aa, Ba[:,0], [eig1[0,0], eig2[0,0], eig3[0,0], eig4[0,0], eig5[0,0]])\n Kaw.setM(Ka)\n if eigc == 2:\n Ka = ctrl.acker(Aa, Ba[:,0], [eig1[0,0], numpy.complex(eig2[0,0],eig2[1,0]), numpy.complex(eig2[0,0],-eig2[1,0]), eig4[0,0], eig5[0,0]])\n Kaw.setM(Ka)\n if eigc == 4:\n Ka = ctrl.acker(Aa, Ba[:,0], [eig1[0,0], numpy.complex(eig2[0,0],eig2[1,0]), numpy.complex(eig2[0,0],-eig2[1,0]), numpy.complex(eig3[0,0],eig3[1,0]), numpy.complex(eig3[0,0],-eig3[1,0])])\n Kaw.setM(Ka)\n if eigo == 0:\n La = numpy.matrix([[0, 2*eig1o[0,0]/3 + 2*eig2o[0,0]/3, 0], [0, -2*eig1o[0,0]*eig2o[0,0]/3, 0]])\n Law.setM(La) \n if eigo == 2:\n La = numpy.matrix([[0, 2*numpy.complex(eig2o[0,0],eig2o[1,0])/3 + 2*numpy.complex(eig2o[0,0],-eig2o[1,0])/3, 0], [0, -2*numpy.complex(eig2o[0,0],eig2o[1,0])*numpy.complex(eig2o[0,0],-eig2o[1,0])/3, 0]])\n Law.setM(La)\n sol = numpy.linalg.eig((Aa-Ba[:,0]*Ka))\n print('Lastne vrednosti Aa so: '+str(round(sol[0][0],3))+', '+str(round(sol[0][1],3))+', '+str(round(sol[0][2],3))+', '+str(round(sol[0][3],3))+' in '+str(round(sol[0][4],3)))\n sol = numpy.linalg.eig(A11+La*A21)\n print('Lastni vrednosti A11+La*A21 sta: '+str(round(sol[0][0],3))+' in '+str(round(sol[0][1],3))) \n sys = simulation(Aa, Ba, Ca, A11, A12, A21, A22, B1, B2, La, Ka, Ta)\n T = numpy.linspace(0, 17, 100)\n T, yout = ctrl.step_response(sys, T, X0a)\n\nani = animation.FuncAnimation(fig, fun_animation, init_func=anim_init, frames=100, repeat=True, interval=170, blit=True)\n\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 Ka in La', 'Nastavi lastne vrednosti'],\n value= 'Nastavi Ka in La',\n description='',\n disabled=False\n)\n\n# Define the number of complex eigenvalues for the controller\nselc = widgets.Dropdown(\n options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti', 'štiri kompleksne lastne vrednosti'],\n value= 'štiri kompleksne lastne vrednosti',\n description='Aa:',\n disabled=False\n)\n\n# Define the number of complex eigenvalues for the observer\nselo = widgets.Dropdown(\n options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti'],\n value= 'brez kompleksnih lastnih vrednosti',\n description='Aobs:',\n disabled=False\n)\n\nalltogether = widgets.VBox([\n widgets.HBox([\n selm,\n selc,\n selo\n ]),\n widgets.Label('',border=3),\n widgets.HBox([\n widgets.Label('Ka:',border=3),\n Kaw,\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n widgets.Label('La:',border=3),\n Law\n ]),\n widgets.Label('',border=3),\n widgets.HBox([\n widgets.Label('Aa\\'s eigs:',border=3),\n eig1, eig2, eig3, eig4, eig5,\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n widgets.Label('Aobs\\'s eigs:',border=3),\n eig1o, eig2o\n ]),\n widgets.Label('',border=3),\n widgets.HBox([\n Ydw,\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n START\n ])\n])\n\nout = widgets.interactive_output(main_function,{'Ka':Kaw, 'La':Law, 'Ydw':Ydw, 'eig1':eig1, 'eig2':eig2, \n 'eig3':eig3, 'eig4':eig4, 'eig5':eig5,\n 'eig1o':eig1o, 'eig2o':eig2o,\n 'selm':selm, 'selc':selc, 'selo':selo, 'DW':DW})\ndisplay(out, alltogether)\n```\n\n\n \n\n\n\n\n\n\n\n Output()\n\n\n\n VBox(children=(HBox(children=(Dropdown(options=('Nastavi Ka in La', 'Nastavi lastne vrednosti'), value='Nastav…\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "33bc9e7c470a05a790f25d4826894220a1e78641", "size": 472865, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-38-Krmiljenje_horizontalne_pozicije_lunarne_sonde.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-38-Krmiljenje_horizontalne_pozicije_lunarne_sonde.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-38-Krmiljenje_horizontalne_pozicije_lunarne_sonde.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": 48.1238550784, "max_line_length": 134581, "alphanum_fraction": 0.6951836148, "converted": true, "num_tokens": 8158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.16667539640920676, "lm_q1q2_score": 0.0729744077173761}} {"text": "##### Copyright 2020 The OpenFermion Developers\n\n\n```python\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# FQE vs OpenFermion vs Cirq: Diagonal Coulomb Operators\n\n\n \n \n \n \n
\n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\nSpecial routines are available for evolving under a diagonal Coulomb operator. This notebook describes how to use these built in routines and how they work.\n\n\n```python\ntry:\n import fqe\nexcept ImportError:\n !pip install fqe --quiet\n```\n\n\n```python\nfrom itertools import product\nimport fqe\nfrom fqe.hamiltonians.diagonal_coulomb import DiagonalCoulomb\n\nimport numpy as np\n\nimport openfermion as of\n\nfrom scipy.linalg import expm\n```\n\n\n```python\n#Utility function\ndef uncompress_tei(tei_mat, notation='chemistry'):\n \"\"\"\n uncompress chemist notation integrals\n\n tei_tensor[i, k, j, l] = tei_mat[(i, j), (k, l)]\n [1, 1, 2, 2] = [1, 1, 2, 2] = [1, 1, 2, 2] = [1, 1, 2, 2]\n [i, j, k, l] = [k, l, i, j] = [j, i, l, k]* = [l, k, j, i]*\n\n For real we also have swap of i <> j and k <> l\n [j, i, k, l] = [l, k, i, j] = [i, j, l, k] = [k, l, j, i]\n\n tei_mat[(i, j), (k, l)] = int dr1 int dr2 phi_i(dr1) phi_j(dr1) O(r12) phi_k(dr1) phi_l(dr1)\n\n Physics notation is the notation that is used in FQE.\n\n Args:\n tei_mat: compressed two electron integral matrix\n\n Returns:\n uncompressed 4-electron integral tensor. No antisymmetry.\n \"\"\"\n if notation not in ['chemistry', 'physics']:\n return ValueError(\"notation can be [chemistry, physics]\")\n\n norbs = int(0.5 * (np.sqrt(8 * tei_mat.shape[0] + 1) - 1))\n basis = {}\n cnt = 0\n for i, j in product(range(norbs), repeat=2):\n if i >= j:\n basis[(i, j)] = cnt\n cnt += 1\n\n tei_tensor = np.zeros((norbs, norbs, norbs, norbs))\n for i, j, k, l in product(range(norbs), repeat=4):\n if i >= j and k >= l:\n tei_tensor[i, j, k, l] = tei_mat[basis[(i, j)], basis[(k, l)]]\n tei_tensor[k, l, i, j] = tei_mat[basis[(i, j)], basis[(k, l)]]\n tei_tensor[j, i, l, k] = tei_mat[basis[(i, j)], basis[(k, l)]]\n tei_tensor[l, k, j, i] = tei_mat[basis[(i, j)], basis[(k, l)]]\n\n tei_tensor[j, i, k, l] = tei_mat[basis[(i, j)], basis[(k, l)]]\n tei_tensor[l, k, i, j] = tei_mat[basis[(i, j)], basis[(k, l)]]\n tei_tensor[i, j, l, k] = tei_mat[basis[(i, j)], basis[(k, l)]]\n tei_tensor[k, l, j, i] = tei_mat[basis[(i, j)], basis[(k, l)]]\n\n if notation == 'chemistry':\n return tei_tensor\n elif notation == 'physics':\n return np.asarray(tei_tensor.transpose(0, 2, 1, 3), order='C')\n\n return tei_tensor\n\n```\n\nThe first example we will perform is diagonal Coulomb evolution on the Hartree-Fock state. The diagonal Coulomb operator is defined as\n\n\\begin{align}\nV = \\sum_{\\alpha, \\beta \\in \\{\\uparrow, \\downarrow\\}}\\sum_{p,q} V_{pq,pq}n_{p,\\alpha}n_{q,\\beta}\n\\end{align}\n\nThe number of free parpameters are $\\mathcal{O}(N^{2})$ where $N$ is the rank of the spatial basis. The `DiagonalCoulomb` Hamiltonian takes either a generic 4-index tensor or the $N \\times N$ matrix defining $V$. If the 4-index tensor is given the $N \\times N$ matrix is constructed along with the diagonal correction. If the goal is to just evolve under $V$ it is recommended the user input the $N \\times N$ matrix directly.\n\nAll the terms in $V$ commute and thus we can evolve under $V$ exactly by counting the accumulated phase on each bitstring.\n\n\nTo start out let's define a Hartree-Fock wavefunction for 4-orbitals and 2-electrons $S_{z} =0$.\n\n\n```python\nnorbs = 4\ntedim = norbs * (norbs + 1) // 2\nif (norbs // 2) % 2 == 0:\n n_elec = norbs // 2\nelse:\n n_elec = (norbs // 2) + 1\nsz = 0\nfqe_wfn = fqe.Wavefunction([[n_elec, sz, norbs]])\nfci_data = fqe_wfn.sector((n_elec, sz))\nfci_graph = fci_data.get_fcigraph()\nhf_wf = np.zeros((fci_data.lena(), fci_data.lenb()), dtype=np.complex128)\nhf_wf[0, 0] = 1 # right most bit is zero orbital.\nfqe_wfn.set_wfn(strategy='from_data',\n raw_data={(n_elec, sz): hf_wf})\nfqe_wfn.print_wfn()\n```\n\nNow we can define a random 2-electron operator $V$. To define $V$ we need a $4 \\times 4$ matrix. We will generate this matrix by making a full random two-electron integral matrix and then just take the diagonal elements\n\n\n```python\ntei_compressed = np.random.randn(tedim**2).reshape((tedim, tedim))\ntei_compressed = 0.5 * (tei_compressed + tei_compressed.T)\ntei_tensor = uncompress_tei(tei_compressed, notation='physics')\n\ndiagonal_coulomb = of.FermionOperator()\ndiagonal_coulomb_mat = np.zeros((norbs, norbs))\nfor i, j in product(range(norbs), repeat=2):\n diagonal_coulomb_mat[i, j] = tei_tensor[i, j, i, j]\n for sigma, tau in product(range(2), repeat=2):\n diagonal_coulomb += of.FermionOperator(\n ((2 * i + sigma, 1), (2 * i + sigma, 0), (2 * j + tau, 1),\n (2 * j + tau, 0)), coefficient=diagonal_coulomb_mat[i, j])\n\ndc_ham = DiagonalCoulomb(diagonal_coulomb_mat)\n\n```\n\nEvolution under $V$ can be computed by looking at each bitstring, seeing if $n_{p\\alpha}n_{q\\beta}$ is non-zero and then phasing that string by $V_{pq}$. For the Hartree-Fock state we can easily calculate this phase accumulation. The alpha and beta bitstrings are \"0001\" and \"0001\". \n\n\n```python\nalpha_occs = [list(range(fci_graph.nalpha()))]\nbeta_occs = [list(range(fci_graph.nbeta()))]\noccs = alpha_occs[0] + beta_occs[0]\ndiag_ele = 0.\nfor ind in occs:\n for jnd in occs:\n diag_ele += diagonal_coulomb_mat[ind, jnd]\nevolved_phase = np.exp(-1j * diag_ele)\nprint(evolved_phase)\n\n# evolve FQE wavefunction\nevolved_hf_wfn = fqe_wfn.time_evolve(1, dc_ham)\n\n# check they the accumulated phase is equivalent!\nassert np.isclose(evolved_hf_wfn.get_coeff((n_elec, sz))[0, 0], evolved_phase)\n\n```\n\nWe can now try this out for more than 2 electrons. Let's reinitialize a wavefunction on 6-orbitals with 4-electrons $S_{z} = 0$ to a random state.\n\n\n```python\nnorbs = 6\ntedim = norbs * (norbs + 1) // 2\nif (norbs // 2) % 2 == 0:\n n_elec = norbs // 2\nelse:\n n_elec = (norbs // 2) + 1\nsz = 0\nfqe_wfn = fqe.Wavefunction([[n_elec, sz, norbs]])\nfqe_wfn.set_wfn(strategy='random')\ninital_coeffs = fqe_wfn.get_coeff((n_elec, sz)).copy()\nprint(\"Random initial wavefunction\")\nfqe_wfn.print_wfn()\n```\n\nWe need to build our Diagoanl Coulomb operator For this bigger system.\n\n\n```python\ntei_compressed = np.random.randn(tedim**2).reshape((tedim, tedim))\ntei_compressed = 0.5 * (tei_compressed + tei_compressed.T)\ntei_tensor = uncompress_tei(tei_compressed, notation='physics')\n\ndiagonal_coulomb = of.FermionOperator()\ndiagonal_coulomb_mat = np.zeros((norbs, norbs))\nfor i, j in product(range(norbs), repeat=2):\n diagonal_coulomb_mat[i, j] = tei_tensor[i, j, i, j]\n for sigma, tau in product(range(2), repeat=2):\n diagonal_coulomb += of.FermionOperator(\n ((2 * i + sigma, 1), (2 * i + sigma, 0), (2 * j + tau, 1),\n (2 * j + tau, 0)), coefficient=diagonal_coulomb_mat[i, j])\n\ndc_ham = DiagonalCoulomb(diagonal_coulomb_mat)\n\n```\n\nNow we can convert our wavefunction to a cirq wavefunction, evolve under the diagonal_coulomb operator we constructed and then compare the outputs.\n\n\n```python\ncirq_wfn = fqe.to_cirq(fqe_wfn).reshape((-1, 1))\nfinal_cirq_wfn = expm(-1j * of.get_sparse_operator(diagonal_coulomb)) @ cirq_wfn\n# recover a fqe wavefunction\nfrom_cirq_wfn = fqe.from_cirq(final_cirq_wfn.flatten(), 1.0E-8)\n\n```\n\n\n```python\nfqe_wfn = fqe_wfn.time_evolve(1, dc_ham)\nprint(\"Evolved wavefunction\")\nfqe_wfn.print_wfn()\n```\n\n\n```python\nprint(\"From Cirq Evolution\")\nfrom_cirq_wfn.print_wfn()\nassert np.allclose(from_cirq_wfn.get_coeff((n_elec, sz)),\n fqe_wfn.get_coeff((n_elec, sz)))\nprint(\"Wavefunctions are equivalent\")\n```\n\nFinally, we can compare against evolving each term of $V$ individually.\n\n\n```python\nfqe_wfn = fqe.Wavefunction([[n_elec, sz, norbs]])\nfqe_wfn.set_wfn(strategy='from_data',\n raw_data={(n_elec, sz): inital_coeffs})\nfor term, coeff in diagonal_coulomb.terms.items():\n op = of.FermionOperator(term, coefficient=coeff)\n fqe_wfn = fqe_wfn.time_evolve(1, op)\n\nassert np.allclose(from_cirq_wfn.get_coeff((n_elec, sz)),\n fqe_wfn.get_coeff((n_elec, sz)))\nprint(\"Individual term evolution is equivalent\")\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "3b477d6116596f517905bb40bea0d9144078f881", "size": 14367, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/diagonal_coulomb_evolution.ipynb", "max_stars_repo_name": "rmlarose/OpenFermion-FQE", "max_stars_repo_head_hexsha": "54489126725fe3bb83218b6fde9d44f6cf130359", "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/tutorials/diagonal_coulomb_evolution.ipynb", "max_issues_repo_name": "rmlarose/OpenFermion-FQE", "max_issues_repo_head_hexsha": "54489126725fe3bb83218b6fde9d44f6cf130359", "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/diagonal_coulomb_evolution.ipynb", "max_forks_repo_name": "rmlarose/OpenFermion-FQE", "max_forks_repo_head_hexsha": "54489126725fe3bb83218b6fde9d44f6cf130359", "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": 35.3866995074, "max_line_length": 440, "alphanum_fraction": 0.5645576669, "converted": true, "num_tokens": 3030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.16885694377651225, "lm_q1q2_score": 0.07198736118350474}} {"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols, eye\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n\n```python\nlamda = symbols('lamda') # Note that lambda is a reserved word in python, so we use lamda (without the b)\n```\n\n# Eigenvalues and eigenvectors\n\n## What are eigenvectors?\n\n* A Matrix is a mathematical object that acts on a (column) vector, resulting in a new vector, i.e. A**x**=**b**\n* An eigenvector is the resulting vector that is parallel to **x** (some multiple of **x**)\n$$ {A}\\underline{x}=\\lambda \\underline{x} $$\n\n* The eigenvectors with an eigenvalue of zero are the vectors in the nullspace\n* If A is singular (takes some non-zero vector into 0) then λ=0\n\n## What are the eigenvectors and eigenvalues for projection matrices?\n\n* A projection matrix P projects some vector (**b**) onto a subspace (in 3-space we are talking about a plane through the origin)\n* P**b** is not in the same direction as **b**\n* A vector **x** that is already in the subspace will result in P**x**=**x**, so λ=1\n* Another good **x** would be one perpendicular to the subspace, i.e. P**x**=0**x**, so λ=0\n\n## What are the eigenvectors and eigenvalues for permutation matrices?\n\n* A permutation matrix such as the one below changes the order of the elements in a (column) vector\n$$ \\begin{bmatrix} 0 & 1 \\\\ 1 & 0 \\end{bmatrix} $$\n* A good example of a vector that would remain in the same direction after multiplication by the permutation matrix above would the following vector\n$$ \\begin{bmatrix} 1 \\\\ 1 \\end{bmatrix} $$\n* The eigenvalue would just be λ=1\n* The next (eigen)vector would also work\n$$ \\begin{bmatrix} -1 \\\\ 1 \\end{bmatrix} $$\n* It would have an eigenvalue of λ=-1\n\n## The trace and the determinant\n\n* The trace is the sum of the values down the main diagonal of a square matrix\n* Note how this is the same as the sum of the eigenvalues (look at the permutation matrix above and its eigenvalues)\n* The determinant of A is the product of the eigenvalues\n\n## How to solve A**x**=λ**x**\n\n$$ A\\underline { x } =\\lambda \\underline { x } \\\\ \\left( A-\\lambda I \\right) \\underline { x } =\\underline { 0 } $$\n\n* The only solution to this equation is for A-λI to be singular and therefor have a determinant of zero\n$$ \\left|{A}-\\lambda{I}\\right|=0 $$\n\n* This is called the characteristic (or eigenvalue) equation\n* There will be *n* λ's for a *n*×*n* matrix(some of which may be of equal value) \n\n\n```python\nA = Matrix([[3, 1], [1, 3]])\nI = eye(2)\nA, I # Printing A and the 2-by-2 identity matrix to the screen\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}3 & 1\\\\1 & 3\\end{matrix}\\right], & \\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n\n```python\n(A - lamda * I) # Printing A minus lambda times the identity matrix to the screen\n```\n\n\n\n\n$$\\left[\\begin{matrix}- \\lambda + 3 & 1\\\\1 & - \\lambda + 3\\end{matrix}\\right]$$\n\n\n\n* This will have the following determinant\n\n\n```python\n(A - lamda * I).det()\n```\n\n\n\n\n$$\\lambda^{2} - 6 \\lambda + 8$$\n\n\n\n* For this 2×2 matrix the absolute value of the -6 is the trace of A and the 8 is the determinant of A\n\n\n```python\n((A - lamda * I).det()).factor()\n```\n\n\n\n\n$$\\left(\\lambda - 4\\right) \\left(\\lambda - 2\\right)$$\n\n\n\n* I now have two eigenvalues of 2 and 4\n\n* In python we could also use the .*eigenvals()* statement\n\n\n```python\nA.eigenvals() # There is one value of 2 and one value of 4\n```\n\n\n\n\n$$\\begin{Bmatrix}2 : 1, & 4 : 1\\end{Bmatrix}$$\n\n\n\n* The eigenvectors are calculated by substituting the two values of λ into the original equation\n$$ \\left( {A}-\\lambda{I} \\right)\\underline{x}=\\underline{0} $$\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}2, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}4, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* The results above is interpreted as follows\n * The first eigenvalue has one eigenvector and the second eigenvalue also has a single eigenvector\n\n* Note the similarity between the eigenvectors of the two examples above\n* It is easy to see that adding a constant multiple of the identity matrix to another matrix (above we added 3I to the initial matrix) doesn't change the eigenvectors; it does add that constant to the eigenvalues though (we went from -1 and 1 to 2 and 4)\n$$ A\\underline { x } =\\lambda \\underline { x } \\\\ \\therefore \\quad \\left( A+cI \\right) \\underline { x } =\\left( \\lambda +c \\right) \\underline { x } $$\n\n* If we add another matrix to A (not a constant multiple of I) or even multiply them, then the influence on the original eigenvalues and eigenvectors of A is NOT so predictable (as above)\n\n## The eigenvalues and eigenvectors of a rotation matrix\n\n* Consider this rotation matrix that rotates a vector by 90o (it is orthogonal)\n * Think about it, though: what vector can come out parallel to itself after a 90o rotation?\n\n\n```python\nQ = Matrix([[0, -1], [1, 0]])\nQ\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & -1\\\\1 & 0\\end{matrix}\\right]$$\n\n\n\n* From the trace and determinant above we know that we will have the following equation\n$$ {\\lambda}^{2}-{0}{\\lambda}+{1}={0} \\\\ {\\lambda}^{2}=-{1} $$\n\n\n```python\nQ.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}- i : 1, & i : 1\\end{Bmatrix}$$\n\n\n\n\n```python\nQ.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}- i, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- i\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}i, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}i\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* Note how the eigenvalues are complex conjugates\n* Symmetric matrices will only have real eigenvalues\n* An *anti*-symmetric matrix (where the transpose is the original matrix times the scalar -1, as our example above) will only have complex eigenvalues\n* Matrices in between can have a mix of these\n\n## Eigenvalues and eigenvectors of an upper triangular matrix\n\n* Compute the eigenvalues and eigenvectors of the following matrix (note it is upper triangular)\n\n\n```python\nA = Matrix([[3, 1], [0, 3]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}3 & 1\\\\0 & 3\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}3 : 2\\end{Bmatrix}$$\n\n\n\n* We have two eigenvalues, both equal to 3\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}3, & 2, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* This is a degenerate matrix; it does not have independent eigenvectors\n\n* Look at this upper triangular matrix\n\n\n```python\nA = Matrix([[3, 1, 1], [0, 3, 4], [0, 0, 3]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}3 & 1 & 1\\\\0 & 3 & 4\\\\0 & 0 & 3\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}3 : 3\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}3, & 3, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n## Example problems\n\n### Example problem 1\n\n* Find the eigenvalues and eigenvectors of the square of the following matrix as well as the inverse of the matrix minus the identity matrix\n$$ {A}=\\begin{bmatrix} 1 & 2 & 3 \\\\ 0 & 1 & -2 \\\\ 0 & 1 & 4 \\end{bmatrix} $$\n\n#### Solution\n\n* Notice the following\n$$ A\\underline { x } =\\lambda \\underline { x } \\\\ { A }^{ 2 }\\underline { x } =A\\left( A\\underline { x } \\right) =A\\left( \\lambda \\underline { x } \\right) =\\lambda \\left( A\\underline { x } \\right) ={ \\lambda }^{ 2 }\\underline { x } $$\n* Once we know the eigenvalues for A we than simply square them to get the eigenvalues of the matrix squared\n\n* Similarly for the inverse of the matrix we have the following (for a non-zero λ, which is fine as A must be invertible for this problem)\n$$ { A }^{ -1 }\\underline { x } ={ A }^{ -1 }\\frac { A\\underline { x } }{ \\lambda } ={ A }^{ -1 }A\\frac { 1 }{ \\lambda } \\underline { x } =\\frac { 1 }{ \\lambda } \\underline { x} $$\n\n\n```python\nA = Matrix([[1, 2, 3], [0, 1, -2], [0, 1, 4]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 2 & 3\\\\0 & 1 & -2\\\\0 & 1 & 4\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}1 : 1, & 2 : 1, & 3 : 1\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}2, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-1\\\\-2\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}3, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}\\frac{1}{2}\\\\-1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* From this it is clear that the eigenvalues of A2 will be 1, 4, and 9 and for A-1 would be a 1, a half and a third\n\n\n```python\n(A ** 2).eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}1 : 1, & 4 : 1, & 9 : 1\\end{Bmatrix}$$\n\n\n\n\n```python\n(A.inv()).eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}\\frac{1}{3} : 1, & \\frac{1}{2} : 1, & 1 : 1\\end{Bmatrix}$$\n\n\n\n* The eigenvectors will be as follows (exactly the same)\n\n\n```python\n(A ** 2).eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}4, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-1\\\\-2\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}9, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}\\frac{1}{2}\\\\-1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\n(A.inv()).eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}\\frac{1}{3}, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}\\frac{1}{2}\\\\-1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}\\frac{1}{2}, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-1\\\\-2\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0a6d2e4098bb5f12470b6baecdfb86a4ebdd485d", "size": 27036, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_21_Eigenvalues_and_eigenvectors.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_21_Eigenvalues_and_eigenvectors.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_21_Eigenvalues_and_eigenvectors.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": 26.2740524781, "max_line_length": 459, "alphanum_fraction": 0.4724441485, "converted": true, "num_tokens": 4021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.20434190235957034, "lm_q1q2_score": 0.0719695793792227}} {"text": "


\n \n

Modelos de inventarios

\n


\n
\n\n\n


\n\n\n\nSantiago Pérez Angarita\n\n\nEste cuadernillo explorará los **Modelos de inventario** cuya demanda tiene un comportamiento determinístico o estocástico. Se reconocerán algunas funciones básicas de **Python** que tendrán una aplicación posterior en los modelos anteriormente mencionados. \n\n## ¿Qué es un inventario?\n\nCuando hablamos de **inventarios**, nos referirimos a mercancías, materiales, piezas, entre otro tipo de bienes puestos en reserva para uso o ventas futuras. Algunas de las razones para que una empresa tenga un inventario se relacionan con la posibilidad de hacer una buena planeación a futuro de sus activos o como provisión ante comportamientos fluctuantes o de incertidumbre. Es por esto que, vamos a considerar dos preguntas en las políticas de inventarios: i) **¿Qué tanto debe ser renovado el inventario?** y ii) **¿Cuándo debe ser renovado el inventario?**, Vale aclarar que estás preguntas tendrán una respuesta conforme al comportamiento que tenga la demanda dentro del modelo generado. \n\nEn este cuadernillo se van a considerar dos tipos de modelos de inventario: i) Los determinísticos, que son aquellos cuya demanda es conocida y, ii) Los estocásticos en donde la demanda es una variable aleatoria para cualquier periodo. De acuerdo con ello, el siguiente diagrama resume algunos de los modelos a considerar durante este curso de acuerdo al comportamiento de la demanda:\n\n\n\nAhora bien, antes de continuar con el desarrollo de cada uno de los modelos anteriormente mencionados, se hace necesario hablar de algunos de los costos asociados a un inventario, como lo son: i) Los **costos de retención**, que corresponden a aquellos costos asociados al mantenimiento del inventario tales como: seguros, intereses, depreciación, transporte, impuestos, hurtos, daños, etc.) y ii) **los costos de ordenar**, que cubre los fletes, despachos, órdenes de compra, servicio telefónico etc. \n\n### Cantidad económica de pedido\n\n**Situación 1** (*Tomada del libro : Producción y operaciones aplicadas a las Pyme, autor: Carlos José Bello Pérez*)\n\n\n\n\nLa empresa Jean & Jean, fabricante de ropa informal, tiene previsto un programa anual de producción de 40 000 unidades de jeans para dama, la información proveniente del departamento de registro y costos es la siguiente: \n\n**Costo unitario**\n\n|Tela| 107 metros/unidad | \\$ 3600/metro |\n|--------|--------|---------|\n|Mano de obra| 16 minutos/unidad | \\$ 16.11/minutos |\n|Gastos generales| \\$ 17440000/40000un. | |\n\n\n**Costo de pedido**\n\n|Hora máquinas| 8 horas / pedido | \\$ 746 / hora | \n|---:|---:|---:| \n|Mano de obra preparación| 18 hora/ pedido | \\$ 966.6 / hora|\n\n**Carga gastos generales y administrativos**\n\nHoras máquinas + Mano de obra \n\n**Costo de almacenamiento en porcentaje del inventario promedio**\n\n|Seguros| 0.4|\n|----|----|\n|Intereses|2.3|\n|Depreciación|1.6|\n|Transporte|0.6|\n|Impuestos|1.8|\n|Manejo y distribución|1.2|\n|Obsolescencia|0.5|\n|Pérdida|0.2|\n|Equipos|0.8|\n|Espacio|2.5|\n\n\n¿Cuál es número de \"corridas\" de producción que generan el menor costo posible?\n\n¿Cuál es el menor costo posible?\n\n\n\n\n```python\n#Gasto tela x unidad\ntela_x_unidad=1.07*3600\nmano_obra_x_unidad=16*16.11\ngastos_generales_x_unidad=17440000/4000\nprint(\"Costo unitario de la tela es:\",tela_x_unidad)\nprint(\"Costo unitario de la mano de obra es:\",mano_obra_x_unidad)\nprint(\"Costo unitario de los gastos generales\",gastos_generales_x_unidad)\n```\n\n Costo unitario de la tela es: 3852.0\n Costo unitario de la mano de obra es: 257.76\n Costo unitario de los gastos generales 4360.0\n\n\n\n```python\n#Costo de preparación\nMaquinas_x_pedido=8*746\nMano_de_obra_x_pedido=18*966.6\nprint(\"Costo por pedido de la maquinaria:\",Maquinas_x_pedido)\nprint(\"Costo por pedido mano de obra:\",Mano_de_obra_x_pedido)\n```\n\n Costo por pedido de la maquinaria: 5968\n Costo por pedido mano de obra: 17398.8\n\n\n\n```python\n#Gasto general y administrativo\ngastos_generales_x_pedido=Maquinas_x_pedido+Mano_de_obra_x_pedido\nprint(\"gastos generales por pedido:\",gastos_generales_x_pedido)\n```\n\n gastos generales por pedido: 23366.8\n\n\n\n```python\nprint (\"Total costo unitario\",tela_x_unidad+gastos_generales_x_unidad)\nprint(\"Total costo por pedido\",Maquinas_x_pedido+Mano_de_obra_x_pedido+gastos_generales_x_pedido)\n```\n\n Total costo unitario 8212.0\n Total costo por pedido 46733.6\n\n\n\n```python\n#Costos de almacenamiento\n\n\np=0.4+2.3+1.6+0.6+1.8+1.2+0.5+0.2+0.8+2.5\nprint(\"Costo de almacenamiento (% del inventario)\",round(p,1))\n```\n\n Costo de almacenamiento (% del inventario) 11.9\n\n\n$$C_t=Cu*S+Cp*(S/q0)+(P*Cu*q0/2)$$\n\n\n```python\nfrom sympy import *\nx=Symbol(\"x\")\nCosto=4545.76*40000+46733.6*(40000/x)+(0.119*4545.76*x/2)\n```\n\n\n```python\nplot(Costo,(x,500,40000))\n```\n\n\n```python\nCosto.subs(x,40000)\n```\n\n\n\n\n$\\displaystyle 192696042.4$\n\n\n\nAntes de hallar las respuestas de la **situación 1** es importante interpretar el comportamiento del modelo de cantidad económica como un diagrama que depende del tiempo y del tamaño del inventario:\n\n\n\nDe igual forma, se identifican las siguientes ecuaciones que responden no solo a las preguntas de **¿Qué tanto debe ser renovado el inventario?** y **¿Cuándo debe ser renovado el inventario?**, sino también los costos y tiempos asociados al **modelo de cantidad económica de pedido**\n\n**¿Cuánto? Cantidad económica de pedido que minimiza costos**\n\n$Q^*=\\sqrt{\\dfrac{2*S*Cp}{p*Cu}}$ \\\\\n\n**Costo de mantener una unidad en el inventario**\n\n$C_m=T_r * C_u$ \\\\\n\n**Costo total= Costo de retención + Costo de ordenar**\n\n$C_{total}=\\dfrac{1}{2} Q\\cdot C_m + \\dfrac{D}{Q} \\cdot C_p$\n\n**¿Cuándo? Punto de reorden**\n\n$P_o=S\\cdot /t_E$ (Ecuación de más fácil comprensión en el cuaderno del profesor)\n\nTiempo de ciclo\n\n$T=\\dfrac{DH \\cdot Q^*}{D}$\n\n\n```python\nCantidad_óptima_x_pedido=sqrt((2*40000*46733.6)/(0.119*4545.76))\n```\n\n\n```python\nCantidad_óptima_x_pedido\n```\n\n\n\n\n$\\displaystyle 2628.95335110281$\n\n\n\n\n```python\nCantidad_pedidos_anuales=N(40000/Cantidad_óptima_x_pedido)\nCantidad_pedidos_anuales \n#N para que haga calculo\n```\n\n\n\n\n$\\displaystyle 15.2151805901084$\n\n\n\n\n```python\nPeriodo_entre_pedidos=N(365/Cantidad_pedidos_anuales)\nPeriodo_entre_pedidos\n#Cada cuanto se debe renovar inventario\n```\n\n\n\n\n$\\displaystyle 23.9891993288131$\n\n\n\n\n```python\nCosto.subs(x,2629)\n```\n\n\n\n\n$\\displaystyle 183252520.327476$\n\n\n\n**CALCULADORA EOQ**\n\n\n```python\nD=input(\"Por favor digite el valor de la demanda anual:\" )\nC_p=input(\"Por favor digite el costo de pedido del modelo:\" )\nC_u=input(\"Por favor digite el costo unitario:\" )\nTr=input(\"Por favor digite la tasa de retención:\" )\nt_E=input(\"POr favor digite el tiempo de espera:\" )\nD, C_p, C_u, Tr, t_E = float(D), float(C_p), float(C_u), float(Tr), float(t_E) #Hago esto(float) porque las variables pueden tener decimales\nC_m=Tr*C_u # Esta fórmula calcula el costo de mantener una unidad \nQ=((2*D*C_p)/(C_m))**(1/2)\nC_t=((1/2)*Q*C_m)+((D/Q)*C_p)+C_u*D\nT=(365*Q/D)\nprint(\"La cantidad de económica de pedido es:\", Q)\nprint(\"El costo mínimo es: \",C_t)\nprint(T)\n```\n\n Por favor digite el valor de la demanda anual:1\n Por favor digite el costo de pedido del modelo:1\n Por favor digite el costo unitario:1\n Por favor digite la tasa de retención:1\n POr favor digite el tiempo de espera:1\n La cantidad de económica de pedido es: 1.4142135623730951\n El costo mínimo es: 2.414213562373095\n 516.1879502661798\n\n\n### Tamaño de lote de producción\n\n\n**Situación 2** (*Tomada del libro : Producción y operaciones aplicadas a las Pyme, autor: Carlos José Bello Pérez*)\n\nLa siguiente información se obtuvo de la compañía Snaptools\n\n| | |\n|-----|-----|\n|Consumo estimado para el año 2005 | 105000 unidades |\n|Tasa de producción para el año 2005 | 250000 unidades|\n|Costo unitario promedio| \\$ 26.75/ unidad |\n|Costo alquiler bodega | \\$ 2.5 / unidad|\n|Costo preparación pedido| \\$ 37.4 / pedido|\n|Seguros inventarios |10\\% costo inventario promedio|\n|Costo promedio recepción | \\$30.06 /pedido|\n|Gastos generales y administrativos oficina compras| \\$ 70.16/pedido|\n|Pérdidas de producto|2\\% del consumo total|\n|Sobre costo (intereses| 8\\% del costo unitario|\n\n\nSi hay un tiempo de espera de cinco(5) días para la recepción y 234 días laborales por año ¿Cuál es el tamaño de lote de producción?\n\n\n\nAntes de hallar las respuestas de la **situación 2** es importante interpretar el comportamiento del modelo de tamaño de lote de producción como un diagrama que depende del tiempo y del tamaño del inventario:\n\n\n\nIgual que en el modelo anterior, se identifican las siguientes ecuaciones que responden no solo a las preguntas de ¿Qué tanto debe ser renovado el inventario? y ¿Cuándo debe ser renovado el inventario?, sino también los costos y tiempos asociados al **modelo de tamaño de lote de producción.** \n\n**Inventario máximo**\n\nI=(p-d)*t\n\n**Inventario máximo** \n\n$Inv_{max}=\\left(1-\\dfrac{D}{P}\\right) \\cdot Q$\n\n\n**Duración fase de producción** \n\n$t =\\dfrac{Q}{p}$\n\n**¿Cuánto? Tamaño de lote de producción económico**\n\n $Q^* =\\sqrt{\\dfrac{2 D C_p}{\\left(1-\\dfrac{D}{P}\\right) C_m }}$\n\n**Inventario máximo** \n\n$Inv_{max}=\\left(1-\\dfrac{D}{P}\\right) \\cdot Q$\n\n**Inventario promedio** \n\n$Inv_{prom}=\\dfrac{1}{2} \\cdot \\left(1-\\dfrac{D}{P}\\right) \\cdot Q$\n\n**¿Cuánto? Tamaño de lote de producción económico**\n\n $Q^* =\\sqrt{\\dfrac{2 D C_p}{\\left(1-\\dfrac{D}{P}\\right) C_m }}$\n\n**¿Cuándo? Punto de reorden**\n\n$P_o=d\\cdot t_E$\n\n**Costo total**\n\n$C_T=\\dfrac{1}{2} \\cdot \\left(1-\\dfrac{D}{P}\\right) Q C_m + \\dfrac{D}{Q} C_p$\n\n**Tiempo de ciclo**\n\n$T = \\dfrac{DH \\cdot Q}{D}$\n\n\n\n```python\nD=input(\"Digite la demanda anual del modelo:\" )\nP=input(\"Digite la producción anual del modelo:\" )\nC_p=input(\"Digite el costo de pedido:\" )\nTR=input(\"Digite la tasa de retención:\" )\nC_u=input(\"Digite el costo unitario:\" )\nDH=input(\"¿Cuántos días laboran al año?:\" )\nD, P, C_p, TR, C_u, DH = float(D), float(P), float(C_p), float(TR), float(C_u), float(DH)\nC_m=TR*C_u\nQ=((2*D*C_p)/((1-(D/P))*C_m))**(1/2)\nC_t=(1/2)*(1-(D/P))*Q*C_m +(D/Q)*C_p\nInv_max=(1-(D/P))*Q\nT=(DH*Q)/D\nt=Q/(P/DH)\nprint(\"El tamaño de lote producción es: \",Q)\nprint(\"El costo mínimo es:\", C_t)\nprint(\"El inventario máximo es:\" ,Inv_max)\nprint(\"El tiempo de ciclo es\", T, \"días\")\nprint(\"La duración de la fase de producción es:\", t)\n```\n\n Digite la demanda anual del modelo:6000\n Digite la producción anual del modelo:24000\n Digite el costo de pedido:150\n Digite la tasa de retención:0.12\n Digite el costo unitario:10\n ¿Cuántos días laboran al año?:120\n El tamaño de lote producción es: 1414.213562373095\n El costo mínimo es: 1272.7922061357854\n El inventario máximo es: 1060.6601717798212\n El tiempo de ciclo es 28.284271247461906 días\n La duración de la fase de producción es: 7.0710678118654755\n\n\n\n```python\n(105000/234)*5\n```\n\n\n\n\n 2243.5897435897436\n\n\n\n### Faltantes planeados\n\n**Situación 3** \n\nSuponga que el Jefe de inventarios de la empresa Jean & Jean de la **Situación 1**, considera necesario incluir algunos de sus Jeans como pedidos en espera, con el fin de reducir algunos de los gastos de la compañía. Tenga en cuenta la siguiente información: \n\n|Costo de ordenar en espera| \\$ 1622 / unidad | \n|----|----|\n|Días laborales por año | 234 días |\n\nSi se espera que no más del 15\\% de unidades de Jeans sean pedidos en espera ¿Usted considera que se reducirían algunos de los gatos de Jean & Jean?\n\nAntes de hallar las respuestas de la **situación 3** es importante interpretar el comportamiento del modelo de faltantes planeados como un diagrama que depende del tiempo y del tamaño del inventario:\n\n\n\nDe igual forma, se identifican las siguientes ecuaciones que responden a la cantidades óptimas de pedidos en espera y cantidades óptima de pedido, también los costos y tiempos asociados al modelo de faltantes planeados.\n\n**Inventario promedio**\n \n\n$Inv_{Prom}=\\dfrac{(Q-S)^2}{2Q}$\n\n**Días en los que el inventario está disponible**\n\n$t_1=\\dfrac{Q-S}{d}$ días\n\n**Días en los que se agotan las existencias**\n\n$t_2=\\dfrac{S}{d}$ días\n\n**Número de pedidos por año**\n\n$N_P=\\dfrac{D}{Q}$\n\n**Pedidos promedios en espera**\n\n$S_{Prom} = \\dfrac{S^2}{2Q}$\n\n**Cantidad óptima de pedido**\n\n $Q^* =\\sqrt{\\dfrac{2 D C_p}{C_m} \\left( \\dfrac{C_m + C_E}{C_E} \\right)}$\n \n**Pedidos en espera óptimos**\n\n$S^* =Q^* \\left(\\dfrac{C_m}{C_m + C_E} \\right)$\n\n**Costo total por año**\n\n$C_{total}=\\dfrac{(Q-S)^2}{2Q} \\cdot C_m + \\dfrac{D}{Q} \\cdot C_p + \\dfrac{S^2}{2Q} \\cdot C_E $\n\n**CALCULADORA FP**\n\n\n```python\nD=input(\"Digite la demanda anual del modelo:\" )\nC_p=input(\"Digite el costo de ordenar el pedido:\" )\nC_E=input(\"Digite el costo de ordenar en espera:\" )\nTR=input(\"Digite la tasa de retención:\" )\nC_u=input(\"Digite el costo unitario:\" )\nDH=input(\"¿Cuántos días laboran al año?:\" )\nD, C_p, TR, C_u, DH, C_E = float(D), float(C_p), float(TR), float(C_u), float(DH), float(C_E)\nC_m=TR*C_u\nQ=(((2*D*C_p)/(C_m))*((C_m +C_E)/C_E))**(1/2)\nS=Q*(C_m/(C_m + C_E))\nt_1=(Q-S)/(D/DH)\nt_2=S/(D/DH)\nC_t=((Q-S)**2/(2*Q)) * C_m + (D/Q)*C_p + (S**2/2*Q)*C_E\nprint(\"La cantidad óptima de pedido es: \", Q)\nprint(\"Pedidos en espera óptimos: \", S)\nprint(\"El costo mínimo es:\", C_t)\nprint(\"El inventario máximo es:\" ,Inv_max)\nprint(\"Los días en los que el inventario está disponible son:\", t_1)\nprint(\"Los días en los que se agotan las existencias son:\", t_2)\n```\n\n Digite la demanda anual del modelo:1\n Digite el costo de ordenar el pedido:1\n Digite el costo de ordenar en espera:1\n Digite la tasa de retención:1\n Digite el costo unitario:1\n ¿Cuántos días laboran al año?:1\n La cantidad óptima de pedido es: 2.0\n Pedidos en espera óptimos: 1.0\n El costo mínimo es: 1.75\n El inventario máximo es: 1060.6601717798212\n Los días en los que el inventario está disponible son: 1.0\n Los días en los que se agotan las existencias son: 1.0\n\n\n## Modelos estocásticos \n\n### Periódo único\n\n**Situación 4**\n\nLa empresa Jean & Jean de la **Situación 1** solicitó un \"satélite\" para la creación de un nuevo diseño de jean con motivos **darks** para la época de Halloween, el cual sería vendido en 45000 pesos, y además tendría un **costo de compra** de 35000 pesos. Suponga que, al finalizar la época de Halloween no fue posible vender la totalidad de jeans **darks**, la empresa para recuperar un poco de dinero, decide rebajar el precio de venta de ese pequeño lote de jeans a 30000 pesos. Con base en la experiencia anterior, la demanda de los clientes en el \"*Madrugón*\" describe una distribución de probabilidad normal con media de 10000 jeans y una desviación estándar de 150 unidades. \n\nDe acuerdo a la situación anterior, ¿Cuál debería ser la cantidad de pedido recomendada?\n\nAntes de responder a la pregunta de la **situación 4**, es importante identificar las siguientes ecuaciones que respondena la cantidad óptima y a los costos asociados de este modelo. \n\n**Costo de subestimar la demanda**\n\n$C_{SUB}$=Precio regular (unidad) $-$ Costo de compra(unidad)\n\n**Costo de sobreestimar la demanda**\n\n$C_{SOB}=$ Costo de compra(unidad) $-$ Precio de venta (Rescate)\n\n$P(demanda \\leq Q^*)= \\dfrac{C_{SUB}}{C_{SUB}+ C_{SOB}}$\n\n$Q^*= \\mu + \\mathbb{z} \\cdot \\sigma$\n\nTenga en cuenta que $\\mathbb{z}$ es el valor asociado a la probabilidad acumulada $P(demanda \\leq Q^*)$ de una distribución normal estándar. \n\n**ACTIVIDAD** : Realice una calculadora como las de los modelos anteriores para dar respuesta a la **Situación 4**\n\n### Punto de reorden\n\n**ACTIVIDAD** : De acuerdo a la bibliografía descrita en el contenido programático del curso de **Modelos 2**, investigue en qué consiste el **modelo de punto de Reorden** y dé tres(3) ejemplos de situaciones que le permitan aplicarlo. \n\n**Pista:** Tenga en cuenta que el diagrama asociado a este modelo es el presentado a continuación\n\n\n**EJERCICIOS DE PRÁCTICA**\n\n* Hyundai compra un componente utilizado en la fabricación de generadores automotrices directamente con el proveedor. La operación de producción de generadores de Hyundai, la cual funciona a un ritmo constante, requerirá 1000 componentes por mes durante todo el año. Suponga que los costos de pedido son de 75000 pesos , el costo unitario es de 7500 pesos por componente y los costos de retención anuales son de 20\\% del valor del inventario. Responda las siguientes preguntas de política de inventario: \n\n ** ¿Cuál es la cantidad económica de este componente? \n \n ** ¿Cuáles son los costos de retención y pedido anuales totales asociados con su cantidad recomendada? \n \n ** Suponga que Hyundai, decidió operar con una política de inventario de pedidos en espera. Se estima que los costos de éstos son de 15000 pesos por unidad por año. Identifique lo siguiente: i) Cantidad de pedido de costo mínimo; ii)Número de pedidos en espera , iii) Inventario máximo, iv) Tiempo de ciclo; v) Costo anual total\n \n \n* Editorial Carvajal produce libros para el mercado minorista. Se espera que la demanda de un libro actual se dé a una tasa anual constante de 7200 ejemplares. El costo de un ejemplar del libro es de 43500 pesos. El costo de retención está basado en un tasa anual de 18\\% y los costos de preparación de la producción son de 450000 pesos por preparación. El equipo con el que se produce el libro tiene un volumen de producción anual de 25000 ejemplares. De acuerdo a la siguiente información encuentre: i) Tamaño del lote de producción de costo mínimo; ii) Número de fases de producción por año; iii) Inventario máximo y iv) Costo anual total \n\n\n* Un reconocido fabricante de varias marcas de pasta dental utiliza el modelo de tamaño del lote de producción para determinar las cantidades de producción de sus productos. El producto conocido como *Total 12* actualmente se produce en tamaños del lote de producción de 5000 unidades. Debido a una reciente escasez de una materia prima particular, el proveedor de la materia prima anunció que un incremento del costo se transferirá al fabricante de *Total 12*. Las estimaciones actuales son que el nuevo costo de la materia prima incrementará el costo de fabricación de la pasta 25\\% por unidad. ¿Cuál será el efecto de este incremento de precio en los tamaños del lote de producción de *Total 12*?\n\n\n* Hitachi está considerando la compra de un envío especial de aires acondicionados fabricados en Japón. Cada unidad costará a Hitachi 240000 pesos, y se venderá en 375000 pesos. Hitachi no quiere acarrear un excedente de aires acondicionados hasta el año siguiente. Por tanto, venderá todos los acondicionadores sobrantes a un distribuidor en 150000 pesos por unidad. Asegúrese de que la demanda de acondicionadores de aire sigue una distribución de probabilidad normal con $\\mu=20$ y $\\delta=8$\n\n\n```python\n\n```\n", "meta": {"hexsha": "befc7ac5c2adcc33151344f8a8526ca94bc1434c", "size": 46183, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Cuadernos/Modelos II/Modelos de inventarios.ipynb", "max_stars_repo_name": "Izainea/modelosdeoptimizacion", "max_stars_repo_head_hexsha": "7151512c386c16e6f224136a97360c6db4c9ef0f", "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": "Cuadernos/Modelos II/Modelos de inventarios.ipynb", "max_issues_repo_name": "Izainea/modelosdeoptimizacion", "max_issues_repo_head_hexsha": "7151512c386c16e6f224136a97360c6db4c9ef0f", "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": "Cuadernos/Modelos II/Modelos de inventarios.ipynb", "max_forks_repo_name": "Izainea/modelosdeoptimizacion", "max_forks_repo_head_hexsha": "7151512c386c16e6f224136a97360c6db4c9ef0f", "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": 53.0229621125, "max_line_length": 16400, "alphanum_fraction": 0.7255916679, "converted": true, "num_tokens": 5843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.07133197972110988}} {"text": "Probabilistic Programming and Bayesian Methods for Hackers \n========\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n#### Looking for a printed version of Bayesian Methods for Hackers?\n\n_Bayesian Methods for Hackers_ is now a published book by Addison-Wesley, available on [Amazon](http://www.amazon.com/Bayesian-Methods-Hackers-Probabilistic-Addison-Wesley/dp/0133902838)! \n\n\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assumes that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json, matplotlib\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials) / 2, 2, k + 1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials) - 1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$ pass. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2 * p / (1 + p), color=\"#348ABD\", lw=3)\n# plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2 * (0.2) / 1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Is my code bug-free?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1. / 3, 2. / 3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.ylim(0,1)\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n#### Expected Value\nExpected value (EV) is one of the most important concepts in probability. The EV for a given probability distribution can be described as \"the mean value in the long run for many repeated samples from that distribution.\" To borrow a metaphor from physics, a distribution's EV acts like its \"center of mass.\" Imagine repeating the same experiment many times over, and taking the average over each outcome. The more you repeat the experiment, the closer this average will become to the distributions EV. (side note: as the number of repeated experiments goes to infinity, the difference between the average outcome and the EV becomes arbitrarily small.)\n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots, \\; \\; \\lambda \\in \\mathbb{R}_{>0} $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1. / l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0, 1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```python\nimport pymc as pm\n\nalpha = 1.0 / count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = pm.Exponential(\"lambda_1\", alpha)\nlambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\ntau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```python\nprint(\"Random output:\", tau.random(), tau.random(), tau.random())\n```\n\n Random output: 64 5 12\n\n\n\n```python\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. Deterministic functions will be covered in Chapter 2. \n\n\n```python\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n# Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n [-----------------100%-----------------] 40000 of 40000 complete in 6.5 sec\n\n\n```python\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```python\nfigsize(12.5, 10)\n# histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data) - 20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n# type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n# type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n# type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "77783db67573ebdecc2739515d766f0b7df9dedc", "size": 372371, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_stars_repo_name": "torch77/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "afea55a0c0e31073ce8846bb1b99f8e28522495f", "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": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_issues_repo_name": "torch77/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "afea55a0c0e31073ce8846bb1b99f8e28522495f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_forks_repo_name": "torch77/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "afea55a0c0e31073ce8846bb1b99f8e28522495f", "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": 327.7913732394, "max_line_length": 105392, "alphanum_fraction": 0.8993584355, "converted": true, "num_tokens": 11683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683139517237, "lm_q2_score": 0.21733751597763015, "lm_q1q2_score": 0.07121461741884588}} {"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n \n\n \n\n\n\n[Python for Probability, Statistics, and Machine Learning](https://www.springer.com/fr/book/9783319307152)\n\n\n```python\nfrom __future__ import division\nimport numpy as np\nnp.random.seed(1234)\n```\n\n\n```python\n%pylab inline\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\nThe estimation problem starts with the desire to infer something meaningful\nfrom data. For parametric estimation, the strategy is to postulate a model for\nthe data and then use the data to fit model parameters. This leads to two\nfundamental questions: where to get the model and how to estimate the\nparameters? The first question is best answered by the maxim: *all models are\nwrong, some are useful*. In other words, choosing a model depends as much on\nthe application as on the model itself. Think about models as building\ndifferent telescopes to view the sky. No one would ever claim that the\ntelescope generates the sky! It is same with data models. Models give us\nmultiple perspectives on the data that themselves are proxies for some deeper\nunderlying phenomenon.\n\nSome categories of data may be more commonly studied using certain types of\nmodels, but this is usually very domain-specific and ultimately depends on the\naims of the analysis. In some cases, there may be strong physical reasons\nbehind choosing a model. For example, one could postulate that the model is\nlinear with some noise as in the following:\n\n$$\nY = a X + \\epsilon\n$$\n\n which basically says that you, as the experimenter, dial in some\nvalue for $X$ and then read off something directly proportional to $X$ as the\nmeasurement, $Y$, plus some additive noise that you attribute to jitter in the\napparatus. Then, the next step is to estimate the paramater $a$ in the model,\ngiven some postulated claim about the nature of $\\epsilon$. How to compute the\nmodel parameters depends on the particular methodology. The two broad rubrics\nare parametric and non-parametric estimation. In the former, we assume we know\nthe density function of the data and then try to derive the embedded parameters\nfor it. In the latter, we claim only to know that the density function is a\nmember of a broad class of density functions and then use the data\nto characterize a member of that class. Broadly speaking, the former consumes\nless data than the latter, because there are fewer unknowns to compute from\nthe data.\n\nLet's concentrate on parametric estimation for now. The tradition is to denote\nthe unknown parameter to be estimated as $\\theta$ which is a member of a large\nspace of alternates, $\\Theta$. To judge between potential $\\theta$ values, we\nneed an objective function, known as a *risk* function,\n$L(\\theta,\\hat{\\theta})$, where $\\hat{\\theta}(\\mathbf{x})$ is an\nestimate for the unknown $\\theta$ that is derived from the available\ndata $\\mathbf{x}$. The most common and useful risk function is the\nsquared error loss,\n\n$$\nL(\\theta,\\hat{\\theta}) = (\\theta-\\hat{\\theta})^2\n$$\n\n Although neat, this is not practical because we need to know the\nunknown $\\theta$ to compute it. The other problem is because $\\hat{\\theta}$ is\na function of the observed data, it is also a random variable with its own\nprobability density function. This leads to the notion of the *expected risk*\nfunction,\n\n$$\nR(\\theta,\\hat{\\theta}) = \\mathbb{E}_\\theta(L(\\theta,\\hat{\\theta})) = \\int L(\\theta,\\hat{\\theta}(\\mathbf{x})) f(\\mathbf{x};\\theta) d \\mathbf{x}\n$$\n\n In other words, given a fixed $\\theta$, integrate over the\nprobability density function of the data, $f(\\mathbf{x})$, to compute the\nrisk. Plugging in for the squared error loss, we compute the\nmean squared error,\n\n$$\n\\mathbb{E}_\\theta(\\theta-\\hat{\\theta})^2 =\\int (\\theta-\\hat{\\theta})^2 f(\\mathbf{x};\\theta) d \\mathbf{x}\n$$\n\n This has the important factorization into the *bias*,\n\n$$\n\\texttt{bias} = \\mathbb{E}_\\theta(\\hat{\\theta})-\\theta\n$$\n\n with the corresponding variance, $\\mathbb{V}_\\theta(\\hat{\\theta})$ as\nin the following *mean squared error* (MSE):\n\n$$\n\\mathbb{E}_\\theta(\\theta-\\hat{\\theta})^2= \\texttt{bias}^2+\\mathbb{V}_\\theta(\\hat{\\theta})\n$$\n\n This is an important trade-off that we will return to repeatedly. The\nidea is the bias is nonzero when the estimator $\\hat{\\theta}$, integrated\nover all possible data, $f(\\mathbf{x})$, does not equal the underlying target\nparameter $\\theta$. In some sense, the estimator misses the target, no matter\nhow much data is used. When the bias equals zero, the estimated is *unbiased*.\nFor fixed MSE, low bias implies high variance and vice-versa. This trade-off\nwas once not emphasized and instead much attention was paid to the smallest\nvariance of unbiased estimators (see Cramer-Rao bounds). In practice,\nunderstanding and exploiting the trade-off between bias and variance and\nreducing the MSE is more important.\n\nWith all this set up, we can now ask how bad can bad get by\nexamining *minimax* risk,\n\n$$\nR_{\\texttt{mmx}} = \\inf_{\\hat{\\theta}} \\sup_\\theta R(\\theta,\\hat{\\theta})\n$$\n\n where the $\\inf$ is take over all estimators. Intuitively, this\nmeans if we found the worst possible $\\theta$ and swept over all possible\nparameter estimators $\\hat{\\theta}$, and then took the smallest possible risk\nwe could find, we would have the minimax risk. Thus, an estimator,\n$\\hat{\\theta}_{\\texttt{mmx}}$, is a *minimax estimator* if it achieves this\nfeat,\n\n$$\n\\sup_\\theta R(\\theta,\\hat{\\theta}_{\\texttt{mmx}}) =\\inf_{\\hat{\\theta}} \\sup_\\theta R(\\theta,\\hat{\\theta})\n$$\n\n In other words, even in the face of the worst $\\theta$ (i.e., the\n$\\sup_\\theta$), $\\hat{\\theta}_{\\texttt{mmx}}$ still achieves the minimax\nrisk. There is a greater theory that revolves around minimax estimators of\nvarious kinds, but this is far beyond our scope here. The main thing to focus\non is that under certain technical but easily satisfiable conditions, the\nmaximum likelihood estimator is approximately minimax. Maximum likelihood is\nthe subject of the next section. Let's get started with the simplest\napplication: coin-flipping.\n\n## Setting up the Coin Flipping Experiment\n\nSuppose we have coin and want to estimate the probability of heads ($p$) for\nit. We model the distribution of heads and tails as a Bernoulli distribution\nwith the following probability mass function:\n\n$$\n\\phi(x)= p^x (1-p)^{(1-x)}\n$$\n\n where $x$ is the outcome, *1* for heads and *0* for tails. Note that\nmaximum likelihood is a parametric method that requires the specification of a\nparticular model for which we will compute embedded parameters. For $n$\nindependent flips, we have the joint density as the product of $n$ of\nthese functions as in,\n\n$$\n\\phi(\\mathbf{x})=\\prod_{i=1}^n p^x_i (1-p)^{(1-x_i)}\n$$\n\n The following is the *likelihood function*,\n\n$$\n\\mathcal{L}(p ; \\mathbf{x})= \\prod_{i=1}^n p^{ x_i }(1-p)^{1-x_i}\n$$\n\n This is basically notation. We have just renamed the\nprevious equation to emphasize the $p$ parameter, which is what\nwe want to estimate.\n\nThe principle of *maximum likelihood* is to maximize the likelihood as the\nfunction of $p$ after plugging in all of the $x_i$ data. We then call this\nmaximizer $\\hat{p}$ which is a function of the observed $x_i$ data, and as\nsuch, is a random variable with its own distribution. This method therefore\ningests data and an assumed model for the probability density, and produces a\nfunction that estimates the embedded parameter in the assumed probability\ndensity. Thus, maximum likelihood generates the *functions* of data that we\nneed in order to get at the underlying parameters of the model. Note that there\nis no limit to the ways we can functionally manipulate the data we have\ncollected. The maximum likelihood principle gives us a systematic method for\nconstructing these functions subject to the assumed model. This is a point\nworth emphasizing: the maximum likelihood principle yields functions as\nsolutions the same way solving differential equations yields functions as\nsolutions. It is very, very much harder to produce a function than to produce a\nvalue as a solution, even with the assumption of a convenient probability\ndensity. Thus, the power of the principle is that you can construct such\nfunctions subject to the model assumptions.\n\n### Simulating the Experiment\n\nWe need the following code to simulate coin flipping.\n\n\n```python\nfrom scipy.stats import bernoulli \np_true=1/2.0 # estimate this!\nfp=bernoulli(p_true) # create bernoulli random variate\nxs = fp.rvs(100) # generate some samples\nprint xs[:30] # see first 30 samples\n```\n\n [0 1 0 1 1 0 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 0 0 1 1 0 1 0 1]\n\n\n Now, we can write out the likelihood function using Sympy. Note\nthat we give the Sympy variables the `positive=True` attribute upon\nconstruction because this eases Sympy's internal simplification algorithms.\n\n\n```python\nimport sympy\nx,p,z=sympy.symbols('x p z', positive=True)\nphi=p**x*(1-p)**(1-x) # distribution function\nL=np.prod([phi.subs(x,i) for i in xs]) # likelihood function \nprint L # approx 0.5?\n```\n\n p**57*(-p + 1)**43\n\n\n Note that, once we plug in the data, the likelihood function is\nsolely a function of the unknown parameter ($p$ in this case). The following\ncode uses calculus to find the extrema of the likelihood function. Note that\ntaking the `log` of $L$ makes the maximization problem tractable but doesn't\nchange the extrema.\n\n\n```python\nlogL=sympy.expand_log(sympy.log(L))\nsol,=sympy.solve(sympy.diff(logL,p),p)\nprint sol\n```\n\n 57/100\n\n\n**Programming Tip.**\n\nNote that `sol,=sympy.solve` statement includes\na comma after the `sol` variable. This is because the `solve`\nfunction returns a list containing a single element. Using\nthis assignment unpacks that single element into the `sol` variable\ndirectly. This is another one of the many small elegancies of Python.\n\n \n\nThe following code generates [Figure](#fig:Maximum_likelihood_10_2).\n\n\n```python\n\nfig,ax=subplots()\nx=np.linspace(0,1,100)\nax.plot(x,map(sympy.lambdify(p,logL,'numpy'),x),'k-',lw=3)\nax.plot(sol,logL.subs(p,sol),'o',\n color='gray',ms=15,label='Estimated')\nax.plot(p_true,logL.subs(p,p_true),'s',\n color='k',ms=15,label='Actual')\nax.set_xlabel('$p$',fontsize=18)\nax.set_ylabel('Likelihood',fontsize=18)\nax.set_title('Estimate not equal to true value',fontsize=18)\nax.legend(loc=0)\n```\n\n**Programming Tip.**\n\nIn the prior code, we use the `lambdify` function in `lambdify(p,logL,'numpy')` to\ntake a Sympy expression and convert it into a Numpy version that is easier to\ncompute. The `lambdify` function has an extra argument where you can specify\nthe function space that it should use to convert the expression. In the above\nthis is set to Numpy.\n\n\n\n\n\n
\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\n

Histogram 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\n

Probability 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\n

The 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
  • Monocular cortex
  • \n \\begin{equation*}\n z_i=\\frac{i-1}{500}\n \\end{equation*}\n \n
  • Binocular Cortex
  • \n\\begin{equation}\nz_i=\\frac{i-1}{310}\n\\mbox{ for i = 1:310}\n\\end{equation}\n\n\\begin{equation}\nz_i=\\frac{i-311}{190}\n\\mbox{ for i = 311:500}\n\\end{equation}\n \n\n\n\n5. The input statistics include: input firing rate $\\mu_{i,j}$, correlation magnitudes between eyes $q_{i,j}$, and input correlation width $\\sigma$ in order to generate inputs covariances matrix $\\widetilde{Q}_{i,j}$ where: \n\n\\begin{equation*}\n\\widetilde{Q}_{i,j}=q_{i,j}\\langle \\mu_i x_i\\rangle\\langle \\mu_j x_j\\rangle exp(-\\frac{(z_i - z_j)^2}{2\\sigma_q^2})\n\\end{equation*}\n\n6. In order to reproduce more biological heterogeneity to the inputs, a Gaussian random noise was added to the covariance matrix, such that: \n\\begin{equation*}\nQ_{i,j}=\\widetilde{Q}_{i,j} + 2(\\xi_i + \\xi_j)\n\\end{equation*}\n\n where $\\xi_{i,j}$ is a Gaussian random noise with a unit variance. \n\n---\n\n# Model 1: BCM Model \n\nThe most common model that has integrated Hebbian-like and homeostatic plasticity is the Bienenstock-Cooper-Munro (BCM) theory or rule [3, 5]. The theory of this model is based on the correlation between pre and postsynaptic activity (can be a single-synapse or multi-synapse) to predict the synaptic weight behavior over the time of MD. The key difference between this modal and Hebbian theory is that BCM uses a sliding threshold $\\theta$– averaged over some period of time- to predict the synaptic weight change [5]. In symbols, the input activity **x** is under LTP if y>$\\theta$ and under LTD otherwise. But, $\\theta$ is changing with respect to the postsynaptic activity that must be maintained near a set-point activity level, $y_0$. The following equations are used to simulate the synaptic strength **w** to involve Hebbian and homeostatic elements [5]:\n\n\n\\begin{equation*}\n\\tau_w\\frac{dw}{dt}=xy(y-\\theta)\n\\end{equation*}\n\nIn the above equation, $\\tau_w$ is a time constant that sets the Hebbian learning rate, so the input activity **x** may undergo LTP or LTD\n\n\\begin{equation*}\n\\tau_\\theta\\frac{d\\theta}{dt}=-\\theta+y\\frac{y}{y_o}\n\\end{equation*}\n\nThe above equation is considered the element involving the homeostatic process, where **$\\theta$** is a superlinear function of the average firing rate over a time $\\tau_\\theta$, such that the postsynaptic activity can be maintained near a set-point activity level, $y_0$.\n\nConsequentially, this model does not capture the MD behavior under the zero activity or when blocking the NMDA receptors to prevent Hebbian plasticity [5] as shown in the preliminary simulation results in figure 3. Moreover, this model does not predict a realistic steady state behavior by reaching a zeros state [5]. \n\n\nParameter | Normal Condition | During MD\n---| --- | ---\nx | 1.0 | 0.5\n$y_o$ | 1.0 | 1.0\n$\\tau_w$ | xx | xx\n$\\tau_\\theta$ | xx | xx\n\nVariable | Initial Condition\n--- | ---\nW | 1.0\n$\\theta$ | 1.0\n\n\n\n\n**Figure 3:** The Synaptic Strength behavior in the Monocular Cortex during MD at Time 0 using the BCM Model [5].\n\nThe typical synaptic weight behavior under normal MD conditions should initially decrease due to LTD and subsequently increase. However, as it can be seen from these simple equations, the time constants $\\tau_w$ and $\\tau_\\theta$ play significant role in altering the strength **W**. From figure 3, the ratio of the time constants impacted the synaptic weight behavior $w$. When the ratio is 1, there is a little depression due to the LTD, but it was quickly recovered. This quick change is due to the fast-homeostatic plasticity which was set to be equal to the Hebbian. Thus, in order to allow for a significant initial LTD to occur, the homeostatic plasticity should be sufficiently slower than the Hebbian. However, by slowing down the homeostatic plasticity through increasing the ratio, the synaptic strengths stars to lose stability and shows oscillations. In the results show, the MD was applied at time of 0, with initial conditions that reflect the experimental methods. However, the model does not capture the full behavior and requires homeostatic plasticity to stabilize the Hebbian plasticity, but that trade would result in oscillations.\n\n---\n\n\n\n# Task 1 and 2\n\nThe following code was written to reproduce the results published in [5] for the BCM model. Given the parameters and initial conditions listed above:\n1. Implement the BCM model equations to be solved using odeint in both cases: when $\\tau_\\theta$$/\\tau_w$=1 and $\\tau_\\theta$$/\\tau_w$=3\n2. Plot the results of **W** and $\\theta$ in the same figure, as shown in figure 3.\n3. Reflect on your results by answering the following questions:\n 1. What is the main cause of the weight change oscillations, if any ? \n 2. If the time constants were doubled, what other parameters need to be changed to reach the same conclusion?\n\n\n\n```python\n## Task 1 BCM Model Single in MC\n\nx=0.5 # x = 1 in the normal condition x=0.5 under MD\nt_w=0.2 # set the time constant that sets the Hebbian learning rate to 0.2 days \nt_theta=0.2\ny_o=1.0\n\n# Iniital Conditions\nInit_w=1.0 # initial w strenght\nInit_th=1.0 # initial threshold Theta\n\ny0=[Init_w,Init_th]\nt=np.linspace(0, 10, 10000) # Create time array\n\ndef BCM(y, t):\n w = y[0]\n theta_ = y[1]\n\n y_1=w*x # The Y equation to be added here\n dw_dt=(x*y_1*(y_1-theta_))/t_w # dw_dt To be added here \n dth_dt=(-theta_+y_1*y_1/y_o)/t_theta # dth_dt To be added here \n \n return [dw_dt,dth_dt]\n\n# ODE Solution using odeint()\nsoln = odeint(BCM, y0, t)\nW_sol = soln[:, 0].reshape(-1,1)\nthrshold_sol = soln[:, 1].reshape(-1,1)\n\n\n## Now i change the time canstans \nt_theta =t_theta*3 # set the time constant that sets the Hebbian learning rate to 0.2*3 days \n\nsoln = odeint(BCM, y0, t)\nW_sol = np.concatenate((W_sol, soln[:, 0].reshape(-1,1)), axis=1) \nthrshold_sol = np.concatenate((thrshold_sol, soln[:, 1].reshape(-1,1)), axis=1) \ninitial_once = np.ones(len(t))\n\n\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nplt.plot(t, initial_once)\nplt.plot(t, W_sol[:,0],'r-',label='W')\nplt.plot(t, thrshold_sol[:,0],'k--',label=r'$\\theta$')\nplt.xlabel('Time (days)')\nplt.ylabel('Synaptic Strength W (Unitless)')\nplt.title(r'BCM Model: $\\tau_\\theta$/$\\tau_w$=1')\nplt.legend(loc='best')\nplt.subplot(1,2,2)\nplt.plot(t, initial_once)\nplt.plot(t, W_sol[:,1],'r-',label='W')\nplt.plot(t, thrshold_sol[:,1],'k--',label=r'$\\theta$')\nplt.title(r'BCM Model: $\\tau_\\theta$/$\\tau_w$=3')\nplt.xlabel('Time (days)')\nplt.ylabel('Synaptic Strength W (Unitless)')\nplt.legend(loc='best')\n\n\n\n\n\n```\n\n# Task 1 and 2 Answers \n(write down here)\n\n1. The oscillations occurred because **Y** is changing quickly with **W** in the same direction and reaching the set-level value $y_0$ while $\\theta$ is slow and averaging the earlier values of **W**. \n\n2. The time scale of the simulation needs to be doubled as well. \n\n\n\n# Model 2: BCM+Stabilizing Terms\n\nIn this model, the authors added stabilizing factors to saturate the strength behavior within a certain range with respect to the experimental findings. They also aimed to show that the BCM does not account for the block of one plasticity than the other. This modification also takes into account the limits at which the LTP and LTD should occur. \n\n\\begin{equation*}\n\\tau_w\\frac{dw}{dt}=[w_{max} - w]_+[xy-\\theta]_+ -[w-w_{min}]_+[\\theta-xy]_+ +\\gamma w(1-\\frac{\\bar{y}}{y_o})\n\\end{equation*}\n\nIn the above equation, the operation $[x]_+$ means $[x]_+ = x $ only when $x>0$, otherwise $[x]_+ =0$.\n\\\n\\\nThe synaptic strength $w$ is assumed to be modified by the sum of:\n1. an LTP term $[w_{max} - w]_+[xy-\\theta]_+ $\n2. an LTD term $[w-w_{min}]_+[\\theta-xy]_+ $\n3. a multiplicative homeostatic term $\\gamma w(1-\\bar{y}/y_o)$ \n\nThe LTP should occur when the product of presynaptic $x$ and postsynaptic activities $y$, is greater than a fixed threshold $\\theta$ such that $xy>\\theta$ otherwise LTD should occur. At the same time, the LTD and LTP terms should saturate with respect to the weight limited values ($w_{max}$ and $w_{min}$).\n\nThe homeostatic term changes the weight $w$ to move the “time-averaged postsynaptic activity” $\\bar{y}$ toward a set-point value $y_0$. This term would produce weight change proportional to $w$. The parameter $\\gamma$ determines the relativity of homeostasis to Hebbian plasticity strength learning speed [5]. \n\n\n\\begin{equation*}\n\\tau_\\bar{y} \\frac{d\\bar{y}}{dt}=-\\bar{y}+y\n\\end{equation*}\n\nSince it is assumed that the threshold limit $\\theta$ is fixed, we are considering the “time-averaged postsynaptic activity” $\\bar{y}$. In the above equation, it is assumed that the postsynaptic activity is averaged exponentially with time constant $\\tau_\\bar{y}$ to produce the overall $\\bar{y}$, which is directly related to the weight equation.\n\n\nParameter | Normal Condition | Strong MD | weaker MD\n---| --- | --- | ---\nx | 1.0 | 0.5 | 0.73\n$y_o$ | 0.8 | 0.8 | 0.8\n$\\tau_w$ | 0.3 | 0.3 | 0.3\n$\\tau_\\bar{y}$| 3.0 | 3.0 | 3.0\n$\\theta$ | 0.6 | 0.6 | 0.6 \n$w_{max}$ | 1.0 | 1.0 | 1.0 \n$w_{min}$ | 0.6 | 0.6 | 0.6 \n$\\gamma$ | 0.23 | 0.23 | 0.23 \n\n\nVariable | Initial Condition\n--- | ---\nW | 0.9\n$\\bar{y}$ | 0.9\n\n\n\n\n**Figure 4:** The Synaptic Strength behavior in the Monocular Cortex during MD after adding stabilizing terms [5].\n\nThe simulation results of this modified BCM model with stabilizing terms are partially consistent with the experimental findings; however, the model was too sensitive to the parameters’ selection [5]. In figure 4a, the input activity strength (strength of MD) was $x=0.5$ as a strong MD. The model was able to capture the initial LTD reflected by the initial decrease in $w$, illustrating the fast Hebbian dynamic. Following that, the model also captured the slow homeostatic dynamic by an increase in $w$. This did not hold true when the MD strength was set to a weaker value, $x=0.73$. As shown in figure 4b, the initial LTD was followed by a stable oscillation [5]. \n\nTo test the model validity with the experimental paradigm, the Hebbian dynamic was blocked by setting the LTP and LTD terms to 0 on day 7 mimicking NMDA receptor antagonist in animal models. The simulation result in figure 4c shows that under strong MD, $x=0.5$, the slow homeostatic dynamic was able to derive and upscale the overall synaptic strength. This behavior is due to the fact that the homeostatic dynamic was constitutively active, but not cancelled by the absence of Hebbian dynamic. On the other hand, the experimental findings show no significant change of the visual responses following the NMDA block [5]. \n\n---\n\n\n# Task 3 and 4\n\\\nThe following code was written to reproduce the results published in [5] for BCM+Stabilizing Terms model. Given the parameters and initial conditions listed above:\n1. Implement the model equations to be solved using odeint in both cases: when $x=0.5$ and $x=0.73$\n2. Plot the results of $W$ and $\\bar{y}$ in the same figure, as shown in figure 4a,b.\n3. Plot the blockade of Hebbian plasticity when $x=0.5$ and when $x=0.3$\n4. Reflect on your results by answering the following questions:\n 1. How does the MD strength, $x$ value alter the behavior of $w$ during the blockade of Hebbian plasticity?\n 2. How the results of this modified model differ from those in BCM model?\n\n---\n\n\n```python\n## Task 3 BCM+Stabilizing Terms\n\n# Parameters for Equation 3\nw_max = 1.0\nw_min = 0.6\nt_w = 0.3 \nt_y= 3.0\ny_o = 0.8\ntheta = 0.6\ngamma = 0.23 \n\n# Iniital Conditions\nInit_w = 0.9 # initial w strenght\nInit_yb = 0.9 # initial average postsynaptic activity y-bar\ny0=[Init_w,Init_yb]\n\n\nt=np.linspace(0, 30, 1000) # Create time array\n\ndef TL(x):\n TL_out=x*(x>0);\n return TL_out\n\n \ndef BCM_Stable(y, t,flag_NMDA):\n w = y[0]\n dy = y[1]\n y_1=x*w # Needs to be added \n \n term1=w_max-w\n term2=x*y_1-theta\n term3=w-w_min\n term4=theta-x*y_1\n \n if t>7 and flag_NMDA==1: # ******************************** This if statement needs to be coded \n NMDA=0\n else:\n NMDA=1\n\n\n dw_dt = (NMDA*(TL(term1)*TL(term2)-TL(term3)*TL(term4))+gamma*w*(1-dy/y_o))/t_w # Needs to be added \n dy_dt = (-dy+y_1)/t_y # Needs to be added \n \n return [dw_dt,dy_dt]\n\n\nflag_NMDA=0 # No blockade of Hebbian plasticity\nx=0.5\nsoln = odeint(BCM_Stable, y0, t,args=(flag_NMDA,))\n\nW_sol = soln[:, 0].reshape(-1,1)\ny_b_sol = soln[:, 1].reshape(-1,1)\n\n\n# Now we change the x to 0.73\nx = 0.73\nflag_NMDA=0 # No blockade of Hebbian plasticity\nsoln = odeint(BCM_Stable, y0, t,args=(flag_NMDA,))\nW_sol = np.concatenate((W_sol, soln[:, 0].reshape(-1,1)), axis=1)\ny_b_sol = np.concatenate((y_b_sol, soln[:, 1].reshape(-1,1)), axis=1)\n\n# Now we change the x to 0.5 and apply NMDA block\nx = 0.5\nflag_NMDA=1 # blockade of Hebbian plasticity in on \nsoln = odeint(BCM_Stable, y0, t,args=(flag_NMDA,))\nW_sol = np.concatenate((W_sol, soln[:, 0].reshape(-1,1)), axis=1)\ny_b_sol = np.concatenate((y_b_sol, soln[:, 1].reshape(-1,1)), axis=1)\n\ninitial_once=np.ones(len(t))*0.9\n \n \nplt.figure(figsize=(15,5))\nplt.subplot(1,3,1)\nplt.plot(t, initial_once)\nplt.plot(t, W_sol[:,0],'r-',label='W')\nplt.plot(t, y_b_sol[:,0],'k--',label=r'$\\bar{y}$')\nplt.xlabel('Time (days)')\nplt.ylabel('Synaptic Strength W (Unitless)')\nplt.title('BCM+Stabilizing Terms, x=0.5')\nplt.legend(loc='best')\nplt.ylim((0.35,1.3))\n \nplt.subplot(1,3,2)\nplt.plot(t, initial_once)\nplt.plot(t, W_sol[:,1],'r-',label='W')\nplt.plot(t, y_b_sol[:,1],'k--',label=r'$\\bar{y}$')\nplt.title('x=0.73')\nplt.xlabel('Time (days)')\nplt.ylim((0.35,1.3))\nplt.legend(loc='best')\n\nplt.subplot(1,3,3)\nplt.plot(t, initial_once)\nplt.plot(t, W_sol[:,2],'r-',label='W')\nplt.plot(t, y_b_sol[:,2],'k--',label=r'$\\bar{y}$')\nplt.title('x=0.5 + NMDA Blockade')\nplt.xlabel('Time (days)')\nind1=(t>7.0).nonzero()\n#print(ind1[0]) # to read the index when t>7\nplt.fill_between(t[234:],y_b_sol[234:,2].ptp()-0.1,W_sol[234:,2].max()+0.1, facecolor=\"orange\", color='green',alpha=0.2) \n#plt.ylim((0,2.6))\nplt.legend(loc='best')\n\n```\n\n# Task 3 and 4 Answers\n \n\nThe stronger the value of MD the higher overshot peak of $w$ and longer oscillation. \n\nIn this model, the synaptic strength is limited within a range between w_min and w_max, which maintains non-zero steady state W. In BCM model, the zero state behavior is not physiologically relevant. \n\n---\n\n\n# Model 3a: Two-Factor Model Single Synapse \n\nThe two-factor model is proposed in the paper as the solution for the stability and steady state issues of the synaptic strength. The author showed that the model consists mainly of two factors: the Hebbian and homeostatic components and multiplying those two factors should produce the synaptic strength. A synapse-specific Hebbian factor $\\rho$ and postsynaptic-cell-specific homeostatic factor $H$. \n\n\\begin{equation*}\nw=H\\rho\n\\end{equation*}\n\n\\begin{equation*}\n\\tau_\\rho\\frac{d\\rho}{dt}=(\\rho_{max}-\\rho)+[xy-\\theta]_+ - (\\rho-\\rho_{min})[\\theta-xy]_+\n\\end{equation*}\n\n\\begin{equation*}\n\\tau_H \\frac{dH}{dt}=H(1-\\frac{y}{y_o})\n\\end{equation*}\n\nand solving for $w$\n\\begin{equation*}\n\\tau_\\rho\\frac{dw}{dt}=(H\\rho_{max}-w)+[xy-\\theta]_+ -(w-H\\rho_{min})[\\theta-xy]_+ +\\frac{\\tau_\\rho}{\\tau_H} w(1-\\frac{y}{y_o})\n\\end{equation*}\n\nAs it can be seen from the equations above, there is a limited range of the Hebbian factor that can be reached $\\rho_{max}$ and $\\rho_{min}$ , which is controlled by the homeostatic factor. It is also critical to notice that the learning speeds of both mechanisms are controlled by the time constants $\\tau_\\rho$ and $\\tau_H$. Differently from all the previous models, the homeostatic factor $H$ depends only on the postsynaptic activity $y$, and not on the synaptic weight $w$.\n\nThe authors discussed the physiological relevance of this model in greater details in [5], and mainly that the two-factor model can be addressed in different aspects based on the study objective, as we are going to observe. In the paper, this model was implemented in all forms of simulation: as a single-synapse model, multi-synapse model, in monocular and in Binocular cortex. \n\n\n\n\n\n**Figure 5** The Synaptic Strength behavior in the Monocular Cortex during and after MD using the two-factor model assuming a single synapse input [5].\n\nFrom figure 5, the proposed two-factor model result shows a prediction of an overshoot following the restoration of normal vision. As it can be seen, the synaptic strength was initially decreased during MD illustrating the Hebbian LTD and followed by a slow homeostatic increase. Although it was assumed that the homeostatic time constant is 40 times slower than the Hebbian time constant, under mild MD the model was able to capture that behavior which was also verified experimentally. The overshot during the recovery was a critical prediction, which was also verified experimentally [5]. Quantitively, the homeostatic factor would impact the synaptic strength to overshoot following the recovery from MD because it depends on post synaptic activity. The immediate recovery from MD would then be purely homeostatic factor dependent, which caused an overshoot of synaptic strength. \n\n\nParameter | Normal Condition | During MD\n---| --- | --- \nx | 1.0 | 0.5 \n$y_o$ | 1.0 | 1.0 \n$\\tau_\\rho$ | 0.2 | 0.2\n$\\tau_H$| 8.0 | 8.0 \n$\\theta$ | 0.6 | 0.6 \n$\\rho_{max}$ | 1.0 | 1.0 \n$\\rho_{min}$ | 0.6 | 0.6 \n\n\nVariable | Initial Condition\n--- | ---\nW or $\\rho$| 1.0\nH | 1.0\n\n---\n\n\n\n### Task 5\n\nThe following code was written to reproduce the results published in [5] for the Two factor model. Given the parameters and initial conditions listed above:\n\n1. Implement the model equations to be solved using odeint in the case where $x=0.5$ when $t<5$ and $x=1$ otherwise.\n\n2. The authors proposed that the $\\tau_\\rho$ is 40 times faster than $\\tau_H$, what does that mean in terms of stable plasticity dynamics. \n\n3. Does the synaptic strength return to the initial value as the time goes to infinity?\n\n---\n\n\n\n\n\n```python\n## Task 5 Two-factor model single-synapse\np_max = 1.0\np_min = 0.6\ntheta = 0.6\nt_p = 0.2\nt_h = 8.0\ny_o = 1.0\n\ndef Tow_Factor_singleS_MainText(y,t):\n P = y[0]\n H = y[1]\n \n def TL(x):\n TL_out=x*(x>0);\n return TL_out\n\n if t>=5.0:\n x=1.0\n else:\n x=0.5 \n \n dP_dt=((p_max-P)*TL(x*x*P*H-theta)-(P-p_min)*TL(theta-x*x*P*H))/t_p\n dH_dt = (H*(1-x*P*H))/t_h\n \n return [dP_dt,dH_dt]\n\n\n# Iniital Conditions\nx=0.5\nP_0=1\nH_0=1\n\ny0=[P_0,H_0]\nt=np.linspace(0, 12, 10000) # Create time array\nsoln=odeint(Tow_Factor_singleS_MainText, y0, t)\n\n# Assigns variable names to solution matrix\nP_sol = soln[:, 0]\nH_sol = soln[:, 1]\nW_sol=P_sol*H_sol\n\ninitial_once=np.ones(len(t))\n\nplt.figure()\nplt.plot(t,initial_once,'grey')\nplt.plot([5,5],[0.6,1.8],'grey')\nplt.plot(t, W_sol,'r-')\nplt.plot(t,H_sol*p_max,'b--')\nplt.plot(t,H_sol*p_min,'k--')\nplt.text(2,1.8,'x=0.5')\nplt.text(2,1.4,r'$\\rho_{max}$H')\nplt.text(10,0.8,r'$\\rho_{min}$H')\nplt.text(5.6,1.2,'W',color='red')\nplt.fill_between([0,5],[1.8,1.8], facecolor=\"orange\", color='orange',alpha=0.2) \nplt.ylim((0.58,1.9))\nplt.xlabel('Time (days)')\nplt.ylabel('Synaptic Strength W (Unitless)')\nplt.title('Two-Factor Model Single Synap')\n```\n\n# Task 5 Answers\n\n$\\tau_\\rho$ is 40 times faster than $\\tau_H$ which means that the system is stable even if t_H goes to infinity. From the stability analysis in [5], the synaptic weight reaches an overshoot before it converges. \n\nYes, as the time goes to infinity, the synaptic weight returns to its pre-MD value and specifically at time of 40 days. \n\n\n# Model 3b: Two-Factor Model Multi-synapse \n\nThe two-factor model simulation results predicted the experimental findings with more realistic behavior of the synapse weight. Thus, it was essential to test the model behavior during the MD of the contralateral eye in the Binocular cortex. The single synapse equations were modified to include multiple inputs statistics while the same concept is held constant. The synapse-specific Hebbian factor $\\rho$ was changed to: \n\n\n\\begin{equation*}\n\\tau_\\rho\\frac{d\\rho_i}{dt}=(\\rho_{max}-\\rho_i)+[\\phi_i]_+ - (\\rho_i-\\rho_{min}(H))[-\\phi_i]_+\n\\end{equation*}\n\nwhere $[\\phi_i]_+$ is $Cov[x_i,y]-\\theta$ and the $Cov$ is definded as $Q_{i,j}$ in Modeling Theory \n\nAdditionally, the postsynaptic-cell-specific homeostatic factor $H$ was changed to: \n\n\\begin{equation*}\nH=Max(h,1)\n\\end{equation*}\n\nWhere $h$ is defined as: \n\\begin{equation*}\n\\tau_h\\frac{dh}{dt}=-h+F(H_{target})\n\\end{equation*}\n\nWhere, $F(x)$ is a monotonically increasing function that is 0 for $x \\leq 1$ and saturates when $x$ is more than $1$ such that \n\\\n\\begin{equation*}\nF(x)=[1+\\tanh(x-1)]\\Theta(x-1.01)\n\\end{equation*}\n\nWhere $\\Theta(x)$ is a step function, $\\Theta(x) = 1$ for $x ≥ 0$, and $0$ otherwise. \n\nThe relationships above also modify the synaptic strength to be: \n\n\\begin{equation*}\nw_i=HA_i\\rho_i\n\\end{equation*}\n\nWhere $A_i$ is the axonal arborization function defined in the Modeling Theory based on the input statistics. \n\n\nWhen it comes to simulate the Binocular cortex, it is also informative to report the Ocular Dominance Index (ODI) with respect to the contralateral and ipsilateral eye in terms of their individual synaptic strengths. Thus, given the above conditions, the ODI was defined as: \n\\begin{equation*}\nODI=\\frac{C-I}{C+I}\n\\end{equation*}\n\nWhere $C$ and $I$ are the synaptic strenghts $w_i$. \n\n\n\n\n\n**Figure 6:** The Synaptic Strength behavior and the two-factor multi-synapse varibles change in the Binocular cortex before, during, and after MD [5].\n\nIn order to simulate these results, several parameters need to be considered: \n\nParameter | Before MD | During MD | Recovery \n---| --- | --- | --- \nx | 1.0 | 0.5 | 1.0\n$y_o$ | 1.0 | 1.0 | 1.0\n$\\tau_\\rho$ | 0.2 | 0.2| 0.2\n$\\tau_H$| 4.0 | 4.0 | 4.0 \n$\\theta$ | 0.6 | 0.6 | 0.6 \n$\\rho_{max}$ | 1.0 | 1.0 | 1.0\n$\\rho_{min}$ | 0.7 | 0.7 | 0.7 \n\n\n\nVariable | Initial Condition\n--- | ---\n$\\rho_i$| 1.0 $A_i$\nH | 1.0\n\n\nFrom figure6, it shows the simulation results of the multi-synapse model in the Binocular cortex before, during, and after MD. As it can be seen, the response of closed eye during MD decreased for a period of time reflecting the Hebbian LTD factor reduction. It was followed by a slower upscaling from the H factor reflecting an overall scaling of weight rather than an individual synaptic-specific factor. This dynamic was verified with the experimental findings and the results show no significant difference [5]. By exploring each of the model’s variables individually, \\rho and W show how the contralateral eye inputs stop firing during MD, which resulted in the LTD shown around the indices of C in A and B. By compering these results with the single synapse model in figure 5, the eyes’ responses in D, red = closed eye, blue open eye. This is in agreement with the previous prediction regarding the overshoot during the recovery and the homeostatic overall scaling. \n\n---\n\n\n# Task 6\n\nThe following code was written to reproduce the results published in [5] for Two-factor multi-synapse model in the Binocular cortex before, during, and after MD. Given the parameters and initial conditions listed above:\n\n1. Implement the model equations to be solved using odeint in the case where there are 500 neurons and a 0.62% ratio of contra-eye neurons are under MD.\n2. How significant can the random noise alter the results?\n\n\n# Task 6.2 Answer\n\nSince the random noise was Gaussian random distribution, it has a negligible effect on the results. By not adding the noise, the results are the same. \n\n\n# Task 7\nThe following code was written to reproduce the results published in [5] for Two-factor multi-synapse model in the Binocular cortex before, during, and after MD. Given the parameters and initial conditions listed above:\n\n1.\tModify the code to simulate the inactivation of the three mechanisms listed in the introduction; Blocking TrK, TNf, and NMDA in order to reproduce the following figure: \n\n\n\n**Figure 7** The simulation results of the inactivation conditions in the Binocular cortex before, during, and after MD [5].\n \n#### Hint: Each inactivation needs to be solved individually. \n\n# Task 8 \nThe following code was written to reproduce the results published in [5] for Two-factor multi-synapse model in the Binocular cortex before, during, and after MD. Given the parameters and initial conditions listed above:\n\n1. Modify the code to produce the simulation results in the monocular cortex assuming only contra-eye is only under MD. The expected results should be similar to the published results in figure 8.\n\n\n\n**Figure 8** The simulation results in the monocular cortex before, during, and after MD using 500 inputs from the contralateral eye [5].\n\n---\n\n# Task 6.1 Answer\n\n\n```python\nfrom matplotlib.colors import LogNorm\n# Parameters again \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\nrcontra=0.62; # ratio of contra-eye neurons\nN_total=500; # total #neurons \nN_contra=round(rcontra*N_total); # #contra-eye neurons \nN_ipsi=N_total-N_contra; # #ipsi-eye neurons \nInput_mu=1.0; # baseline firing rate\nInput_BE=0.5; # between-eye correlation\nInput_MD=0.5; # MD factor\nInput_L=0.2; # input correlation width\n\nth_corr=0.6; # constant threshold\nP_y0=1.0; # homeostatic setpoint\nP_rhom=0.7; # minimum value of Hebbian factor\nP_rhoM=1.0; # maximum value of Hebbian factor\nP_tau_rho=0.2; # Hebbian time-constant (day) \nP_tau_Hh=4.0; # homeostatic hidden averaging time (day) \n\nT_wu=50; # warm-up (day) \nT_baseline=1.0; # warm-up (day) \nT_MD=7; # MD period (day) \nT_recovery=3.0; # recovery period (day) \n\n#T_stage=[T_wu,T_baseline,T_MD,T_recovery]\nT_stage=[50.0,1.0,7.0,3.0]\n\nflag_trk=1.0;\nflag_tnf=1.0;\nflag_nmda=1.0;\n\ndef Hfun_arr(x):\n \n Hfun_out=np.empty_like(x)\n for i in range(len(x)):\n Hfun_out[i]=np.max([1.0,x[i]]) \n \n return Hfun_out\n\ndef Hfun1(x):\n \n Hfun_out1=max(1.0,x)\n return Hfun_out1\n\n\ndef InputStat(MDflag):\n def F(x):\n outF= 1.0/(1.0+np.exp(np.dot(3.0,(x-1.0))))\n return outF\n \n muC=Input_mu*(Input_MD*(MDflag==1.0)+1*(MDflag!=1.0))\n muI=Input_mu*(Input_MD*(MDflag==2.0)+1*(MDflag!=2.0))\n axC=np.linspace(0,1,N_contra).reshape(-1,1);\n axI=np.linspace(0,1,N_ipsi).reshape(-1,1);\n Mu=np.append(muC*np.ones(np.shape(axC)), muI*(np.ones(np.shape(axI)))).reshape(-1,1);\n QCC=(np.power(muC,2.0)*np.exp(-0.5*np.power(OutSub(axC,axC),2.0)/Input_L**2.0))/ma.sqrt(2.0*np.pi*Input_L**2.0);\n QII=(np.power(muI,2.0)*np.exp(-0.5*np.power(OutSub(axI,axI),2.0)/Input_L**2.0))/ma.sqrt(2.0*np.pi*Input_L**2.0);\n QCI=(Input_BE*muC*muI*np.exp(-0.5*np.power(OutSub(axC,axI),2.0)/Input_L**2.0))/ma.sqrt(2.0*np.pi*Input_L**2.0);\n Q=np.concatenate((QCC, QCI), axis=1)\n QCI=np.transpose(QCI)\n Q1=np.concatenate((QCI, QII), axis=1)\n Q=np.concatenate((Q,Q1), axis=0)\n axC=np.power(axC-0.5,2.0);\n axI=np.power(axI-0.5,2.0);\n both=np.append(axC, axI)\n S=F(both/(Input_L**2.0));\n S=S/np.sum(S);\n Nz=np.random.standard_normal([N_total,N_total]); \n Q=Q+(Nz+np.transpose(Nz));\n S=S.reshape(-1,1)\n Mu=Mu.reshape(-1,1)\n return [Mu,Q,S]\n \n\n # outer product of the subtraction of two vectors \ndef OutSub(In1,In2):\n OuSubOut=In1@np.ones(np.shape(np.transpose(In2)))-np.ones(np.shape(In1))@np.transpose(In2);\n return OuSubOut\n\ndef PlastRule(y,t,Mu,Q,S,stages):\n \n y=y.reshape(-1,1)\n rho=y[range(0, N_total)]\n Hh=y[-1];\n \n def Hhfun(x):\n \n out=(1.0+ma.tanh(x-1.0))*(x>1.05)\n return out\n def TL(x):\n TL_out=x*(x>0); #threshold-linear function\n return TL_out\n \n H=Hfun1(Hh)\n \n if Flags[stages][2]==0:\n H=1.0;\n \n w=(H*rho)*S;\n y_1=np.transpose(Mu)@w\n Corr=(Q@w)-th_corr;\n HON=((Flags[stages][3]) or (t<4))\n rr=Flags[stages][1]\n\n outall=np.zeros(y.shape)\n \n outall[range(0, N_total)]=HON*(rr*(TL(P_rhoM-rho)*TL(Corr))-TL(rho-(P_rhom/ma.sqrt(H)))*TL(-Corr))/P_tau_rho;\n outall[-1]=(-Hh+Hhfun((H*P_y0)/y_1))/P_tau_Hh;\n outall=outall.ravel()\n \n return outall\n\n\n# simulation the two-factor rule of plasticity\ndef PlastSim(Init,S,stages):\n def TL(x):\n TL_out=x*(x>0);\n return TL_out\n\n Init_time1=Init[0]\n Init_rho1=Init[1]\n Init_Hh1=Init[2]\n Init_H1=Init[3]\n sr=100\n\n Mu,Q,s1=InputStat(Flags[stages][0]); # acquire input statistics\n \n time_vec=Init_time1+np.linspace(0,T_stage[stages],sr)\n\n print('******ok*******')\n y0=np.append(Init_rho1, Init_Hh1)\n \n \n solo= odeint(PlastRule,y0,time_vec,args=(Mu,Q,S,stages))\n solo=np.transpose(solo)\n\n \n Hist_rho=solo[range(0, N_total),:]\n Hist_Hh=solo[-1,:]\n \n Hist_time=time_vec\n Hist_H=Hfun_arr(Hist_Hh);\n\n\n\n if Flags[stages][2]==0:\n Hist_H=np.ones(np.shape(Hist_Hh));\n \n Hist_time=Hist_time.reshape(1,-1)\n Hist_H=Hist_H.reshape(1,-1)\n Hist_Hh=Hist_Hh.reshape(1,-1)\n \n Hist_w=Hist_rho*(np.ones([N_total,1])@Hist_H)*(S@np.ones(np.shape(Hist_time)));\n Hist_y=np.transpose(Mu)@Hist_w\n \n W_c_only=np.sum(Hist_w[range(N_contra),:],0)\n W_i_only=np.sum(Hist_w[-N_ipsi:,:],0)\n\n Hist_resp=[W_c_only,W_i_only]\n Hist_ODI=(W_c_only-W_i_only)/(W_c_only+W_i_only)\n \n\n \n Hist_ODI=Hist_ODI.reshape(1,-1)\n \n\n return [Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]\n\n## *****************************************************************# \n\n\nMu,Q,S=InputStat(0);\n\nInit_time=-T_wu;\nV1=np.linspace(1,N_contra,N_contra);\nV2=np.linspace(1,N_ipsi,N_ipsi);\nV3=(abs(V1-0.5*N_contra)<.25*N_contra)+0\nV4=(abs(V2-0.5*N_ipsi<.25*N_ipsi))+0\nV5=np.append(V3,V4)\nInit_rho=P_rhom+(P_rhoM-P_rhom)*V5\n\n\nInit_Hh=0.0;\nInit_H=1.0;\nInit=[Init_time,Init_rho,Init_Hh,Init_H]\n\n\nstages=[0,1,2,3]; # wp=0 baseline=1 md=2 recovery=3\nFlags=[[0.0,1.0,1.0,1.0],[0.0,1.0,flag_tnf,1.0],[1.0,flag_trk,flag_tnf,flag_nmda],[0.0,flag_trk,flag_tnf,1.0]]\n\n\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,0)\nInit=[Hist_time[0,-1],Hist_rho[:,-1:],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,1)\n\nallw=Hist_w\nall_rho=Hist_rho\nall_Hist_H=Hist_H\nall_Hist_resp=Hist_resp\nall_Hist_ODI=Hist_ODI\nall_Hist_Hh=Hist_Hh\nall_Hist_time=Hist_time\nall_Hist_y=Hist_y\n\n \nInit=[Hist_time[0,-1],Hist_rho[:,-1:],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,2)\n\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\nInit=[Hist_time[0,-1],Hist_rho[:,-1:],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,3)\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\n\nall_Hist_time=all_Hist_time-1\n\nplt.figure(figsize=(15,10))\nplt.subplot(2,3,1)\nplt.pcolor(all_Hist_time,np.linspace(1,N_total,N_total),allw,cmap='jet')\nplt.xlabel('Time (days)')\nplt.ylabel('Index')\nplt.title('w')\nplt.colorbar()\nplt.tight_layout()\n\nplt.subplot(2,3,2)\nplt.pcolor(all_Hist_time,np.linspace(1,N_total,N_total),all_rho, cmap='jet')\nplt.xlabel('Time (days)')\nplt.ylabel('Index')\nplt.title(r'$\\rho$')\nplt.colorbar()\nplt.tight_layout()\n\n\nplt.subplot(2,3,3)\nplt.plot(all_Hist_time.ravel(),all_Hist_ODI.ravel(),'k')\nplt.ylabel('ODI')\nplt.xlabel('Time (days)')\nplt.ylim((0,0.4))\nplt.grid()\n\n\n\nplt.subplot(2,3,4)\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[0,:]/all_Hist_resp[0,0]),'r',label='Closed Eye')\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[1,:]/all_Hist_resp[1,0]),'b', label='Open Eye')\nplt.ylabel('Response')\nplt.xlabel('Time (days)')\nplt.ylim((0.6,1.4))\nplt.grid()\nplt.legend(loc='best')\n\n\n\nplt.subplot(2,3,5)\nplt.plot(all_Hist_time.ravel(),all_Hist_Hh.ravel(),'g',label='h')\nplt.plot(all_Hist_time.ravel(),all_Hist_H.ravel(),'k',label='H')\nplt.ylabel('H,h')\nplt.xlabel('Time (days)')\nplt.ylim((0,1.5))\nplt.grid()\nplt.legend(loc='best')\n\nplt.subplot(2,3,6)\nplt.plot(all_Hist_time.ravel(),all_Hist_y.ravel(),'r')\nplt.ylabel('y')\nplt.xlabel('Time (days)')\nplt.ylim((0.5,1.5))\nplt.tight_layout()\nplt.grid()\n\n\n```\n\n# Task 7 Answer\n\n\n```python\nfrom matplotlib.colors import LogNorm\n# Parameters again \nfrom IPython.core.debugger import set_trace\n\nimport sys\nimport numpy\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\n\n\nrcontra=0.62; # ratio of contra-eye neurons\nN_total=500; # total #neurons \nN_contra=round(rcontra*N_total); # #contra-eye neurons \nN_ipsi=N_total-N_contra; # #ipsi-eye neurons \nInput_mu=1.; # baseline firing rate\nInput_BE=.5; # between-eye correlation\nInput_MD=.5; # MD factor\nInput_L=.2; # input correlation width\n\nth_corr=.6; # constant threshold\nP_y0=1.; # homeostatic setpoint\nP_rhom=.7; # minimum value of Hebbian factor\nP_rhoM=1.; # maximum value of Hebbian factor\nP_tau_rho=.2; # Hebbian time-constant (day) \nP_tau_Hh=4.; # homeostatic hidden averaging time (day) \n\nT_wu=50; # warm-up (day) \nT_baseline=1; # warm-up (day) \nT_MD=7; # MD period (day) \nT_recovery=3; # recovery period (day) \n\n#T_stage=[T_wu,T_baseline,T_MD,T_recovery]\nT_stage=[50,1,7,3]\n\n\ndef Hfun(x):\n \n Hfun_out=np.empty_like(x)\n for i in range(len(x)):\n Hfun_out[i]=np.max([1,x[i]]) \n \n return Hfun_out\n\ndef Hfun1(x):\n \n Hfun_out1=max(1,x)\n return Hfun_out1\n\n\ndef InputStat(MDflag):\n def F(x):\n outF= 1./(1+np.exp(np.dot(3,(x-1))))\n return outF\n \n muC=Input_mu*(Input_MD*(MDflag==1)+1*(MDflag!=1));\n muI=Input_mu*(Input_MD*(MDflag==2)+1*(MDflag!=2));\n \n axC=np.linspace(0,1,N_contra).reshape(-1,1);\n axI=np.linspace(0,1,N_ipsi).reshape(-1,1);\n\n Mu=np.append(muC*np.ones(np.shape(axC)), muI*(np.ones(np.shape(axI)))).reshape(-1,1);\n \n \n QCC=np.power(muC,2)*np.exp(-.5*np.power(OutSub(axC,axC),2)/Input_L**2)/ma.sqrt(2*np.pi*Input_L**2);\n QII=np.power(muI,2)*np.exp(-.5*np.power(OutSub(axI,axI),2)/Input_L**2)/ma.sqrt(2*np.pi*Input_L**2);\n QCI=Input_BE*muC*muI*np.exp(-.5*np.power(OutSub(axC,axI),2)/Input_L**2)/ma.sqrt(2*np.pi*Input_L**2);\n \n \n Q=np.concatenate((QCC, QCI), axis=1)\n QCI=np.transpose(QCI)\n Q1=np.concatenate((QCI, QII), axis=1)\n Q=np.concatenate((Q,Q1), axis=0)\n axC=np.power(axC-0.5,2);\n axI=np.power(axI-0.5,2);\n both=np.append(axC, axI)\n S=F(both/(Input_L**2));\n S=S/np.sum(S);\n Nz=np.random.standard_normal([N_total,N_total]); \n\n\n Q=Q+(Nz+np.transpose(Nz));\n S=S.reshape(-1,1)\n Mu=Mu.reshape(-1,1)\n return [Mu,Q,S]\n \n\n # outer product of the subtraction of two vectors \ndef OutSub(In1,In2):\n \n OuSubOut=In1@np.ones(np.shape(np.transpose(In2)))-np.ones(np.shape(In1))@np.transpose(In2);\n return OuSubOut\n\n#def PlastRule(y,t,Mu,Q,S,stages,i,result):\ndef PlastRule(y,t,Mu,Q,S,stages):\n \n y=y.reshape(-1,1)\n rho=y[range(0, 500)]\n Hh=y[-1];\n \n def Hhfun(x):\n \n out=(1+np.tanh(x-1))*(x>1.05)\n return out\n def TL(x):\n TL_out=x*(x>0); #threshold-linear function\n return TL_out\n \n H=Hfun1(Hh)\n \n if Flags[stages][2]==0:\n H=1;\n \n w=H*S*rho;\n y_1=np.transpose(Mu)@w\n Corr=Q@w-th_corr;\n HON=((Flags[stages][3]) or (t<4))\n \n rr=Flags[stages][1]\n\n outall=np.zeros(y.shape)\n \n outall[range(0, 500)]=HON*(rr*TL(P_rhoM-rho)*TL(Corr)-TL(rho-P_rhom/np.sqrt(H))*TL(-Corr))/P_tau_rho;\n outall[-1]=(-Hh+Hhfun(H*P_y0/y_1))/P_tau_Hh;\n outall=outall.ravel()\n \n return outall\n\n\n# simulation the two-factor rule of plasticity\ndef PlastSim(Init,S,stages):\n def TL(x):\n TL_out=x*(x>0);\n return TL_out\n\n Init_time1=Init[0]\n Init_rho1=Init[1]\n Init_Hh1=Init[2]\n Init_H1=Init[3]\n sr=100\n\n Mu,Q,s1=InputStat(Flags[stages][0]); # acquire input statistics\n \n time_vec=Init_time1+np.linspace(0,T_stage[stages],sr)\n\n print('******ok*******')\n y0=np.append(Init_rho1, Init_Hh1)\n \n \n solo= odeint(PlastRule,y0,time_vec,args=(Mu,Q,S,stages))\n solo=np.transpose(solo)\n\n \n Hist_rho=solo[range(0, 500),:]\n Hist_Hh=solo[-1,:]\n \n Hist_time=time_vec[:]\n Hist_H=Hfun(Hist_Hh);\n\n\n\n if Flags[stages][2]==0:\n print('TNF=',Flags[stages][2])\n Hist_H=np.ones(np.shape(Hist_Hh));\n \n Hist_time=Hist_time.reshape(1,-1)\n Hist_H=Hist_H.reshape(1,-1)\n Hist_Hh=Hist_Hh.reshape(1,-1)\n \n #Hist_w=Hist_rho*(np.ones([500,1])*Hist_H)*(S*np.ones(np.shape(Hist_time)));\n \n Hist_w=Hist_rho*(np.ones([500,1])@Hist_H)*(S@np.ones(np.shape(Hist_time)));\n\n Hist_y=np.transpose(Mu)@Hist_w\n \n W_c_only=np.sum(Hist_w[range(N_contra),:],0)\n W_i_only=np.sum(Hist_w[-N_ipsi:,:],0)\n\n Hist_resp=[W_c_only,W_i_only]\n Hist_ODI=(W_c_only-W_i_only)/(W_c_only+W_i_only)\n \n\n \n Hist_ODI=Hist_ODI.reshape(1,-1)\n \n\n return [Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]\n\n## *****************************************************************# \n\n\nMu,Q,S=InputStat(0);\n\nInit_time=-T_wu;\nV1=np.linspace(1,N_contra,N_contra);\nV2=np.linspace(1,N_ipsi,N_ipsi);\nV3=(abs(V1-0.5*N_contra)<.25*N_contra)+0\nV4=(abs(V2-0.5*N_ipsi<.25*N_ipsi))+0\nV5=np.append(V3,V4)\nInit_rho=P_rhom+(P_rhoM-P_rhom)*V5\n\n\nInit_Hh=0;\nInit_H=1;\nInit=[Init_time,Init_rho,Init_Hh,Init_H]\n\nflag_trk=0\nflag_tnf=1\nflag_nmda=1\n\nstages=[0,1,2,3]; # wp=0 baseline=1 md=2 recovery=3\nFlags=[[0,1,1,1],[0,1,flag_tnf,1],[1.0,flag_trk,flag_tnf,flag_nmda],[0,flag_trk,flag_tnf,1.0]]\n\n\n\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,0)\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,1)\n\nallw=(Hist_w)\nall_rho=(Hist_rho)\nall_Hist_H=(Hist_H)\nall_Hist_resp=(Hist_resp)\nall_Hist_ODI=(Hist_ODI)\nall_Hist_Hh=(Hist_Hh)\nall_Hist_time=(Hist_time)\nall_Hist_y=(Hist_y)\n\n \nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,2)\n\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,3)\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\n\nall_Hist_time=all_Hist_time-1\n\n\n\nplt.figure(figsize=(15,10))\nplt.subplot(3,4,1)\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[0,:]/all_Hist_resp[0,0]),'r',label='Closed Eye')\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[1,:]/all_Hist_resp[1,0]),'b', label='Open Eye')\nplt.ylabel('Response')\nplt.xlabel('Time (days)')\nplt.ylim((0.6,1.4))\nplt.grid()\nplt.legend(loc='best')\nplt.title('TrKB inactivation')\n\n\n\nplt.subplot(3,4,2)\nplt.plot(all_Hist_time.ravel(),all_Hist_ODI.ravel(),'k')\nplt.ylabel('ODI')\nplt.xlabel('Time (days)')\nplt.ylim((0,0.4))\nplt.grid()\n\n\nplt.subplot(3,4,3)\nplt.plot(all_Hist_time.ravel(),all_Hist_Hh.ravel(),'g',label='h')\nplt.plot(all_Hist_time.ravel(),all_Hist_H.ravel(),'k',label='H')\nplt.ylabel('H,h')\nplt.xlabel('Time (days)')\nplt.ylim((0,1.5))\nplt.grid()\nplt.legend(loc='best')\n\n\n\nplt.subplot(3,4,4)\nplt.pcolor(all_Hist_time,np.linspace(1,500,500),all_rho, cmap='jet')\nplt.xlabel('Time (days)')\nplt.ylabel('Index')\nplt.title(r'$\\rho$')\nplt.colorbar()\nplt.tight_layout()\n\n#********************************************************************\nMu,Q,S=InputStat(0);\n\nInit_time=-T_wu;\nV1=np.linspace(1,N_contra,N_contra);\nV2=np.linspace(1,N_ipsi,N_ipsi);\nV3=(abs(V1-0.5*N_contra)<.25*N_contra)+0\nV4=(abs(V2-0.5*N_ipsi<.25*N_ipsi))+0\nV5=np.append(V3,V4)\nInit_rho=P_rhom+(P_rhoM-P_rhom)*V5\n\n\nInit_Hh=0;\nInit_H=1;\nInit=[Init_time,Init_rho,Init_Hh,Init_H]\n\nflag_trk=1\nflag_tnf=1\nflag_nmda=0\n\nstages=[0,1,2,3]; # wp=0 baseline=1 md=2 recovery=3\nFlags=[[0,1,1,1],[0,1,flag_tnf,1],[1.0,flag_trk,flag_tnf,flag_nmda],[0,flag_trk,flag_tnf,1.0]]\n\n\n\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,0)\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,1)\n\nallw=(Hist_w)\nall_rho=(Hist_rho)\nall_Hist_H=(Hist_H)\nall_Hist_resp=(Hist_resp)\nall_Hist_ODI=(Hist_ODI)\nall_Hist_Hh=(Hist_Hh)\nall_Hist_time=(Hist_time)\nall_Hist_y=(Hist_y)\n\n \nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,2)\n\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,3)\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\n\nall_Hist_time=all_Hist_time-1\n\n\n\n\nplt.subplot(3,4,5)\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[0,:]/all_Hist_resp[0,0]),'r',label='Closed Eye')\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[1,:]/all_Hist_resp[1,0]),'b', label='Open Eye')\nplt.ylabel('Response')\nplt.xlabel('Time (days)')\nplt.ylim((0.6,1.4))\nplt.grid()\nplt.legend(loc='best')\nplt.title('NMDA Blockade')\n\n\n\nplt.subplot(3,4,6)\nplt.plot(all_Hist_time.ravel(),all_Hist_ODI.ravel(),'k')\nplt.ylabel('ODI')\nplt.xlabel('Time (days)')\nplt.ylim((0,0.4))\nplt.grid()\n\n\nplt.subplot(3,4,7)\nplt.plot(all_Hist_time.ravel(),all_Hist_Hh.ravel(),'g',label='h')\nplt.plot(all_Hist_time.ravel(),all_Hist_H.ravel(),'k',label='H')\nplt.ylabel('H,h')\nplt.xlabel('Time (days)')\nplt.ylim((0,1.5))\nplt.grid()\nplt.legend(loc='best')\n\n\n\nplt.subplot(3,4,8)\nplt.pcolor(all_Hist_time,np.linspace(1,500,500),all_rho, cmap='jet')\nplt.xlabel('Time (days)')\nplt.ylabel('Index')\nplt.title(r'$\\rho$')\nplt.colorbar()\nplt.tight_layout()\n\n#*******************************************************************************\n\nMu,Q,S=InputStat(0);\n\nInit_time=-T_wu;\nV1=np.linspace(1,N_contra,N_contra);\nV2=np.linspace(1,N_ipsi,N_ipsi);\nV3=(abs(V1-0.5*N_contra)<.25*N_contra)+0\nV4=(abs(V2-0.5*N_ipsi<.25*N_ipsi))+0\nV5=np.append(V3,V4)\nInit_rho=P_rhom+(P_rhoM-P_rhom)*V5\n\n\nInit_Hh=0;\nInit_H=1;\nInit=[Init_time,Init_rho,Init_Hh,Init_H]\n\nflag_trk=1\nflag_tnf=0\nflag_nmda=1\n\nstages=[0,1,2,3]; # wp=0 baseline=1 md=2 recovery=3\nFlags=[[0,1,1,1],[0,1,flag_tnf,1],[1.0,flag_trk,flag_tnf,flag_nmda],[0,flag_trk,flag_tnf,1.0]]\n\n\n\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,0)\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,1)\n\nallw=(Hist_w)\nall_rho=(Hist_rho)\nall_Hist_H=(Hist_H)\nall_Hist_resp=(Hist_resp)\nall_Hist_ODI=(Hist_ODI)\nall_Hist_Hh=(Hist_Hh)\nall_Hist_time=(Hist_time)\nall_Hist_y=(Hist_y)\n\n \nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,2)\n\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,3)\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\n\nall_Hist_time=all_Hist_time-1\n\n\n\n\n#lt.figure(figsize=(12,5))\nplt.subplot(3,4,9)\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[0,:]/all_Hist_resp[0,0]),'r',label='Closed Eye')\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[1,:]/all_Hist_resp[1,0]),'b', label='Open Eye')\nplt.ylabel('Response')\nplt.xlabel('Time (days)')\nplt.ylim((0.6,1.4))\nplt.grid()\nplt.legend(loc='best')\nplt.title('TNF-a Blockade')\n\n\n\nplt.subplot(3,4,10)\nplt.plot(all_Hist_time.ravel(),all_Hist_ODI.ravel(),'k')\nplt.ylabel('ODI')\nplt.xlabel('Time (days)')\nplt.ylim((0,0.4))\nplt.grid()\n\n\nplt.subplot(3,4,11)\nplt.plot(all_Hist_time.ravel(),all_Hist_Hh.ravel(),'g',label='h')\nplt.plot(all_Hist_time.ravel(),all_Hist_H.ravel(),'k',label='H')\nplt.ylabel('H,h')\nplt.xlabel('Time (days)')\nplt.ylim((0,1.5))\nplt.grid()\nplt.legend(loc='best')\n\n\n\nplt.subplot(3,4,12)\nplt.pcolor(all_Hist_time,np.linspace(1,500,500),all_rho, cmap='jet')\nplt.xlabel('Time (days)')\nplt.ylabel('Index')\nplt.title(r'$\\rho$')\nplt.colorbar()\nplt.tight_layout()\n\n\n```\n\n# Task 8 Answer\n\n\n```python\nfrom matplotlib.colors import LogNorm\n# Parameters again \nfrom IPython.core.debugger import set_trace\n\nimport sys\nimport numpy\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\nrcontra=1.0; # ratio of contra-eye neurons\nN_total=500; # total #neurons \nN_contra=round(rcontra*N_total); # #contra-eye neurons \nN_ipsi=N_total-N_contra; # #ipsi-eye neurons \nInput_mu=1.; # baseline firing rate\nInput_BE=.5; # between-eye correlation\nInput_MD=.5; # MD factor\nInput_L=.2; # input correlation width\n\nth_corr=.6; # constant threshold\nP_y0=1.; # homeostatic setpoint\nP_rhom=.7; # minimum value of Hebbian factor\nP_rhoM=1.; # maximum value of Hebbian factor\nP_tau_rho=.2; # Hebbian time-constant (day) \nP_tau_Hh=4.; # homeostatic hidden averaging time (day) \n\nT_wu=50; # warm-up (day) \nT_baseline=1; # warm-up (day) \nT_MD=7; # MD period (day) \nT_recovery=3; # recovery period (day) \n\n#T_stage=[T_wu,T_baseline,T_MD,T_recovery]\nT_stage=[50,1,7,3]\n\n\ndef Hfun(x):\n \n Hfun_out=np.empty_like(x)\n for i in range(len(x)):\n Hfun_out[i]=np.max([1,x[i]]) \n \n return Hfun_out\n\ndef Hfun1(x):\n \n Hfun_out1=max(1,x)\n return Hfun_out1\n\n\ndef InputStat(MDflag):\n def F(x):\n outF= 1./(1+np.exp(np.dot(3,(x-1))))\n return outF\n \n muC=Input_mu*(Input_MD*(MDflag==1)+1*(MDflag!=1));\n muI=Input_mu*(Input_MD*(MDflag==2)+1*(MDflag!=2));\n \n axC=np.linspace(0,1,N_contra).reshape(-1,1);\n axI=np.linspace(0,1,N_ipsi).reshape(-1,1);\n\n Mu=np.append(muC*np.ones(np.shape(axC)), muI*(np.ones(np.shape(axI)))).reshape(-1,1);\n \n \n QCC=np.power(muC,2)*np.exp(-.5*np.power(OutSub(axC,axC),2)/Input_L**2)/ma.sqrt(2*np.pi*Input_L**2);\n QII=np.power(muI,2)*np.exp(-.5*np.power(OutSub(axI,axI),2)/Input_L**2)/ma.sqrt(2*np.pi*Input_L**2);\n QCI=Input_BE*muC*muI*np.exp(-.5*np.power(OutSub(axC,axI),2)/Input_L**2)/ma.sqrt(2*np.pi*Input_L**2);\n \n \n Q=np.concatenate((QCC, QCI), axis=1)\n QCI=np.transpose(QCI)\n Q1=np.concatenate((QCI, QII), axis=1)\n Q=np.concatenate((Q,Q1), axis=0)\n axC=np.power(axC-0.5,2);\n axI=np.power(axI-0.5,2);\n both=np.append(axC, axI)\n S=F(both/(Input_L**2));\n S=S/np.sum(S);\n Nz=np.random.standard_normal([N_total,N_total]); \n\n\n Q=Q+(Nz+np.transpose(Nz));\n S=S.reshape(-1,1)\n Mu=Mu.reshape(-1,1)\n return [Mu,Q,S]\n \n\n # outer product of the subtraction of two vectors \ndef OutSub(In1,In2):\n \n OuSubOut=In1@np.ones(np.shape(np.transpose(In2)))-np.ones(np.shape(In1))@np.transpose(In2);\n return OuSubOut\n\n#def PlastRule(y,t,Mu,Q,S,stages,i,result):\ndef PlastRule(y,t,Mu,Q,S,stages):\n \n y=y.reshape(-1,1)\n rho=y[range(0, 500)]\n Hh=y[-1];\n \n def Hhfun(x):\n \n out=(1+np.tanh(x-1))*(x>1.05)\n return out\n def TL(x):\n TL_out=x*(x>0); #threshold-linear function\n return TL_out\n \n H=Hfun1(Hh)\n \n if Flags[stages][2]==0:\n H=1;\n \n w=H*S*rho;\n y_1=np.transpose(Mu)@w\n Corr=Q@w-th_corr;\n HON=((Flags[stages][3]) or (t<4))\n \n rr=Flags[stages][1]\n\n outall=np.zeros(y.shape)\n \n outall[range(0, 500)]=HON*(rr*TL(P_rhoM-rho)*TL(Corr)-TL(rho-P_rhom/np.sqrt(H))*TL(-Corr))/P_tau_rho;\n outall[-1]=(-Hh+Hhfun(H*P_y0/y_1))/P_tau_Hh;\n outall=outall.ravel()\n \n return outall\n\n\n# simulation the two-factor rule of plasticity\ndef PlastSim(Init,S,stages):\n def TL(x):\n TL_out=x*(x>0);\n return TL_out\n\n Init_time1=Init[0]\n Init_rho1=Init[1]\n Init_Hh1=Init[2]\n Init_H1=Init[3]\n sr=100\n\n Mu,Q,s1=InputStat(Flags[stages][0]); # acquire input statistics\n \n time_vec=Init_time1+np.linspace(0,T_stage[stages],sr)\n\n print('******ok*******')\n y0=np.append(Init_rho1, Init_Hh1)\n \n \n solo= odeint(PlastRule,y0,time_vec,args=(Mu,Q,S,stages))\n solo=np.transpose(solo)\n\n \n Hist_rho=solo[range(0, 500),:]\n Hist_Hh=solo[-1,:]\n \n Hist_time=time_vec[:]\n Hist_H=Hfun(Hist_Hh);\n\n\n\n if Flags[stages][2]==0:\n print('TNF=',Flags[stages][2])\n Hist_H=np.ones(np.shape(Hist_Hh));\n \n Hist_time=Hist_time.reshape(1,-1)\n Hist_H=Hist_H.reshape(1,-1)\n Hist_Hh=Hist_Hh.reshape(1,-1)\n \n #Hist_w=Hist_rho*(np.ones([500,1])*Hist_H)*(S*np.ones(np.shape(Hist_time)));\n \n Hist_w=Hist_rho*(np.ones([500,1])@Hist_H)*(S@np.ones(np.shape(Hist_time)));\n\n Hist_y=np.transpose(Mu)@Hist_w\n \n W_c_only=np.sum(Hist_w[range(N_contra),:],0)\n W_i_only=np.sum(Hist_w[-N_ipsi:,:],0)\n\n Hist_resp=[W_c_only,W_i_only]\n Hist_ODI=(W_c_only-W_i_only)/(W_c_only+W_i_only)\n \n\n \n Hist_ODI=Hist_ODI.reshape(1,-1)\n \n\n return [Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]\n\n## *****************************************************************# \n\n\nMu,Q,S=InputStat(0);\n\nInit_time=-T_wu;\nV1=np.linspace(1,N_contra,N_contra);\nV2=np.linspace(1,N_ipsi,N_ipsi);\nV3=(abs(V1-0.5*N_contra)<.25*N_contra)+0\nV4=(abs(V2-0.5*N_ipsi<.25*N_ipsi))+0\nV5=np.append(V3,V4)\nInit_rho=P_rhom+(P_rhoM-P_rhom)*V5\n\n\nInit_Hh=0;\nInit_H=1;\nInit=[Init_time,Init_rho,Init_Hh,Init_H]\n\nflag_trk=1\nflag_tnf=1\nflag_nmda=1\n\nstages=[0,1,2,3]; # wp=0 baseline=1 md=2 recovery=3\nFlags=[[0,1,1,1],[0,1,flag_tnf,1],[1.0,flag_trk,flag_tnf,flag_nmda],[0,flag_trk,flag_tnf,1.0]]\n\n\n\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,0)\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,1)\n\nallw=(Hist_w)\nall_rho=(Hist_rho)\nall_Hist_H=(Hist_H)\nall_Hist_resp=(Hist_resp)\nall_Hist_ODI=(Hist_ODI)\nall_Hist_Hh=(Hist_Hh)\nall_Hist_time=(Hist_time)\nall_Hist_y=(Hist_y)\n\n \nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,2)\n\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\nInit=[Hist_time[0,-1],Hist_rho[:,-1],Hist_Hh[0,-1],Hist_H[0,-1]]\n[Hist_rho,Hist_H,Hist_w,Hist_resp,Hist_ODI,Hist_Hh,Hist_time,Hist_y]=PlastSim(Init,S,3)\nallw=np.concatenate((allw, Hist_w), axis=1)\nall_rho=np.concatenate((all_rho, Hist_rho), axis=1)\nall_Hist_H=np.concatenate((all_Hist_H, Hist_H), axis=1)\nall_Hist_resp=np.concatenate((all_Hist_resp,Hist_resp), axis=1)\nall_Hist_ODI=np.concatenate((all_Hist_ODI, Hist_ODI), axis=1)\nall_Hist_Hh=np.concatenate((all_Hist_Hh, Hist_Hh), axis=1)\nall_Hist_time=np.concatenate((all_Hist_time, Hist_time), axis=1)\nall_Hist_y=np.concatenate((all_Hist_y, Hist_y), axis=1)\n\n\nall_Hist_time=all_Hist_time-1\n\n\n\n\n\nplt.figure(figsize=(15,10))\nplt.subplot(2,3,1)\nplt.pcolor(all_Hist_time,np.linspace(1,500,500),allw,cmap='jet')\nplt.xlabel('Time (days)')\nplt.ylabel('Index')\nplt.title('w')\nplt.colorbar()\nplt.tight_layout()\n\nplt.subplot(2,3,2)\nplt.pcolor(all_Hist_time,np.linspace(1,500,500),all_rho, cmap='jet')\nplt.xlabel('Time (days)')\nplt.ylabel('Index')\nplt.title(r'$\\rho$')\nplt.colorbar()\nplt.tight_layout()\n\n\nplt.subplot(2,3,3)\nplt.plot(np.linspace(1,500,500).ravel(),S.ravel(),'k')\nplt.ylabel('A')\nplt.xlabel('Time (days)')\n#plt.ylim((0,0.4))\nplt.grid()\n\n\n\nplt.subplot(2,3,4)\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[0,:]/all_Hist_resp[0,0]),'r',label='Closed Eye')\nplt.plot(all_Hist_time.ravel(),(all_Hist_resp[1,:]/all_Hist_resp[1,0]),'b', label='Open Eye')\nplt.ylabel('Response')\nplt.xlabel('Time (days)')\nplt.ylim((0.5,1.8))\nplt.grid()\nplt.legend(loc='best')\n\n\n\n\nplt.subplot(2,3,5)\nplt.plot(all_Hist_time.ravel(),all_Hist_Hh.ravel(),'g',label='h')\nplt.plot(all_Hist_time.ravel(),all_Hist_H.ravel(),'k',label='H')\nplt.ylabel('H,h')\nplt.xlabel('Time (days)')\nplt.ylim((0,1.9))\nplt.grid()\nplt.legend(loc='best')\n\n\nplt.subplot(2,3,6)\nplt.plot(all_Hist_time.ravel(),all_Hist_y.ravel(),'r')\nplt.ylabel('y')\nplt.xlabel('Time (days)')\n#plt.ylim((0.5,1.5))\nplt.tight_layout()\nplt.grid()\n\n\n```\n\n# List of References\n[1]\tA. Citri and R. C. Malenka, \"Synaptic Plasticity: Multiple Forms, Functions, and Mechanisms,\" Neuropsychopharmacology, vol. 33, no. 1, pp. 18-41, 2008/01/01 2008, doi: 10.1038/sj.npp.1301559.\n\n[2]\tJ. Lisman, \"Glutamatergic synapses are structurally and biochemically complex because of multiple plasticity processes: long-term potentiation, long-term depression, short-term potentiation and scaling,\" Philosophical Transactions of the Royal Society B: Biological Sciences, vol. 372, no. 1715, p. 20160260, 2017.\n\n[3]\tL. N. Cooper, N. Intrator, B. S. Blais, and H. Z. Shouval, Theory of Cortical Plasticity. WORLD SCIENTIFIC, 2004, p. 332.\n\n[4]\tK. Fox and M. Stryker, \"Integrating Hebbian and homeostatic plasticity: introduction,\" ed: The Royal Society, 2017.\n\n[5]\tT. Toyoizumi, M. Kaneko, M. P. Stryker, and K. D. Miller, \"Modeling the dynamic interaction of Hebbian and homeostatic plasticity,\" Neuron, vol. 84, no. 2, pp. 497-510, 2014.\n\n[6] J. Li, E. Park, L. R. Zhong, and L. Chen, \"Homeostatic synaptic plasticity as a metaplasticity mechanism — a molecular and cellular perspective,\" Current Opinion in Neurobiology, vol. 54, pp. 44-53, 2019/02/01/ 2019, doi: https://doi.org/10.1016/j.conb.2018.08.010.\n\n[7]\tM. Kaneko, D. Stellwagen, R. C. Malenka, and M. P. Stryker, \"Tumor necrosis factor-alpha mediates one component of competitive, experience-dependent plasticity in developing visual cortex,\" (in eng), Neuron, vol. 58, no. 5, pp. 673-680, 2008, doi: 10.1016/j.neuron.2008.04.023.\n\n[8]\tG. G. Turrigiano, \"The dialectic of Hebb and homeostasis,\" Philosophical Transactions of the Royal Society B: Biological Sciences, vol. 372, no. 1715, p. 20160258, 2017.\n\n[9]\tT. Keck et al., \"Integrating Hebbian and homeostatic plasticity: the current state of the field and future research directions,\" Philosophical Transactions of the Royal Society B: Biological Sciences, vol. 372, no. 1715, p. 20160158, 2017.\n\n\n\n\nSo far, this project needs a few more interpretation of the results and I need to show the parameters sensitivity with some figures. The preliminary results from task 1, 3, and 5 matches the published results except the two-factor model result; which appears to be off the scale by a factor of 2. The issue I am facing is the time scale of the parameters versus the simulation sampling time. I should be able to solve that issue by normalizing the time scale. Giving the fact that variables of this model are mostly unitless, consistency might be off with different ODE solvers being used. Additionally, the major missing part is to implement the multi-synapse models and reproduce the paper’s results. The paper has a complex statistical method for that implementation, but never mention some parameters, such as the covariance in the MC. If this model is modified to analyze only single-synapse models, then it can be considered as a sufficient work for the notebook. \n\nI am dedicating myself to finish this project according to the following chart. \n\n\n\n\n", "meta": {"hexsha": "8a75847451fceabb959bda93b9e8437c47049e9f", "size": 669254, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Copy of Alhawwash_BME695_Project_working_v3_Solved.ipynb", "max_stars_repo_name": "EMBRIO-Institute/example-project-1", "max_stars_repo_head_hexsha": "e24708664d41116d57a32e69a7cd4b404411a76b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-14T14:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T14:13:08.000Z", "max_issues_repo_path": "notebooks/Copy of Alhawwash_BME695_Project_working_v3_Solved.ipynb", "max_issues_repo_name": "EMBRIO-Institute/example-project-1", "max_issues_repo_head_hexsha": "e24708664d41116d57a32e69a7cd4b404411a76b", "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": "notebooks/Copy of Alhawwash_BME695_Project_working_v3_Solved.ipynb", "max_forks_repo_name": "EMBRIO-Institute/example-project-1", "max_forks_repo_head_hexsha": "e24708664d41116d57a32e69a7cd4b404411a76b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-18T15:31:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T15:31:23.000Z", "avg_line_length": 669254.0, "max_line_length": 669254, "alphanum_fraction": 0.9309126281, "converted": true, "num_tokens": 21282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.1645164608483867, "lm_q1q2_score": 0.07076631943266017}} {"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# Quantum Approximate Optimization Algorithm for the Ising model\n\n\n \n \n \n \n
    \n View on QuantumLib\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
    \n\nThis notebook provides an introduction to the Quantum Approximate Optimization Algorithm (QAOA) using the Cirq. The presentation mostly follows [Farhi et al.](https://arxiv.org/abs/1411.4028). We will show how to construct the QAOA circuit and use it to solve some simple problems.\n\n\n```\n# install cirq\n!pip install cirq==0.5 --quiet\n```\n\nTo verify that Cirq is installed in your environment, try to `import cirq` and print out a diagram of the Bristlecone device.\n\n\n```\nimport cirq\nimport numpy as np\nimport sympy\nimport matplotlib.pyplot as plt\n\nprint(cirq.google.Bristlecone)\n```\n\n (0, 5)────(0, 6)\n │ │\n │ │\n (1, 4)───(1, 5)────(1, 6)────(1, 7)\n │ │ │ │\n │ │ │ │\n (2, 3)───(2, 4)───(2, 5)────(2, 6)────(2, 7)───(2, 8)\n │ │ │ │ │ │\n │ │ │ │ │ │\n (3, 2)───(3, 3)───(3, 4)───(3, 5)────(3, 6)────(3, 7)───(3, 8)───(3, 9)\n │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │\n (4, 1)───(4, 2)───(4, 3)───(4, 4)───(4, 5)────(4, 6)────(4, 7)───(4, 8)───(4, 9)───(4, 10)\n │ │ │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │ │ │\n (5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4)───(5, 5)────(5, 6)────(5, 7)───(5, 8)───(5, 9)───(5, 10)───(5, 11)\n │ │ │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │ │ │\n (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5)────(6, 6)────(6, 7)───(6, 8)───(6, 9)───(6, 10)\n │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │\n (7, 2)───(7, 3)───(7, 4)───(7, 5)────(7, 6)────(7, 7)───(7, 8)───(7, 9)\n │ │ │ │ │ │\n │ │ │ │ │ │\n (8, 3)───(8, 4)───(8, 5)────(8, 6)────(8, 7)───(8, 8)\n │ │ │ │\n │ │ │ │\n (9, 4)───(9, 5)────(9, 6)────(9, 7)\n │ │\n │ │\n (10, 5)───(10, 6)\n\n\n### Description of QAOA\n\nLet's start out with a description of the QAOA algorithm. We'll discuss the structure of the problem it tries to solve and the quantum circuit we need to build to implement it.\n\nSuppose you have a function $C(z)$ that depends on a collection of variables $z = z_1,z_2,\\ldots, z_n$, where each $z_j$ can be equal to either $+1$ or $-1$ (the important thing here is that each $z_j$ has two possible values, and by convention we choose those values to be $\\pm 1$). The QAOA is a general-purpose algorithm whose goal is to produce an assignment of the $z_j$ that gives a relatively low value of $C(z)$. It's not guaranteed to give the lowest possible value of $C(z)$---hence the name \"Approximate\"---except in a particular limit which we will discuss.\n\nThe QAOA algorithm acts on $n$ qubits. As you might guess, each qubit represents one of the variables in our function, and the $2^n$ states of the computational basis correspond to the $2^n$ possible assignments of the $z$ variables. To be more specific, let's agree that the value of $z_j$ corresponds to the measurement outcome of the Pauli-$Z$ operator on the $j$th qubit. There is a potential confusion here because the state $| 0 \\rangle$ corresponds to $z = +1$, while the state $| 1\\rangle$ corresponds to $z=-1$. This is unfortunate, but is something that we'll just have to deal with.\n\nThe QAOA algorithm is fairly simple to explain, though the reasons behind why it works are not obvious at first glance. As usual, we begin with all of our qubits initialized in the $|0\\rangle$ state. The first step is to act with $H^{\\otimes n}$, the Hadamard operator on each qubit. This prepares an equal superposition of all bitstrings, i.e., an equal superposition of all possible $z$ assignments:\n$$\nH^{\\otimes n} |0^n\\rangle =\\frac{1}{2^{n/2}} \\sum_{x \\in \\{0,1\\}^n} |x\\rangle.\n$$\nThis should be thought of as the \"real\" initial state of the algorithm. The point of the remaining steps is to affect the amplitudes so that those with small $C(z)$ values grow while those with large $C(z)$ values shrink. Then at the end when we measure the qubits we'll be more likely to find a bitstring with a small value of $C(z)$.\n\nThe meat of the algorithm relies on the following unitary operator:\n$$\nU(\\gamma,C) = e^{i\\pi \\gamma C(Z)/2}.\n$$\nThis operator deserves some explanation. First, $\\gamma$ is a paramter which we will later treat as a variational parameter, adjusting its value to produce the best possible result. $C$ here is the function we are trying to minimize, and the notation $C(Z)$ is supposed to tell you to plug in the Pauli-$Z$ operator for each qubit in place of the argument $z$. For example, if \n$$\nC(z) = 3z_1 z_2 - z_2z_3 + z_4\n$$\nthen\n$$\nC(Z) = 3Z_1 Z_2 - Z_2Z_3 + Z_4.\n$$\nIt looks like I didn't do much, but the point here is that $C(z)$ is a number while $C(Z)$ is a matrix. That matrix is diagonal in the computational basis, and those diagonal entries represent all the possible values of $C(z)$.\n\nAfter acting with $H^{\\otimes n}$, we act with $U(C,\\gamma)$. The result is still a sum over all possible bit-strings, but now the coefficients are complex phases which depend on $C$. At this point there is still an equal probability to measure any particular string, though, because Born's rule only depends on the square of the amplitude. So the algorithm is not done yet. Below we will have to figure out how to implement $U(\\gamma, C)$ in Cirq so that we can perform this step in the algorithm.\n\nThe next step of the algorithm is to act with the unitary operator\n$$\nU(\\beta,B) = e^{i\\pi\\beta B/2},~~~ B = \\sum_{j=1}^n X_j,\n$$\nwhere $\\beta$ is another variational parameter. Since the Pauli-$X$ operators on each qubit commute with each other, we can alternatively write this as\n$$\nU(\\beta, B) = \\prod_{j=1}^n e^{i\\pi\\beta X_j/2}.\n$$\nSo this is just a rotation of each qubit around the $X$-axis on the Bloch sphere by an amount determined by $\\beta$. This operation is _not_ diagonal in the computational basis, and the resulting state will not be an equal superposition over all bitstrings. So after this step there will be constructive and destructive interference, which hopefully leads to enhancement of states corresponding to small values of $C$. This $U(\\beta, B)$ is sometimes called a \"mixing\" operation. Note that, up to an inconsequential global phase, we can also write\n$$\nU(\\beta, B) = \\prod_{j=1}^n X_j^{\\beta}.\n$$\n\nThe total circuit consists of repeating the previous two steps a total of $p\\geq 1$ times, where the choice of $p$ is up to you. The parameters $\\gamma$ and $\\beta$ can be chosen independently at each step. So at the conclusion of the circuit, the state of the qubits is\n$$\n|\\gamma,\\beta\\rangle = U(\\beta_p,B)U(\\gamma_p,C)\\cdots U(\\beta_1,B)U(\\gamma_1,C)H^{\\otimes n}|0^n\\rangle.\n$$\nIf we choose $\\gamma$ and $\\beta$ so that the expectation value\n$$\nF(\\gamma,\\beta) = \\langle \\gamma,\\beta|C(Z)|\\gamma,\\beta\\rangle\n$$\nis minimized, then measuring the state $|\\gamma,\\beta\\rangle$ in the computational basis gives us a good candidate bitstring for the minimum of $C(z)$. That's the whole thing!\n\nIn summary we have to perform the following tasks in order to implement the QAOA:\n\n\n1. Figure out out to perform the $U(\\gamma, C)$ operation in Cirq for our choice of $C$.\n2. Create a quantum circuit alternating $U(\\gamma, C)$ and $U(\\beta, B)$ operations as many times as desired. \n3. Find the optimal value of the variational parameters in our circuit.\n4. Measure the output of our circuit.\n\n### Toy problem: ground state of Ising model\n\nThe Ising Model defines the energy function\n$$\nE = -\\sum_{\\langle i,j \\rangle} Z_i Z_j - \\sum_i h_i Z_i,\n$$\nwhere the notation $\\langle i,j\\rangle$ means a sum over all nearest-neighbor pairs. The picture here is that the qubits live on the vertices of a graph, and the edges of the graph define which qubits are neighbors. We'll just take out graph to be a rectangular lattice with some number of rows and some number of columns. The numbers $h_i$ have the physical interpretation of an external magnetic field.\n\nWe are interested in finding a low-lying state of the Ising Model, by which I mean a state that has a relatively low amount of energy. This is a difficult problem in general. The pairwise interaction terms would tell you that neighboring qubits should be in the same state to lower the energy, while the magnetic field terms tell you that a given qubit wants to point \"in the same direction\" as its local field, and the strength of that preference depends on the magnitude of the field. These two different kinds of pressure are not always in agreement!\n\nThis type of problem is a perfect candidate for the QAOA, where we use the energy $E$ as our cost function $C$.\n\n### ZZ Gate\n\nThe first thing we need to do is create the operation $U(\\gamma, C)$, where $C$ is equal to the Ising Model energy function. The first thing to note is that, since all of the terms in the energy commute, we can decompose this operation as\n$$\nU(\\gamma, C) = \\prod_{\\langle i,j\\rangle}e^{-i\\pi\\gamma Z_iZ_j/2} \\prod_i e^{-i\\pi \\gamma h_i Z_i/2}.\n$$\nThis requires that we have the two-qubit gate $\\exp(-i\\pi\\gamma ZZ/2)$ at our disposal. In matrix form, this is\n$$\n\\begin{align}\n\\exp(-i \\pi\\gamma Z\\otimes Z/2) = \\begin{bmatrix}\ne^{-i\\pi \\gamma/2} & 0 &0&0\\\\\n0 & e^{i\\pi \\gamma/2} &0&0\\\\\n0&0& e^{i\\pi \\gamma/2} &0 \\\\\n0&0 & 0 & e^{-i\\pi \\gamma/2}\n\\end{bmatrix}\n\\end{align}\n$$\nAs of version 0.5.0, Cirq has a built-in gate `cirq.ZZ` which is equivalent to this once you account for a global phase:\n\n\n```\na = cirq.NamedQubit(\"a\")\nb = cirq.NamedQubit(\"b\")\ngamma = 0.3 # Put your own value here.\ncircuit = cirq.Circuit.from_ops(cirq.ZZ(a,b)**gamma)\nprint(circuit)\ncirq.unitary(circuit).round(2)\n```\n\n a: ───ZZ───────\n │\n b: ───ZZ^0.3───\n\n\n\n\n\n array([[1. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ],\n [0. +0.j , 0.59+0.81j, 0. +0.j , 0. +0.j ],\n [0. +0.j , 0. +0.j , 0.59+0.81j, 0. +0.j ],\n [0. +0.j , 0. +0.j , 0. +0.j , 1. +0.j ]])\n\n\n\nWe should also check that the matrix is what we expect:\n\n\n```\ntest_matrix = np.array([[np.exp(-1j*np.pi*gamma/2),0, 0, 0],\n [0, np.exp(1j*np.pi*gamma/2), 0, 0],\n [0, 0, np.exp(1j*np.pi*gamma/2), 0],\n [0, 0, 0,np.exp(-1j*np.pi*gamma/2)]])\ncirq.testing.assert_allclose_up_to_global_phase(test_matrix, cirq.unitary(circuit), atol=1e-5)\n```\n\n### Z Gate\n\nThe magnetic field terms can be handled in a similar way. The single-qubit unitary\n$$\n\\exp(-i\\pi \\gamma hZ/2) = \\begin{bmatrix}\ne^{-i\\pi \\gamma h/2} & 0 \\\\\n0 & e^{i\\pi \\gamma h/2}\n\\end{bmatrix}\n$$\nis equivalent up to global phase to `cirq.Z**(h*gamma)`:\n\n\n```\na = cirq.NamedQubit(\"a\")\ngamma = 0.3 # Put your own value here.\nh = 1.3 # Put your own value here.\ncircuit = cirq.Circuit.from_ops(cirq.Z(a)**(gamma*h))\nprint(circuit)\nprint(cirq.unitary(circuit).round(2))\n\ntest_matrix = np.array([[np.exp(-1j*np.pi*gamma*h/2),0],\n [0, np.exp(1j*np.pi*gamma*h/2)]])\ncirq.testing.assert_allclose_up_to_global_phase(test_matrix, cirq.unitary(circuit), atol=1e-5)\n```\n\n a: ───Z^0.39───\n [[1. +0.j 0. +0.j ]\n [0. +0.j 0.34+0.94j]]\n\n\n### Exercise: More general two-qubit gate\n\nThe Ising Model is particularly simple because the nearest-neighbor interaction $Z_i Z_j$ is already given in terms of a product of Pauli matrices. But suppose instead I told you that the cost function was a sum of terms that looked like\n$$\nC(z_i,z_j) = \\begin{cases}\nc_{00} \\text{ if } z_i =1,~z_j=1,\\\\\nc_{01} \\text{ if } z_i =1,~z_j=-1,\\\\\nc_{10} \\text{ if } z_i =-1,~z_j=1,\\\\\nc_{11} \\text{ if } z_i =-1,~z_j=-1.\n\\end{cases}\n$$\nFor some numbers $c_{ab}$. How would you make the analogous two-qubit gate for this case?\n\nYou can either make a custom gate from scratch, or build a solution from the standard elementary gates.\n\n### Create Circuit\n\nUsing the `cirq.ZZ` gate we can now create the QAOA circuit. We're going to focus on the Ising Model an a rectangular lattice with an arbitrary number of rows and columns. Here are some things to think about:\n\n1. `cirq.GridQubit`s are natural because our qubits actually do live on a grid. Cirq does not care what kind of qubit you make, though.\n2. It's a good idea to define separate functions to place the C and B layers for the circuit. Really these should be generators that yield the required gates.\n3. You might consider wrapping everything inside a class. We won't do that here, but if you want to play around with different numbers of rows/columns or different numbers of B/C layers it can be convenient.\n\nFirst we'll define the basic paramters of our model and the generators for the different layers:\n\n\n\n```\nn_cols = 3\nn_rows = 3\nh = 0.5*np.ones((n_rows,n_cols))\n\n# Arranging the qubits in a list-of-lists like this makes them easy to refer to later.\nqubits = [[cirq.GridQubit(i,j) for j in range(n_cols)] for i in range(n_rows)]\n\n\ndef beta_layer(beta):\n \"\"\"Generator for U(beta, B) layer (mixing layer) of QAOA\"\"\"\n for row in qubits:\n for qubit in row:\n yield cirq.X(qubit)**beta\n \ndef gamma_layer(gamma, h):\n \"\"\"Generator for U(gamma, C) layer of QAOA\n\n Args:\n gamma: Float variational parameter for the circuit\n h: Array of floats of external magnetic field values\n \"\"\"\n for i in range(n_rows):\n for j in range(n_cols):\n if i < n_rows-1:\n yield cirq.ZZ(qubits[i][j], qubits[i+1][j])**gamma\n if j < n_cols-1:\n yield cirq.ZZ(qubits[i][j], qubits[i][j+1])**gamma\n yield cirq.Z(qubits[i][j])**(gamma*h[i,j])\n```\n\nLet's test these functions by constructing the circuit. Try making a circuit with different numbers of layers. How would you automatically make a circuit with a specified number of layers? Make sure the parameters of these layers are distinct `sympy.Symbol`s for later optimization. Print the circuit to see that it's doing what you want it to do.\n\n\n```\nqaoa = cirq.Circuit()\nqaoa.append(cirq.H.on_each(*[q for row in qubits for q in row]))\n# YOUR CODE HERE\nprint(qaoa)\n```\n\n (0, 0): ───H───\n \n (0, 1): ───H───\n \n (0, 2): ───H───\n \n (1, 0): ───H───\n \n (1, 1): ───H───\n \n (1, 2): ───H───\n \n (2, 0): ───H───\n \n (2, 1): ───H───\n \n (2, 2): ───H───\n\n\n#### Solution\n\nWe'll just illustrate the solution for a single $C$ layer and a single $B$ layer.\n\n\n```\nqaoa = cirq.Circuit()\ngamma = sympy.Symbol('g')\nbeta = sympy.Symbol('b')\nqaoa.append(cirq.H.on_each(*[q for row in qubits for q in row]))\nqaoa.append(gamma_layer(gamma,h))\nqaoa.append(beta_layer(beta))\nprint(qaoa)\n```\n\n ┌──────────────────┐ ┌──────────────────┐\n (0, 0): ───H───ZZ─────ZZ─────Z^(0.5*g)───X^b────────────────────────────────────────────────────────────────────────────────────────────\n │ │\n (0, 1): ───H───┼──────ZZ^g───ZZ──────────ZZ──────Z^(0.5*g)─────────────X^b──────────────────────────────────────────────────────────────\n │ │ │\n (0, 2): ───H───┼─────────────┼───────────ZZ^g────ZZ────────────────────Z^(0.5*g)────X^b─────────────────────────────────────────────────\n │ │ │\n (1, 0): ───H───ZZ^g───ZZ─────┼───────────ZZ──────┼────────Z^(0.5*g)────X^b──────────────────────────────────────────────────────────────\n │ │ │ │\n (1, 1): ───H──────────┼──────ZZ^g────────ZZ^g────┼────────ZZ───────────ZZ───────────Z^(0.5*g)─────────────X^b───────────────────────────\n │ │ │ │\n (1, 2): ───H──────────┼──────────────────────────ZZ^g─────┼────────────ZZ^g─────────ZZ────────────────────Z^(0.5*g)───X^b───────────────\n │ │ │\n (2, 0): ───H──────────ZZ^g────────────────────────────────┼────────────ZZ───────────┼────────Z^(0.5*g)────X^b───────────────────────────\n │ │ │\n (2, 1): ───H──────────────────────────────────────────────ZZ^g─────────ZZ^g─────────┼─────────────────────ZZ──────────Z^(0.5*g)───X^b───\n │ │\n (2, 2): ───H────────────────────────────────────────────────────────────────────────ZZ^g──────────────────ZZ^g────────Z^(0.5*g)───X^b───\n └──────────────────┘ └──────────────────┘\n\n\n### Define Expectation Value\n\nTo train the QAOA circuit---that is, find the optimal values of the paramters---we're going to need to be able to compute the expectation value of the Ising Model energy. We'll do this within Cirq by defining an energy function. We'll divide the total energy by the number of qubits to keep the numbers under control, basically because we expect the energy to scale with the size of the system.\n\nIf we were using real hardware, the only way to compute the expectation value of the energy would be to estimate it by sampling. Using the simulator we can alternatively compute the wavefunction and then get calculate the expectation value from that. Not only does this save us from having to worry about statistical error, it also tends to be faster that simulating the sampling process.\n\n\n```\ndef energy_from_wavefunction(wf, h):\n \"\"\"Computes the energy-per-site of the Ising Model directly from the\n a given wavefunction. \n\n Args:\n wf: Array of size 2**(n_rows*n_cols) specifying the wavefunction.\n h: Array of shape (n_rows, n_cols) giving the magnetic field values.\n\n Returns:\n energy: Float equal to the expectation value of the energy per site \n \"\"\"\n\n n_sites = n_rows*n_cols\n\n # Z is an array of shape (n_sites, 2**n_sites). Each row consists of the \n # 2**n_sites non-zero entries in the operator that is the Pauli-Z matrix on\n # one of the qubits times the identites on the other qubits. The\n # (i*n_cols + j)th row corresponds to qubit (i,j).\n Z = np.array([(-1)**(np.arange(2**n_sites) >> i) for i in range(n_sites-1,-1,-1)])\n\n # Create the operator corresponding to the interaction energy summed over all\n # nearest-neighbor pairs of qubits\n ZZ_filter = np.zeros_like(wf, dtype=float)\n for i in range(n_rows):\n for j in range(n_cols):\n if i < n_rows-1:\n ZZ_filter += Z[i*n_cols + j]*Z[(i+1)*n_cols + j]\n if j < n_cols-1:\n ZZ_filter += Z[i*n_cols + j]*Z[i*n_cols + (j+1)]\n\n energy_operator = -ZZ_filter - h.reshape(n_sites).dot(Z)\n\n\n # Expectation value of the energy divided by the number of sites\n return np.sum(np.abs(wf)**2 * energy_operator) / n_sites\n```\n\nWe'll also need a helper function that computes the expected value of the energy given some parameters of the QAOA.\n\n\n```\ndef energy_from_params(gamma, beta, qaoa, h):\n sim = cirq.Simulator()\n params = cirq.ParamResolver({'g':gamma, 'b':beta})\n wf = sim.simulate(qaoa, param_resolver = params).final_state\n return energy_from_wavefunction(wf, h) \n```\n\n### Training\n\nNow we need to figure out the best values of $\\gamma$ and $\\beta$ by minimizing the expectation value of the energy. We'll start by doing a brute-force search of the parameter space for illustrative purposes:\n\n\n```\n%%time\ngrid_size = 50\ngamma_max = 2\nbeta_max = 2\n\nenergies = np.zeros((grid_size,grid_size))\nfor i in range(grid_size):\n for j in range(grid_size):\n energies[i,j] = energy_from_params(i*gamma_max/grid_size, j*beta_max/grid_size, qaoa, h)\n```\n\n CPU times: user 17.9 s, sys: 0 ns, total: 17.9 s\n Wall time: 17.9 s\n\n\n\n```\nplt.ylabel('gamma')\nplt.xlabel('beta')\nplt.title('Energy as a Function of Parameters')\nplt.imshow(energies, extent=(0,beta_max,gamma_max,0));\n```\n\nBy inspection we can see that the energy function has a number of interesting properties. First, note that the function is periodic in $\\beta$ and $\\gamma$ with shorter periods than one might naively expect given the definition of the gates. The details of why that's true will take us away from the main content of this Colab, but it's a good thing to understand so that the parameter space can be efficiently truncated.\n\nThe other main thing to notice is that there are many local minima and maxima. This makes it challenging to use gradient-based methods for optimization. We'll see that explicitly next. Part of the challenge for algorithms of this type is finding efficient ways to optimize the paramters.\n\n#### Gradient Descent\n\nFor practice let's try to minimize the expectation value of the energy using gradient descent. We know that there are local minima that we might get stuck in, depending on initialization, but it's still a worthwhile exercise.\n\nThe first step is to define a function which approximates the gradient of the energy. We'll do this by symmetric difference, i.e., $f'(x) \\approx (f(x+\\epsilon)-f(x-\\epsilon))/(2\\epsilon)$. You should experiment with different values of $\\epsilon$ as well as different formulas for the gradient. \n\n\n```\ndef gradient_energy(gamma, beta, qaoa, h):\n \"\"\"Uses a symmetric difference to calulate the gradient.\"\"\"\n eps = 10**-3 # Try different values of the discretization parameter\n\n # Gamma-component of the gradient\n grad_g = energy_from_params(gamma + eps, beta, qaoa, h)\n grad_g -= energy_from_params(gamma - eps, beta, qaoa, h)\n grad_g /= 2*eps\n\n # Beta-compoonent of the gradient\n grad_b = energy_from_params(gamma, beta + eps, qaoa, h)\n grad_b -= energy_from_params(gamma, beta - eps, qaoa, h)\n grad_b /= 2*eps \n\n return grad_g, grad_b\n```\n\nNow we'll implement a gradient descent algorithm that minimizes the energy. Note that it will get stuck in local minima depending on the initialization.\n\n\n```\ngamma, beta = 0.2, 0.7 # Try different initializations\neta = 10**-2 # Try adjusting the learning rate.\nfor i in range(151):\n grad_g, grad_b = gradient_energy(gamma, beta, qaoa, h)\n gamma -= eta*grad_g\n beta -= eta*grad_b\n if not i%25:\n print('Step: {} Energy: {}'.format(i, energy_from_params(gamma, beta, qaoa, h)))\nprint('Learned gamma: {} Learned beta: {}'.format(gamma, beta, qaoa, h))\n```\n\n Step: 0 Energy: 0.3555179724197741\n Step: 25 Energy: -0.60656794301801\n Step: 50 Energy: -0.6068781974520839\n Step: 75 Energy: -0.6068778212318446\n Step: 100 Energy: -0.6068778804908308\n Step: 125 Energy: -0.6068782185651193\n Step: 150 Energy: -0.6068782066830509\n Learned gamma: 0.19753242844183583 Learned beta: 0.26843952111680774\n\n\n### Results\n\nWe've optimized our parameters. How well did we do?\n\nFor a $3\\times 3$ grid we have $9$ qubits and $12$ interacting nearest-neighbor pairs. If all of the qubits are in the $|0\\rangle$ state or all are in the $|1\\rangle$ state, then the energy-per-qubit is $-12/9 = -1.33$ at zero external magnetic field $h$, and will be close to that if the magnetic field is small. Notice that the QAOA algorithm we analyzed above is __not__ getting close to that ground state. Is this a problem?\n\nWell, not really. The QAOA algorithm still succeeds if we can find the ground state after a small numbe of measurements. The QAOA prepares a certain state which is a linear combination of the ground state and many other states. When we measure the qubits, we find the ground-state configuration with some probability. If that probability is relatively large, then after a reasonably small number of measurements we'll locate the ground state.\n\nPractically speaking, this means we should measure the state prepared by the QAOA several times and record the lowest-energy state we find. The QAOA can be successful by biasing these measurements toward the ground state, even if they do not produce the ground state with $100\\%$ probability\n\nLet's make a copy of our qaoa circuit for measurement purposes and attach a measurement gate to each qubit:\n\n\n```\nmeasurement_circuit = qaoa.copy()\nmeasurement_circuit.append(cirq.measure(*[qubit for row in qubits for qubit in row],key='m'))\nmeasurement_circuit\n```\n\n\n\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='\n# Task 1: Data Exploration and Visualization\n\n\n```python\ndef open_file(filename):\n with open(filename, 'r') as f:\n data = f.readlines()\n return data\n```\n\n\n```python\ndata_raw = dict()\n\ndata_raw['sk'] = open_file('Data/Sentences/train_sentences.sk')\ndata_raw['cs'] = open_file('Data/Sentences/train_sentences.cs')\ndata_raw['en'] = open_file('Data/Sentences/train_sentences.en')\n```\n\n\n```python\ndef show_statistics(data):\n for language, sentences in data.items():\n \n word_list = ' '.join(sentences).split()\n \n number_of_sentences = len(sentences)\n number_of_words = len(word_list)\n number_of_unique_words = len(set(word_list))\n sample_extract = ' '.join(sentences[0].split()[0:7])\n \n # take a few minutes to try populate these variables\n \n # here is a hint -- word_list breaks the collections of sentences into a list of words\n #word_list = ' '.join(sentences).split()\n \n \n \n print(f'Language: {language}')\n print('-----------------------')\n print(f'Number of sentences\\t:\\t {number_of_sentences}')\n print(f'Number of words\\t\\t:\\t {number_of_words}')\n print(f'Number of unique words\\t:\\t {number_of_unique_words}')\n print(f'Sample extract\\t\\t:\\t {sample_extract}...\\n')\n```\n\n\n```python\nshow_statistics(data_raw)\n```\n\n Language: sk\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 2016\n Number of unique words\t:\t 1322\n Sample extract\t\t:\t Pán de Grandes Pascual jasne vysvetlil, aká...\n \n Language: cs\n -----------------------\n Number of sentences\t:\t 10\n Number of words\t\t:\t 158\n Number of unique words\t:\t 141\n Sample extract\t\t:\t Upozorňujeme, že jejím cílem je šetřit penězi...\n \n Language: en\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 2381\n Number of unique words\t:\t 1037\n Sample extract\t\t:\t I can understand your approach a little...\n \n\n\n\n```python\ndo_law_of_zipf(data_raw)\n```\n\n\n \n\n \n\n\n\n# Task 2: Data Cleaning and Preprocessing\n\n\n```python\ndef preprocess(text):\n '''\n Removes punctuation and digits from a string, and converts all characters to lowercase. \n Also clears all \\n and hyphens (splits hyphenated words into two words).\n \n '''\n \n preprocessed_text = text\n preprocessed_text = text.lower().replace('-', ' ')\n translation_table = str.maketrans('\\n', ' ', string.punctuation+string.digits)\n preprocessed_text = preprocessed_text.translate(translation_table)\n \n return preprocessed_text\n```\n\n\n```python\npreprocess(\"I have 5 mangoes.\\n What do u do?\")\n```\n\n\n\n\n 'i have mangoes what do u do'\n\n\n\n\n```python\ndata_preprocessed = {k: [preprocess(sentence) for sentence in v ] for k, v in data_raw.items()}\n```\n\n\n```python\nshow_statistics(data_raw)\n\nprint('\\n')\n\nshow_statistics(data_preprocessed)\n```\n\n Language: sk\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 2016\n Number of unique words\t:\t 1322\n Sample extract\t\t:\t Pán de Grandes Pascual jasne vysvetlil, aká...\n \n Language: cs\n -----------------------\n Number of sentences\t:\t 10\n Number of words\t\t:\t 158\n Number of unique words\t:\t 141\n Sample extract\t\t:\t Upozorňujeme, že jejím cílem je šetřit penězi...\n \n Language: en\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 2381\n Number of unique words\t:\t 1037\n Sample extract\t\t:\t I can understand your approach a little...\n \n \n \n Language: sk\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 1996\n Number of unique words\t:\t 1207\n Sample extract\t\t:\t pán de grandes pascual jasne vysvetlil aká...\n \n Language: cs\n -----------------------\n Number of sentences\t:\t 10\n Number of words\t\t:\t 155\n Number of unique words\t:\t 133\n Sample extract\t\t:\t upozorňujeme že jejím cílem je šetřit penězi...\n \n Language: en\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 2366\n Number of unique words\t:\t 904\n Sample extract\t\t:\t i can understand your approach a little...\n \n\n\n\n# Task 3: The Naive Bayes Model\n\n**Bayes' Theorem**\n\n\\begin{equation}\nP(A | B)=\\frac{P(B | A) \\times P(A)}{P(B)}\n\\end{equation}\n\nNow, let's translate this theory into our specific problem. In our case, where we want to categorise a sentence `my name is Ari` into one of `sk`, `cs`, or `en`, the following are the probabilities we want to determine.\n\n\\begin{equation}\nP(\\text {sk} | \\text {my name is Ari})=\\frac{P(\\text {my name is Ari} | \\text {sk}) \\times P(\\text {sk})}{P(\\text {my name is Ari})}\n\\end{equation}\n\n\\begin{equation}\nP(\\text {cs} | \\text {my name is Ari})=\\frac{P(\\text {my name is Ari} | \\text {cs}) \\times P(\\text {cs})}{P(\\text {my name is Ari})}\n\\end{equation}\n\n\\begin{equation}\nP(\\text {en} | \\text {my name is Ari})=\\frac{P(\\text {my name is Ari} | \\text {en}) \\times P(\\text {en})}{P(\\text {my name is Ari})}\n\\end{equation}\n\n## Unseen Data\n\nSince we assume conditional independence across our features, our numerator term for any of the above equations can be broken into the following.\n\n\\begin{equation}\nP(\\text {my name is Ari} | \\text {en}) = P(\\text {my} | \\text {en}) \\times P(\\text {name} | \\text {en}) \\times P(\\text {is} | \\text {en}) \\times P(\\text {Ari} | \\text {en})\n\\end{equation}\n\n## Vectorizing Training Data\n\n|Sentence \t|| my \t| is \t| I \t| love \t| name \t| it \t| Ari \t|\n|-----------------\t||:------:\t|:--:\t|:-:\t|:----:\t|:----:\t|:--------:\t|:---:\t|\n| my name is Ari \t|| 1 \t| 1 \t| 0 \t| 0 \t| 1 \t| 0 \t| 1 \t|\n| I love it \t|| 0 \t| 0 \t| 1 \t| 1 \t| 0 \t| 1 \t| 0 \t|\n\n\n```python\nsentences_train, y_train = [], []\n\nfor k,v in data_preprocessed.items():\n for sentence in v:\n sentences_train.append(sentence)\n y_train.append(k)\n \n```\n\n\n```python\nvectorizer = CountVectorizer()\n```\n\n\n```python\nX_train = vectorizer.fit_transform(sentences_train)\n```\n\n\n```python\nX_train\n```\n\n\n\n\n <210x2208 sparse matrix of type ''\n \twith 3867 stored elements in Compressed Sparse Row format>\n\n\n\n## Initializing Model Parameters and Training\n\n\n```python\nnaive_classifier = MultinomialNB()\nnaive_classifier.fit(X_train, y_train)\n```\n\n\n\n\n MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)\n\n\n\n## Vectorizing Validation Data and Evaluating Model\n\n\n```python\ndata_val = dict()\n\ndata_val['sk'] = open_file('Data/Sentences/val_sentences.sk')\ndata_val['cs'] = open_file('Data/Sentences/val_sentences.cs')\ndata_val['en'] = open_file('Data/Sentences/val_sentences.en')\n```\n\n\n```python\ndata_val_processed = {k:[preprocess(sentence) for sentence in v] for k,v in data_val.items()}\n\nsentences_val, y_val =[],[]\n\nfor k,v in data_val_processed.items():\n for sentence in v:\n sentences_val.append(sentence)\n y_val.append(k)\n```\n\n\n```python\nX_val = vectorizer.transform(sentences_val)\n```\n\n\n```python\npredictions = naive_classifier.predict(X_val)\n```\n\n\n```python\nplot_confusion_matrix(y_val, predictions, ['sk', 'cs', 'en'])\n```\n\n\n \n\n \n\n\n\n```python\nf1_score(y_val, predictions, average='weighted')\n```\n\n\n\n\n 0.6149824401040264\n\n\n\n\n# Task 4: Simple Adjustments and Highlighting Model Shortcomings\n\n\n```python\nnaive_classifier = MultinomialNB(\n alpha = 0.0001,\n fit_prior=False\n)\n\nnaive_classifier.fit(X_train, y_train)\n\npredictions = naive_classifier.predict(X_val)\n\nplot_confusion_matrix(y_val, predictions, ['sk', 'cs', 'en'])\n```\n\n\n \n\n \n\n\n\n```python\nf1_score(y_val, predictions, average='weighted')\n```\n\n\n\n\n 0.8368507601649364\n\n\n\n\n# Task 5: Using Subwords to Shift Perspective\n\n**Dummy Dataset**\n\nplaying ; eating ; play ; reads ; tea\n\n**Step 1**\n\nBreak each word into characters\n\nplaying > p l a y i n g\n\n\n**Step 2**\n\nFind common character sequences\n\nea, ing, play\n\n**Step 3**\n\nConvert dataset using these subwords into\n\nplay ing ; ea t ing ; play ; r ea d s ; t ea\n\n\n```python\n# taken from https://arxiv.org/abs/1508.07909\n\nimport re, collections\ndef get_stats(vocab):\n pairs = collections.defaultdict(int) \n for word, freq in vocab.items():\n symbols = word.split()\n for i in range(len(symbols)-1):\n pairs[symbols[i],symbols[i+1]] += freq \n return pairs\n\ndef merge_vocab(pair, v_in):\n v_out = {}\n bigram = re.escape(' '.join(pair))\n p = re.compile(r'(?= 2:\n merges[subword] += v\n```\n\n\n```python\nmerge_ordered = sorted(merges, key=merges.get, reverse=True)\n```\n\n\n```python\npkl.dump(merge_ordered, open('Data/Auxiliary/merge_ordered.pkl', 'wb'))\n```\n\n\n```python\ndef split_into_subwords(text):\n merges = pkl.load(open('Data/Auxiliary/merge_ordered.pkl', 'rb'))\n subwords = []\n for word in text.split():\n for subword in merges:\n subword_count = word.count(subword)\n if subword_count > 0:\n word = word.replace(subword, ' ')\n subwords.extend([subword]*subword_count)\n return ' '.join(subwords)\n```\n\n\n```python\nsplit_into_subwords('hello my name is ari')\n```\n\n\n\n\n 'lo na me is ar'\n\n\n\n\n```python\ndata_preprocessed_subwords={k: [split_into_subwords(sentence) for sentence in v] for k, v in data_preprocessed.items()}\n```\n\n\n```python\nshow_statistics(data_preprocessed_subwords)\n```\n\n Language: sk\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 3431\n Number of unique words\t:\t 75\n Sample extract\t\t:\t de an de al as ne as...\n \n Language: cs\n -----------------------\n Number of sentences\t:\t 10\n Number of words\t\t:\t 239\n Number of unique words\t:\t 59\n Sample extract\t\t:\t po je me or že je le...\n \n Language: en\n -----------------------\n Number of sentences\t:\t 100\n Number of words\t\t:\t 3863\n Number of unique words\t:\t 75\n Sample extract\t\t:\t an st an er ou ro ch...\n \n\n\n\n```python\ndata_train_subwords=[]\n\nfor sentence in sentences_train:\n data_train_subwords.append(split_into_subwords(sentence))\n```\n\n\n```python\ndata_val_subwords=[]\n\nfor sentence in sentences_val:\n data_val_subwords.append(split_into_subwords(sentence))\n```\n\n\n```python\nvectorizer=CountVectorizer()\n```\n\n\n```python\nX_train = vectorizer.fit_transform(data_train_subwords)\nX_val = vectorizer.transform(data_val_subwords)\n```\n\n\n```python\nnaive_classifier = MultinomialNB(\n alpha = 1.0,\n fit_prior = False\n)\n\nnaive_classifier.fit(X_train, y_train)\n\npredictions = naive_classifier.predict(X_val)\n```\n\n\n```python\nplot_confusion_matrix(y_val, predictions, ['sk','cs', 'en'])\n```\n\n\n \n\n \n\n\n\n```python\nf1_score(y_val, predictions, average='weighted')\n```\n\n\n\n\n 0.8456381060126386\n\n\n\n\n```python\njoblib.dump(naive_classifier, 'Data/Models/final_model.joblib')\njoblib.dump(vectorizer, 'Data/Vectorizers/final_model.joblib')\n```\n\n\n\n\n ['Data/Vectorizers/final_model.joblib']\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "557968d0105984f047d571299b8f629cfe41838c", "size": 224463, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Language_Classifier.ipynb", "max_stars_repo_name": "Rifat007/Language-Classification-using-Naive-Bayes", "max_stars_repo_head_hexsha": "6299182e0cce694103de6432c88b4e44649c9413", "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": "Language_Classifier.ipynb", "max_issues_repo_name": "Rifat007/Language-Classification-using-Naive-Bayes", "max_issues_repo_head_hexsha": "6299182e0cce694103de6432c88b4e44649c9413", "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": "Language_Classifier.ipynb", "max_forks_repo_name": "Rifat007/Language-Classification-using-Naive-Bayes", "max_forks_repo_head_hexsha": "6299182e0cce694103de6432c88b4e44649c9413", "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": 40.878346385, "max_line_length": 1219, "alphanum_fraction": 0.4954892343, "converted": true, "num_tokens": 4235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.1480471999111614, "lm_q1q2_score": 0.07055628287461557}} {"text": "\n\n# Brief introduction to JAX \n\nmurphyk@gmail.com.\n\n[JAX](https://github.com/google/jax) is a version of NumPy that runs fast on CPU, GPU and TPU, by compiling down to XLA. It also has an excellent automatic differentiation library, extending the earlier [autograd](https://github.com/hips/autograd) package, which makes it easy to compute higher order derivatives, per-example gradients (instead of aggregated gradients), and gradients of complex code (e.g., optimize an optimizer).\nThe JAX interface is almost identical to NumPy (by design), but with some small differences, and lots of additional features.\nWe give a brief introduction below. More details can be found in the other tutorials listed below.\n\n\n\n\n\n\n## Other tutorials\n\n- [JAX homepage](https://github.com/google/jax)\n- [JAX 101 (Deepmind tutorial)](https://jax.readthedocs.io/en/latest/jax-101/index.html)\n- [Thinking in JAX (Google tutorial)](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/thinking_in_jax.ipynb)\n- [Awesome JAX: extensive list of tutorials and code](https://github.com/n2cholas/awesome-jax)\n- [flax tutorial](https://flax.readthedocs.io/en/latest/notebooks/jax_for_the_impatient.html).\n- [From PyTorch to JAX: towards neural net frameworks that purify stateful code](https://sjmielke.com/jax-purify.htm)\n- [Getting started with JAX: MLPs, CNNs & RNNs](https://roberttlange.github.io/posts/2020/03/blog-post-10/)\n- [CMA-ES in JAX](https://roberttlange.github.io/posts/2021/02/cma-es-jax/) blog post for fitting DNNs using blackbox optimization.\n\n\n## JAX libraries related to ML\n\nin this tutorial, we focus on core JAX.\nHowever, since JAX is quite low level (like numpy), many libraries are being developed\nthat build on top of it, to provide more specialized functionality.\nWe summarize a few of the ML-related libraries below.\nSee also https://github.com/n2cholas/awesome-jax which has a more extensive list.\n\n### DNN libraries\n\nJAX is a purely functional library, which differs from Tensorflow and\nPytorch, which are stateful. The main advantages of functional programming\nare that we can safely transform the code, and/or run it in parallel, without worrying about\nglobal state changing behind the scenes. The main disadvantage is that code (especially DNNs) can be harder to write.\nTo simplify the task, various DNN libraries have been designed, as we list below. In this book, we use Flax.\n\n|Name|Description|\n|----|----|\n|[Stax](https://github.com/google/jax/blob/master/jax/experimental/stax.py)|Barebones library for specifying DNNs|\n|[Flax](https://github.com/google/flax)|Library for specifying and training DNNs|\n|[Haiku](https://github.com/deepmind/dm-haiku)|Library for specifying DNNs, similar to Sonnet|\n|[Jraph](https://github.com/deepmind/jraph)| Library for graph neural networks|\n|[Trax](https://github.com/google/trax)|Library for specifying and training DNNs, with a focus on sequence models|\n|[T5X](https://github.com/google-research/google-research/tree/master/flax_models/t5x)| T5 (a large seq2seq model) in JAX/Flax | \n|[Objax](https://github.com/google/objax)|PyTorch-like library for JAX (stateful/ object-oriented, not compatible with other JAX libraries)|\n|[Elegy](https://github.com/poets-ai/elegy)|Keras-like library for Jax|\n|[FlaxVision](https://github.com/rolandgvc/flaxvision)|Flax version of [torchvision](https://github.com/pytorch/vision)|\n|[Neural tangents](https://github.com/google/neural-tangents)|Library to compute a kernel from a DNN|\n\n### RL libraries\n\n|Name|Description|\n|----|----|\n|[RLax](https://github.com/deepmind/rlax)|Library from Deepmind|\n|[Coax](https://github.com/microsoft/coax)|Lightweight library from Microsoft for solving Open-AI gym environments|\n\n### Probabilistic programming languages\n\n\n|Name|Description|\n|----|----|\n|[NumPyro](https://github.com/pyro-ppl/numpyro)|Library for PPL|\n|[Oryx](https://github.com/tensorflow/probability/tree/master/spinoffs/oryx)|Lightweight library for PPL|\n\n### Other libraries\n\nThere are also many other JAX libraries for tasks that are not about defining DNN models. We list some of them below.\n\n|Name|Description|\n|----|----|\n|[Optax](https://github.com/deepmind/optax)|Library for defining gradient-based optimizers|\n|[Chex](https://github.com/deepmind/chex)|Library for debugging and developing reliable JAX code|\n|[Distrax](https://github.com/deepmind/distrax)| Library for probability distributions and bijectors|\n\n\n\n\n# Setup\n\n\n```\n# Standard Python libraries\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom functools import partial\nimport os\nimport time\nimport numpy as np\nnp.set_printoptions(precision=3)\nimport glob\nimport matplotlib.pyplot as plt\nimport PIL\nimport imageio\n\nfrom typing import Tuple, NamedTuple\n\nfrom IPython import display\n%matplotlib inline\n\nimport sklearn\n\n```\n\n\n```\n\n# Load JAX\nimport jax\nimport jax.numpy as jnp\n\nfrom jax import random, vmap, jit, grad, value_and_grad, hessian, jacfwd, jacrev\nprint(\"jax version {}\".format(jax.__version__))\n# Check the jax backend\nprint(\"jax backend {}\".format(jax.lib.xla_bridge.get_backend().platform))\nkey = random.PRNGKey(0)\n```\n\n jax version 0.2.9\n jax backend gpu\n\n\n\n```\n%%capture\n!pip install git+https://github.com/deepmind/dm-haiku\nimport haiku as hk\n```\n\n\n```\n%%capture\n!pip install --upgrade -q git+https://github.com/google/flax.git\nimport flax\n```\n\n# Hardware accelerators\n\nColab makes it easy to use GPUs and TPUs for speeding up some workflows, especially related to deep learning.\n\n## GPUs\n\nColab offers graphics processing units (GPUs) which can be much faster than CPUs (central processing units), as we illustrate below.\n\n\n```\n# Check if GPU is available and its model, memory ...etc.\n!nvidia-smi\n\n```\n\n Tue Feb 9 13:54:21 2021 \n +-----------------------------------------------------------------------------+\n | NVIDIA-SMI 460.39 Driver Version: 418.67 CUDA Version: 10.1 |\n |-------------------------------+----------------------+----------------------+\n | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n | | | MIG M. |\n |===============================+======================+======================|\n | 0 Tesla V100-SXM2... Off | 00000000:00:04.0 Off | 0 |\n | N/A 41C P0 40W / 300W | 14549MiB / 16130MiB | 0% Default |\n | | | ERR! |\n +-------------------------------+----------------------+----------------------+\n \n +-----------------------------------------------------------------------------+\n | Processes: |\n | GPU GI CI PID Type Process name GPU Memory |\n | ID ID Usage |\n |=============================================================================|\n | No running processes found |\n +-----------------------------------------------------------------------------+\n\n\n\n```\n\n# Check if JAX is using GPU\nprint(\"jax backend {}\".format(jax.lib.xla_bridge.get_backend().platform))\n# Check the devices avaiable for JAX\njax.devices()\n```\n\n jax backend gpu\n\n\n\n\n\n [GpuDevice(id=0)]\n\n\n\nLet's see how JAX can speed up things like matrix-matrix multiplication.\n\nFirst the numpy/CPU version.\n\n\n```\n# Parameters for the experiment\nsize = int(1e3)\nnumber_of_loops=int(1e2)\n\n```\n\n\n```\n# Standard numpy CPU\n\ndef f(x=None):\n if not isinstance(x, np.ndarray):\n x=np.ones((size, size), dtype=np.float32) \n return np.dot(x, x.T)\n\n\n```\n\n\n```\n%timeit -o -n $number_of_loops f()\n```\n\n 100 loops, best of 3: 14.9 ms per loop\n\n\n\n\n\n \n\n\n\n\n```\nres = _ # get result of last cell\ntime_cpu = res.best\nprint(time_cpu)\n```\n\n 0.014857908460000999\n\n\nNow we look at the JAX version. JAX supports execution on [XLA](https://www.tensorflow.org/xla) devices, which can be CPU, GPU or even TPU. We added that block_until_ready because JAX uses [asynchronous execution](https://jax.readthedocs.io/en/latest/async_dispatch.html) by default.\n\n\n\n```\n# JAX device execution\n# https://github.com/google/jax/issues/1598\n\ndef jf(x=None): \n if not isinstance(x, jnp.ndarray):\n x=jnp.ones((size, size), dtype=jnp.float32)\n return jnp.dot(x, x.T)\n\n\nf_gpu = jit(jf, backend='gpu')\nf_cpu = jit(jf, backend='cpu')\n```\n\n\n```\n# Time the CPU version\n\n%timeit -o -n $number_of_loops f_cpu() \n```\n\n 100 loops, best of 3: 14.5 ms per loop\n\n\n\n\n\n \n\n\n\n\n```\nres = _\ntime_jcpu = res.best\nprint(time_jcpu)\n```\n\n 0.014495725080000738\n\n\n\n```\n# Time the GPU version\n\n%timeit -o -n $number_of_loops f_gpu().block_until_ready() \n```\n\n The slowest run took 44.47 times longer than the fastest. This could mean that an intermediate result is being cached.\n 100 loops, best of 3: 276 µs per loop\n\n\n\n\n\n \n\n\n\n\n```\nres = _\ntime_jgpu = res.best\nprint(time_jgpu)\n```\n\n 0.0002756696500000544\n\n\n\n```\nprint('JAX CPU time {:0.6f}, Numpy CPU time {:0.6f}, speedup {:0.6f}'.format(\n time_jcpu, time_cpu, time_cpu/time_jcpu))\nprint('JAX GPU time {:0.6f}, JAX CPU time {:0.6f}, speedup {:0.6f}'.format(\n time_jgpu, time_jcpu, time_jcpu/time_jgpu))\nprint('JAX GPU time {:0.6f}, Numpy CPU time {:0.6f}, speedup {:0.6f}'.format(\n time_jgpu, time_cpu, time_cpu/time_jgpu))\n```\n\n JAX CPU time 0.014496, Numpy CPU time 0.014858, speedup 1.024986\n JAX GPU time 0.000276, JAX CPU time 0.014496, speedup 52.583682\n JAX GPU time 0.000276, Numpy CPU time 0.014858, speedup 53.897513\n\n\nThis illustrates the power of XLA (Accelerated Linear Algebra compiler), even for apples to apples comparison of same hardware. JAX can be faster even on a CPU than the standard numpy. Note that due to various factors exectution times can vary per run even on a single machine, however the overall performance of human writtten vs. compiler emitted (i.e. numpy C backend vs. JAX XLA jit backend) is a topic of its own.\n\nWe can move numpy arrays to the GPU for speed. The result will be transferred back to CPU for printing, saving, etc.\n\n\n```\nfrom jax import device_put\n\nx = np.ones((size, size)).astype(np.float32)\nprint(type(x))\n%timeit -o -n $number_of_loops f(x)\n\nx = device_put(x)\nprint(type(x))\n%timeit -o -n $number_of_loops jf(x)\n```\n\n \n 100 loops, best of 3: 14.1 ms per loop\n \n 100 loops, best of 3: 639 µs per loop\n\n\n\n\n\n \n\n\n\n## TPUs\n\nWe can turn on the tensor processing unit as shown below.\nEverything else \"just works\" as before.\n\n\n```\nimport jax.tools.colab_tpu\njax.tools.colab_tpu.setup_tpu()\n```\n\n# Vmap \n\nWe often write a function to process a single vector or matrix, and then want to apply it to a batch of data. Using for loops is slow, and manually batchifying code is complex. Fortunately we can use the `vmap` function, which will map our function across a set of inputs, automatically batchifying it.\n\n\n\n## Example: 1d convolution\n\n(This example is from the Deepmind tutorial.)\n\nConsider standard 1d convolution of two vectors.\n\n\n\n```\nx = jnp.arange(5)\nw = jnp.array([2., 3., 4.])\n\ndef convolve(x, w):\n output = []\n for i in range(1, len(x)-1):\n output.append(jnp.dot(x[i-1:i+2], w))\n return jnp.array(output)\n\nconvolve(x, w)\n```\n\n\n\n\n DeviceArray([11., 20., 29.], dtype=float32)\n\n\n\nNow suppose we want to convolve multiple vectors with multiple kernels. The simplest way is to use a for loop, but this is slow.\n\n\n\n```\nxs = jnp.stack([x, x])\nws = jnp.stack([w, w])\n\ndef manually_batched_convolve(xs, ws):\n output = []\n for i in range(xs.shape[0]):\n output.append(convolve(xs[i], ws[i]))\n return jnp.stack(output)\n\nmanually_batched_convolve(xs, ws)\n```\n\n\n\n\n DeviceArray([[11., 20., 29.],\n [11., 20., 29.]], dtype=float32)\n\n\n\nWe can manually vectorize the code, but it is complex.\n\n\n```\ndef manually_vectorised_convolve(xs, ws):\n output = []\n for i in range(1, xs.shape[-1] -1):\n output.append(jnp.sum(xs[:, i-1:i+2] * ws, axis=1))\n return jnp.stack(output, axis=1)\n\nmanually_vectorised_convolve(xs, ws)\n```\n\n\n\n\n DeviceArray([[11., 20., 29.],\n [11., 20., 29.]], dtype=float32)\n\n\n\nFortunately vmap can do this for us!\n\n\n```\nauto_batch_convolve = jax.vmap(convolve)\n\nauto_batch_convolve(xs, ws)\n```\n\n\n\n\n DeviceArray([[11., 20., 29.],\n [11., 20., 29.]], dtype=float32)\n\n\n\n## Axes\n\nBy default, vmap vectorizes over the first axis of each of its inputs. If the first argument has a batch and the second does not, ,specify `in_axes=[0,None]`, so the second argument is not vectorized over.\n\n\n```\njax.vmap(convolve, in_axes=[0, None])(xs, w)\n\n```\n\n\n\n\n DeviceArray([[11., 20., 29.],\n [11., 20., 29.]], dtype=float32)\n\n\n\nWe can also vectorize over other dimensions.\n\n\n```\n\nprint(xs.shape)\nxst = jnp.transpose(xs)\nprint(xst.shape)\n\nwst = jnp.transpose(ws)\n\nauto_batch_convolve_v2 = jax.vmap(convolve, in_axes=1, out_axes=1)\nauto_batch_convolve_v2(xst, wst)\n```\n\n (2, 5)\n (5, 2)\n\n\n\n\n\n DeviceArray([[11., 11.],\n [20., 20.],\n [29., 29.]], dtype=float32)\n\n\n\n## Example: logistic regression\n\nWe now give another example, using binary logistic regression.\nLet us start with a predictor for a single example\n.\n\n\n```\n\nD = 2\nN = 3\n\nw = np.random.normal(size=(D,))\nX = np.random.normal(size=(N,D))\n\ndef sigmoid(x): return 0.5 * (jnp.tanh(x / 2.) + 1)\n\ndef predict_single(x):\n return sigmoid(jnp.dot(w, x)) # <(D) , (D)> = (1) # inner product\n \nprint(predict_single(X[0,:])) # works\n\nprint(predict_single(X)) # fails\n```\n\nWe can manually vectorize the code by remembering the shapes, so \n$X w$ multiplies each row of $X$ with $w$.\n\n\n```\ndef predict_batch(X):\n return sigmoid(jnp.dot(X, w)) # (N,D) * (D,1) = (N,1) # matrix-vector multiply\n\nprint(predict_batch(X)) \n```\n\n [0.223 0.636 0.427]\n\n\nFortunately we can use vmap.\n\n\n```\nprint(vmap(predict_single)(X))\n```\n\n [0.223 0.636 0.427]\n\n\n## Failure cases\n\nVmap requires that the shapes of all the variables that are created by the function that is being mapped are the same for all values of the input arguments, as explained [here](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html). So vmap cannot be used to do any kind of embarassingly parallel task. Below we give a simple example of where this fails, since internally we create a vector whose length depends on the input 'length'.\n\n\n```\ndef example_fun(length, val=4):\n return jnp.sum(jnp.ones((length,)) * val)\n\nxs = jnp.arange(1,10)\n\n# Python map works fine\nv = list(map(example_fun, xs))\nprint(v)\n```\n\n [DeviceArray(4., dtype=float32), DeviceArray(8., dtype=float32), DeviceArray(12., dtype=float32), DeviceArray(16., dtype=float32), DeviceArray(20., dtype=float32), DeviceArray(24., dtype=float32), DeviceArray(28., dtype=float32), DeviceArray(32., dtype=float32), DeviceArray(36., dtype=float32)]\n\n\nThe following fails.\n\n\n```\nv = vmap(example_fun)(xs)\nprint(v)\n```\n\n# Stochastics\n\nJAX is designed to be deterministic, but in some cases, we want to introduce randomness in a controlled way, and to reason about it. We discuss this below\n\n## Random number generation\n\nOne of the biggest differences from NumPy is the way Jax treates pseudo random number generation (PRNG).\nThis is because Jax does not maintain any global state, i.e., it is purely functional.\nThis design \"provides reproducible results invariant to compilation boundaries and backends,\nwhile also maximizing performance by enabling vectorized generation and parallelization across random calls\"\n(to quote [the official page](https://github.com/google/jax#a-brief-tour)).\n\nFor example, consider this Numpy snippet. Each call to np.random.uniform updates the global state. The value of foo() is therefore only guaranteed to give the same result every time if we evaluate bar() and baz() in the same order (eg left to right). This is why foo1 and foo2 give different answers.\n\n\n\n```\nimport numpy as np\n\n\ndef bar(): return np.random.uniform(size=(3))\ndef baz(): return np.random.uniform(size=(3))\n\ndef foo(seed): \n np.random.seed(seed)\n return bar() + 2*baz()\n\ndef foo1(seed): \n np.random.seed(seed)\n a = bar()\n b = 2*baz()\n return a+b\n\ndef foo2(seed): \n np.random.seed(seed)\n a = 2*baz() \n b = bar()\n return a+b\n\nseed = 0\n\nprint(foo(seed))\nprint(foo1(seed))\nprint(foo2(seed))\n```\n\n [1.639 1.562 1.895]\n [1.639 1.562 1.895]\n [1.643 1.854 1.851]\n\n\n\n\nJax may evaluate parts of expressions such as `bar() + baz()` in parallel, which would violate reproducibility. To prevent this, the user must pass in an explicit PRNG key to every function that requires a source of randomness. Using the same key will give the same results.See the example below.\n\n\n```\n\n\nkey = random.PRNGKey(0)\nprint(random.normal(key, shape=(3,))) # [ 1.81608593 -0.48262325 0.33988902]\nprint(random.normal(key, shape=(3,))) # [ 1.81608593 -0.48262325 0.33988902] ## identical results\n\n\n```\n\n [ 1.816 -0.483 0.34 ]\n [ 1.816 -0.483 0.34 ]\n\n\nWhen generating independent samples, it is important to use different keys, to ensure results are not correlated. We can do this by *splitting* the key into the the 'master' key (which will be used in later parts of the code via splitting), and the 'subkey', which is used temporarily to generate randomness and then thrown away, as we illustrate below.\n\n\n```\n# To make a new key, we split the current key into two pieces.\nkey, subkey = random.split(key)\nprint(random.normal(subkey, shape=(3,))) # [ 1.1378783 -1.22095478 -0.59153646]\n\n# We can continue to split off new pieces from the global key.\nkey, subkey = random.split(key)\nprint(random.normal(subkey, shape=(3,))) # [-0.06607265 0.16676566 1.17800343]\n\n\n```\n\n [ 1.138 -1.221 -0.592]\n [-0.066 0.167 1.178]\n\n\nWe now reimplement the numpy example in Jax and show that we get the result no matter the order of evaluation of bar and baz.\n\n\n```\n\ndef bar(key): \n return jax.random.uniform(key,shape=(3,))\n\ndef baz(key):\n return jax.random.uniform(key,shape=(3,))\n\ndef foo(key): \n subkey1, subkey2 = random.split(key, num=2) \n return bar(subkey1) + 2 * baz(subkey2)\n\ndef foo1(key): \n subkey1, subkey2 = random.split(key, num=2) \n a = bar(subkey1) \n b = 2 * baz(subkey2)\n return a+b\n\ndef foo2(key): \n subkey1, subkey2 = random.split(key, num=2) \n a = 2 * baz(subkey2)\n b = bar(subkey1)\n return a+b\n\nkey = random.PRNGKey(0)\nkey, subkey = random.split(key) \nprint(foo(subkey))\nprint(foo1(subkey))\nprint(foo2(subkey))\n```\n\n [2.079 2.002 1.089]\n [2.079 2.002 1.089]\n [2.079 2.002 1.089]\n\n\nIn Jax (but not in python), a random draw of N samples in parallel will not give the same results as N draws of individual samples, as we show below. \n\n\n```\nkey = random.PRNGKey(42)\nsubkeys = random.split(key, 3)\nsequence = np.stack([jax.random.normal(subkey) for subkey in subkeys])\nprint(\"individually:\", sequence)\n\nkey = random.PRNGKey(42)\nprint(\"all at once: \", jax.random.normal(key, shape=(3,)))\n```\n\n individually: [-0.048 0.108 -1.223]\n all at once: [ 0.187 -1.281 -1.559]\n\n\n\n```\nnp.random.seed(0)\nsequence = np.stack([np.random.normal() for i in range(3)])\nprint(\"individually:\", sequence)\n\nnp.random.seed(0)\nprint(\"all at once: \", np.random.normal(size=(3,)))\n\n```\n\n individually: [1.764 0.4 0.979]\n all at once: [1.764 0.4 0.979]\n\n\nHaiku has a handy method for generating a sequence of random keys from a seed key, as we show below.\n\n\n```\nimport haiku as hk\nrng = jax.random.PRNGKey(0)\nrng_seq = hk.PRNGSequence(rng)\nfor i in range(5):\n rng = next(rng_seq)\n samples = jax.random.bernoulli(rng, 0.5, shape=(3,))\n print(samples)\n```\n\n [False True True]\n [ True False False]\n [ True True True]\n [False False True]\n [ True True False]\n\n\n## Probability distributions\n\n*TODO*\n\n\n# Autograd \n\nIn this section, we illustrate automatic differentation using JAX.\nFor details, see see [this video](https://www.youtube.com/watch?v=wG_nF1awSSY&t=697s) or [The Autodiff Cookbook](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html).\n\n\n\n## Derivatives\n\nWe can compute $(\\nabla f)(x)$ using `grad(f)(x)`. For example, consider\n\n\n$f(x) = x^3 + 2x^2 - 3x + 1$\n\n$f'(x) = 3x^2 + 4x -3$\n\n$f''(x) = 6x + 4$\n\n$f'''(x) = 6$\n\n$f^{iv}(x) = 0$\n\n\n\n\n```\nf = lambda x: x**3 + 2*x**2 - 3*x + 1\n\ndfdx = jax.grad(f)\nd2fdx = jax.grad(dfdx)\nd3fdx = jax.grad(d2fdx)\nd4fdx = jax.grad(d3fdx)\n\nprint(dfdx(1.))\nprint(d2fdx(1.))\nprint(d3fdx(1.))\nprint(d4fdx(1.))\n```\n\n 4.0\n 10.0\n 6.0\n 0.0\n\n\n## Partial derivatives\n\n\n$$\n\\begin{align}\nf(x,y) &= x^2 + y \\\\\n\\frac{\\partial f}{\\partial x} &= 2x \\\\\n\\frac{\\partial f}{\\partial y} &= 1 \n\\end{align}\n$$\n\n\n\n```\ndef f(x,y):\n return x**2 + y\n\n# Partial derviatives\nx = 2.0; y= 3.0;\nv, gx = value_and_grad(f, argnums=0)(x,y)\nprint(v)\nprint(gx)\n\ngy = grad(f, argnums=1)(x,y)\nprint(gy)\n\n```\n\n 7.0\n 4.0\n 1.0\n\n\n## Gradients \n\nLinear function: multi-input, scalar output.\n\n$$\n\\begin{align}\nf(x; a) &= a^T x\\\\\n\\nabla_x f(x;a) &= a\n\\end{align}\n$$\n\n\n```\n\n\ndef fun1d(x):\n return jnp.dot(a, x)[0]\n\nDin = 3; Dout = 1;\na = np.random.normal(size=(Dout, Din))\nx = np.random.normal(size=(Din,))\n\ng = grad(fun1d)(x)\nassert np.allclose(g, a)\n\n\n# It is often useful to get the function value and gradient at the same time\nval_grad_fn = jax.value_and_grad(fun1d)\nv, g = val_grad_fn(x)\nprint(v)\nprint(g)\nassert np.allclose(v, fun1d(x))\nassert np.allclose(a, g)\n\n```\n\n -1.0599848\n [-1.311 0.546 0.915]\n\n\nLinear function: multi-input, multi-output.\n\n$$\n\\begin{align}\nf(x;A) &= A x \\\\\n\\frac{\\partial f(x;A)}{\\partial x} &= A\n\\end{align}\n$$\n\n\n```\n# We construct a multi-output linear function.\n# We check forward and reverse mode give same Jacobians.\n\n\ndef fun(x):\n return jnp.dot(A, x)\n\nDin = 3; Dout = 4;\nA = np.random.normal(size=(Dout, Din))\nx = np.random.normal(size=(Din,))\nJf = jacfwd(fun)(x)\nJr = jacrev(fun)(x)\nassert np.allclose(Jf, Jr)\nassert np.allclose(Jf, A)\n```\n\nQuadratic form.\n\n$$\n\\begin{align}\nf(x;A) &= x^T A x \\\\\n\\nabla_x f(x;A) &= (A+A^T) x\n\\end{align}\n$$\n\n\n```\n\nD = 4\nA = np.random.normal(size=(D,D))\nx = np.random.normal(size=(D,))\nquadfun = lambda x: jnp.dot(x, jnp.dot(A, x))\n\ng = grad(quadfun)(x)\nassert np.allclose(g, jnp.dot(A+A.T, x))\n\n\n```\n\nChain rule applied to sigmoid function.\n\n$$\n\\begin{align}\n\\mu(x;w) &=\\sigma(w^T x) \\\\\n\\nabla_w \\mu(x;w) &= \\sigma'(w^T x) x \\\\\n\\sigma'(a) &= \\sigma(a) * (1-\\sigma(a)) \n\\end{align}\n$$\n\n\n```\n\n\nD = 4\nw = np.random.normal(size=(D,))\nx = np.random.normal(size=(D,))\ny = 0 \n\ndef sigmoid(x): return 0.5 * (jnp.tanh(x / 2.) + 1)\ndef mu(w): return sigmoid(jnp.dot(w,x))\ndef deriv_mu(w): return mu(w) * (1-mu(w)) * x\nderiv_mu_jax = grad(mu)\n\nprint(deriv_mu(w))\nprint(deriv_mu_jax(w))\n\nassert np.allclose(deriv_mu(w), deriv_mu_jax(w), atol=1e-3)\n\n\n```\n\n [-0.458 0.022 -0.266 -0.005]\n [-0.458 0.022 -0.266 -0.005]\n\n\n## Auxiliary return values\n\nA function can return its value and other auxiliary results; the latter are not differentiated. \n\n\n```\ndef f(x,y):\n return x**2+y, 42\n\n(v,aux), g = value_and_grad(f, has_aux=True)(x,y)\nprint(v)\nprint(aux)\nprint(g)\n```\n\n 7.0\n 42\n 4.0\n\n\n## Jacobians\n\n\nExample: Linear function: multi-input, multi-output.\n\n$$\n\\begin{align}\nf(x;A) &= A x \\\\\n\\frac{\\partial f(x;A)}{\\partial x} &= A\n\\end{align}\n$$\n\n\n\n```\n# We construct a multi-output linear function.\n# We check forward and reverse mode give same Jacobians.\n\n\ndef fun(x):\n return jnp.dot(A, x)\n\nDin = 3; Dout = 4;\nA = np.random.normal(size=(Dout, Din))\nx = np.random.normal(size=(Din,))\nJf = jacfwd(fun)(x)\nJr = jacrev(fun)(x)\nassert np.allclose(Jf, Jr)\n```\n\n## Hessians\n\nQuadratic form.\n\n$$\n\\begin{align}\nf(x;A) &= x^T A x \\\\\n\\nabla_x^2 f(x;A) &= A + A^T\n\\end{align}\n$$\n\n\n```\n\nD = 4\nA = np.random.normal(size=(D,D))\nx = np.random.normal(size=(D,))\n\nquadfun = lambda x: jnp.dot(x, jnp.dot(A, x))\n\n\nH1 = hessian(quadfun)(x)\nassert np.allclose(H1, A+A.T)\n\ndef my_hessian(fun):\n return jacfwd(jacrev(fun))\n\nH2 = my_hessian(quadfun)(x)\nassert np.allclose(H1, H2)\n```\n\n## Example: Binary logistic regression\n\n\n```\n\ndef sigmoid(x): return 0.5 * (jnp.tanh(x / 2.) + 1)\n\ndef predict_single(w, x):\n return sigmoid(jnp.dot(w, x)) # <(D) , (D)> = (1) # inner product\n \ndef predict_batch(w, X):\n return sigmoid(jnp.dot(X, w)) # (N,D) * (D,1) = (N,1) # matrix-vector multiply\n\n# negative log likelihood\ndef loss(weights, inputs, targets):\n preds = predict_batch(weights, inputs)\n logprobs = jnp.log(preds) * targets + jnp.log(1 - preds) * (1 - targets)\n return -jnp.sum(logprobs)\n\n\nD = 2\nN = 3\nw = jax.random.normal(key, shape=(D,))\nX = jax.random.normal(key, shape=(N,D))\ny = jax.random.choice(key, 2, shape=(N,)) # uniform binary labels\n#logits = jnp.dot(X, w)\n#y = jax.random.categorical(key, logits)\n\nprint(loss(w, X, y))\n\n# Gradient function\ngrad_fun = grad(loss)\n\n# Gradient of each example in the batch - 2 different ways\ngrad_fun_w = partial(grad_fun, w)\ngrads = vmap(grad_fun_w)(X,y)\nprint(grads)\nassert grads.shape == (N,D)\n\ngrads2 = vmap(grad_fun, in_axes=(None, 0, 0))(w, X, y) \nassert np.allclose(grads, grads2)\n\n# Gradient for entire batch\ngrad_sum = jnp.sum(grads, axis=0)\nassert grad_sum.shape == (D,)\nprint(grad_sum)\n```\n\n 1.5545294\n [[ 0.042 -0.287]\n [-0.236 -0.454]\n [-0.14 0.067]]\n [-0.334 -0.673]\n\n\n\n```\n# Textbook implementation of gradient\ndef NLL_grad(weights, batch):\n X, y = batch\n N = X.shape[0]\n mu = predict_batch(weights, X)\n g = jnp.sum(jnp.dot(jnp.diag(mu - y), X), axis=0)\n return g\n\ngrad_sum_batch = NLL_grad(w, (X,y))\nprint(grad_sum_batch)\nassert np.allclose(grad_sum, grad_sum_batch)\n```\n\n [-0.334 -0.673]\n\n\n\n```\n# We can also compute Hessians, as we illustrate below.\n\nhessian_fun = hessian(loss)\n\n# Hessian on one example\nH0 = hessian_fun(w, X[0,:], y[0])\nprint('Hessian(example 0)\\n{}'.format(H0))\n\n# Hessian for batch\nHbatch = vmap(hessian_fun, in_axes=(None, 0, 0))(w, X, y) \nprint('Hbatch shape {}'.format(Hbatch.shape))\n\nHbatch_sum = jnp.sum(Hbatch, axis=0)\nprint('Hbatch sum\\n {}'.format(Hbatch_sum))\n```\n\n Hessian(example 0)\n [[ 0.006 -0.042]\n [-0.042 0.286]]\n Hbatch shape (3, 2, 2)\n Hbatch sum\n [[0.118 0.139]\n [0.139 0.65 ]]\n\n\n\n```\n# Textbook implementation of Hessian\n\ndef NLL_hessian(weights, batch):\n X, y = batch\n mu = predict_batch(weights, X)\n S = jnp.diag(mu * (1-mu))\n H = jnp.dot(jnp.dot(X.T, S), X)\n return H\n\nH2 = NLL_hessian(w, (X,y) )\n\nassert np.allclose(Hbatch_sum, H2, atol=1e-2)\n```\n\n## Vector Jacobian Products (VJP) and Jacobian Vector Products (JVP)\n\nConsider a bilinear mapping $f(x,W) = x W$.\nFor fixed parameters, we have\n$f1(x) = W x$, so $J(x) = W$, and $u^T J(x) = J(x)^T u = W^T u$.\n\n\n\n```\nn = 3; m = 2;\nW = jax.random.normal(key, shape=(m,n))\nx = jax.random.normal(key, shape=(n,))\nu = jax.random.normal(key, shape=(m,))\n\ndef f1(x): return jnp.dot(W,x)\n\nJ1 = jacfwd(f1)(x)\nprint(J1.shape)\n\nassert np.allclose(J1, W)\ntmp1 = jnp.dot(u.T, J1)\nprint(tmp1)\n\n(val, jvp_fun) = jax.vjp(f1, x)\n\ntmp2 = jvp_fun(u)\n\nassert np.allclose(tmp1, tmp2)\n\ntmp3 = np.dot(W.T, u)\nassert np.allclose(tmp1, tmp3)\n\n\n\n```\n\n (2, 3)\n [ 0.922 1.216 -0.61 ]\n\n\nFor fixed inputs, we have\n$f2(W) = W x$, so $J(W) = \\text{something complex}$,\nbut $u^T J(W) = J(W)^T u = u x^T$.\n\n\n```\n\ndef f2(W): return jnp.dot(W,x)\n\nJ2 = jacfwd(f2)(W)\nprint(J2.shape)\n\ntmp1 = jnp.dot(u.T, J2)\nprint(tmp1)\nprint(tmp1.shape)\n\n(val, jvp_fun) = jax.vjp(f2, W)\ntmp2 = jvp_fun(u)\nassert np.allclose(tmp1, tmp2)\n\ntmp3 = np.outer(u, x)\nassert np.allclose(tmp1, tmp3)\n\n```\n\n (2, 2, 3)\n [[-1.425 0.379 -0.267]\n [ 1.555 -0.413 0.291]]\n (2, 3)\n\n\n## Stop-gradient\n\nSometimes we want to take the gradient of a complex expression wrt some parameters $\\theta$, but treating $\\theta$ as a constant for some parts of the expression. For example, consider the TD(0) update in reinforcement learning, which as the following form:\n\n\n$\\Delta \\theta = (r_t + v_{\\theta}(s_t) - v_{\\theta}(s_{t-1})) \\nabla v_{\\theta}(s_{t-1})$\n\nwhere $s$ is the state, $r$ is the reward, and $v$ is the value function.\nThis update is not the gradient of any loss function.\nHowever it can be **written** as the gradient of the pseudo loss function\n\n$L(\\theta) = [r_t + v_{\\theta}(s_t) - v_{\\theta}(s_{t-1})]^2$\n\nsince\n\n$\\nabla_{\\theta} L(\\theta) = 2 [r_t + v_{\\theta}(s_t) - v_{\\theta}(s_{t-1})] \\nabla v_{\\theta}(s_{t-1})$\n\nif the dependency of the target $r_t + v_{\\theta}(s_t)$ on the parameter $\\theta$ is ignored. We can implement this in JAX using `stop_gradient`, as we show below.\n\n\n\n\n```\ndef td_loss(theta, s_prev, r_t, s_t):\n v_prev = value_fn(theta, s_prev)\n target = r_t + value_fn(theta, s_t)\n return 0.5*(jax.lax.stop_gradient(target) - v_prev) ** 2\n\ntd_update = jax.grad(td_loss)\n\n# An example transition.\ns_prev = jnp.array([1., 2., -1.])\nr_t = jnp.array(1.)\ns_t = jnp.array([2., 1., 0.])\n\n# Value function and initial parameters\nvalue_fn = lambda theta, state: jnp.dot(theta, state)\ntheta = jnp.array([0.1, -0.1, 0.])\n\nprint(td_update(theta, s_prev, r_t, s_t))\n\n\n```\n\n [-1.2 -2.4 1.2]\n\n\n## Straight through estimator\n\nThe straight-through estimator is a trick for defining a 'gradient' of a function that is otherwise non-differentiable. Given a non-differentiable function $f : \\mathbb{R}^n \\to \\mathbb{R}^n$ that is used as part of a larger function that we wish to find a gradient of, we simply pretend during the backward pass that $f$ is the identity function, so gradients pass through $f$ ignoring the $f'$ term. This can be implemented neatly using `jax.lax.stop_gradient`.\n\nHere is an example of a non-differentiable function that converts a soft probability distribution to a one-hot vector (discretization).\n\n\n\n```\ndef onehot(labels, num_classes):\n y = (labels[..., None] == jnp.arange(num_classes)[None])\n return y.astype(jnp.float32)\n\ndef quantize(y_soft): \n y_hard = onehot(jnp.argmax(y_soft), 3)[0]\n return y_hard\n\ny_soft = np.array([0.1, 0.2, 0.7])\nprint(quantize(y_soft))\n\n\n\n```\n\n [0. 0. 1.]\n\n\nNow suppose we define some linear function of the quantized variable of the form $f(y) = w^T q(y)$. If $w=[1,2,3]$ and $q(y)=[0,0,1]$, we get $f(y) = 3$. But the gradient is 0 because $q$ is not differentiable.\n\n\n\n```\ndef f(y):\n w = jnp.array([1,2,3])\n yq = quantize(y)\n return jnp.dot(w, yq)\n\nprint(f(y_soft))\nprint(grad(f)(y_soft))\n\n\n```\n\n 3.0\n [0. 0. 0.]\n\n\nTo use the straight-through estimator, we replace $q(y)$ with \n$$y + SG(q(y)-y)$$, where SG is stop gradient. In the forwards pass, we have $y+q(y)-y=q(y)$. In the backwards pass, the gradient of SG is 0, so we effectively replace $q(y)$ with $y$. So in the backwarsd pass we have\n$$\n\\begin{align}\nf(y) &= w^T q(y) \\approx w^T y \\\\\n\\nabla_y f(y) &\\approx w\n\\end{align}\n$$\n\n\n```\n\n\ndef f_ste(y):\n w = jnp.array([1,2,3])\n yq = quantize(y)\n yy = y + jax.lax.stop_gradient(yq - y) # gives yq on fwd, and y on backward\n return jnp.dot(w, yy)\n\nprint(f_ste(y_soft))\nprint(grad(f_ste)(y_soft))\n```\n\n 3.0\n [1. 2. 3.]\n\n\n## Per-example gradients\n\nIn some applications, we want to compute the gradient for every example in a batch, not just the sum of gradients over the batch. This is hard in other frameworks like TF and PyTorch but easy in JAX, as we show below.\n\n\n```\ndef loss(w, x):\n return jnp.dot(w,x)\n\nw = jnp.ones((3,))\nx0 = jnp.array([1.0, 2.0, 3.0])\nx1 = 2*x0\nX = jnp.stack([x0, x1])\nprint(X.shape)\n\nperex_grads = jax.jit(jax.vmap(jax.grad(loss), in_axes=(None, 0)))\nprint(perex_grads(w, X))\n\n```\n\n (2, 3)\n [[1. 2. 3.]\n [2. 4. 6.]]\n\n\nTo explain the above code in more depth, note that the vmap converts the function loss to take a batch of inputs for each of its arguments, and returns a batch of outputs. To make it work with a single weight vector, we specify in_axes=(None,0), meaning the first argument (w) is not replicated, and the second argument (x) is replicated along dimension 0. \n\n\n```\ngradfn = jax.grad(loss)\n\nW = jnp.stack([w, w])\nprint(jax.vmap(gradfn)(W, X))\n\nprint(jax.vmap(gradfn, in_axes=(None,0))(w, X))\n\n\n```\n\n [[1. 2. 3.]\n [2. 4. 6.]]\n [[1. 2. 3.]\n [2. 4. 6.]]\n\n\n\n# JIT (just in time compilation) \n\nIn this section, we illustrate how to use the Jax JIT compiler to make code go faster (even on a CPU). However, it does not work on arbitrary Python code, as we explain below.\n\n\n\n\n\n```\n\n\ndef slow_f(x):\n # Element-wise ops see a large benefit from fusion\n return x * x + x * 2.0\n\nx = jnp.ones((5000, 5000))\n%timeit slow_f(x) \n\nfast_f = jit(slow_f)\n%timeit fast_f(x) \n \nassert np.allclose(slow_f(x), fast_f(x))\n```\n\n The slowest run took 242.68 times longer than the fastest. This could mean that an intermediate result is being cached.\n 1 loop, best of 3: 1.42 ms per loop\n The slowest run took 149.09 times longer than the fastest. This could mean that an intermediate result is being cached.\n 1000 loops, best of 3: 506 µs per loop\n\n\nWe can also add the `@jit` decorator in front of a function.\n\n\n\n\n```\n@jit\ndef faster_f(x):\n return x * x + x * 2.0\n \n%timeit faster_f(x)\nassert np.allclose(faster_f(x), fast_f(x)) \n```\n\n The slowest run took 35.82 times longer than the fastest. This could mean that an intermediate result is being cached.\n 1000 loops, best of 3: 507 µs per loop\n\n\n## How it works: Jaxprs and tracing\n\nIn this section, we briefly explain the mechanics behind JIT, which will help you understand when it does not work.\n\nFirst, consider this function.\n\n\n```\n\ndef f(x):\n y = jnp.ones((1,5)) * x\n return y\n\n\n```\n\nWhen a function is first executed (applied to an argument), it is converted to an intermediate representatio called a JAX expression or jaxpr, by a process called tracing, as we show below.\n\n\n```\nprint(f(3.0))\nprint(jax.make_jaxpr(f)(3.0))\n```\n\n [[3. 3. 3. 3. 3.]]\n { lambda ; a.\n let b = broadcast_in_dim[ broadcast_dimensions=( )\n shape=(1, 5) ] 1.0\n c = mul b a\n in (c,) }\n\n\nThe XLA JIT compiler can then convert the jaxpr to code that runs fast on a CPU, GPU or TPU; the original python code is no longer needed.\n\n\n```\nf_jit = jit(f)\nprint(f_jit(3.0))\n```\n\n [[3. 3. 3. 3. 3.]]\n\n\nHowever, the jaxpr is created by tracing the function for a specific value. If different code is executed depending on the value of the input arguments, the resulting jaxpr will be different, so the function cannot be JITed, as we illustrate below. \n\n\n```\n\ndef f(x):\n if x > 0:\n return x\n else:\n return 2 * x\n\nprint(f(3.0))\n\nf_jit = jit(f)\nprint(f_jit(3.0))\n```\n\nJit will create a new compiled version for each different ShapedArray, but will reuse the code for different values of the same shape. If the code path depends on the concrete value, we can either just jit a subfunction (whose code path is constant), or we can create a different jaxpr for each concrete value of the input arguments as we explain below.\n\n\n\n## Static argnum\n\nNote that JIT compilation requires that the control flow through the function can be determined by the shape (but not concrete value) of its inputs. The function below violates this, since when x<0, it takes one branch, whereas when x>0, it takes the other.\n\n\n```\n@jit\ndef f(x):\n if x > 0:\n return x\n else:\n return 2 * x\n\n\n# This will fail!\ntry:\n print(f(3))\nexcept Exception as e:\n print(\"ERROR:\", e)\n \n\n```\n\n ERROR: Abstract tracer value encountered where concrete value is expected.\n \n The problem arose with the `bool` function. \n \n While tracing the function f at :1, this concrete value was not available in Python because it depends on the value of the arguments to f at :1 at flattened positions [0], and the computation of these values is being staged out (that is, delayed rather than executed eagerly).\n \n You can use transformation parameters such as `static_argnums` for `jit` to avoid tracing particular arguments of transformed functions, though at the cost of more recompiles.\n \n See https://jax.readthedocs.io/en/latest/faq.html#abstract-tracer-value-encountered-where-concrete-value-is-expected-error for more information.\n \n Encountered tracer value: Tracedwith\n\n\nWe can fix this by telling JAX to trace the control flow through the function using concrete values of some of its arguments. JAX will then compile different versions, depending on the input values. See below for an example.\n\n\n\n```\n\n\ndef f(x):\n if x > 0:\n return x\n else:\n return 2 * x\n\nf = jit(f, static_argnums=(0,))\n\nprint(f(3))\n\n\n```\n\n 3\n\n\n\n```\n@partial(jit, static_argnums=(0,))\ndef f(x):\n if x > 0:\n return x\n else:\n return 2 * x\nprint(f(3))\n```\n\n 3\n\n\n## Jit and vmap\n\nUnfortunately, the static argnum method fails when the function is passed to vmap, because the latter can take arguments of different shape.\n\n\n```\nxs = jnp.arange(5)\n\n@partial(jit, static_argnums=(0,))\ndef f(x):\n if x > 0:\n return x\n else:\n return 2 * x\n\nys = vmap(f)(xs)\n```\n\n\n```\ndef f(x):\n if x > 0:\n return x\n else:\n return 2 * x\n\nxs = jnp.arange(5)\nys = jit(vmap(f)(xs))\nprint(ys)\n```\n\n## Side effects\n\nSince the jaxpr is created only once, if your function has global side-effects, such as using print, they will only happen once, even if the function is called multiple times. See example below.\n\n\n\n```\ndef f(x):\n print('x', x)\n y = 2 * x\n print('y', y)\n return y\n\ny1 = f(2)\nprint('f', y1)\nprint('\\ncall function a second time')\ny1 = f(2)\nprint('f', y1)\n\nprint('\\njit version follows')\n@jit\ndef f(x):\n print('x', x)\n y = 2 * x\n print('y', y)\n return y\ny2 = f(2)\nprint('f', y2)\n\nprint('\\ncall jitted function a second time')\ny2 = f(2)\nprint('f', y2)\n```\n\n x 2\n y 4\n f 4\n \n call function a second time\n x 2\n y 4\n f 4\n \n jit version follows\n x Tracedwith\n y Tracedwith\n f 4\n \n call jitted function a second time\n f 4\n\n\n## Caching\n\nIf you write `f=jax.jit(g)`, then g will get compiled and the XLA code will be cahced. Subsequent calls to f reuse the cached code for speed. But if the jit is called inside a loop, it is effectively making a new f each time, which is slow.\n\nAlso, if you specify static_argnums,hen the cached code will be used only for the same values of arguments labelled as static. If any of them change, recompilation occurs. \n\n\n## Strings\n\nJit does not work with functions that consume or return strings.\n\n\n```\ndef f(x: int, y: str):\n if y=='add':\n return x+1\n else:\n return x-1\n\nprint(f(42, 'add'))\nprint(f(42, 'sub'))\n\nfj = jax.jit(f)\nprint(fj(42, 'add'))\n\n```\n\n# Pytrees\n\nA Pytree is a container of leaf elements and/or more pytrees. Containers include lists, tuples, and dicts. A leaf element is anything that’s not a pytree, e.g. an array.\nPytrees are useful for representing hierarchical sets of parameters for DNNs (and other structured dsta). \n\n\n## Simple example\n\n\n```\nfrom jax import tree_util\n\n# a simple pytree\nt1 = [1, {\"k1\": 2, \"k2\": (3, 4)}, 5]\nprint('tree', t1)\nleaves = jax.tree_leaves(t1)\nprint('num leaves', len(leaves))\n\nt4 = [jnp.array([1, 2, 3]), \"foo\"]\nprint('tree', t4)\nleaves = jax.tree_leaves(t4)\nprint('num leaves', len(leaves))\n\n\n```\n\n tree [1, {'k1': 2, 'k2': (3, 4)}, 5]\n num leaves 5\n tree [DeviceArray([1, 2, 3], dtype=int32), 'foo']\n num leaves 2\n\n\n## Treemap\n\n\nWe can map functions down a pytree in the same way that we can map a function down a list. We can also combine elements in two pytrees that have the same shape to make a third pytree.\n\n\n```\nt1 = [1, {\"k1\": 2, \"k2\": (3, 4)}, 5]\nprint(t1)\n\nt2 = tree_util.tree_map(lambda x: x*x, t1)\nprint('square each element', t2)\n\n\nt3 = tree_util.tree_multimap(lambda x,y: x+y, t1, t2)\nprint('t1+t2', t3)\n```\n\n [1, {'k1': 2, 'k2': (3, 4)}, 5]\n square each element [1, {'k1': 4, 'k2': (9, 16)}, 25]\n t1+t2 [2, {'k1': 6, 'k2': (12, 20)}, 30]\n\n\nIf we have a list of dicts, we can convert to a dict of lists, as shown below.\n\n\n```\n\ndata = [dict(t=1, obs='a', val=-1), dict(t=2, obs='b', val=-2), dict(t=3, obs='c', val=-3)]\n\ndata2 = jax.tree_multimap(lambda d0, d1, d2: list((d0, d1, d2)),\n data[0], data[1], data[2])\nprint(data2)\n\ndef join_trees(list_of_trees):\n d = jax.tree_multimap(lambda *xs: list(xs), *list_of_trees)\n return d\n\nprint(join_trees(data))\n```\n\n {'obs': ['a', 'b', 'c'], 't': [1, 2, 3], 'val': [-1, -2, -3]}\n {'obs': ['a', 'b', 'c'], 't': [1, 2, 3], 'val': [-1, -2, -3]}\n\n\n## Flattening\n\n\n\n```\n\nt1 = [1, {\"k1\": 2, \"k2\": (3, 4)}, 5]\nleaves, foo = jax.tree_util.tree_flatten(t1)\nprint(leaves)\nprint(foo)\n```\n\n [1, 2, 3, 4, 5]\n PyTreeDef(list, [*,PyTreeDef(dict[['k1', 'k2']], [*,PyTreeDef(tuple, [*,*])]),*])\n\n\n## Example: Linear regression \n\nIn this section we show how to use pytrees as a container for parameters of a linear reregression model. \nThe code is based on the [flax JAX tutorial](https://flax.readthedocs.io/en/latest/notebooks/jax_for_the_impatient.html). When we compute the gradient, it will also be a pytree, and will have the same shape as the parameters, so we can add the params to the gradient without having to flatten and unflatten the parameters.\n\n\n```\n\n\n# Create the predict function from a set of parameters\ndef make_predict_pytree(params):\n def predict(x):\n return jnp.dot(params['W'],x)+params['b']\n return predict\n\n# Create the loss from the data points set\ndef make_mse_pytree(x_batched,y_batched): # returns fn(params)->real\n def mse(params):\n # Define the squared loss for a single pair (x,y)\n def squared_error(x,y):\n y_pred = make_predict_pytree(params)(x)\n return jnp.inner(y-y_pred,y-y_pred)/2.0\n # We vectorize the previous to compute the average of the loss on all samples.\n return jnp.mean(jax.vmap(squared_error)(x_batched,y_batched), axis=0)\n return jax.jit(mse) # And finally we jit the result.\n```\n\n\n```\n# Set problem dimensions\nN = 20\nxdim = 10\nydim = 5\n\n# Generate random ground truth W and b\nkey = random.PRNGKey(0)\nWtrue = random.normal(key, (ydim, xdim))\nbtrue = random.normal(key, (ydim,))\nparams_true = {'W': Wtrue, 'b': btrue}\ntrue_predict_fun = make_predict_pytree(params_true)\n\n# Generate data with additional observation noise\nX = random.normal(key, (N, xdim))\nYtrue = jax.vmap(true_predict_fun)(X)\nY = Ytrue + 0.1*random.normal(key, (N, ydim))\n\n# Generate MSE for our samples\nmse_fun = make_mse_pytree(X, Y)\n```\n\n\n```\n# Initialize estimated W and b with zeros.\nparams = {'W': jnp.zeros_like(Wtrue), 'b': jnp.zeros_like(btrue)}\n\nmse_pytree = make_mse_pytree(X, Y)\nprint(mse_pytree(params_true))\nprint(mse_pytree(params))\nprint(jax.grad(mse_pytree)(params))\n```\n\n 0.022292046\n 24.97824\n {'W': DeviceArray([[-0.039, 0.755, 0.542, 0.36 , 0.224, 1.651, 1.534,\n -1.342, -0.15 , -1.638],\n [-0.324, 0.141, -0.402, 0.498, 1.829, 4.308, 2.138,\n -2.43 , -0.381, -2.178],\n [ 1.7 , -0.707, -0.656, -0.568, 1.824, -2.194, -0.477,\n 0.96 , 1.622, 1.408],\n [-0.862, 0.321, -0.388, -0.74 , -0.82 , 0.441, 0.772,\n -1.713, -1.592, -0.557],\n [ 1.338, -0.632, -0.968, -1.127, 1.775, 0.323, 1.405,\n -0.638, 1.077, -0.739]], dtype=float32), 'b': DeviceArray([ 0.036, 1.092, -0.413, -1.389, -0.862], dtype=float32)}\n\n\n\n```\nalpha = 0.3 # Gradient step size\nprint('Loss for \"true\" W,b: ', mse_pytree(params_true))\nfor i in range(101):\n gradients = jax.grad(mse_pytree)(params)\n params = jax.tree_multimap(lambda old,grad: old-alpha*grad, params, gradients)\n if (i%10==0):\n print(\"Loss step {}: \".format(i), mse_pytree(params))\n\n\n```\n\n Loss for \"true\" W,b: 0.022292046\n Loss step 0: 6.559746\n Loss step 10: 0.17232792\n Loss step 20: 0.04339735\n Loss step 30: 0.024473606\n Loss step 40: 0.017078906\n Loss step 50: 0.013489485\n Loss step 60: 0.011695381\n Loss step 70: 0.01079526\n Loss step 80: 0.010343453\n Loss step 90: 0.010116666\n Loss step 100: 0.0100028105\n\n\n\n```\nprint(jax.tree_multimap(lambda x,y: np.allclose(x,y, atol=1e-1), params, params_true))\n```\n\n {'W': True, 'b': True}\n\n\nCompare the above to what the training code would look like\nif W and b were passed in as separate arguments:\n```\nfor i in range(101):\n grad_W = jax.grad(mse_fun,0)(What,bhat)\n grad_b = jax.grad(mse_fun,1)(What,bhat)\n What = What - alpha*grad_W\n bhat = bhat - alpha*grad_b \n if (i%10==0):\n print(\"Loss step {}: \".format(i), mse_fun(What,bhat)\n```\n\n## Example: MLPs\n\nWe now show a more interesting example, from the Deepmind tutorial, where we fit an MLP using SGD. The basic structure is similar to the linear regression case.\n\n\n\n```\n# define the model \ndef init_mlp_params(layer_widths):\n params = []\n for n_in, n_out in zip(layer_widths[:-1], layer_widths[1:]):\n params.append(\n dict(weights=np.random.normal(size=(n_in, n_out)) * np.sqrt(2/n_in),\n biases=np.ones(shape=(n_out,))\n )\n )\n return params\n\ndef forward(params, x):\n *hidden, last = params\n for layer in hidden:\n x = jax.nn.relu(x @ layer['weights'] + layer['biases'])\n return x @ last['weights'] + last['biases']\n\ndef loss_fn(params, x, y):\n return jnp.mean((forward(params, x) - y) ** 2)\n```\n\n\n```\n# MLP with 2 hidden layers and linear output\nnp.random.seed(0)\nparams = init_mlp_params([1, 128, 128, 1])\njax.tree_map(lambda x: x.shape, params)\n\n```\n\n\n\n\n [{'biases': (128,), 'weights': (1, 128)},\n {'biases': (128,), 'weights': (128, 128)},\n {'biases': (1,), 'weights': (128, 1)}]\n\n\n\n\n```\nLEARNING_RATE = 0.0001\n\n@jax.jit\ndef update(params, x, y):\n grads = jax.grad(loss_fn)(params, x, y)\n return jax.tree_multimap(\n lambda p, g: p - LEARNING_RATE * g, params, grads)\n\nnp.random.seed(0)\nxs = np.random.normal(size=(200, 1))\nys = xs ** 2\n\nfor _ in range(1000):\n params = update(params, xs, ys)\n\nplt.scatter(xs, ys, label='truth')\nplt.scatter(xs, forward(params, xs), label='Prediction')\nplt.legend()\n```\n\n# Looping constructs\n\nFor loops in Python are slow, even when JIT-compiled. However, there are built-in primitives for loops that are fast, as we illustrate below.\n\n## For loops.\n\nThe semantics of the for loop function in JAX is as follows:\n```\ndef fori_loop(lower, upper, body_fun, init_val):\n val = init_val\n for i in range(lower, upper):\n val = body_fun(i, val)\n return val\n```\nWe see that ```val``` is used to accumulate the results across iterations.\n\nBelow is an example.\n\n\n```\n# sum from 1 to N = N*(N+1)/2\n\ndef sum_exact(N):\n return int(N*(N+1)/2)\n\ndef sum_slow(N):\n s = 0\n for i in range(1,N+1):\n s += i\n return s\n\nN = 10\n\nassert sum_slow(N) == sum_exact(N)\n\ndef sum_fast(N):\n s = jax.lax.fori_loop(1, N+1, lambda i,partial_sum: i+partial_sum, 0)\n return s\n\nassert sum_fast(N) == sum_exact(N) \n```\n\n\n```\nN = 1000\n%timeit sum_slow(N)\n%timeit sum_fast(N)\n```\n\n 10000 loops, best of 3: 44.1 µs per loop\n 10 loops, best of 3: 41 ms per loop\n\n\n\n```\nN = 100000\n%timeit sum_slow(N)\n%timeit sum_fast(N)\n```\n\n 100 loops, best of 3: 5.04 ms per loop\n 1 loop, best of 3: 2.88 s per loop\n\n\n\n```\n# Let's do more compute per step of the for loop\n\nD = 10\nX = jax.random.normal(key, shape=(D,D))\n\ndef sum_slow(N):\n s = jnp.zeros_like(X)\n for i in range(1,N+1):\n s += jnp.dot(X, X)\n return s\n\ndef sum_fast(N):\n s = jnp.zeros_like(X)\n s = jax.lax.fori_loop(1, N+1, lambda i,s: s+jnp.dot(X,X), s)\n return s\n\nN = 10\nassert np.allclose(sum_fast(N), sum_slow(N))\n```\n\n\n```\nN = 1000\n%timeit sum_slow(N)\n%timeit sum_fast(N)\n```\n\n 1 loop, best of 3: 482 ms per loop\n 10 loops, best of 3: 46.3 ms per loop\n\n\n## While loops\n\nHere is the semantics of the JAX while loop\n\n\n```\ndef while_loop(cond_fun, body_fun, init_val):\n val = init_val\n while cond_fun(val):\n val = body_fun(val)\n return val\n```\n\nBelow is an example.\n\n\n```\n\n\ndef sum_slow_while(N):\n s = 0\n i = 0\n while (i <= N):\n s += i\n i += 1\n return s\n\n\ndef sum_fast_while(N):\n init_val = (0,0)\n def cond_fun(val):\n s,i = val\n return i<=N\n def body_fun(val):\n s,i = val\n s += i\n i += 1\n return (s,i)\n val = jax.lax.while_loop(cond_fun, body_fun, init_val)\n s2 = val[0]\n return s2\n\nN = 10\nassert sum_slow_while(N) == sum_exact(N)\nassert sum_slow_while(N) == sum_fast_while(N)\n```\n\n# Common gotchas\n\n## Handling state\n\nIn this section, we discuss how to transform code that uses object-oriented programming (which can be stateful) to pure functional programming, which is stateless, as required by JAX. Our presentation is based on the Deepmind tutorial.\n\n\n\n\n\n\nTo start, consider a simple class that maintains an internal counter, and when called, increments the counter and returns the next number from some sequence. \n\n\n```\n#import string\n#DICTIONARY = list(string.ascii_lowercase)\nSEQUENCE = jnp.arange(0,100,2)\n\nclass Counter:\n\n def __init__(self):\n self.n = 0\n\n def count(self) -> int:\n #res = DICTIONARY[self.n]\n res = SEQUENCE[self.n]\n self.n += 1\n return res\n\n def reset(self):\n self.n = 0\n\n\ncounter = Counter()\n\nfor _ in range(3):\n print(counter.count())\n```\n\n 0\n 2\n 4\n\n\nThe trouble with the above code is that the call to `count` depends on the internal state of the object (the value `n`), even though this is not an argument to the function. (The code is therefoe said to violate 'referential transparency'.) When we Jit compile it, Jax will only call the code once (to convert to a jaxpr), so the side effect of updating `n` will not happen, resulting in incorrect behavior, as we show below,\n\n\n```\ncounter.reset()\nfast_count = jax.jit(counter.count)\n\nfor _ in range(3):\n print(fast_count())\n```\n\n 0\n 0\n 0\n\n\nWe can solve this problem by passing the state as an argument into the function.\n\n\n```\nCounterState = int\nResult = int\n\nclass CounterV2:\n\n def count(self, n: CounterState) -> Tuple[Result, CounterState]:\n return SEQUENCE[n], n+1\n\n def reset(self) -> CounterState:\n return 0\n\ncounter = CounterV2()\nstate = counter.reset()\n\nfor _ in range(3):\n value, state = counter.count(state)\n print(value)\n```\n\n 0\n 2\n 4\n\n\nThis version is functionally pure, so jit-compiles nicely.\n\n\n```\nstate = counter.reset()\nfast_count = jax.jit(counter.count)\n\nfor _ in range(3):\n value, state = fast_count(state)\n print(value)\n```\n\n 0\n 2\n 4\n\n\n\nWe can apply the same process to any stateful method to convert it into a stateless one. We took a class of the form\n\n```\nclass StatefulClass\n\n state: State\n\n def stateful_method(*args, **kwargs) -> Output:\n```\n\nand turned it into a class of the form\n\n```\nclass StatelessClass\n\n def stateless_method(state: State, *args, **kwargs) -> (Output, State):\n```\n\nThis is a common [functional programming](https://en.wikipedia.org/wiki/Functional_programming) pattern, and, essentially, is the way that state is handled in all JAX programs (as we saw with the way Jax handles random number state, or parameters of a model that get updated).\nNote that the stateless version of the code no longer needs to use a class, but can instead group the functions into a common namespace using modules.\n\nIn some cases (eg when working with DNNs), it is more convenient to write code in an OO way. There are several libraries (notably [Flax](https://github.com/google/flax) and [Haiku](https://github.com/deepmind/dm-haiku)) that let you define a model in an OO way, and then generate functionally pure code. \n\n## Mutation of arrays \n\nSince JAX is functional, you cannot mutate arrays in place,\nsince this makes program analysis and transformation very difficult. JAX requires a pure functional expression of a numerical program.\nInstead, JAX offers the functional update functions: `index_update`, `index_add`, `index_min`, `index_max`, and the `index` helper. These are illustrated below. \n\nNote: If the input values of `index_update` aren't reused, jit-compiled code will perform these operations in-place, rather than making a copy. \n \n\n\n```\n# You cannot assign directly to elements of an array.\n\nA = jnp.zeros((3,3), dtype=np.float32)\n\n# In place update of JAX's array will yield an error!\ntry:\n A[1, :] = 1.0\nexcept:\n print('must use index_update')\n```\n\n must use index_update\n\n\n\n```\nfrom jax.ops import index, index_add, index_update\n\nD = 3\nA = 2*jnp.ones((D,D))\nprint(\"original array:\")\nprint(A)\n\nA2 = index_update(A, index[1, :], 42.0) # A[1,:] = 42\nprint(\"original array:\")\nprint(A) # unchanged\nprint(\"new array:\")\nprint(A2)\n\nA3 = A.at[1,:].set(42.0) # A3=np.copy(A), A3[1,:] = 42\nprint(\"original array:\")\nprint(A) # unchanged\nprint(\"new array:\")\nprint(A3)\n\nA4 = A.at[1,:].mul(42.0) # A4=np.copy(A), A4[1,:] *= 42\nprint(\"original array:\")\nprint(A) # unchanged\nprint(\"new array:\")\nprint(A4)\n\n\n```\n\n original array:\n [[2. 2. 2.]\n [2. 2. 2.]\n [2. 2. 2.]]\n original array:\n [[2. 2. 2.]\n [2. 2. 2.]\n [2. 2. 2.]]\n new array:\n [[ 2. 2. 2.]\n [42. 42. 42.]\n [ 2. 2. 2.]]\n original array:\n [[2. 2. 2.]\n [2. 2. 2.]\n [2. 2. 2.]]\n new array:\n [[ 2. 2. 2.]\n [42. 42. 42.]\n [ 2. 2. 2.]]\n original array:\n [[2. 2. 2.]\n [2. 2. 2.]\n [2. 2. 2.]]\n new array:\n [[ 2. 2. 2.]\n [84. 84. 84.]\n [ 2. 2. 2.]]\n\n\n## Implicitly casting lists to vectors\n\nYou cannot treat a list of numbers as a vector. Instead you must explicitly create the vector using the np.array() constructor.\n\n\n\n\n\n```\n# You cannot treat a list of numbers as a vector. \ntry:\n S = jnp.diag([1.0, 2.0, 3.0])\nexcept:\n print('must convert indices to np.array')\n```\n\n must convert indices to np.array\n\n\n\n```\n# Instead you should explicitly construct the vector.\n\nS = jnp.diag(jnp.array([1.0, 2.0, 3.0]))\n```\n", "meta": {"hexsha": "a6c20af7862bbfe8a315cf7fbdb50cdc16f2a424", "size": 198597, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/jax_intro.ipynb", "max_stars_repo_name": "Prahitha/pyprobml", "max_stars_repo_head_hexsha": "7dc7f58d4abd7a006e471bcaddd5dc24e294196f", "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": "notebooks/jax_intro.ipynb", "max_issues_repo_name": "Prahitha/pyprobml", "max_issues_repo_head_hexsha": "7dc7f58d4abd7a006e471bcaddd5dc24e294196f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-19T12:25:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T12:25:26.000Z", "max_forks_repo_path": "notebooks/jax_intro.ipynb", "max_forks_repo_name": "Nirzu97/pyprobml", "max_forks_repo_head_hexsha": "397173b09668d21aac5c047b830db577cbb30530", "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": 44.9314479638, "max_line_length": 13530, "alphanum_fraction": 0.5634626908, "converted": true, "num_tokens": 16942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.14608724333058226, "lm_q1q2_score": 0.0701918055551411}} {"text": "```\nfrom IPython.core.display import HTML\ncss_file = './custom.css'\nHTML(open(css_file, \"r\").read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n###### Content provided under a Creative Commons Attribution license, CC-BY 4.0; code under MIT License. (c)2014 [David I. Ketcheson](http://davidketcheson.info)\n\n##### version 0.1 - May 2014\n\n# Hyperbolic Conservation Laws\n\n\\begin{equation*}\n\\newcommand{Dx}{\\Delta x}\n\\newcommand{Dt}{\\Delta t}\n\\newcommand{imh}{{i-1/2}}\n\\newcommand{iph}{{i+1/2}}\n\\end{equation*}\nMany models of wave phenomena are governed by *hyperbolic conservation laws*. In this short course, we will learn about hyperbolic conservation laws and their numerical solution.\n\n## Conservation of mass\n\nImagine a fluid flowing in a narrow tube. We'll use $q$ to indicate the density of the fluid and $u$ to indicate its velocity. Both of these are functions of space and time: $q = q(x,t)$; $u=u(x,t)$. The total mass in the section of tube $[x_1,x_2]$ is\n\n\\begin{equation}\n\\int_{x_1}^{x_2} q(x,t) dx.\n\\end{equation}\n\nThis total mass can change in time due to fluid flowing in or out of this section of the tube. We call the rate of flow the *flux*, and represent it with the function $f(q)$. Thus the net rate of flow of mass into (or out of) the interval $[x_1,x_2]$ at time $t$ is\n\n$$f(q(x_1,t)) - f(q(x_2,t)).$$\n\nWe just said that this rate of flow must equal the time rate of change of total mass; i.e.\n\n$$\\frac{d}{dt} \\int_{x_1}^{x_2} q(x,t) dx = f(q(x_1,t)) - f(q(x_2,t)).$$\n\nNow since $\\int_{x_1}^{x_2} \\frac{\\partial}{\\partial x} f(q) dx = f(q(x_2,t)) - f(q(x_1,t))$, we can rewrite this as\n\n$$\\frac{d}{dt} \\int_{x_1}^{x_2} q(x,t) dx = -\\int_{x_1}^{x_2} \\frac{\\partial}{\\partial x} f(q) dx.$$\n\nUnder certain smoothness assumptions on $q$, we can move the time derivative inside the integral. We'll also put everything on the left side, to obtain\n\n$$\\int_{x_1}^{x_2} \\left(\\frac{\\partial}{\\partial t}q(x,t) + \\frac{\\partial}{\\partial x} f(q)\\right) dx = 0.$$\n\nSince this integral is zero for *any* choice of $x_1,x_2$, it must be that the integrand (the expression in parentheses) is actually zero *everywhere*! Therefore we can write the **differential conservation law**\n\n$$q_t + f_x = 0.$$\n\nHere and throughout the course, we use subscripts to denote partial derivatives.\nThis equation expresses the fact that the total mass is conserved -- since locally the mass can change only due to a net inflow or outflow.\n\n## Advection\n\nIn order to solve the conservation law above, we need an expression for the flux, $f$. The rate of flow is just mass times velocity: $f=u q$. Thus we obtain the **continuity equation**\n\n$$q_t + (uq)_x = 0.$$\n\nIn general, we need another equation to determine the velocity $u(x,t)$. In [Lesson 4](Lesson_04_Fluid_dynamics.ipynb) we'll look at the full equations of fluid dynamics, but for now let's consider the simplest case, in which all of the fluid flows at a single, constant velocity $u(x,t)=a$. Then the continuity equation becomes the **advection equation**\n\n$$q_t + a q_x = 0.$$\n\nThis equation has a very simple solution. If we are given the density $q(x,0)=q_0(x)$ at time zero, then the solution is just\n\n$$q(x,t) = q_0(x-at).$$\n\nLet's plot the solution of the advection equation on the interval $[0,1]$ for the initial condition\n$$q_0(x) = e^{-2(x-1/2)^2}.$$\n\nFirst, let's import all the modules we'll need.\n\n\n```\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom clawpack.visclaw.JSAnimation import IPython_display\n```\n\nNext, we'll set up a grid and the initial condition:\n\n\n```\nx = np.linspace(0,1,1000) # Spatial grid\nt = np.linspace(0,1) # Temporal grid\na = 1.0 # Advection speed\n\ndef q_0(x): # Initial condition\n return np.exp(-200.*(x-0.2)**2)\n```\n\nFinally, let's make an animation of the solution. It will take a few moments to run this code. For now, you don't need to worry about understanding all of the plotting code below. Just play with the animation until you have a feel for how the solution behaves.\n\n\n```\nfig = plt.figure(figsize=(8,4)) # Create an empty figure\nax = plt.axes()\nline, = ax.plot([], [],linewidth=2) # Create an empty line plot\nplt.axis((0,1,-0.1,1.1)) # Set the bounds of the plot\n\ndef plot_q(t):\n line.set_data(x,q_0(x-a*t)) # Replace the line plot with the solution at time t\n \nanimation.FuncAnimation(fig, plot_q, frames=t) # Animate the solution\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 Once \n Loop \n Reflect \n
    \n
    \n\n\n\n\n\n\n\nAs you can see, the initial pulse just moves to the right at speed $a$ as time advances. This isn't very interesting, but it captures the most important feature of hyperbolic equations: waves travel at finite speed.\n\n## Characteristics\n\nNotice that the solution value is constant along the line $x-at=x_0$, in the $x-t$ plane, for each value of $x_0$. These lines are called **characteristics**; they are the trajectories along which solution information is transmitted. The value $a$ is referred to as the **characteristic velocity**. The code below plots some of these characteristics.\n\nWhen we learn about more complicated conservation laws, we'll see that information still travels along characteristics, but those characteristics aren't necessarily straight lines.\n\n\n```\nfig = plt.figure(figsize=(8,4))\nax = plt.axes()\n\nfor x_0 in np.linspace(0,1,10):\n ax.plot(x,(x-x_0)/a,'-k')\nplt.ylim(0,1)\n```\n\n## A finite volume method for advection\n\nWe can easily solve the advection equation exactly. But the advection equation is a prototype for more complicated conservation laws that we will only be able to solve approximately by using numerical methods. In order to better understand these methods, we will discuss them first in the context of the advection equation.\n\nFor simplicity, we'll suppose that we wish to solve the advection equation on the interval $[0,1]$. We introduce a set of equally spaced *grid cells* of width $\\Dx$, and write $x_i$ to mean the center of cell $i$. Thus the first cell is the interval $[0,\\Dx]$ and $x_1=\\Dx/2$. We will also write $x_\\imh$ or $x_\\iph$ to denote the left or right boundary of cell $i$, respectively.\n\nWe write $Q_i$ to denote the *average* value of the solution over cell $i$:\n\n$$Q_i = \\frac{1}{\\Dx} \\int_{x_\\imh}^{x_\\iph} q \\ dx.$$\n\nThe simplest finite volume method is obtained by supposing that the solution is actually *equal* to $Q_i$ over all of cell $i$.\n\n\n\nSuppose $a>0$. Then the flux into cell $i$ from the left is $a Q_{i-1}$ and the flux out of cell $i$ to the right is $a Q_i$. Then our integral conservation law reads\n\n$$Q_i'(t) = -\\frac{a}{\\Dx}\\left(Q_i - Q_{i-1}\\right).$$\n\nApplying a forward difference in time we obtain the *upwind method*\n\n$$Q^{n+1}_i = Q^n_i -\\frac{a}{\\Dx}\\left(Q_i - Q_{i-1}\\right).$$\n\nWe call this the upwind method because the solution behaves as if it were being blown by a wind to the right, and the method uses the value $Q_{i-1}$ from the upwind direction.\n\nHere is a bit of Python code to solve the advection equation using the upwind method.\n\n\n```\na = 1.0 # advection speed\n\nm = 50 # number of cells\ndx = 1./m # Size of 1 grid cell\nx = np.arange(-dx/2, 1.+dx/2, dx) # Cell centers, including ghost cells\n\nt = 0. # Initial time\nT = 0.5 # Final time\ndt = 0.8 * dx / a # Time step\n\nQ = np.exp(-200*(x-0.2)**2) # Initial data\nQnew = np.empty(Q.shape)\n\nwhile t < T:\n \n # Extrapolation at boundaries:\n Qnew[0] = Q[1]\n Qnew[-1] = Q[-2]\n \n for i in range(1,len(x)):\n Qnew[i] = Q[i] - a*dt/dx * (Q[i]-Q[i-1])\n \n Q = Qnew.copy()\n t = t + dt\n \nplt.plot(x,Q,linewidth = 2)\nplt.title('t = '+str(t))\n```\n\nNotice how we set up a grid that contains an extra cell at each end, outside of the problem domain $[0,1]$. These are called **ghost cells** and are often useful in handling the solution at the grid boundaries.\n\n\n\n The technique we have used to set the ghost cell values above, by copying the last value inside the grid to the ghost cells, is known as **zero-order extrapolation**. It is useful for allowing waves to pass out of the domain (so-called *non-reflecting* boundaries). Note that we don't actually need the ghost cell at the right end for the upwind method, but for other methods we will.\n\nThe upwind method is simple, but it is not very accurate. Notice how the computed solution becomes wider and shorter over time. This behavior is referred to as *dissipation*.\n\n### Exercise\n\nNow do the following with the code above:\n\n1. Set $m=1000$ or more and notice that it takes some time to compute the solution. Rewrite the inner loop (over $i$) as a single line with no loop, using numpy slicing. For large values of $m$, the code with slicing is much faster.\n1. Notice that the last step of the simulation goes past time $T$. Modify the code so that the last step is adjusted to exactly reach $T$.\n2. Change the code so that animation of the solution versus time is plotted. You will want to accumulate frames of the solution in a list and then use the same kind of code we used above to animate the exact solution.\n3. Add some code to plot the exact solution.\n\n*Extra credit*: change the left boundary condition so that there is a sinusoidal wave coming in from the left:\n$$u(0,t) = \\sin(t).$$\n\n\n```\n\n```\n\nAfter making it through the exercise above, you should feel pretty comfortable with the basics of scientific programming in Python.\n\n## The CFL condition\n\nTake a look at the line of code that sets the time step:\n```python\n dt = 0.8 * dx / a \n```\nYou might be wondering where that formula came from. Rearranging that equation, we have\n$$a \\frac{\\Delta t}{\\Delta x} = 0.8.$$\nThe quantity $\\nu = a \\frac{\\Delta t}{\\Delta x}$ is the distance the exact solution moves during each time step, in units of grid cells. It is referred to as the *CFL number* or just the *Courant number* after the authors Courant, Friedrichs and Lewy who [established its importance](http://www.stat.uchicago.edu/~lekheng/courses/302/classics/courant-friedrichs-lewy.pdf). Try the following values of $\\nu$ in the code above, and compare the results with those you obtained already using $\\nu=0.8$.\n1. $\\nu = 1.0$\n2. $\\nu = 1.5$\n3. $\\nu = 0.1$\n\nFinally, try setting $a$ to a negative value. What happens?\n\nThe results you have observed can be explained as follows. Over a time step of size $\\Dt$, the solution moves by an amount $a \\Dt$. So $q(x_i,t_n)$ should be given exactly by $q(x_i-a\\Dt,t_{n-1})$. This is referred to as the *domain of dependence* of the solution.\n\nThe upwind method uses the values $Q_i^{n-1}$ and $Q_{i-1}^{n-1}$ to compute $Q_i^n$. The points $(x_{i-1},t_n)$ and $(x_i,t_n)$ (as well as the locations of solution values they depend, and the ones those depend on, and so forth) are the *numerical domain of dependence*.\n\nFor this to work, the true domain of dependence $x_i-a\\Dt$ must lie within the numerical domain of dependence, as $\\Dt,\\Dt \\to 0$. This is known as the [CFL condition](http://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition).\n\nFor the upwind method, that means that we must have\n$$x_i - \\Dx \\le x_i - a \\Dt \\le x_i$$\nor in other words\n$$0 \\le a \\frac{\\Dt}{\\Dx} \\le 1.$$\n\nIf the CFL condition is violated, the information that is used by the numerical method doesn't include the true information that influences the exact solution, so the numerical solution cannot be convergent.\n\n## The Lax-Friedrichs method\n\nThe upwind method gets its name from the fact that it uses the value $U_{i-1}$ and not $U_{i+1}$. Assuming $a>0$, the correct solution value $U_i^{n+1}$ should come from a point to the left of $x_i$ at time $t_n$ (i.e., the wind blows to the right, so $x_{i-1}$ is *upwind* of $x_i$).\n\nThis bias is fine for the advection equation, where we know everything moves in the same direction. But for more complicated conservation laws, things may move in either direction. It will be useful to have a method that uses information from both directions. The simplest such method is known as the **Lax-Friedrichs** method. For the conservation law $q_t + f(q)_x$, this method is\n\n$$Q_i^{n+1} = \\frac{1}{2}(Q_{i-1}^n + Q_{i+1}^n) - \\frac{\\Dt}{2\\Dx}\\left(f(Q_{i+1}^n) - f(Q_{i-1}^n)\\right).$$\n\nNotice that the flux difference term clearly approximates $f(q)_x$. Meanwhile, the value of $q$ itself is approximated by taking the average of two neighboring values. This average makes this method dissipative too (but it ensures that the solution is stable).\n\n### Exercise\n\n1. What does the CFL condition imply for the time step when using the Lax-Friedrichs method?\n\n2. In the cell below, implement the Lax-Friedrichs method for advection.\n\n\n```\n\n```\n\n*Extra credit*: Compute the norm of the difference between the approximate and exact solution. How does it change if you decrease $\\Dx$?\n\n## Accuracy\n\nThe methods we have used so far (i.e., the *upwind method* and the *Lax-Friedrichs method*) are both dissipative. Furthermore, both of these methods are only *first order accurate*, meaning that if we reduce the values of $\\Dt$ and $\\Dx$ by a factor of two, the overall error decreases only by a factor of two. In [Lesson 3](Lesson_03_High-resolution_methods.ipynb), we will learn about more accurate methods.\n", "meta": {"hexsha": "bd9c4ce2cb460cc3f17aa00be873e3ecd2c43c45", "size": 769736, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lesson_01_Advection.ipynb", "max_stars_repo_name": "Qu-Bit/HyperPython", "max_stars_repo_head_hexsha": "86e745858327deeba97a0e9e6718ea459ddf0470", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-04-01T11:51:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-01T11:51:01.000Z", "max_issues_repo_path": "Lesson_01_Advection.ipynb", "max_issues_repo_name": "Qu-Bit/HyperPython", "max_issues_repo_head_hexsha": "86e745858327deeba97a0e9e6718ea459ddf0470", "max_issues_repo_licenses": ["CC-BY-4.0", "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_01_Advection.ipynb", "max_forks_repo_name": "Qu-Bit/HyperPython", "max_forks_repo_head_hexsha": "86e745858327deeba97a0e9e6718ea459ddf0470", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 88.5364619278, "max_line_length": 11583, "alphanum_fraction": 0.7992870283, "converted": true, "num_tokens": 4957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032526, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.07008634085606276}} {"text": "```python\nfrom IPython.core.display import HTML\nHTML(\"\")\n```\n\n\n\n\n\n\n\n\n# Lecture 11, Solution methods for multiobjective optimization \n\n## Reminder:\n\n### Mathematical formulation of multiobjective optimization problems\n\nMultiobjective optimization problems are often formulated as\n$$\n\\begin{align} \\\n\\min \\quad &\\{f_1(x),\\ldots,f_k(x)\\}\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_q(x) = 0\\text{ for all }q=1,\\ldots,Q\\\\\n&a_i\\leq x_i\\leq b_i\\text{ for all } i=1,\\ldots,n\\\\\n&x\\in \\mathbb R^n,\n\\end{align}\n$$\nwhere $$f_1,\\ldots,f_k:\\{x\\in\\mathbb R^n: g_j(x) \\geq 0 \\text{ for all }j=1,\\ldots,J \\text{ and } h_q(x) = 0\\text{ for all }q=1,\\ldots,Q\\}\\mapsto\\mathbb R$$ are the objective functions.\n\n## Pareto optimality\nA feasible solution $x_1$ is Pareto optimal to the multiobjective optimization problem, if there does not exist a feasible solution $x_2$, $x_1\\neq x_2$, such that \n$$\n\\left\\{\n\\begin{align}\n&f_i(x_2)\\leq f_i(x_1)\\text{ for all }i\\in \\{1,\\ldots,k\\}\\\\\n&f_j(x_2)0$ and show that this is not Pareto optimal:\n\nBy choosing solution $(x,0)$, we have \n\n$$\n\\left\\{\n\\begin{align}\nf_1(x,0)=x^2International Society on MCDM\n\n## Our example problem for this lecture\n\nWe study a hypothetical decision problem of buying a car, when you can choose to have a car with power between (denoted by $p$) 50 and 200 kW and average consumption (denoted by $c$) per 100 km between 3 and 10 l. However, in addition to the average consumption and power, you need to decide the volume of the cylinders (v), which may be between 1000 $cm^3$ and 4000 $cm^3$. Finally, the price of the car follows now a function \n\n$$\n\\left(\\sqrt{\\frac{p-50}{50}}\\\\\n+\\left(\\frac{p-50}{50}\\right)^2+0.3(10-c)\\\\ +10^{-5}\\left(v-\\left(1000+3000\\frac{p-50}{150}\\right)\\right)^2\\right)10000\\\\+5000\n$$\n\nin euros. This problem can be formulated as a multiobjective optimization problem\n\n$$\n\\begin{align}\n\\min \\quad & \\{c,-p,P\\},\\\\\n\\text{s.t. }\\quad\n&50\\leq p\\leq 200\\\\\n&3\\leq c\\leq 10\\\\\n&1000\\leq v\\leq 4000,\\\\\n\\text{where }\\quad&P = \\left(\\sqrt{\\frac{p-50}{50}}+\\left(\\frac{p-50}{50}\\right)^2+0.3(10-c)\\right.\\\\\n& \\left.+ 10^{-5}\\left(v-\\left(1000+3000\\frac{p-50}{150}\\right)\\right)^2\\right)10000+5000\n\\end{align}\n$$\n\n\n```python\n#Let us define a Python function which returns the value of this\nimport math\ndef car_problem(c,p,v):\n# import pdb; pdb.set_trace()\n return [#Objective function values\n c,-p,\n (math.sqrt((p-50.)/50.)+((p-50.)/50.)**2+\n 0.3*(10.-c)+0.00001*(v-(1000.+3000.*(p-50.)/150.))**2)*10000.\n +5000.] \n```\n\n\n```python\nprint(\"Car with 3 l/100km consumption, 50kW and 1000cm^3 engine would cost \"\n +str(car_problem(3,50,1000)[2])+\"€\")\nprint(\"Car with 3 l/100km consumption, 100kW and 2000cm^3 engine would cost \"\n +str(car_problem(3,100,2000)[2])+\"€\")\nprint(\"Car with 3 l/100km consumption, 100kW and 1000cm^3 engine would cost \"\n +str(car_problem(3,100,1000)[2])+\"€\")\n```\n\n Car with 3 l/100km consumption, 50kW and 1000cm^3 engine would cost 26000.0€\n Car with 3 l/100km consumption, 100kW and 2000cm^3 engine would cost 46000.0€\n Car with 3 l/100km consumption, 100kW and 1000cm^3 engine would cost 146000.0€\n\n\n## Normalization of the objectives\n\n**In many of the methods, the normalization of the objectives is necessary.**\n\nWe can normalize the objectives using the nadir and ideal and setting the normalized objective as\n$$ \\tilde f_i = \\frac{f_i-z_i^{ideal}}{z_i^{nadir}-z_i^{ideal}}$$\n\n## Calculating the ideal\n\n**Finding the ideal for problems is usually easy, if you can optimize the objective functions separately.**\n\nFor the car problem, ideal can be computed easily using the script:\n\n\n```python\n#Calculating the ideal\nfrom scipy.optimize import minimize\nimport ad\ndef calc_ideal(f):\n ideal = [0]*3 #Because three objectives\n solutions = [] #list for storing the actual solutions, which give the ideal\n bounds = ((3,10),(50,200),(1000,4000)) #Bounds of the problem\n starting_point = [3,50,1000]\n for i in range(3):\n res=minimize(\n #Minimize each objective at the time\n lambda x: f(x[0],x[1],x[2])[i], starting_point, method='SLSQP'\n #Jacobian using automatic differentiation (note: SLSQP can estimate gradiants itself with some extra function evaluations)\n #,jac=ad.gh(lambda x: f(x[0],x[1],x[2])[i])[0]\n #bounds given above\n ,bounds = bounds\n ,options = {'disp':True, 'ftol': 1e-20, 'maxiter': 1000})\n solutions.append(f(res.x[0],res.x[1],res.x[2]))\n ideal[i]=res.fun\n return ideal,solutions\n```\n\n\n```python\nideal, solutions= calc_ideal(car_problem)\nprint (\"ideal is \"+str(ideal))\n```\n\n Optimization terminated successfully (Exit mode 0)\n Current function value: 3.0\n Iterations: 1\n Function evaluations: 4\n Gradient evaluations: 1\n Optimization terminated successfully (Exit mode 0)\n Current function value: -200.0\n Iterations: 5\n Function evaluations: 20\n Gradient evaluations: 5\n Optimization terminated successfully (Exit mode 0)\n Current function value: 5000.0\n Iterations: 6\n Function evaluations: 8\n Gradient evaluations: 2\n ideal is [3.0, -200.0, 5000.0]\n\n\n## Pay-off table method\n\n**Finding the nadir value is however, usually much harder.**\n\nUsually, the nadir value is estimated using the so-called pay-off table method.\n\nThe pay-off table method does not guarantee to find the exact nadir for problems with more than two objectives. \n\nThe method is, however, a generally accepted way of approximating the nadir vector.\n\nIn the pay-off table method:\n1. the objective values for attaining the individual minima are added in table\n2. the nadir is estimated by each objectives maxima in the table.\n3. the ideal values are located in the diagonal of the pay-off table\n\n\n\n### $x^{(*,i)} =$ optimal solution for $f_i$ \n\n### The nadir for the car selection problem\nThe table now becomes by using the *solutions* that we returned while calculating the ideal\n\n\n```python\nfor solution in solutions:\n print(solution) \n```\n\n [3.0, -50.0, 26000.0]\n [3.0, -200.0, 1033320.5080756888]\n [10.0, -50.0, 5000.0]\n\n\nThus, the esimation of the nadir vector is \n$$(10,-50,1033320.5080756888)$$\n\nThis is actually the real Nadir vector for this problem.\n\n### Normalized car problem\n\n\n```python\n#Let us define a Python function which returns the value of this\nimport math\ndef car_problem_normalized(c,p,v):\n z_ideal = [3.0, -200.0, 5000]\n z_nadir = [10,-50,1033320.5080756888]\n z = car_problem(c,p,v) \n return [(zi-zideali)/(znadiri-zideali) for \n (zi,zideali,znadiri) in zip(z,z_ideal,z_nadir)]\n```\n\nthe zip function in Python\n\n\n```python\nprint(\"Normalized value of the car problem at (3,50,1000) is \"\n +str(car_problem_normalized(3,50,1000)))\nprint(\"Normalized value of the car problem at (3,125,2500) is \"\n +str(car_problem_normalized(3,125,2500)))\nprint(\"Normalized value of the car problem at (10,100,1000) is \"\n +str(car_problem_normalized(10,100,1000)))\n```\n\n Normalized value of the car problem at (3,50,1000) is [0.0, 1.0, 0.020421648537670038]\n Normalized value of the car problem at (3,125,2500) is [0.0, 0.5, 0.054212133547970276]\n Normalized value of the car problem at (10,100,1000) is [1.0, 0.6666666666666666, 0.11669513450097163]\n\n\n**So, value 1 now indicates the worst value on the Pareto frontier and value 0 indicates the best values**\n\nLet's set the ideal and nadir for later reference:\n\n\n```python\nz_ideal = [3.0, -200.0, 5000]\nz_nadir = [10.,-50,1033320.5080756888]\n```\n\n**From now on, we will deal with the normalized problem, although, we write just $f$.** The aim of this is to simplify presentation.\n", "meta": {"hexsha": "d0af18a90ed1d56c04d8f157dce40d407e8607dd", "size": 25478, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture 11, Methods for multiobjective optimization.ipynb", "max_stars_repo_name": "bshavazipour/TIES483-2022", "max_stars_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "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": "Lecture 11, Methods for multiobjective optimization.ipynb", "max_issues_repo_name": "bshavazipour/TIES483-2022", "max_issues_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "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": "Lecture 11, Methods for multiobjective optimization.ipynb", "max_forks_repo_name": "bshavazipour/TIES483-2022", "max_forks_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-03T09:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T09:40:02.000Z", "avg_line_length": 28.6269662921, "max_line_length": 437, "alphanum_fraction": 0.5449014836, "converted": true, "num_tokens": 4394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189024594807, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.06979961087089344}} {"text": "
    \n
    \n

    For Loop

    \n

    Iterate over the elements of a sequence (such as a string, tuple, list or array) or other iterable object

    \n
    \n
    \n\n- [Overview](#Overview)\n- [Indentation](#Indentation)\n- [Examples](#Examples)\n - [Summing](#Summing)\n - [Taylor series](#Taylor-series)\n - [Factorial](#Factorial)\n - [Fibonacci series](#Fibonacci-series)\n- [Looping with indices](#Looping-with-indices)\n- [Nested loops](#Nested-loops)\n- [Debugging](#Debugging)\n- [Glossary](#Glossary)\n- [Exercises](#Exercises)\n\n## Overview\n\n\nComputers are often used to automate repetitive tasks since repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration.\n\nThe `for` statement is used to iterate over (step through) the elements of a sequence (such as a string, tuple, list or array) or other iterable object. In other words the `for` statement can be used to repeat a block of code a predetermined number of times (once for each element in the sequence). The framework of the `for` statement is:\n\n\n\nwhere `sequence` is some iterable object like a string, tuple, list, or array and `var` is a variable name that gets updated each time the loop repeats. The syntax of a `for` statement is similar to a function definition. It has a header that ends with a colon and an indented body. The body can contain any number of statements. This type of flow is called a loop because the third step loops back around to the top.\n\n
    \n
    \n

    Take Note

    \n
    \n
    \n

    Note 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

    \n
    \n
    \n\n
    \n
    \n

    More Information

    \n
    \n
    \n

    You can get more information about the `for` statement by executing `help(\"for\")` in a *Code Cell*

    \n
    \n
    \n\n\n```python\nhelp(\"for\")\n```\n\nConsider the following example:\n\n\n```python\nprint(\"Begin\")\nfor val in [20, 30, 10, 0]:\n print(\"val =\", val)\nprint(\"End\")\n```\n\nA `for` statement is also called a loop because the flow of execution runs through the body and then loops back to the top. Each time through the loop, the next number in the list is assigned to the variable name `val`. The loop continues until it has gone through all numbers in the list.\n\nThis example could also have be written as:\n\n\n```python\n%load_ext nbtutor\n```\n\n\n```python\n%%nbtutor -rf\nprint(\"Begin\")\nseq = [20, 30, 10, 0]\nfor val in seq:\n print(\"val =\", val)\nprint(\"End\")\n```\n\nExecute the *Code Cell* and step through the code execution line-by-line. Executing the *Code Cell* above does the following:\n- Line 2: Creates the objects `20`, `30`, `10`, and `0` in memory as well as a `list` object with the name `seq`.\n- Line 3: Steps through the objects in the list `seq` one at a time and assigns the name `val` to each object\n - The first time the loop executes `val` gets assigned to the first object in the list `seq`, which is `20`\n - The second time the loop executes `val` gets assigned to the second object in the list `seq`, which is `30`\n - The third time the loop executes `val` gets assigned to the third object in the list `seq`, which is `10`\n - Etc.\n - Once the loop has stepped through all objects in the list `seq` then the loop terminates\n- Line 4: Gets repeated for each object in the list `seq`\n \n\n## Indentation\n\nIndentation means the amount of white space placed in front of your code. *Python* uses 4 spaces as 1 indentation and it is this indentation that \"tells\" *Python* which statements must get repeated as they belong inside the `for` statement.\n\nConsider the following example:\n\n\n```python\nfor var in range(3):\n print(\"I’m inside the for loop\")\nprint(\"I’m outside the for loop\")\n```\n\nFrom this you should note that line 2 is executed 3 times and after the loop has terminated only then is line 3 executed. You should also note that the variable `var` is not used inside the loop. The variable `var` will still get assigned to each value in the list as the `for` statement iterates through the list. Place a `print` statement after line 1 to print out the variable `var` and verify this.\n\n
    \n
    \n

    Take Note

    \n
    \n
    \n

    Be very careful and aware of indentation when typing your programs, as this can sometimes lead to unexpected results and logic errors.

    \n

    There 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 !!!

    \n
    \n
    \n\n\n```python\nfoo = 0\nfor var in range(5):\n print(\"foo =\", foo)\n foo = foo + var\nprint(\"foo =\", foo)\n```\n\n\n```python\nfoo = 0\nfor var in range(5):\n print(\"foo =\", foo)\nfoo = foo + var\nprint(\"foo =\", foo)\n```\n\n
    \n
    \n

    More Information

    \n
    \n
    \n

    Most 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 !!

    \n
    \n
    \n\n## Examples\n\nMany of the examples that follow can be solved using lists and/or arrays alone without a `for` statement. I recommend, as a means of practice, trying to solve each of the following examples in as many different ways as you can.\n\n### Summing\n\nAs a first example let us create a function that computes the sum of the first `N` integers:\n\n$$\n \\sum^{N}_{k=1} k = 1 + 2 + 3 + \\dots + N\n$$\n\n\n```python\ndef sum_ints(N):\n summation = 0\n for term in range(1, N+1):\n summation = summation + term\n return summation\n```\n\n\n```python\nprint(sum_ints(100))\n```\n\nThe `range` object is used to create the sequence of terms from `1` up to (and including) `N`. The `for` statement is used to step through each term in this sequence. The `summation` variable is updated each time trough the loop by taking the current `summation` value plus the `term` value.\n\n### Taylor series\n\nA Taylor series is an approximation to any function using a series of polynomial terms. In the limit of using an infinite number of terms, the approximation is exact. Although a Taylor series does not intuitively require a `for` statement, it is useful to illustrate the `for` statement.\n\nA feature of a Taylor series approximation is that each new term contributes less to the function approximation than the terms before. So, at some point the additional Taylor terms don’t contribute much to the overall function value and we might as well stop adding additional terms. Therefore, when we use a computer to compute a function\nvalue using a Taylor series approximation, we will always use a finite number of terms.\n\nAs an example, the value of $\\pi$ can be computed from the following Taylor series:\n\n$$\n \\pi = 4 \\sum^{\\infty}_{k=0}\n \\frac{\n \\left( -1 \\right)^k\n }{\n 2k + 1\n } = 4 \\left[ \n 1 - \\frac{1}{3} + \\frac{1}{5} - \\frac{1}{7} + \\frac{1}{9} - \\dots\n \\right]\n$$\n\nSuppose that we want to write a function that approximates the value of $\\pi$ by using the above Taylor series and `N` number of terms:\n\n\n```python\ndef taylor_pi(N):\n pi = 0\n for k in range(N):\n term = (-1)**k / (2*k + 1)\n pi = pi + term\n return 4 * pi\n```\n\n\n```python\nimport numpy as np\n\npi = taylor_pi(100)\nprint(pi)\nprint(np.pi)\n```\n\nCompared to the true value of $\\pi = 3.14159\\dots$, the 1st 100 terms of this Taylor series approximation is only accurate to 2 digits. Note that since we start counting at $k = 0$, we only need to repeat the loop up to $k = 99$ to add up the first 100 terms. Also note that we must initialise the name `pi` to zero outside the `for` statement. If we do not do this, *Python* will produce an error message upon executing line 5 for the first time: we’re instructing *Python* to add the value $(-1)^k/(2k+1)$ to the name `pi` (whose value is unknown). If we did not assign zero to the name `pi` outside the `for` statement, we cannot expect *Python* to perform the required computation.\n\nIf we want to compute $\\pi$ more accurately, we have to sum more terms in this Taylor series. If we compute the sum of the first 1000 terms we get\n\n\n```python\nimport numpy as np\n\npi = taylor_pi(1000)\nprint(pi)\nprint(np.pi)\n```\n\nEven the first 1000 terms in the Taylor series produces an approximate value for $\\pi$ that is only accurate to 3 digits.\n\nBefore you decide that Taylor series approximations are of no use, consider the approximation to the exponential function:\n\n$$\ne^x = \\sum^{\\infty}_{k=0} \\frac{x^k}{k!}\n = 1 + x + \\frac{1}{2}x^2 + \\frac{1}{6}x^3 + \\dots\n$$\n\nLet us use this Taylor series approximation to compute the value of $e$ (i.e. compute $e^x$ for $x = 1$):\n\n\n```python\nimport numpy as np\n\n\ndef taylor_exp(x, N):\n exp = 0\n for k in range(N):\n exp = exp + x**k / np.math.factorial(k)\n return exp\n```\n\n\n```python\nimport numpy as np\n\ne = taylor_exp(1, 18)\nprint(e)\nprint(np.exp(1))\n```\n\nwhich is accurate to 15 decimals when only summing the first 18 terms. Here we have an example where a few terms in this Taylor series produces a very accurate approximation, whereas the 1000 term approximation to $\\pi$ was still inaccurate.\n\n### Factorial\n\nLet us create a function that computes the factorial of an integer:\n\n$$\nN! = \\prod_{k=1}^{N} k = 1 \\times 2 \\times 3 \\times \\dots \\times N\n$$\n\n\n```python\ndef factorial(N):\n prod = 1\n for term in range(1, N+1):\n prod = prod * term\n return prod\n```\n\n\n```python\nprint(factorial(10))\n```\n\nAgain the `range` object is used to create the sequence of terms from `1` up to (and including) `N` and the `for` statement is used to step through each term in this sequence. The `prod` variable is updated each time the loop execute by taking the current `prod` value times the `term` value.\n\nWould this function work if we initialize `prod = 0`? What would the result be?\n\n
    \n
    \n

    More Information

    \n
    \n
    \n

    Remember that you can use the `numpy.math.factorial(N)` function to verify the result of this example.

    \n
    \n
    \n\n### Fibonacci series\n\nA very famous series was proposed by the mathematician Fibonacci: The first two terms of the series are given by $L_0 = 0$ and $L_1 = 1$. Hereafter, each new term in the series is given by the sum of the previous two terms in the series:\n\n$$\n L_k = L_{k−1} + L_{k−2} \\qquad \\text{for} \\quad k = 2, 3, 4, \\dots\n$$\n\nUsing the above formula, the following sequence is generated: $0, 1, 1, 2, 3, 5, 8, 13, \\dots$\n\nLet us first do this problem step by step using *Python* as a calculator. Let us compute the fifth term ($k = 4$):\n\n\n```python\nL0 = 0\nL1 = 1\nL2 = L0 + L1\nL3 = L1 + L2\nL4 = L2 + L3\nprint(L4)\n```\n\nLet us pretend we are only interested in the fifth term ($k = 4$). The solution above requires five variables with five values. If we require the twentieth term ($k = 19$), we would have twenty variables using this approach.\n\nIn computing the next term we only need the previous two terms, which means we can get away with only using three variables regardless of how many terms we need to compute. Let us do that by shifting objects. The computed $k$ th term in the $k$ th iteration becomes the ($k − 1$) th term when we increment $k$ by 1. Similarly the ($k − 1$) th term becomes the ($k − 2$) th term. Let us rewrite the above code to use only three variables:\n\n\n```python\nprevious2 = 0\nprevious1 = 1\nnew = previous1 + previous2 # k = 2\n\nprevious2 = previous1\nprevious1 = new\nnew = previous1 + previous2 # k = 3\n\nprevious2 = previous1\nprevious1 = new\nnew = previous1 + previous2 # k = 4\n\nprint(new)\n```\n\nLet us see how we would go about computing the $N$ th term ($k = N$) of the Fibonacci series. We know how many terms we want to compute and we have a pattern of what we would like to repeat. So, let us compute the $N$ th term using the `for` statement:\n\n\n```python\ndef fibo(N):\n previous2 = 0\n previous1 = 1\n for k in range(2, N+1):\n new = previous1 + previous2\n # shift variables for next loop\n previous2 = previous1\n previous1 = new\n return new\n```\n\n\n```python\nprint(fibo(7))\n```\n\nIt is important to note that when we shift the objects we do it in such a way that we don’t end up with all names bound to the same object. We therefore start with the `previous2` name in line 7, since its current value was used to compute the current $k$ th Fibonacci term and it is not used to compute the next Fibonacci term.\nWe therefore bind the name term `previous2` to the same object bound by `previous1` and similarly we bind the name `previous1` to the same object bound by `new` that we just computed.\nNow we are ready to increment $k$ to compute the next term of the Fibonacci series. When $k$ is incremented, and the loop repeats, the name `new` will get bound to a new object resulting from `previous1 + previous2`.\n\nLet us go one step further and collect the Fibonacci terms into a list:\n\n\n```python\ndef fibo(N):\n previous2 = 0\n previous1 = 1\n store = [previous2, previous1]\n for k in range(2, N+1):\n new = previous1 + previous2\n store.append(new)\n # shift variables for next loop\n previous2 = previous1\n previous1 = new\n return store\n```\n\n\n```python\nprint(fibo(7))\n```\n\nIf it were required of us to store the Fibonacci terms in a list, from the beginning, then this list object and negative indexing makes the idea of taking the previous two terms and adding them together to get the next term a lot easier to follow:\n\n\n```python\ndef fibo(N):\n store = [0, 1]\n for k in range(2, N+1):\n new = store[-1] + store[-2] # add last two elements in store\n store.append(new)\n return store\n```\n\n\n```python\nprint(fibo(7))\n```\n\nTry modifiy this last example to use only positive indexing instead of negative indexing. You may need a new variable or would you be able to use `k`.\n\n## Looping with indices\n\nAgain consider the example of an object falling from a height above the ground.\nThe equations describing the motion of this object, assuming constant acceleration, are:\n\n$$ \n\\begin{align}\n a(t) &= g \\: \\text{(constant)} \\\\\n v(t) &= \\int a(t) \\: \\mathrm{d}t = v_0 + gt \\\\\n s(t) &= \\int v(t) \\: \\mathrm{d}t = s_0 + v_0t + 0.5 gt^2\n\\end{align}\n$$\n\nwhere $g$ is the gravitationaly acceleration $[m/s^2]$, $v_0$ the initial object velocity $[m/s]$, $s_0$ the initial object height $[m]$ above the ground, and $t$ is the time $[s]$.\n\nThe time it takes for this object to hit the ground ($t_e$) can be computed using:\n\n$$ t_e = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} $$\n\nwhere\n$$\n\\begin{align}\n a &= 0.5g = 0.5 (-9.81) \\\\\n b &= v_0 \\\\\n c &= s_0\n\\end{align}\n$$\n\nLet us calculate $t_e$ for the following initial values:\n\n- $s_0=100$ and $v_0 = 50$\n- $s_0=200$ and $v_0 = 40$\n- $s_0=300$ and $v_0 = 30$\n- $s_0=400$ and $v_0 = 20$\n- $s_0=500$ and $v_0 = 10$\n\n\n```python\ndef end_time(s0, v0):\n a = -0.5 * 9.81\n b, c = v0, s0\n return (-b - (b**2 - 4*a*c)**0.5) / (2*a)\n```\n\n\n```python\n# 0 1 2 3 4\ns0 = [100, 200, 300, 400, 500]\nv0 = [ 50, 40, 30, 20, 10]\n\nfor i in range(5):\n te = end_time(s0[i], v0[i])\n print(i, s0[i], v0[i], te)\n```\n\nYou should note in this example we need to repeat the computation of $t_e$ 5 times, once for each pair of initial values. The `range` object is used to create the sequence of index numbers from `0` up to `4` in increments of `1` and the `for` statement is used to step through this sequence one index at a time. The loop starts with `i` equal to `0` and ends with `i` equal to `4`. The `s0` and `v0` lists are indexed with `i` so when `i` is `0`, for example, this indexing yields `100` and `50` respectively.\n\n## Nested loops\n\nLet us now calculate $t_e$ for the following initial values:\n\n- $s_0=100$ and $v_0 = [10, 20, 30, 40]$\n- $s_0=200$ and $v_0 = [10, 20, 30, 40]$\n- $s_0=300$ and $v_0 = [10, 20, 30, 40]$\n\nNotice that $v_0$ repeats for each $s_0$ value (4 $v_0$ values for each $s_0$ value) and in total there should be 12 solutions for $t_e$\n\n\n```python\ns0 = [100, 200, 300]\nv0 = [10, 20, 30, 40]\n\nfor s in s0:\n print(\"Start Inner\")\n for v in v0:\n te = end_time(s, v)\n print(s, v, te)\n print(\"End Inner\")\n```\n\nYou should note that the outer loop (lines 4 through 9) repeats 3 times (once for each value in `s0`), which means the inner loop (lines 6 through 8) repeats $4 \\times 3 = 12$ times (once for each value in `v0` repeated for each value in `s0`).\n\n
    \n
    \n

    Take Note

    \n
    \n
    \n

    Notice 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.

    \n

    Make sure you understand the behaviour and output of the following three examples and why they are different!!

    \n
    \n
    \n\n\n```python\na = 0.0\nfor i in range(10):\n a += 10 * 1\n for j in range(5):\n a /= 2\n a *= 10\nprint(\"a = \", a)\n```\n\n\n```python\na = 0.0\nfor i in range(10):\n a += 10 * 1\n for j in range(5):\n a /= 2\n a *= 10\nprint(\"a = \", a)\n```\n\n\n```python\na = 0.0\nfor i in range(10):\n a += 10 * 1\nfor j in range(5):\n a /= 2\na *= 10\nprint(\"a = \", a)\n```\n\n## Debugging\n\n\nAs you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more places for bugs to hide.\n\nOne way to cut your debugging time is “debugging by bisection”. For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps.\n\nInstead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a print statement (or something else that has a verifiable effect) and run the program.\n\nIf the mid-point check is incorrect, there must be a problem in the first half of the program. If it is correct, the problem is in the second half.\n\nEvery time you perform a check like this, you halve the number of lines you have to search. After six steps (which is fewer than 100), you would be down to one or two lines of code, at least in theory.\n\nIn practice it is not always clear what the “middle of the program” is and not always possible to check it. It doesn’t make sense to count lines and find the exact midpoint. Instead, think about places in the program where there might be errors and places where it is easy to put a check. Then choose a spot where you think the chances are about the same that the bug is before or after the check.\n\nWhen you use indices to traverse the values in a sequence, it is tricky to get the beginning and end of the traversal right. Here is a function that is supposed to compare two words and return True if one of the words is the reverse of the other, but it contains one error:\n\n\n```python\ndef is_reversed(one, two):\n check = []\n j = len(two)\n for i in range(len(one)):\n check.append(one[i] == two[j])\n j = j-1\n return all(check)\n```\n\n`i` and `j` are indices: `i` traverses `one` forward while `j` traverses `two` backward. If we find two numbers that match we append `True` else we append `False` to the list `check`. The `all` function is used to return `True` if all entries in `check` are `True` else it will return `False`.\n\nIf we test this function with the lists `[1, 2, 3, 4]` and `[4, 3, 2, 1]`, we expect the return value `True` but we get an `IndexError`:\n\n\n```python\nis_reversed([1, 2, 3, 4], [4, 3, 2, 1])\n```\n\nFor debugging this kind of error, my first move is to print the values of the indices immediately before the line where the error appears.\n\n\n```python\ndef is_reversed(one, two):\n check = []\n j = len(two)\n for i in range(len(one)):\n print(i, j)\n check.append(one[i] == two[j])\n j = j-1\n return all(check)\n```\n\nNow when I run the program again, I get more information:\n\n\n```python\nis_reversed([1, 2, 3, 4], [4, 3, 2, 1])\n```\n\nThe first time through the loop, the value of `j` is 4, which is out of range for the list `two`. The index of the last number is `3`, so the initial value for `j` should be `len(two) - 1`.\n\nIf I fix that error and run the program again, I get:\n\n\n```python\ndef is_reversed(one, two):\n check = []\n j = len(two) - 1\n for i in range(len(one)):\n print(i, j)\n check.append(one[i] == two[j])\n j = j-1\n return all(check)\n```\n\n\n```python\nis_reversed([1, 2, 3, 4], [4, 3, 2, 1])\n```\n\nThis time we get the right answer\n\n## Glossary\n\n**decrement**: An update that decreases the value of a variable.\n\n**increment**: An update that increases the value of a variable (often by one).\n\n**index**: An integer value used to select an item in a sequence, such as a number in a list. In *Python* indices start from 0.\n\n**initialization**: An assignment that gives an initial value to a variable that will be updated.\n\n**iteration**: Repeated execution of a set of statements using either a recursive function call or a loop.\n\n**reassignment**: Assigning a new value to a variable that already exists.\n\n**sequence**: An ordered collection of objects where each value is identified by an integer index.\n\n**traverse**: To iterate through the items in a sequence, performing a similar operation on each.\n\n**update**: An assignment where the new value of the variable depends on the old.\n\n## Exercises\n\nMany of the exercises that follow can be solved using lists and/or arrays alone without a `for` statement. Again I recommend, as a means of practice, trying to solve each of the following exercises in as many different ways as you can.\n\n1) Write a function (called `add`) that takes two positive integers as input. This function must multiply the two positive integers by using the addition (`+`) operator. Use the multiplication (`*`) operator only to verify your answer. Recall that you can write\n\n$$\n 7\\times4 =\n 7 + 7 + 7 + 7 =\n 4 + 4 + 4 + 4 + 4 + 4 + 4\n$$\n\n2) Write a function (called `die_throws`) that takes a positive integer `N` as input. This function must simulate the throwing of a die `N` times and must return a list of the `N` die values.\n\n*Hint*: You can use `np.random.randint` to generate a random integer between 1 to 6.\n\n3) An alternating series is a series where the terms alternate signs. Write a function that takes a positive integer `N` as input. This function must return the sum of the first `N` terms of the following series:\n\n$$\n\\sum^{100}_{n=1} (-1)^{n+1} \\frac{1}{n} = 1 - \\frac{1}{2} + \\frac{1}{3} - \\frac{1}{4} + \\dots - \\frac{1}{100}\n$$\n\n4) Find the pattern of the following series. Write a function that takes a positive integer `N` as input. This function must return the sum of the first `N` terms of the following series:\n\n$$\n1 + \\frac{1}{2} - \\frac{1}{4} + \\frac{1}{8} - \\frac{1}{16} + \\frac{1}{32} - \\dots\n$$\n\n5) The Basel problem was first posed by Pietro Mengoli in 1644 and was solved by Leonhard Euler in 1735 which brought Leonhard Euler immediate fame at the age of 28. Euler showed that the sequence\n\n$$\n1 + \\frac{1}{4} + \\frac{1}{9} + \\frac{1}{16} + \\frac{1}{25} + \\frac{1}{36} + \\dots\n$$\n\nconverges to $\\pi^2/6$. Write a function that takes a positive integer `N` as input. This function must return the sum of the first `N` terms of this series. Compare the accuracy to $\\pi^2/6$ for different inputs of `N`.\n\n6) A very famous series was proposed by the mathematician Fibonacci: The first two terms of the series are given by $L_0 = 0$ and $L_1 = 1$. Hereafter, each new term in the series is given by the sum of the previous two terms in the series i.e.\n\n$$\nL_k = L_{k-2} + L_{k-1} \\qquad \\text{for} \\quad k = 2, 3, 4, \\dots\n$$\n\nUsing the above formula, the following sequence is generated: $0, 1, 1, 2, 3, 5, 8, 13, \\dots$\nWrite a program that computes the first 20 terms of the Fibonacci sequence and displays it on the screen.\n\n7) The sine function can be approximated by the following infinite series:\n\n$$\n\\sin(x) = x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\dots\n$$\n\nWrite a function (called `sine`) that takes `x` and a positive integer `N` as input. This function must return the sum of the first `N` terms of this series. Compare the accuracy of the output for different inputs of `N`.\n\n8) The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of $1/\\pi$:\n\n$$\n\\frac{1}{\\pi} = \\frac{2\\sqrt{2}}{9801} \\sum_{k=0}^{\\infty} \\frac{\\left(4k\\right)!\\left(1103 + 26390k\\right)}{\\left(k!\\right)^4 396^{4k}}\n$$\n\nWrite a function (called `estimate_pi`) that takes a positive integer `N` as input. This function must return the sum of the first `N` terms of this series. Compare the accuracy of the output for different inputs of `N`.\n\n9) Write a function (called `cum_sum`) that takes a list (of positive numbers) as input. This function must return the cumulative sum of values from the input list. For example if `[1, 2, 3, 4, 5]` is given as input, the `cum_sum` function should return `[1, 3, 6, 10, 15]`.\n\n10) Write a function (called `sum_pairs`) that takes a list (of positive numbers) as input. This function should return the sum of consecutive pairs of numbers from the input list. For example if `[1, 2, 3, 4, 5]` is give as input, this `sum_pairs` function should return `[3, 5, 7, 9]`.\n\n11) The wind chill factor (WCF) indicates the perceived air temperature to exposed skin and is given by:\n\n$$\nWCF = 13.12 + 0.6215 T_a - 11.37 v^{0.16} + 0.3965 T_a v^{0.16}\n$$\n\nwhere $T_a$ the air temperature in degrees Celcius and $v$ the air speed in $km/h$.\n\nWrite a program that displays a collection of WCF’s using nested for loop statements. The temperature ($T_a$) must range from `-20` to `55` degrees Celcius in steps of `5` and wind speed ($v$) must range from `0` to `100` $km/h$ in increments of `10`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "f82b531b788c6786494b5ffb62ade70e3e3d4f1d", "size": 40711, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/Chapter06_For_Loop.ipynb", "max_stars_repo_name": "lgpage/solve-it-with-python", "max_stars_repo_head_hexsha": "05e1f31ed3d114d55d3c10196555a2b8c2888ebe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "book/Chapter06_For_Loop.ipynb", "max_issues_repo_name": "lgpage/solve-it-with-python", "max_issues_repo_head_hexsha": "05e1f31ed3d114d55d3c10196555a2b8c2888ebe", "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": "book/Chapter06_For_Loop.ipynb", "max_forks_repo_name": "lgpage/solve-it-with-python", "max_forks_repo_head_hexsha": "05e1f31ed3d114d55d3c10196555a2b8c2888ebe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6732837055, "max_line_length": 696, "alphanum_fraction": 0.5667018742, "converted": true, "num_tokens": 7733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020279, "lm_q2_score": 0.2814056074291439, "lm_q1q2_score": 0.06978505231591428}} {"text": "# Predicting water solubility - Part II?\n\n> Feature selection\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [fastpages, jupyter]\n- image: images/fruit.jpg\n\n# Requirements\n\n - rdkit >= 2020.09.1\n - pandas >= 1.1.3\n - seaborn\n - matplotlib\n - fastcore (!conda install fastcore)\n\n\nIn this tutorial we'll use a dataset compiled by [Sorkun et al (2019)](https://www.nature.com/articles/s41597-019-0151-1) from multiple projects to predict water solubility. You can download the original dataset from [here](https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/OVHAW8).\n\n> ```At the end of the notebook I added a class to process the original dataset in order to remove salts, mixtures, neutralize charges and generate canonical SMILES. I highly recommend checking each structure before modeling. ```\n\nIn this notebook we'll cover three main topics:\n\n - **Featurization of molecules**\n - **What's the correlation between features?**\n - **Feature selection methods**\n\n# Background\n\nDrug solubility is a critical factor in drug development. If a drug is not soluble enough or doesn't dissolve readily its intestinal absoption will be compromised, leading to low concentration in the blood circulation and reduced (or none) biological activity. \n\nCrystal formation of low soluble drugs may also lead to toxicity. In practical terms, poor solubility is one of the factors that lead to fail in drug discovery projects. Therefore, medicinal chemists work hard to design molecules tha have the intended bioactivity and that can display the desired effect in vivo. \n\nDespite being conceptually easy to understand solubility, its estimation isn't easy. That's because the intrinsic solubility of a molecule depends on many factors, including its size, shape, the ability to make intermolecular interactions and crystal packing.\n\n# Import modules\n\n\n```python\n#collapse\n%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\nfrom IPython.display import Image\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FormatStrFormatter\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import Normalizer, normalize, RobustScaler\nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost import XGBRegressor\nfrom sklearn.metrics import make_scorer, mean_squared_error\n\nfrom sklearn.feature_selection import mutual_info_regression, RFECV,SelectFromModel,RFE,VarianceThreshold\nfrom functools import partial\nfrom pathlib import Path\nfrom joblib import load, dump\n\nfrom scipy import stats\nfrom scipy.stats import norm\nfrom statsmodels.graphics.gofplots import qqplot\nfrom rdkit.Chem import Draw\nfrom rdkit.Chem import MolFromSmiles, MolToSmiles\n\nfrom descriptastorus.descriptors.DescriptorGenerator import MakeGenerator\n\n```\n\n WARNING:root:No normalization for BCUT2D_MWHI\n WARNING:root:No normalization for BCUT2D_MWLOW\n WARNING:root:No normalization for BCUT2D_CHGHI\n WARNING:root:No normalization for BCUT2D_CHGLO\n WARNING:root:No normalization for BCUT2D_LOGPHI\n WARNING:root:No normalization for BCUT2D_LOGPLOW\n WARNING:root:No normalization for BCUT2D_MRHI\n WARNING:root:No normalization for BCUT2D_MRLOW\n\n\n\n```python\nnp.random.seed(5)\n```\n\n\n```python\nsns.set(rc={'figure.figsize': (16, 16)})\nsns.set_style('whitegrid')\nsns.set_context('paper',font_scale=1.5)\n```\n\n# Load Data\n\nLet's load the dataset without outliers from the last [post](https://marcossantanaioc.github.io/fiocruzcheminformatics/jupyter/2021/05/31/third.html).\n\n\n```python\ndata = pd.read_csv('../_data/water_solubility_nooutliers.csv')\n```\n\n\n```python\n#collapse_output\ndata.head()\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 \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 \n \n \n \n \n \n \n \n \n
    IDNameInChIInChIKeySMILESSolubilitySDOcurrencesGroupMolWt...NumAromaticRingsNumSaturatedRingsNumAliphaticRingsRingCountTPSALabuteASABalabanJBertzCTprocessed_smilesclass
    0A-3N,N,N-trimethyloctadecan-1-aminium bromideInChI=1S/C21H46N.BrH/c1-5-6-7-8-9-10-11-12-13-...SZEMGTQCPRNXEG-UHFFFAOYSA-M[Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C-3.6161270.01G1392.510...0.00.00.00.00.00158.5206010.000000210.377334CCCCCCCCCCCCCCCCCC[N+](C)(C)Cslightly soluble
    1A-4Benzo[cd]indol-2(1H)-oneInChI=1S/C11H7NO/c13-11-8-5-1-3-7-4-2-6-9(12-1...GPYLCFQEKPUWLD-UHFFFAOYSA-NO=C1Nc2cccc3cccc1c23-3.2547670.01G1169.183...2.00.01.03.029.1075.1835632.582996511.229248O=C1Nc2cccc3cccc1c23slightly soluble
    2A-54-chlorobenzaldehydeInChI=1S/C7H5ClO/c8-7-3-1-6(5-9)2-4-7/h1-5HAVPYQKSLYISFPO-UHFFFAOYSA-NClc1ccc(C=O)cc1-2.1770780.01G1140.569...1.00.00.01.017.0758.2611343.009782202.661065O=Cc1ccc(Cl)cc1slightly soluble
    3A-10vinyltolueneInChI=1S/C9H10/c1-3-9-6-4-5-8(2)7-9/h3-7H,1H2,2H3JZHGRUMIRATHIU-UHFFFAOYSA-NCc1cccc(C=C)c1-3.1231500.01G1118.179...1.00.00.01.00.0055.8366263.070761211.033225C=Cc1cccc(C)c1slightly soluble
    4A-113-(3-ethylcyclopentyl)propanoic acidInChI=1S/C10H18O2/c1-2-8-3-4-9(7-8)5-6-10(11)1...WVRFSLWCFASCIS-UHFFFAOYSA-NCCC1CCC(CCC(O)=O)C1-3.2861160.01G1170.252...0.01.01.01.037.3073.9736552.145839153.917569CCC1CCC(CCC(=O)O)C1slightly soluble
    \n

    5 rows × 28 columns

    \n
    \n\n\n\n# Featurization\n\nIn this dataset 17 features were already calculated for each molecule. These features include a range of physichochemical properties (e.g. MolWt, MolLogP and MolMR), atomic counts (e.g. HeavyAtomCount, NumHDonors and Acceptors) and more abstract topological descriptors (e.g. BalabanJ, BertzCT).\n\n\n```python\ndescriptors = ['MolWt', 'MolLogP', 'MolMR', 'HeavyAtomCount',\n 'NumHAcceptors', 'NumHDonors', 'NumHeteroatoms', 'NumRotatableBonds',\n 'NumValenceElectrons', 'NumAromaticRings', 'NumSaturatedRings',\n 'NumAliphaticRings', 'RingCount', 'TPSA', 'LabuteASA', 'BalabanJ',\n 'BertzCT']\n\nvar = ['Solubility']+ descriptors \n```\n\n\n```python\nprint(len(descriptors))\n```\n\n 17\n\n\nWe can check the correlation between each feature and solubility using seaborn's regplot:\n\n\n```python\nnr_rows = 6\nnr_cols = 3\ntarget = 'Solubility'\n```\n\n\n```python\n#hide_input\nfig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*3.5,nr_rows*3))\n\nfor r in range(0,nr_rows):\n \n for c in range(0,nr_cols): \n i = r*nr_cols+c\n \n if i < len(descriptors):\n \n sns.regplot(x=data[descriptors[i]], y=data[target], ax = axs[r][c])\n \n stp = stats.pearsonr(data[descriptors[i]], data[target])\n\n str_title = \"r = \" + \"{0:.2f}\".format(stp[0]) + \" \" \"p = \" + \"{0:.2f}\".format(stp[1])\n axs[r][c].set_title(str_title,fontsize=11)\nfig.delaxes(axs[-1,-1]) #The indexing is zero-based here \nplt.tight_layout() \nplt.show() \n```\n\nMost features have a negative correlation with solubility. In fact, the available features reflect more or less the size/complexity of the molecule (e.g. MolWt, RingCount, MolMR) and it's capacity to make inter and intramolecular interactions (e.g., NumValenceElectrons, NumHAcceptors, NumHDonors, MolLogP), which are known to influence water solubility. For instance, bigger molecules tend to be less soluble in water (high MolMW and HeavyAtomCount); the same applies for very liphophilic (high MolLogP) molecules. On the other hand, more polar molecules, capable of making hydrogen bonds with water, are usually more soluble. \n\nBased on this preliminary analysis we can start thinking which features to include when training a regression model. For instance, molecular weight and liphophilicity are the features most correlated with the target variable. These features have a strong influence in solubility as demonstrated experimentally and by theorical calculations. As the molecular size and liphophilicity grows, its much harder to dissolve a molecule in water because the solute needs to disrupt a great number interactions within solvent molecules and force its way into bulk water, which demands a great amount of energy. The [influence of lipophilicity](https://pubs.acs.org/doi/10.1021/jo01265a071) is so well known that its part of many predictive models, such as the famous [ESOL (estimated solubility)](https://pubs.acs.org/doi/10.1021/ci034243x), which estimates water solubility based only on the molecular structure. \n\n```Back in the day (2003!) the author of ESOL didn't even use the robust machine learning algorithms we have today to derive the following equation:```\n\n$$logS_{w} = 0.16 - 0.63logP - 0.0062MolWt + 0.066Rot - -0.74AP$$\n\nwhere $logS_{w}$ is the log of the water solubility, $logP$ is the lipophilicity, $MolWt$ is the molecular weight, $Rot$ is the number of rotatable bonds (e.g. single bonds) and $AP$ is the proportion of heavy atoms that are part of aromatic rings. \n\n# Understanding the features\n\nLet's take a look at what those features mean. \n\n## 1) LogP\n\n\nThe logP is the partition coefficient given by:\n\n$$logP = \\frac{C_{n-octanol}}{C_{water}}$$\n\nwhere $C_{n-octanol}$ and $C_{water}$ are the solute concentration in n-octanol and water, respectively. Thus, higher logP means that a smaller concentration of the molecule is available in the water phase of a system, which makes it more lipophilic or hydrophobic. \n\n## 2) Molecular weight\n\nMolecular weight (MolWt) is simply the total mass of a [mole](https://en.wikipedia.org/wiki/Mole_(unit)) of a compound. The MolWt can be calculated by the summing the mass contribution of each atom in a molecule. For example, the molar weight of water is:\n\n$$H_{2}O = 2H * (1.01 g/mol) + 1O * (16 g/mol) = 18.01 g/mol$$\n\n## 3) Molar refractivity\n\nMolar refractivity (MolMR) is the [refractivity](https://en.wikipedia.org/wiki/Molar_refractivity) of a mole of a substance and is a measure of polarizability. It's given by the formula:\n\n$$MolMR = \\frac{n^{2}-1}{n^{2}+2}*\\frac{MolWt}{d}$$\n\nwhere $MolWt$ is the molar weight, $d$ is the density and $n$ is the refractivity index. The right hand side of the equation ($\\frac{MolWt}{d}$) is the volume. Thus, the molar refractivity encodes the molecular volume and is a way to estimate the steric bulk. \n\n## 4) Topological polar surface area (TPSA) and LabuteASA\n\n\n - **TPSA**: The polar surface area is the sum of the surfaces of polar atoms in a molecule, such as oxygen and nitrogen, and sometimes sulphur and its hydrogen. The total polar surface area is a useful feature to encode both the polarity and the hydrogen bonding capacity of a molecule. \n \n\n - [**LabuteASA**](https://www.sciencedirect.com/science/article/abs/pii/S1093326300000681): the accessible surface area (ASA) is the area of a molecule that is accessible to the solvent (e.g. water). The ASA is calculated by summing the surface area of each atom in a molecule. We can also think about ASA as the area a water molecule can touch as we roll it on the surface of the solute.\n\n \n\n**Figure 1**. Representation of the polar surface area, showing the contributions of each polar atom in the molecule.\n\n \n\n**Figure 2**. Representation of the polar surface area, showing the contributions of each polar atom in the molecule.\n\n## 5) Atomic counts\n\nAtomics counts represent how many times an atom or group appears in a molecule. Its possible to count specific substructures (e.g. number of aromatic rings), atoms and atoms types, hydrogen bond donors and acceptors etc. \n\n## 6) Topological descriptors\n\nTopological descriptors in this dataset include [BalabanJ](http://publications.iupac.org/pac/55/2/0199/index.html) and BertzCT and represent more abstract definition of a molecule. For the BalabanJ, the feature value is calculated from the distance matrix, a n x n matrix where n is the number of atoms and the entries represent the distances between each atom in the molecular graph. The BalabanJ descriptor can thus capture topological information such as branching, distance between substructures and the molecular size. \nThe BertzCT descriptor encodes the molecular complexity by taking into account bond connectivity and atom types.\n\n**Now let's get to work!**\n\n# In depth analysis of feature correlation\n\nFirst, let's calculate the Pearson's R coefficient for each pair of features and visualize the results using a heatmap. \n\nThe largest diagonal corresponds to self correlation for each feature (e.g. MolWt x MolWt), and is always 1. The most interesting part are the other values, showing the correlation between each pair of features and target variable. \n\nAs we can see from the heatmap, some features have a high negative linear correlation with solubility, such as MolWt (-0.61), LabuteASA (-0.62), MolLogP (-0.78) and MolMR (-0.64), HeavyAtomCount (-0.57).\n\nWe can also investigate the correlations between features. For the BalabanJ descriptor, the highest correlation was with RingCount (-0.64). For BertzCT, the highest correlations were with features that encode the molecular complexity/size, such as molecular weight, molar refractivity and number of heavy atoms, which is consistent with its definition. \n\n\n```python\ncorr = data[var].corr('pearson')\n```\n\n\n```python\n#collapse_output\nsns.heatmap(corr, annot=True)\n```\n\nWe can also see that the number of hydrogen bond donors have a weak positive correlation with solubility, while the number of H-bond acceptors have a very weak negative correlation. This is interesting because it shows us that increasing the H-bond potential might not be the best strategy to increase solubility. \n\nIn general, [increasing H-bond donors and acceptors also increases solubility](https://www.sciencedirect.com/science/article/abs/pii/S0022354915508666) because it alters the capacity to make H-bonds with water molecules. However, if the molecule can both donate and accept H-bonds, a decrease in solubility might happen due to intermolecular interactions between molecules of the same kind, leading to reduced ability to be solvated by water molecules. \nThe intuition is that a molecule needs to make better interactions with water than with others of its kind, otherwise it will be poorly solvated.\n\nTo summarize this initial analysis, the heatmap give us an idea of what types of features to include in a model. If we were to cherry pick, features like **MolLogP**, **MolMR** and **LabuteASA** would probably be selected. In addition, we must avoid highly correlated features (i.e. that encode the same kind of information) because that would only make our model more complex without any benefit in performance. \n\n\nBut no need to rush! We'll systematically check each feature for better correlations with the target variable and with each other. Remember that our goal is to develop a model with high predictive power, and to do that we need to select the right set of features. \n\n# Training a baseline model\n\nBefore we dive into feature selection, let's try a baseline model and see how it performs when training using all features. For this task, we will use the Random Forest algorithm. First, split the data into training and testing sets.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\ntrainset, testset = train_test_split(data, test_size = 0.30, random_state=42)\n```\n\nSince our features are in different scales, let's normalize them to have zero mean and unit std. This is an important step so that one feature with large std doesn't dominate the others during training, which could lead to overfitting.\n\n> Random forest is robust to the scale of features so this step isn't necessary in this case. We will normalize anyway because it's best practice, especially in models that depends on coefficients and intercepts (e.g. linear regression). \n\n\n```python\nxtrain, xtest = trainset[descriptors].values, testset[descriptors].values\nytrain, ytest = trainset['Solubility'].values, testset['Solubility'].values\n```\n\nWe will do the preprocessing in a more compact way by using sklearn pipeline, which will contain the preprocessing steps and a fit call to the training algorithm.\n\n\n```python\nfrom sklearn.pipeline import Pipeline\n```\n\n\n```python\npipe = Pipeline(steps=[\n ('scaler',RobustScaler()), \n ('estimator', RandomForestRegressor(n_estimators=2000, n_jobs=-1))\n ]\n )\n```\n\nWe will validate our model using 5-fold cross-validation. \n\n\n```python\nfrom sklearn.model_selection import cross_val_score\n```\n\n\n```python\nmetric = make_scorer(mean_squared_error, squared=False) # RMSE\ncross_score = cross_val_score(estimator=pipe, X=xtrain,scoring=metric, y=ytrain, cv=5, n_jobs=-1)\n```\n\n\n```python\nprint(f'Mean 5-fold RMSE = {cross_score.mean():.4f}')\n```\n\n Mean 5-fold RMSE = 0.9983\n\n\nNow the test set:\n\n\n```python\npipe.fit(xtrain,ytrain)\n```\n\n\n\n\n Pipeline(steps=[('scaler', RobustScaler()),\n ('estimator',\n RandomForestRegressor(n_estimators=2000, n_jobs=-1))])\n\n\n\n\n```python\ndef get_preds(estimator, x):\n preds = estimator.predict(x)\n return preds\n```\n\n\n```python\npreds = pipe.predict(xtest)\n```\n\n\n```python\nprint(f'RMSE test set = {mean_squared_error(preds, ytest, squared=False):.3f}')\n```\n\n RMSE test set = 0.963\n\n\nNot bad! This is our baseline. Let's see if we can beat it or simplify our data a little bit without compromising performance. \n\n### The perils of non-informative features\n\nWhat happens if we only have non-informative features in the dataset? What performance could we expect? Intuitively, one would say RMSE >> 0. Let's test that by randomizing the rows of the target variable vector, which will make every feature **non-informative**. \n\n\n```python\nyrandom = np.random.choice(ytrain,ytrain.shape[0])\n```\n\n\n```python\nyrandom.shape,ytrain.shape\n```\n\n\n\n\n ((5967,), (5967,))\n\n\n\n\n```python\nyrandom, ytrain\n```\n\n\n\n\n (array([-1.7 , 1.00830886, -4.45042772, ..., -2.56313048,\n -1.063 , -2.7813 ]),\n array([-5.05611784, -1.02322129, -8.7546501 , ..., -0.7956 ,\n -1.11610783, -4.561 ]))\n\n\n\n\n```python\npipe.fit(xtrain,yrandom)\npreds_random = pipe.predict(xtest)\n```\n\n\n```python\nprint(f'RMSE (randomized target) test set = {mean_squared_error(preds_random, ytest, squared=False)}')\n```\n\n RMSE (randomized target) test set = 2.3878056084158237\n\n\nAs you can see, the RMSE on the test set does increase. In a data set with dozens or even hundreds of features, which is relatively common in QSAR applications, we would expect much higher errors. That's why it's so important to analyze your features carefully in order to remove anything that could hamper performance, including missing or constant values and highly correlated features. \n\n# Feature selection\n\nIn our solubility dataset we have 17 features but we could have more. There are hundreds of molecular descriptors available in literature. So, how does one select the best set of features to include in a model? Let's investigate some feature selection methods!\n\n## 1) Filter methods\n\n\nFilter methods are the easiest to implement because they are model-agnostic, which means we don't need any fancy learning algorithm. This class of methods consists of statistical approaches that use the distribution of the dataset to remove features that don't have much information or correlation with the target variable. Since we don't need a model, filter methods are very fast and can give an initial guess of what types of features to keep. \n\nDespite being fast, filter methods also come with some dangerous drawbacks. Since most methods are **univariate**, important correlations between features may be missed; or worse redudant features could be selected. In addition, most metrics (e.g. Pearson's correlation coefficient) used to select the features are subjective and not always correlate with the metric that will be used to access performance.\n\n> While filter methods tend to be simple and fast, there is a subjective nature to the procedure. Most scoring methods have no obvious cut point to declare which predictors are important enough to go into the model. Even in the case of statistical hypothesis tests, the user must still select the confidence level to apply to the results. In practice, finding an appropriate value for the confidence value α may require several evaluations until acceptable performance is achieved\n \n> ```Applied Predictive Modeling, p.499.```\n\n### 1.1) Basic approaches\n\nBasic approaches are purely statistical and consits of removing constant or quasi-constant features from the dataset. \n\n#### 1.1.1) Remove constant features using variance threshold\n\nThe first method we will use consists of removing constant or quasi-constant features. In this situation, all samples have the same value or almost the same. The intuition to remove this kind of feature is that it doesn't add any useful information to training because most values are not present or are repeated; so we can't differentiate between data points. \n\n\n```python\nfrom sklearn.feature_selection import VarianceThreshold, mutual_info_regression\n```\n\n\n```python\nselector = VarianceThreshold()\n```\n\n\n```python\nscaler = RobustScaler()\nxnorm = scaler.fit(xtrain).transform(xtrain)\n\n```\n\n\n```python\nreducer = VarianceThreshold()\nreducer.fit(xnorm)\n```\n\n\n\n\n VarianceThreshold()\n\n\n\nWe can get the final number of features by using the ```get_support``` method from a fitted reducer. \n\n\n```python\nsum(reducer.get_support())\n```\n\n\n\n\n 17\n\n\n\nWell, it seems we don't have any feature with 0 variance. That's a good thing! But what about features with less than 1% variance?\n\n\n```python\nreducer = VarianceThreshold(threshold=0.01)\nreducer.fit(xnorm)\n```\n\n\n\n\n VarianceThreshold(threshold=0.01)\n\n\n\n\n```python\nsum(reducer.get_support())\n```\n\n\n\n\n 17\n\n\n\nAgain no feature was removed. That's a good start. You can play around with different threshold values depending on the dataset.\n\nLet's try more robust methods!\n\n### 1.2) Univariate selection methods\n\n#### Mutual information\n\n[Mutual information](https://thuijskens.github.io/2017/10/07/feature-selection/) is a *linear* approach that quantifies the amount of information obtained about one random variable using another random variable. The mutual information is given by:\n\n$$\n\\begin{align}\nI(X; Y) = \\int_X \\int_Y p(x, y) \\log \\frac{p(x, y)}{p(x) p(y)} dx dy\n\\end{align}\n$$\n\nIf the joint distribution $p(x,y)$ of variables $X$ and $Y$ equals the individual probabilities $p(x)$ and $p(y)$, the variables are considered independent and the integral is 0. Therefore, our goal is to find variables that are somehow correlated with the dependent variable logS that with maximum information content. \n\n\n```python\nfrom sklearn.feature_selection import mutual_info_regression\n```\n\n\n```python\nimportances = mutual_info_regression(xtrain, ytrain)\n```\n\n\n```python\ndf_importances = pd.DataFrame(importances,index=descriptors)\n```\n\n\n```python\ndf_importances.sort_values(0,ascending=False).head(5)\n```\n\n\n\n\n
    \n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    0
    MolLogP0.618195
    MolWt0.451355
    MolMR0.444390
    LabuteASA0.423057
    NumValenceElectrons0.366864
    \n
    \n\n\n\nIt seems that the top-5 most important features makes sense; as mentioned before logP and the molecular weight are important parameters to estimate water solubility. LabuteASA and NumValenceElectrons are also good estimates of the molecular shape and complexity. In fact, the top-5 features are what we expect based on the Pearson's R heatmap! That's very good, we can see the feature selection methods are showing some consistence and now we are bit more confident that we should include logP and some feature that encode structural information about the molecules. \n\nFor the bottom 5 features we can see that the are mostly related to atomic or fragment counts, which does tells us something about the structure but are not determinant for solubility per se.\n\n\n```python\ndf_importances.sort_values(0,ascending=False).tail(5)\n```\n\n\n\n\n
    \n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    0
    NumRotatableBonds0.080012
    NumHeteroatoms0.070472
    NumHDonors0.059317
    NumAliphaticRings0.024100
    NumSaturatedRings0.019100
    \n
    \n\n\n\nWe can also use the mutual information as metric in the sklearn [SelectKBest](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html#sklearn.feature_selection.SelectKBest) class.\n\n\n```python\nfrom sklearn.feature_selection import SelectKBest\n```\n\n\n```python\nkbest = SelectKBest(score_func=mutual_info_regression)\nxkbest = kbest.fit_transform(xtrain, ytrain)\n```\n\nThe ```get_support``` method returns a bool array that we can use to index the list of descriptors. \n\n\n```python\nnp.array(descriptors)[kbest.get_support()]\n```\n\n\n\n\n array(['MolWt', 'MolLogP', 'MolMR', 'HeavyAtomCount',\n 'NumValenceElectrons', 'NumAromaticRings', 'RingCount',\n 'LabuteASA', 'BalabanJ', 'BertzCT'], dtype=' Wrapper methods evaluate multiple models using procedures that add and/or remove predictors to find the optimal combination that maximizes model performance. In essence, wrapper methods are search algorithms that treat the predictors as the inputs and utilize model performance as the output to be optimized.\n\n> ```Applied Predictive Modeling, p.499.```\n\n### 2.1) Forward selection\n\nIn forward selection we start with 0 features and then add one at a time to evaluate the performance. If the performance on iteration $i+1$ is better than the previous $i^{th}$ iteration, we keep the new feature. The algorithm stops when the addition of new features does not lead to an increase in performance. \n\nLet's implement a naive approach to forward selection.\n\n\n```python\n#hide_input\nfrom sklearn.base import clone\nfrom tqdm.notebook import tqdm\n\nclass ForwardSelection():\n def __init__(self, estimator, X, y, scoring, test_size):\n self.estimator = clone(estimator)\n\n self.X = X\n self.dim = X.shape[1]\n self.y = y\n self.scoring = scoring\n self.test_size = test_size\n \n def fit_predict(self): \n \n index = tuple(range(self.dim))\n \n self.subset = []\n \n Xtrain, Xtest, Ytrain, Ytest = train_test_split(self.X,self.y,test_size=self.test_size)\n \n self.scores = [self._calc_score(self._no_features(Xtrain), Ytrain, Xtest, Ytest)]\n \n for i in index:\n\n Xtransform, Xtest_transform = self.transform(Xtrain,i), self.transform(Xtest,i)\n\n\n score = self._calc_score(Xtransform, Ytrain, Xtest_transform, Ytest)\n\n \n if score < np.min(self.scores):\n print(f'Found import feature {descriptors[i]} with new min RMSE of {score:.3f}')\n self.subset.append(i)\n self.scores.append(score)\n \n \n def transform(self, X, i): \n return X[:, self.subset + [i]].reshape(-1, len(self.subset + [i])) \n \n def _calc_score(self, Xtrain, ytrain, Xtest, y_test):\n \n self.estimator.fit(Xtrain, ytrain)\n preds = self.estimator.predict(Xtest)\n\n score = self.scoring(preds, y_test)\n\n return score\n \n def get_support(self):\n \n return self.subset\n \n def _no_features(self, x):\n return np.zeros(x.shape)\n```\n\n\n```python\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.svm import SVR\nfrom sklearn.neighbors import KNeighborsRegressor\n```\n\n\n```python\npipe_ffs = Pipeline(steps=[('scaler',RobustScaler()), ('estimator', LinearRegression())])\n```\n\n\n```python\nffs = ForwardSelection(pipe_ffs, xtrain, ytrain, \n scoring = partial(mean_squared_error, squared=False),\n test_size=0.25)\n```\n\n\n```python\nffs.fit_predict()\n```\n\n Found import feature MolWt with new min RMSE of 1.756\n Found import feature MolLogP with new min RMSE of 1.426\n Found import feature MolMR with new min RMSE of 1.411\n Found import feature HeavyAtomCount with new min RMSE of 1.396\n Found import feature NumHeteroatoms with new min RMSE of 1.393\n Found import feature NumRotatableBonds with new min RMSE of 1.340\n Found import feature TPSA with new min RMSE of 1.339\n Found import feature LabuteASA with new min RMSE of 1.338\n Found import feature BalabanJ with new min RMSE of 1.338\n\n\n\n```python\nselected_features = np.array(descriptors)[ffs.get_support()]\nprint(f'Number of selected features = {len(selected_features)}')\n```\n\n Number of selected features = 9\n\n\nOur naive forward selector found 13 important features. If we go back to our heatmap, we can see that the selected features do have some correlation with solubility! Furthermore, it's basically the same features selected by the mutual information metric in the previous section. \n\nNow let's try the faster and reliable scikit-learn implementation of forward selection, the [```SequentialFeatureSelector```](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SequentialFeatureSelector.html) class. \n\nWe need to define a number of features to select so let's use 10 and compare the results with the approches so far. \n\n\n```python\nfrom sklearn.feature_selection import SequentialFeatureSelector\n```\n\n\n```python\nssf = SequentialFeatureSelector(estimator=pipe_ffs,n_features_to_select=12,cv=5, direction='forward',scoring='neg_mean_squared_error')\n```\n\n>It seems SequentialFeatureSelector tries to **maximize** the scoring function. If we use the ```make_scorer(mean_squared_error)``` the selector will output features that increase the RMSE. Thus, we'll use the negative mean squared error, neg_mean_squared_error. \n\n\n```python\nssf.fit(xtrain, ytrain)\n```\n\n\n\n\n SequentialFeatureSelector(estimator=Pipeline(steps=[('scaler', RobustScaler()),\n ('estimator',\n LinearRegression())]),\n n_features_to_select=12,\n scoring='neg_mean_squared_error')\n\n\n\n\n```python\nselected_features_ssf = np.array(descriptors)[ssf.get_support()]\n```\n\n\n```python\nselected_features_ssf\n```\n\n\n\n\n array(['MolLogP', 'MolMR', 'HeavyAtomCount', 'NumHAcceptors',\n 'NumHeteroatoms', 'NumRotatableBonds', 'NumValenceElectrons',\n 'NumSaturatedRings', 'RingCount', 'LabuteASA', 'BalabanJ',\n 'BertzCT'], dtype=' **You don't need to use all feature selection methods on your dataset!**\n\n\n \n\n**Figure 3.** Feature selection strategies\n\n# Conclusion\n\nWe learned how to inspect the correlation between features using heatmap and select the most informative subset of features using selection methods. The most important takeaway is that irrelevant features must be removed before training a model. If a feature do not contain relevant information or is highly correlated with other features, it will only make the model more complex, less intepretable and you risk reducing the generalization potential of the model. \n\nIn the next post we will train our solubility prediction model using the selected features. Can we achieve state-of-the art performance? Stay tuned for the next posts!\n\n\n# References\n\n**Molecular descriptors**\n\nhttps://northstar-www.dartmouth.edu/doc/MOE/Documentation/quasar/descr.htm#KH\n\nhttp://www.codessa-pro.com/descriptors/index.htm\n\n\n**Feature selection methods**\n\nhttps://www.kaggle.com/prashant111/comprehensive-guide-on-feature-selection#5.-How-to-choose-the-right-feature-selection-method-\n\nhttps://machinelearningmastery.com/feature-selection-with-real-and-categorical-data/\n\nKuhn, Max., and Kjell Johnson. [Applied Predictive Modeling](https://www.amazon.com/Applied-Predictive-Modeling-Max-Kuhn/dp/1461468485/ref=as_li_ss_tl?dchild=1&keywords=Applied+Predictive+Modeling&qid=1588722749&s=books&sr=1-1&linkCode=sl1&tag=inspiredalgor-20&linkId=45aa03c24c87a9e32f5611baa5e287ff&language=en_US). New York: Springer, 2013.\n\nhttps://towardsdatascience.com/mistakes-in-applying-univariate-feature-selection-methods-34c43ce8b93d\n\nhttps://www.kaggle.com/willkoehrsen/introduction-to-feature-selection\n\nhttps://scikit-learn.org/stable/modules/feature_selection.html\n\n# **Fin**\n", "meta": {"hexsha": "e071bd0beed8be012dd7de91086e107c15212365", "size": 826970, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2021-06-06-feature_selection.ipynb", "max_stars_repo_name": "marcossantanaioc/fiocruzcheminformatics", "max_stars_repo_head_hexsha": "cb1b737c724ede80cf118a00a9a57f89b75acf95", "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-06-06-feature_selection.ipynb", "max_issues_repo_name": "marcossantanaioc/fiocruzcheminformatics", "max_issues_repo_head_hexsha": "cb1b737c724ede80cf118a00a9a57f89b75acf95", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-06T05:20:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:19:36.000Z", "max_forks_repo_path": "_notebooks/2021-06-06-feature_selection.ipynb", "max_forks_repo_name": "marcossantanaioc/fiocruzcheminformatics", "max_forks_repo_head_hexsha": "cb1b737c724ede80cf118a00a9a57f89b75acf95", "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": 312.2998489426, "max_line_length": 345220, "alphanum_fraction": 0.9247759895, "converted": true, "num_tokens": 12319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.1520322377801054, "lm_q1q2_score": 0.06949951578192647}} {"text": "\n\n\n\n

    [75.12] Análisis Numérico

    \n

    Trabajo Práctico 1

    \n

    1er Cuatrimestre 2021

    \n\n--- \n\n

    Búsqueda de raíces

    \n\n---\n\n

    AUTOR

    \n

    Sánchez, Juan Pablo (jpsanchez@fi.uba.ar) - 105.865

    \n

    de Luca Andrea, Felipe (fdeluca@fi.uba.ar) - 105.646

    \n

    Litteri, Iván (ilitteri@fi.uba.ar - 106.223

    \n \n

    CÁTEDRA

    \n

    Sassano

    \n\n

    FECHA DE ENTREGA

    \n

    26 de mayo del 2021

    \n\n

    LENGUAJE ELEGIDO

    \n

    Python

    \n\n

    CALIFICACIÓN

    \n

    \n\n---\n\n*Es importante correr todos los bloques de código si se quiere visualizar algún resultado ya que algunos dependen de bloques previos.*\n\n\n```python\nimport numpy as np\nfrom sympy import *\nfrom matplotlib import pyplot as plt\nfrom scipy import optimize\nimport matplotlib.ticker as mticker\nnp.seterr('raise')\n```\n\n\n\n\n {'divide': 'warn', 'invalid': 'warn', 'over': 'warn', 'under': 'ignore'}\n\n\n\n\n```python\n# Función auxiliar para imprimir iteraciones\ndef imprimir_iteraciones(iteraciones, cant_semillas = 1, n_mostrar = 0):\n print(\"#\\t\\t\\t Valor calculado\\t\\t Variación respecto al anterior\")\n print(*[f\"Semilla {x}\\t\\t\"+f\"{iteraciones[x] : 1.20f}\"[:18] for x in range (0, cant_semillas)], sep = '\\n')\n print(*[f\"Iteracion {x}\\t\\t\"+f\"{iteraciones[x] : 1.20f}\"[:18]+\"\\t\\t\"+f\"{abs(iteraciones[x-1] - iteraciones[x]) : 1.20f}\"[:18] for x in range(cant_semillas, len(iteraciones))], sep = '\\n')\n\n# Función auxiliar para obtener la tolerancia al considerar un número 0. Tipo debe ser np.float32 o np.float64\ndef tol_cero(tipo):\n return np.float32(2)**np.float32(-120) if tipo == np.float32 else np.float64(2)**np.float64(-1000)\n```\n\n# 1. Métodos para seres queridos\n\nEn el marco de la época de la pandemia poder ayudar a los seres queridos es lo más importante que podemos hacer.\n\n## (a) Buscar la forma de implementar un método visto en clase para ayudar o apoyar a un ser querido. De no ser posible dar un ejemplo de un uso de los métodos vistos en clase para el área en que se desarrollen profesionalmente.\n\n

    Ayudamos 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\n

    El 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

    \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.

    \n
    \n
    \n \n

    \n\n

    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\n

    Respecto 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\n

    Se 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\n

    En 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\n

    La 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\n

    A 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\n

    Aclaració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\n

    Se 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\n

    Las 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\n

    Un 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\n

    Nuevamente 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\n

    En 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\n

    Si 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\n

    Mientras 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\n

    El 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\n

    La 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\n

    En 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\n

    Otra 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\n

    Para 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\n

    En 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\n

    En 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\n

    Se 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\n

    Nuevamente, 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\n

    Por 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\n

    El 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\n

    En 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\n

    En 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\n

    Para la primera y última función, nuevamente el orden estuvo alrededor de 2 como se esperaba.

    \n\n

    Aú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\n

    La 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\n

    Para la segunda función, se mantuvo principalmente en 1 una vez más debido a la raíz múltiple de esta.

    \n\n

    Para 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\n

    En 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\n

    En 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\n

    Forzamos 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\n

    En 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 \n\n", "meta": {"hexsha": "15f4112f2abcaf59cce3d744da61842feb18aada", "size": 29110, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/02/.ipynb_checkpoints/TD-14-Routhov_in_Hurwitzov_kriterij_stabilnosti-checkpoint.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/02/TD-14-Routhov_in_Hurwitzov_kriterij_stabilnosti.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/02/TD-14-Routhov_in_Hurwitzov_kriterij_stabilnosti.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": 50.3633217993, "max_line_length": 713, "alphanum_fraction": 0.4944349021, "converted": true, "num_tokens": 7166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.20434189751412135, "lm_q1q2_score": 0.06908332105492937}} {"text": "Probabilistic Programming and Bayesian Methods for Hackers \n========\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n#### Looking for a printed version of Bayesian Methods for Hackers?\n\n_Bayesian Methods for Hackers_ is now a published book by Addison-Wesley, available on [Amazon](http://www.amazon.com/Bayesian-Methods-Hackers-Probabilistic-Addison-Wesley/dp/0133902838)! \n\n\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assumes that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json, matplotlib\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials) / 2, 2, k + 1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials) - 1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$ pass. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2 * p / (1 + p), color=\"#348ABD\", lw=3)\n# plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2 * (0.2) / 1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Is my code bug-free?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1. / 3, 2. / 3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.ylim(0,1)\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n#### Expected Value\nExpected value (EV) is one of the most important concepts in probability. The EV for a given probability distribution can be described as \"the mean value in the long run for many repeated samples from that distribution.\" To borrow a metaphor from physics, a distribution's EV acts like its \"center of mass.\" Imagine repeating the same experiment many times over, and taking the average over each outcome. The more you repeat the experiment, the closer this average will become to the distributions EV. (side note: as the number of repeated experiments goes to infinity, the difference between the average outcome and the EV becomes arbitrarily small.)\n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots, \\; \\; \\lambda \\in \\mathbb{R}_{>0} $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1. / l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0, 1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```python\nimport pymc as pm\n\nalpha = 1.0 / count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = pm.Exponential(\"lambda_1\", alpha)\nlambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\ntau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```python\nprint(\"Random output:\", tau.random(), tau.random(), tau.random())\n```\n\n Random output: 20 65 51\n\n\n\n```python\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. Deterministic functions will be covered in Chapter 2. \n\n\n```python\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n# Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n [-----------------100%-----------------] 40000 of 40000 complete in 6.7 sec\n\n\n```python\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```python\nfigsize(12.5, 10)\n# histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data) - 20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n# type your code here.\nprint('Mean of Lambda 1:',round(lambda_1_samples.mean(),4))\nprint('Mean of Lambda 2:',round(lambda_2_samples.mean(),4))\n```\n\n Mean of Lambda 1: 17.7691\n Mean of Lambda 2: 22.7149\n\n\n\n```python\nlen(lambda_1_samples)\n```\n\n\n\n\n 30000\n\n\n\n\n```python\nlen(lambda_2_samples)\n```\n\n\n\n\n 30000\n\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n# type your code here.\n(lambda_2_samples/lambda_1_samples).mean()\n```\n\n\n\n\n 1.27994684856248\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n# type your code here.\nlen(lambda_1_samples[tau_samples<45])\n```\n\n\n\n\n 15263\n\n\n\n\n```python\nlambda_1_samples[tau_samples<45].mean()\n```\n\n\n\n\n 17.7761608020713\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "02f500582808b49ebf8677c277ceb2a1740a1922", "size": 308188, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_stars_repo_name": "xang1234/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "a662b5a2b8bf016f1d9698eb79d7c44e263ca6ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T14:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T14:00:09.000Z", "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_issues_repo_name": "xang1234/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "a662b5a2b8bf016f1d9698eb79d7c44e263ca6ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_forks_repo_name": "xang1234/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "a662b5a2b8bf016f1d9698eb79d7c44e263ca6ff", "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": 247.540562249, "max_line_length": 92276, "alphanum_fraction": 0.8871370722, "converted": true, "num_tokens": 11840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.24220562872535945, "lm_q1q2_score": 0.0689259100214144}} {"text": "# Pengenalan Notebook Jupyter\nPada pertemuan ini diperkenalkan mengenai Notebook Jupyter yang dapat digunakan untuk mempelajari bahasa pemrograman Pyhthon dan membuat dokumentasinya.\n\nContoh perintah Python\n\n\n```python\nprint(\"Hello, World!\")\n```\n\n Hello, World!\n\n\n## Iterasi for dalam Python\nBerikut ini adalah contoh sederhana iterasi dengan `for`.\n\n\n```python\nfor i in range(0, 11):\n print(i)\n\n```\n\n 0\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n\n\nMenyisipkan kode program tanpa mengeksekusi dan terdapat pewarnaanya.\n\n```python\nfor i in range(0, 11):\n print(i)\n```\n\n## Persamaan\nTerdapat dukungan untuk persamaan dalam Markdown pada Notebook Python menggunakan MathJax.\n\nContoh untuk persamaan kuadrat secara inline $y = ax^2 + bx +c$.\n\nUntuk satu blok persamaan\n\n\\begin{equation}\\label{eqn1}\\tag{1}\ny = ax^2 + bx + c\n\\end{equation}\n\nMerujuk Persamaan \\eqref{eqn1} adalah persamaan kuadrat.\n\n\\begin{equation}\\label{eqn2}\\tag{2}\n\\frac{1 + \\sin\\theta + \\sqrt{2x^ + 10}}{20 + y}\n\\end{equation}\n\n\n### Matriks\nTerdapat matriks berikut\n\n\\begin{equation}\\label{eqn3}\\tag{3}\nM = \\left[\n\\begin{array}{cccc}\n1 & 2 & 3 & 4 \\newline\nx^2 & 2 & 3 & \\sin\\gamma \\newline\n1 & 2 & 3 & 4 \\newline\n1 & 2 & 3 & \\sqrt{20x - \\beta} \\newline\n\\end{array}\n\\right]\n\\end{equation}\n\n\n\n\n```python\n%%html\n\n
    \n \n
    \n```\n\n\n\n
    \n \n
    \n\n\n\n# Plot kurva\nDengan menggunakan matplotlib dapat digambarkan kurva.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.ion()\n\n# generate x\nx = [0, 1, 2, 3, 4, 5, 6]\n\n# generate y\ny = [1, 2, 3, 4, 3, 2, 1]\n\n## plot results\nfig, ax = plt.subplots()\nax.scatter(x, y)\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\n```\n\n### Plot dengan fungsi\nTerdapat fungsi g sebagai berikut\n\n\\begin{equation}\ng(x) = 5 \\sin x\n\\end{equation}\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nplt.ion()\n\n# g(x) = 5 sin x\ndef g(x):\n y = 5 * math.sin(x)\n return y\n\nx = []\ny = []\nfor i in range(0, 21):\n xx = 2 * math.pi * i / 20\n yy = g(xx)\n \n x.append(xx)\n y.append(yy)\n\n## plot results\nfig, ax = plt.subplots()\nax.scatter(x, y)\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\n```\n\n## tabel\nDalam Markdown dapat dibuat tabel dengan lebih sederhana dibandingkan dalam HTML.\n\nTitik | $x$ | $y$ | $z$\n:-: | :-: | :-: | :-:\nA | 1 | 2 | 3\nB | -1 | -2 | -3\nC | 0.11 | 1 | 1\nD | 0 | 0 | 0\nE | 1 | 1 | 1\n\n```markdown\nTitik | $x$ | $y$ | $z$\n:-: | :-: | :-: | :-:\nA | 1 | 2 | 3\nB | -1 | -2 | -3\nC | 0.11 | 1 | 1\nD | 0 | 0 | 0\nE | 1 | 1 | 1\n\n```\n\n\n\nTabel dengan HTML murni dengan hasilnya\n\n\n \n \n \n \n \n \n \n \n \n
    Titik$x$$y$$z$
    A123
    B-1-2-3
    \n\nmenggunakan kode HTML berikut\n\n```html\n\n \n \n \n \n \n \n \n \n \n
    Titik$x$$y$$z$
    A123
    B-1-2-3
    \n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "e5ece08138de240196f0c22024a9f848d1b491a5", "size": 20467, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebook/external/embed_svg.ipynb", "max_stars_repo_name": "dudung/cookbook", "max_stars_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "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": "notebook/external/embed_svg.ipynb", "max_issues_repo_name": "dudung/cookbook", "max_issues_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "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": "notebook/external/embed_svg.ipynb", "max_forks_repo_name": "dudung/cookbook", "max_forks_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "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": 52.3452685422, "max_line_length": 6312, "alphanum_fraction": 0.7561440367, "converted": true, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.2309197682220399, "lm_q1q2_score": 0.06869169019932271}} {"text": "```python\nimport discretize\n```\n\n\n```python\nmesh = discretize.TensorMesh([3, 4])\n```\n\n\n```python\nmesh\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
    TensorMesh12 cells
    MESH EXTENTCELL WIDTHFACTOR
    dirnCminmaxminmaxmax
    x30.001.000.330.331.00
    y40.001.000.250.251.00
    \n\n\n\n\n# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method. IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\n# display is injected in default namespace, but it's a good idea to be explicit.\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n display_pretty, display_html, display_jpeg,\n display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='./images/ipython-logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='./images/python-logo.svg')\n```\n\n\n\n\n \n\n \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\n\n\n\n \n\n \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n
    Header 1Header 2
    row 1, cell 1row 1, cell 2
    row 2, cell 1row 2, cell 2
    \"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    Header 1Header 2
    row 1, cell 1row 1, cell 2
    row 2, cell 1row 2, cell 2
    \n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    Header 1Header 2
    row 1, cell 1row 1, cell 2
    row 2, cell 1row 2, cell 2
    \n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    Header 1Header 2
    row 1, cell 1row 1, cell 2
    row 2, cell 1row 2, cell 2
    \n\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$\\displaystyle F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself. This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol. For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos. At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust. \n\nThe following cell loads a local file called `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML, Video\nfrom base64 import b64encode\nvideo = open(\"images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities, ...\n* ... or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n", "meta": {"hexsha": "786cd34bfc071428e3d0c7ee827bd2db4932312a", "size": 429811, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "04.Jupyter_and_iPython/appendix/a-01-Rich Output.ipynb", "max_stars_repo_name": "scottyhq/2020_ICESat-2_Hackweek_Tutorials", "max_stars_repo_head_hexsha": "a655b29f124d3799242f0019c6686e8e45d384a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2020-07-24T15:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T03:08:31.000Z", "max_issues_repo_path": "04.Jupyter_and_iPython/appendix/a-01-Rich Output.ipynb", "max_issues_repo_name": "scottyhq/2020_ICESat-2_Hackweek_Tutorials", "max_issues_repo_head_hexsha": "a655b29f124d3799242f0019c6686e8e45d384a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:19:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T15:50:57.000Z", "max_forks_repo_path": "04.Jupyter_and_iPython/appendix/a-01-Rich Output.ipynb", "max_forks_repo_name": "scottyhq/2020_ICESat-2_Hackweek_Tutorials", "max_forks_repo_head_hexsha": "a655b29f124d3799242f0019c6686e8e45d384a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-06-30T07:41:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T08:36:25.000Z", "avg_line_length": 393.9605866178, "max_line_length": 239833, "alphanum_fraction": 0.9357671162, "converted": true, "num_tokens": 49407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1384617852362804, "lm_q1q2_score": 0.06869003727324635}} {"text": "# Encoding of categorical variables\n\n## Sources\n\n* [Encoding categorical variables](https://kiwidamien.github.io/encoding-categorical-variables.html)\n* [Benchmarking Categorical Encoders](https://towardsdatascience.com/benchmarking-categorical-encoders-9c322bd77ee8)\n* [Smarter Ways to Encode Categorical Data for Machine Learning](https://towardsdatascience.com/smarter-ways-to-encode-categorical-data-for-machine-learning-part-1-of-3-6dca2f71b159)\n* [Encoding Categorical Variables in Practice](https://medium.com/epfl-extension-school/encoding-categorical-variables-in-practice-a536907f2013)\n* [Types of Categorical Data Encoding Schemes](https://medium.com/analytics-vidhya/types-of-categorical-data-encoding-schemes-a5bbeb4ba02b)\n* [Guide to Encoding Categorical Values in Python ](https://pbpython.com/categorical-encoding.html)\n* [All about Categorical Variable Encoding](https://towardsdatascience.com/all-about-categorical-variable-encoding-305f3361fd02)\n* [Encoding categorical variables: one-hot and beyond](http://www.win-vector.com/blog/2017/04/encoding-categorical-variables-one-hot-and-beyond/)\n\n# Background\n\nMany machine learning algorithms are not able to use non-numeric data. While many features we might use, such as a person's age, or height, are numeric there are many that are not. Usually these features are represented by strings, and we need some way of transforming them to numbers before using scikit-learn's algorithms. The different ways of doing this are called encodings.\n\n**Note**:This notebook does not address the translation of text into numbers/vectors. This is the topic of __word embeddings__ where the aim is to generate vectors such that words with similar meaning are close to one another and that the arithmetic of vectors corresponds to ''arithmetic'' of meaning, e.g. embedding('queen') ~ embedding('king') - embedding('man') + embedding('woman').\n\n## Terminology\n\n**Levels**: A levels of a non-numeric feature are the number of distinct values. The examples listed above are all examples of levels. The number of levels can vary wildly: the number of races for a patient is typically four (asian, black, hispanic, and white), the number of states for the US is 51 (if we include DC separately), while the number of professions is in the thousands.\n\n**Ordinal**: If the levels are ordered, then we call the feature ordinal. For example, if a class grade such as \"B+\" or \"A\" is a non-numeric feature, but the letters are not just different, they are ordered (an \"A\" is better than a \"B+\", which is better than a \"C-\" etc).\n\n**Nominal**: If the levels are just different without an ordering, we call the feature categorical. For example, professions or car brands are categorical. If we use an encoding that maps levels to numbers, we introduce an ordering on the categories, which may not be desirable. Most of this article will be about encoding categorical variables.\n\n## Considerations when choosing encodings\n\n**Do you have many levels?** If so, using an encoding that has a level-per-feature is difficult for tree-based models. Trees separate on features that \"split\" the data into different classes effectively. If there are many levels, it is likely only a tiny fraction of the data belong to one level, so it will be hard for trees to \"find\" that feature to split on. Typically this isn't a problem for linear models.\n\n**Are there many examples of each level?** If there are only 5 doctors in your dataset, you probably are not going to know the doctor category very well (nor will it generalize). Some encoders deal with this gracefully, while others won't. You might consider making an explicit \"other\" category for levels, or grouping categories together. This is a problem for all models.\n\n**Could you have new categories at test time?** Some categorical variables can be completely specified at training time (e.g. the levels for race or blood type would be known even with zero training examples). Other categories, such as profession, are so broad that we probably learn the levels from the training data. Some encoders deal with levels that are only in the test set better than others.\n\n**Are the categories related?** Many encoding schemes treat two different levels as \"equally different\" from one another. If looking at color of a car, a typical encoding has no idea that \"brick red\" and \"red\" are more related than \"red\" and \"yellow\". One way of solving this problem is to cluster the categories into higher levels, and then encode that category as well.\n\n**Is it reversible?** Does it store a lookup table? Given the encoding of a feature, can you recover the original value? If so, we call the encoding reversible. Generally, reversible features also require a lot of storage if there are a lot of levels (to figure out how to go backward). I would generally see reversible as a negative if it requries storing a lookup table as well.\n\n## Example data\n\n\n```python\nimport requests\nimport category_encoders as ce\nimport numpy as np\nimport pandas as pd\n\ndef encode_var(var, encoder, y=None):\n if y is None:\n encoder.fit(var)\n else:\n encoder.fit(var, y)\n new_var = encoder.transform(var)\n if isinstance(new_var, pd.DataFrame):\n new_var.insert(0, 'original', var)\n return new_var\n else:\n return pd.DataFrame({'original': var, 'encoder': new_var})\n \ndef print_res(res, rows_per_level=2):\n out = pd.DataFrame(columns=res.columns)\n for lvl in res.original.unique():\n out = out.append(res[res.original==lvl].head(rows_per_level))\n return out\n```\n\n\n```python\ndownload_data = False\n```\n\n\n```python\nif download_data:\n url = \"http://mlr.cs.umass.edu/ml/machine-learning-databases/autos/imports-85.data\"\n r = requests.get(url)\n with open('imports-85.data', 'wb') as f:\n f.write(r.content)\n```\n\n\n```python\n# Define the headers since the data does not have any\nheaders = [\"symboling\", \"normalized_losses\", \"make\", \"fuel_type\", \"aspiration\",\n \"num_doors\", \"body_style\", \"drive_wheels\", \"engine_location\",\n \"wheel_base\", \"length\", \"width\", \"height\", \"curb_weight\",\n \"engine_type\", \"num_cylinders\", \"engine_size\", \"fuel_system\",\n \"bore\", \"stroke\", \"compression_ratio\", \"horsepower\", \"peak_rpm\",\n \"city_mpg\", \"highway_mpg\", \"price\"]\n# Read in the CSV file and convert \"?\" to NaN\ndf = pd.read_csv(\"imports-85.data\",\n header=None, names=headers, na_values=\"?\" )\n```\n\n\n```python\ndf.head()\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 \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 \n \n \n \n \n \n \n \n \n
    symbolingnormalized_lossesmakefuel_typeaspirationnum_doorsbody_styledrive_wheelsengine_locationwheel_base...engine_sizefuel_systemborestrokecompression_ratiohorsepowerpeak_rpmcity_mpghighway_mpgprice
    03NaNalfa-romerogasstdtwoconvertiblerwdfront88.6...130mpfi3.472.689.0111.05000.0212713495.0
    13NaNalfa-romerogasstdtwoconvertiblerwdfront88.6...130mpfi3.472.689.0111.05000.0212716500.0
    21NaNalfa-romerogasstdtwohatchbackrwdfront94.5...152mpfi2.683.479.0154.05000.0192616500.0
    32164.0audigasstdfoursedanfwdfront99.8...109mpfi3.193.4010.0102.05500.0243013950.0
    42164.0audigasstdfoursedan4wdfront99.4...136mpfi3.193.408.0115.05500.0182217450.0
    \n

    5 rows × 26 columns

    \n
    \n\n\n\n\n```python\ndf.info()\n```\n\n \n RangeIndex: 205 entries, 0 to 204\n Data columns (total 26 columns):\n symboling 205 non-null int64\n normalized_losses 164 non-null float64\n make 205 non-null object\n fuel_type 205 non-null object\n aspiration 205 non-null object\n num_doors 203 non-null object\n body_style 205 non-null object\n drive_wheels 205 non-null object\n engine_location 205 non-null object\n wheel_base 205 non-null float64\n length 205 non-null float64\n width 205 non-null float64\n height 205 non-null float64\n curb_weight 205 non-null int64\n engine_type 205 non-null object\n num_cylinders 205 non-null object\n engine_size 205 non-null int64\n fuel_system 205 non-null object\n bore 201 non-null float64\n stroke 201 non-null float64\n compression_ratio 205 non-null float64\n horsepower 203 non-null float64\n peak_rpm 203 non-null float64\n city_mpg 205 non-null int64\n highway_mpg 205 non-null int64\n price 201 non-null float64\n dtypes: float64(11), int64(5), object(10)\n memory usage: 41.8+ KB\n\n\n# Notation\n\n$$ \\begin{align}\nN: & \\text{Number of observations}\\\\\nN_i: & \\text{Number of observations with level i}\\\\\nn: & \\text{Number of levels}\\\\\ni: & \\text{The i-th level}\\\\\nk: & \\text{The k-th variable of the encoding}\\\\\nx_k(i): & \\text{Value for the k-th variable of the encoding when the original variable has label $i$.}\\\\\n\\bar{y}: & \\text{The average value of the target}\\\\\n\\bar{y}_i: & \\text{The average value of the target for level i}\n\\end{align}$$\n\n\n```python\n\n```\n\n# Unsupervised Encoding Methods\n\n## Label Encoding\n\n**Description**\n\nLabel encoding replaces the *n* labels with values from *0* to *n-1*, in lexicographical order.\n\n**Construction**\n\n$$x(i) = i$$\n\n**When to use**\n\nNever (only for ordinal variables, for which there is the `OrdinalEncoder` class.\n\n\n```python\ndf[\"num_cylinders\"].value_counts().sort_index()\n```\n\n\n\n\n eight 5\n five 11\n four 159\n six 24\n three 1\n twelve 1\n two 4\n Name: num_cylinders, dtype: int64\n\n\n\n\n```python\nfrom sklearn.preprocessing import LabelEncoder\n```\n\n\n```python\nencoder = LabelEncoder()\nres = encode_var(df[\"num_cylinders\"], encoder)\nprint_res(res)\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 \n \n \n \n
    originalencoder
    0four2
    1four2
    2six3
    12six3
    4five1
    5five1
    71eight0
    72eight0
    55two6
    56two6
    18three4
    49twelve5
    \n
    \n\n\n\n## Ordinal Encoding\n\n**Description**\n\nSame as label encoding, but values are ordered in the order of labels.\n\n**When to use**\n\nFor ordinal variables, where the difference between all labels represents the same distance.\n\n\n```python\ndf[\"num_cylinders\"].value_counts(sort=False)\n```\n\n\n\n\n three 1\n five 11\n two 4\n six 24\n four 159\n twelve 1\n eight 5\n Name: num_cylinders, dtype: int64\n\n\n\n\n```python\ndf[\"num_cylinders\"] = df[\"num_cylinders\"].astype('category').cat.reorder_categories(ordered=True, new_categories=['two', 'three', 'four', 'five', 'six', 'eight', 'twelve'])\n```\n\n\n```python\ndf[\"num_cylinders\"].value_counts(sort=False)\n```\n\n\n\n\n two 4\n three 1\n four 159\n five 11\n six 24\n eight 5\n twelve 1\n Name: num_cylinders, dtype: int64\n\n\n\n\n```python\nencoder = ce.ordinal.OrdinalEncoder()\nres = encode_var(df[[\"num_cylinders\"]], encoder)\nprint_res(res)\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 \n \n \n \n
    originalnum_cylinders
    0four3
    1four3
    2six5
    12six5
    4five4
    5five4
    71eight6
    72eight6
    55two1
    56two1
    18three2
    49twelve7
    \n
    \n\n\n\n## Dummy/One Hot Encoding\n\n**Description**\n\nCreates a binary indicator for each level.\n\n**Construction**\n\n$$x_k(i) = \n\\begin{cases} \n1 & \\text{if } k=i \\\\ \n0 & \\text{otherwise}\n\\end{cases}$$\n\n**When to use**\n\nWhen the main interest is in differences in average values for each level and there are sufficient observations for each level.\n\n\n```python\ndf['drive_wheels'].value_counts()\n```\n\n\n\n\n fwd 120\n rwd 76\n 4wd 9\n Name: drive_wheels, dtype: int64\n\n\n\n\n```python\nencoder = ce.one_hot.OneHotEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder)\nprint_res(res)\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
    originaldrive_wheels_1drive_wheels_2drive_wheels_3
    3fwd010
    5fwd010
    0rwd100
    1rwd100
    44wd001
    94wd001
    \n
    \n\n\n\n## Binary Encoding\n\n**Description**\n\nSimilar to One-Hot Encoding, but values of categories are stored as binary bitstrings. Each binary digit create one encoding column, i.e. if there are $n$ levels then there are $\\log_2n$ features.\n\n**Construction**\n\nEach level is associated with its order, which is then translated into bitstrings. The encoding variables are the different valeus in the bitstring.\n\n**When to use**\n\nFor categorical variables with many levels.\n\n\n```python\nencoder = ce.binary.BinaryEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder)\nprint_res(res)\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
    originaldrive_wheels_0drive_wheels_1drive_wheels_2
    3fwd010
    5fwd010
    0rwd001
    1rwd001
    44wd011
    94wd011
    \n
    \n\n\n\n## BaseN Encoding\n\n**Description**\n\nBase-N encoder encodes the categories into arrays of their base-N representation. A base of $1$ is equivalent to one-hot encoding (not really base-1, but useful), a base of $2$ is equivalent to binary encoding. A base of $n$ is equivalent to vanilla ordinal encoding.\n\n**Construction**\n\nEach level is associated with its order, which is then translated into bitstrings. The encoding variables are the different valeus in the bitstring.\n\n**When to use**\n\nFor categorical variables with many levels.\n\n\n```python\nencoder = ce.basen.BaseNEncoder(base=2)\nres = encode_var(df[[\"make\"]], encoder)\nprint_res(res)\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 \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 \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 \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 \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 \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 \n \n \n \n \n \n \n \n \n
    originalmake_0make_1make_2make_3make_4make_5
    150toyota010100
    151toyota010100
    89nissan001101
    90nissan001101
    50mazda001001
    51mazda001001
    30honda000110
    31honda000110
    76mitsubishi001100
    77mitsubishi001100
    182volkswagen010101
    183volkswagen010101
    138subaru010011
    139subaru010011
    194volvo010110
    195volvo010110
    107peugot001110
    108peugot001110
    21dodge000101
    22dodge000101
    10bmw000011
    11bmw000011
    67mercedes-benz001010
    68mercedes-benz001010
    3audi000010
    4audi000010
    118plymouth001111
    119plymouth001111
    132saab010010
    133saab010010
    125porsche010000
    126porsche010000
    43isuzu000111
    44isuzu000111
    0alfa-romero000001
    1alfa-romero000001
    18chevrolet000100
    19chevrolet000100
    47jaguar001000
    48jaguar001000
    130renault010001
    131renault010001
    75mercury001011
    \n
    \n\n\n\n## Simple Encoder\n\n**Description**\n\nCompares each level to the reference level, with the intercept as the grand mean.\n\n**Construction**\n\n$$x_k(i) = \\begin{cases}\n\\frac{n-1}{n} & \\text{if } k = i \\\\\n-\\frac{1}{n} & \\text{otherwise}\n\\end{cases}$$\n\n**When to use**\n\nSame as dummy encoding, but when the interest is in deviations from the grand mean rather than deviations from the reference level.\n\n\n```python\n### Not available in Python\nfrom simple_coding import SimpleEncoder\n```\n\n\n```python\nencoder = SimpleEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder)\nprint_res(res)\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
    originalinterceptdrive_wheels_0drive_wheels_1
    3fwd10.666667-0.333333
    5fwd10.666667-0.333333
    0rwd1-0.333333-0.333333
    1rwd1-0.333333-0.333333
    44wd1-0.3333330.666667
    94wd1-0.3333330.666667
    \n
    \n\n\n\n## Sum encoding / Deviation Encoding / Effect Encoding\n\n**Description**\n\nSum encoding compares each group effect to the grand mean, i.e. the mean of group means (which is not the overall mean). The encoding representation is the difference of indicator variables minus the indicator for one baseline group. Sum encoding is similar to One-Hot encoding, but the interpretation of effects is different (effect relative to the grand mean vs. effect relative to a baseline group).\n\n**Construction**\n\n$$x_k(i) = \\begin{cases}\n-1 & \\text{if } i = 1\\\\\n1 & \\text{if } i+1 = k\\\\\n0 & \\text{otherwise}\n\\end{cases}$$\n\n**When to use**\n\nWhen the main interest is in differences in average values for each level compared to the grand mean and there are sufficient observations for each level.\n\n\n```python\nencoder = ce.sum_coding.SumEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder)\nprint_res(res)\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
    originalinterceptdrive_wheels_0drive_wheels_1
    3fwd10.01.0
    5fwd10.01.0
    0rwd11.00.0
    1rwd11.00.0
    44wd1-1.0-1.0
    94wd1-1.0-1.0
    \n
    \n\n\n\n## (Orthogonal) Polynomial Encoding\n\n**Description**\nOrthogonal polynomial coding is a form of trend analysis in that it is looking for the linear, quadratic and cubic trends in the categorical variable. Orthogonal polynomials are equations such that each is associated with a power of the variable.\n\n**Construction**\n\nEach encoding variable are the coefficients of the orthogonal polynomials of order $n-1$. See this [Post](https://stats.stackexchange.com/questions/105115/polynomial-contrasts-for-regression) for an explanation of the construction.\n\n\n**When to use**\nThis type of coding system should be used only with an ordinal variable in which the levels are equally spaced.\n\n\n```python\nencoder = ce.polynomial.PolynomialEncoder()\nres = encode_var(df[[\"num_cylinders\"]], encoder)\nprint_res(res)\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 \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 \n \n \n \n \n \n \n \n
    originalinterceptnum_cylinders_0num_cylinders_1num_cylinders_2num_cylinders_3num_cylinders_4num_cylinders_5
    0four1-1.889822e-01-3.273268e-014.082483e-010.080582-5.455447e-010.493464
    1four1-1.889822e-01-3.273268e-014.082483e-010.080582-5.455447e-010.493464
    2six11.889822e-01-3.273268e-01-4.082483e-010.0805825.455447e-010.493464
    12six11.889822e-01-3.273268e-01-4.082483e-010.0805825.455447e-010.493464
    4five11.617449e-17-4.364358e-01-1.109626e-160.483494-6.714569e-16-0.657952
    5five11.617449e-17-4.364358e-01-1.109626e-160.483494-6.714569e-16-0.657952
    71eight13.779645e-011.195122e-17-4.082483e-01-0.564076-4.364358e-01-0.197386
    72eight13.779645e-011.195122e-17-4.082483e-01-0.564076-4.364358e-01-0.197386
    55two1-5.669467e-015.455447e-01-4.082483e-010.241747-1.091089e-010.032898
    56two1-5.669467e-015.455447e-01-4.082483e-010.241747-1.091089e-010.032898
    49twelve15.669467e-015.455447e-014.082483e-010.2417471.091089e-010.032898
    18three1-3.779645e-019.521795e-174.082483e-01-0.5640764.364358e-01-0.197386
    \n
    \n\n\n\n## Helmert Encoding\n\n**Description**\n\nHelmert coding compares each level of a categorical variable to the mean of the subsequent levels. The first contrast compares the mean of the dependent variable for the second level with the mean of the dependent variable for the first level. The second contrast compares the mean for the third level with the mean for the first two levels, etc.\n\n**Construction**\n\n$$x_k(i) = \\begin{cases}\n-1 & \\text{if } i < k\\\\\nk & \\text{if } i = k\\\\\n0 & \\text{otherwise}\n\\end{cases}$$\n\nThe representation for level k has -1 for each level before k and then k as value for the current level, starting at *k=2* up to *k=n*.\n\n**When to use**\n\nWhen levels of a categorical variable are ordered from lowest to highest or from smallest to largest. \n\n\n```python\nencoder = ce.helmert.HelmertEncoder()\nres = encode_var(df[[\"body_style\"]], encoder)\nprint_res(res)\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 \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
    originalinterceptbody_style_0body_style_1body_style_2body_style_3
    3sedan10.02.0-1.0-1.0
    4sedan10.02.0-1.0-1.0
    2hatchback11.0-1.0-1.0-1.0
    9hatchback11.0-1.0-1.0-1.0
    7wagon10.00.03.0-1.0
    28wagon10.00.03.0-1.0
    69hardtop10.00.00.04.0
    74hardtop10.00.00.04.0
    0convertible1-1.0-1.0-1.0-1.0
    1convertible1-1.0-1.0-1.0-1.0
    \n
    \n\n\n\n\n```python\ndf[\"body_style\"].unique()\n```\n\n\n\n\n array(['convertible', 'hatchback', 'sedan', 'wagon', 'hardtop'],\n dtype=object)\n\n\n\n## Backward Difference Encoding\n\n**Description**\n\nSimilar to Helmert encoding, but differences are taken with respect to the prior adjacent level (not all prior levels).\n\n**Construction**\n\n$$x_k(i) = \\begin{cases}\n-\\frac{n-k}{n} & \\text{if } i \\leq k\\\\\n\\frac{n}{k} & \\text{otherwise}\n\\end{cases}$$\n\n**When to use**\n\nWhen levels of a categorical variable are ordered from lowest to highest or from smallest to largest, but the interest is in step-wise differences.\n\n\n```python\nencoder = ce.backward_difference.BackwardDifferenceEncoder()\nres = encode_var(df[[\"body_style\"]], encoder)\nprint_res(res)\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 \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
    originalinterceptbody_style_0body_style_1body_style_2body_style_3
    0convertible1-0.8-0.6-0.4-0.2
    1convertible1-0.8-0.6-0.4-0.2
    2hatchback10.2-0.6-0.4-0.2
    9hatchback10.2-0.6-0.4-0.2
    3sedan10.20.4-0.4-0.2
    4sedan10.20.4-0.4-0.2
    7wagon10.20.40.6-0.2
    28wagon10.20.40.6-0.2
    69hardtop10.20.40.60.8
    74hardtop10.20.40.60.8
    \n
    \n\n\n\n## Frequency / Count Encoding\n\n**Description**\n\nFrequency encoding replaces the levels of a categorical variable with their absolute or relative frequency.\n\n**Construction**\n\n$$x(i) = \\frac{N_i}{N}$$\n\n**When to use**\n\nWhen common or uncommon levels have similar influences.\n\n\n```python\nencoder = ce.count.CountEncoder(normalize=True)\nres = encode_var(df[[\"drive_wheels\"]], encoder)\nprint_res(res)\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
    originaldrive_wheels
    3fwd0.585366
    5fwd0.585366
    0rwd0.370732
    1rwd0.370732
    44wd0.043902
    94wd0.043902
    \n
    \n\n\n\n## Hashing\n\n**Description**\n\nHashing converts categorical variables to a higher dimensional space of integers, where the distance between two vectors of categorical variables in approximately maintained the transformed numerical dimensional space. \n\n**Construction**\n\nAny hash funtion from the `hashlib` package.\n\n**When to use**\n\nThis method is advantageous when the cardinality of categorical is very high.\n\n\n```python\nencoder = ce.hashing.HashingEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder)\nprint_res(res)\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    originalcol_0col_1col_2col_3col_4col_5col_6col_7
    0rwd00000100
    1rwd00000100
    3fwd00001000
    5fwd00001000
    44wd00000010
    94wd00000010
    \n
    \n\n\n\n# Supervised Encoding Methods / Bayesian Encoders\n\n## Target / Mean / Impact / Likelihood Encoding\n\n**Description**\n\nTarget encoding replaces each category with the average value of all ovservations for that category, mixed with a prior.\n\nFor the case of *categorical target*: features are replaced with a blend of posterior probability of the target given particular categorical value and the prior probability of the target over all the training data.\n\nFor the case of *continuous target*: features are replaced with a blend of the expected value of the target given particular categorical value and the expected value of the target over all the training data.\n\n**Construction**\n\n$$x(i) = \\bar{y} (1-s) + s \\bar{y}_i$$\nwhere $s$ is a smoothing parameter calculated as:\n$$s=\\frac{1}{1+\\exp{\\left(-\\frac{n-mdl}{a}\\right)}}$$\nwith 'mdl' standing for 'min data in leaf' and $a$ is a regularization parameter. The mdl defines a threshold where prior, i.e. the mean of the target, and target mean for a given category value have the same weight.\n\n**When to use**\n\nThis encoding method brings out the relation between similar categories, but the connections are bounded within the categories and target itself. The advantages of the mean target encoding are that it does not affect the volume of the data and helps in faster learning. Target encoding is powerful in prediction tasks, but runs the risk of target leakage. The leakage can be controlled via regularization, data augmentation by adding noise to the encoding representation, or through double validation.\n\n\n```python\nencoder = ce.target_encoder.TargetEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder, df['price'])\nprint_res(res)\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
    originaldrive_wheels
    3fwd9244.779661
    5fwd9244.779661
    0rwd19757.613333
    1rwd19757.613333
    44wd10243.702296
    94wd10243.702296
    \n
    \n\n\n\n## James-Stein Encoding\n\n**Description**\n\nTarget encoding based on the James-Stein mean estimator, rather than the sample mean. The idea is to improve the estimation of the category's mean target by shrinking them towards the central average.\n\n**Construction**\n\n$$x(i) = \\bar{y} B + (1-B) \\bar{y}_i$$\nwhere $B$ is a shrinkage parameter. A common value is\n$$B=\\frac{Var\\left[y_k\\right]}{Var\\left[y_k\\right]+Var\\left[y\\right]}$$\nbut the value could also be set via cross-valdiation. The intuition behind the equation is that if the mean estiamte of a category is uncertain (high variance), then stronger shrinkage should be applied.\n\n**When to use**\n\nSame as for target encoder.\n\n\n```python\nencoder = ce.james_stein.JamesSteinEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder, df['price'])\nprint_res(res)\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
    originaldrive_wheels
    3fwd9244.779661
    5fwd9244.779661
    0rwd19757.613333
    1rwd19757.613333
    44wd10241.000000
    94wd10241.000000
    \n
    \n\n\n\n## M-estimator Encoding\n\n**Description**\n \nA simplified version of the target encoder as it has only one hyerparameter.\n\n**Construction**\n\n$$x(i) = \\frac{N_i + m \\times \\bar{y}}{\\bar{y}_i + m}$$\nwhere $m$ is a smoothing parameter.\n\n**When to use**\n\nSame as for target encoder.\n\n\n```python\nencoder = ce.m_estimate.MEstimateEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder, df['price'])\nprint_res(res)\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
    originaldrive_wheels
    3fwd9278.076717
    5fwd9278.076717
    0rwd19671.422755
    1rwd19671.422755
    44wd10570.569928
    94wd10570.569928
    \n
    \n\n\n\n## Leave One Out Encoding\n\n**Description**\n\nThe encoding is calculated for each observation $j$ by calculating the average value of the target of all observations with the same target value as observation $j$ except $j$.\n\n**Construction**\n\n$$ x_k^{(j)} = \\frac{a}{b}\\frac{\\sum_{i\\neq j}(y_i(x_i==k)-y_j}{\\sum_{i\\neq j}x_i==k}$$\n\n**When to use**\n\nSame as for target encoder.\n\n\n```python\nencoder = ce.leave_one_out.LeaveOneOutEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder, df['price'])\nprint_res(res)\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
    originaldrive_wheels
    3fwd9244.779661
    5fwd9244.779661
    0rwd19757.613333
    1rwd19757.613333
    44wd10241.000000
    94wd10241.000000
    \n
    \n\n\n\n## Catboost Encoding\n\n**Decription**\n\nCatboost is an improvement over the leave-one-out encoder. It is intended to overcome the target leackage problems.\n\n**Construction**\nSame as LOO encoder, but the sums only range up to the current observations:\n$$ x_k(i) = \\frac{a}{b}\\frac{\\sum_{j\\neq i, j\\leq k}(y_j(x_j==k)-y_i}{\\sum_{j\\neq i, j\\leq k}x_j==k}$$\n\n\n**When to use**\n\n\n```python\nencoder = ce.cat_boost.CatBoostEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder, df['price'])\nprint_res(res)\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
    originaldrive_wheels
    3fwd9278.076717
    5fwd9278.076717
    0rwd19671.422755
    1rwd19671.422755
    44wd10570.569928
    94wd10570.569928
    \n
    \n\n\n\n## Weight of Evidence Encoder\n\n**Description**\n\nThe encoding is a measure of the *strength* that seperates effect from no effect. The encoding can only be used for binary targets.\n\n**Construction**\n\nThe encoding is calculated from a modified odds ratio, which is intended to prevent target leakage:\n$$ \\begin{align}\nnumerator =& \\ \\frac{N_i+a}{N_i\\bar{y}_i + 2a} \\\\\ndenominator =& \\ \\frac{N-N_i+a}{N\\bar{y}-N_i\\bar{y}_i 2a} \\\\\nx(i) =& \\ \\log\\left(\\frac{numerator}{denominator}\\right)\n\\end{align}\n$$\n\n**When to use**\n\nFor binary targets\n\n\n```python\nencoder = ce.woe.WOEEncoder()\nres = encode_var(df[[\"drive_wheels\"]], encoder, df['fuel_type']=='gas')\nprint_res(res)\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
    originaldrive_wheels
    3fwd0.275848
    5fwd0.275848
    0rwd-0.435318
    1rwd-0.435318
    44wd0.162519
    94wd0.162519
    \n
    \n\n\n\n## Probability Ratio Encoding\n\n**Description**\n\nProbability Ratio Encoding is similar to Weight Of Evidence encoding, but the encoding is based on the ratio of probabilities of the positive to the negative class.\n\n**Construction**\n\n$$x(i) = \\frac{y^+/N}{y_k^-/N}=\\frac{y_k^+}{y_k^-}$$\nThis is the same as WoE encoding with no regularization, i.e. $a=0$.\n\n**When to use**\n\nSame as weight of evidence encoding.\n\n\n```python\nencoder = ce.woe.WOEEncoder(regularization=0.)\nres = encode_var(df[[\"drive_wheels\"]], encoder, df['fuel_type']=='gas')\nprint_res(res)\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
    originaldrive_wheels
    3fwd0.287682
    5fwd0.287682
    0rwd-0.448132
    1rwd-0.448132
    44wdinf
    94wdinf
    \n
    \n\n\n\n# Other encodings\n\n* DRACuLa\n* Reverse Helmert\n* Forward Differences\n* Thermometer Encoder\n\n# Cheat Sheet\n\n\n\n# Exercises\n\n**Exercise 1**: Calculate the regressions of 'num_cylinders' on price for each possible encoding. What is the correct interpretation for the coefficients?\n\n**Exercise 2**: Try to find the best encoding for each variable to maximize the generalization performance of a linear regression model to predict the price of a car.\n", "meta": {"hexsha": "00ff6d9c00149f397c09f6513fbe2fd11b75caae", "size": 114284, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notes/06_encoders.ipynb", "max_stars_repo_name": "pbr142/handson-ml", "max_stars_repo_head_hexsha": "ba9d09181f33191ec4fab990b661b44f7b27ad81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-02T13:27:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-02T13:27:03.000Z", "max_issues_repo_path": "notes/06_encoders.ipynb", "max_issues_repo_name": "pbr142/handson-ml", "max_issues_repo_head_hexsha": "ba9d09181f33191ec4fab990b661b44f7b27ad81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:50:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:52:27.000Z", "max_forks_repo_path": "notes/06_encoders.ipynb", "max_forks_repo_name": "pbr142/handson-ml", "max_forks_repo_head_hexsha": "ba9d09181f33191ec4fab990b661b44f7b27ad81", "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": 30.3704491098, "max_line_length": 507, "alphanum_fraction": 0.3706380596, "converted": true, "num_tokens": 19820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897501624599, "lm_q2_score": 0.1847675151370785, "lm_q1q2_score": 0.06773387721224014}} {"text": "# Python 101\n\n**ENGSCI233: Computational Techniques and Computer Systems** \n\n*Department of Engineering Science, University of Auckland*\n\nThe purpose of this notebook is to give you the **very basics** of Python (and computer code in general). You will not be an expert by the end. But you will be on [The Path](https://zen-of-python.info/).\n\nWhen writing computer code, there are ***rules*** and there are ***conventions***.\n\n- If you break a ***rule***, the code will not work.\n- If you break a ***convention***, someone, somewhere puts a mark against your name in a book. At the end, you will be called to account. \n\nSome Python rules:\n\n- ***Syntax*** - we have *very* precise expectations about how you write computer code. If you type an opening bracket, `(`, you must close it again later, `)`. Some control structures are terminated by a colon, `:` - if you omit this, the code will not work. ***Yes, learning syntax for a new code is very pedantic and a total pain.*** But you have to do it anyway, and at least Python returns readable error messages to help you understand your missteps...\n- ***Indentation*** - Python uses this to determine when control structures begin and end. More on what a **control structure** is later. \n\nSome Python conventions:\n\n- ***Commenting*** - it is helpful for the poor soul who has to read your poorly written Python (sometimes that is you, weeks or months later) if you have included little **'sign-posts'** in the code, articulating what you are doing. These are called comments. They begin with a `#` symbol, after which you can write whatever you like and it will not be executed as a command.\n- ***Sensible variable names*** - relating to the thing the variable represents but not too long. For example, if a variable contains the mean temperature, then `Tmean` is a sensible variable name, where as `the_mean_temperature_of_the_profile` or `a1` are not sensible variable names.\n\nHang-on, what's a **variable**?\n\n**Execute the cell below by clicking inside it and hitting Ctrl+Enter**\n\n\n```python\n# this is a comment, nothing happens when Python reads this line\nhello_string = 'Hello, world'\nprint(hello_string)\n```\n\nThe snippet of Python code above does a number of things.\n\n1. The first **line** is a comment - Python sees the `#` symbol and ignores everything that follows **on that line**.\n2. The second line creates a **variable** called `hello_string` and **assigns to it** the ***value*** `'Hello, world'`.\n3. The third line uses a **function** called `print` to display the value of `hello_string` to the screen. `hello_string` was **passed** to `print` as an **input** or **argument**.\n\nOoooooh. LOTS of terminology there. Let's list and define the terms:\n\n- ***line*** - just as you read a book one sentence at a time, Python executes a computer program one line at a time. If Python is executing the 4th line of a program, it *will* have knowledge of the three lines preceding it, *but no* knowledge of the lines that follow.\n- ***variable*** - think of this as a 'container' inside the computer code. A variable has a **name** (in this case, `hello_string`) and a **value**.\n- ***value*** - the thing sitting inside the 'container', in this case it is `'Hello, world'`, which is a particular **type** of variable called a string.\n- ***type*** - a classification of the variable, e.g., `'hi'` and `'Hello, world'` are both *strings*, `3.2`, `5.0` and `-0.12e5` are *floats*, and `2`, `-3412` and `0` are *integers*. There are other types, we will get to some of them later.\n- ***assign to*** - the act of giving a *value* to a *variable*, usually accomplished by an 'equals sign', e.g., `variable = value`.\n- ***function*** - a sequence of Python commands, written down somewhere else, to achieve some small (or large) task. Some functions are given to you as part of Python and its modules. Others you will have to define yourself. Functions inputs are given inside of **round brackets**.\n- ***input/argument*** - a variable that is used by a function as it executes its tasks.\n\n## Learning by doing\n\nObviously, the best way to master any new skill is to practice it. Work your way through the cells and exercises below to grow your Python foundation.\n\n## 1 We can use Python as a glorified calculator\n\nIn the example below, we create a few variables, assign them some simple numbers, and confirm that Python can manage basic arithmetic.\n\n\n```python\na = 2 # a variable named a, assigned a value of 2, which is of type 'integer'\nb = 3\nc = a+b # adding two variables together to create a third one\nprint(c)\n\n# Can you make a change? Define the variable d as the sum of a and b and c. Print it out.\n```\n\nSee also\n\n\n```python\nprint(a-b) # Python does subtraction\nprint(a*b) # and multiplication\nprint(a/b) # and division\nprint(a**b) # and exponentiation\n\n# Can you make a change? Print the value of b minus a, instead of a minus b .\n```\n\nThere are heaps of other mathematical operations we can perform with Python, many of which are made available through the NumPy module.\n\n\n```python\nimport numpy as np\nprint(np.sin(a))\n```\n\nIn the cell above we **imported** `numpy` and told Python to make the module available as a variable called `np`. Then, if I want to use one of its special functions, I use the **syntax** `module.function`.\n\nSome more examples below\n\n\n```python\nprint(np.cos(b))\nprint(np.log(a))\nprint(np.log10(b))\nprint(np.sinh(a))\nprint(np.arctan2(a,b))\n```\n\nNot sure what a particular function does? Write it down and replace the round brackets with a question mark `?`\n\n\n```python\nnp.arctan2?\n\n# what does np.exp do?\n```\n\n#### <homework>\n\nCalculate viscosity of magma according to the forumula given by [Costa et al. [2007]](http://onlinelibrary.wiley.com/doi/10.1029/2008GC002138/abstract)\n\n\\begin{equation}\n\\eta(\\phi) = \\frac{1+\\varphi^\\delta}{\\left[1-F(\\varphi, \\varepsilon, \\gamma)^{B\\cdot\\phi_*}\\right]},\\quad\\text{where}\\quad F=(1-\\xi)\\cdot\\text{erf}\\left[\\frac{\\sqrt{\\pi}}{2\\cdot(1-\\xi)}\\varphi\\cdot(1+\\varphi^\\gamma)\\right]\\quad\\text{with}\\quad\\varphi=\\frac{\\phi}{\\phi_*}.\n\\end{equation}\n\n\n```python\n# parameters\nphi = 0.5\nphi_star = 0.66\npi = 3.14159\nxi = 0.0009\ngamma = 9.8\nB = 2.5 # Einstein coefficient\ndelta = 1.3\n\n# note, the error function is given by erf(x)\nfrom scipy.special import erf # call this as a function, e.g., erf(2)\n\n# **complete the code below**\n# uncomment the partially written code below\n# calculate viscosity in three steps\n# - calculate new variable phi_scaled\n# - calculate F\n# - calculate viscosity\n\n#phi_scaled = phi/phi_star\n\n#F = ____\n\n#print(visc)\n\n```\n\n***How does increasing each of the parameters, $\\phi$, $\\phi_*$, $\\xi$ (`xi`), $\\gamma$, $B$, $\\delta$, change the viscosity, $\\eta$?***\n\n#### </homework>\n\n## 2 Whoops!\n\nI have replicated the very first example in this notebook, **except** that the variable names have been changed AND I have **reversed the order** of the commands.\n\n***Run the cell below***\n\n\n```python\n# this is a comment, nothing happens when Python reads this line\nprint(night_string)\nnight_string = 'Good night, world'\n```\n\nWhat you see above is a Python error message. ***Reading these messages and using them to debug your code is an invaluable skill.***\n\nThere are two key pieces of information:\n\n1. **WHERE** is the error. In this case, the problem occurs on Line 2. We know this, because there is an arrow pointing to it, i.e., `----> 2 print(night_string)`\n2. **WHAT** is the error. In this case, it is that we are attempting to use a variable called `night_string` before it has been created. We know this from the very last piece of information in the error message, i.e., `name 'night_string' is not defined`.\n\nDeciphering these errors **gets easier with practice**, because there are a handful of easy-to-make mistakes that will crop up frequently. \n\nAnother tip, sometimes the error is not on the line that `---->` points to, but instead the command immediately above or below it.\n\n***Fix the error above so that the cell runs correctly.***\n\nTo do this, swap the order of the two commands. The key here is that `night_string` has to be defined (`night_string = 'Good night, world'`) before it can be used in a function (`print(night_string)`).\n\n***See if you can fix the errors in the code below.***\n\n\n```python\n# calculate the harmonic average of the numbers a and b\nhamonic_avg = 2/(1/a+1/b\na = 2\nb = 3\nprint(hamonic_avg)\n```\n\n## 3 Lists and arrays\n\nThere are these things called lists. They are as you would expect, literally a list of ordered items. An example is given below.\n\n\n```python\nmy_list = [1,2,3] # this list has three items\nempty_list = [] # this list has no items\nmixed_list = [-0.2, 300, 'a string', 5.3, True, my_list] # this list has four items of different types, one is another list\n\nprint(mixed_list)\n```\n\nNote, lists use square brackets [] whereas functions use round brackets () - ***syntax!***\n\nWe can **access** the items of a list by passing an **index** to the variable name. The indices begin at 0 (the first item in a list) and increment by 1. For example\n\n\n```python\nprint(my_list[0])\n```\n\n\n```python\nprint(my_list[1]+my_list[2])\n```\n\nWe can also use indices to 'count backward' from the end of the list, for example\n\n\n```python\nprint(my_list[2], my_list[-1]) # these access the same element of the list\nprint(my_list[1], my_list[-2]) # so do these\n```\n\nWe can pull out a smaller list from the list using **index slicing**. This uses the colon, `:`, which essentially says 'and everything in between'. For example, \n\n\n```python\nprint(mixed_list)\nprint(mixed_list[1:3]) # all items between index 1 and 3 NOT including 3\nprint(mixed_list[:3]) # all items from the START of the list up to index 3 NOT including 3\nprint(mixed_list[3:]) # all items from index 3 up to the END of the list\n```\n\nOr we can even reverse a list.\n\n\n```python\nprint(mixed_list[::-1])\n```\n\nAn **array** is a list of numbers. It has special properties\n\n\n```python\nT = np.array([1,2,3]) # array of 1st order temperature measurements\ndT = np.array([0.1, 0.1, -0.1]) # array of corresponding 2nd order temperature deviation\nprint(T+dT) # total temperature change\nprint(T*dT) # product of 1st and 2nd order effects\n```\n\nMake sure your arrays are the same length though! ***Execute the cell below and interpret the error message***\n\n\n```python\nb1 = np.array([4,5,6])\nb2 = np.array([0.1,-0.1])\nprint(b1+b2)\n```\n\n## 4 Doing things over and over\n\nScripting is useful to automate tasks that have to be performed over and over. For instance, consider calculating the value of $e$ using the exponential series\n\n$$ e = 1+\\frac{1}{1!}+\\frac{1}{2!}+\\frac{1}{3!}+\\frac{1}{4!}+\\cdots $$\n\nWe could do it the long way...\n\n\n```python\nfrom math import factorial\ne = 1 + 1/factorial(1) + 1/factorial(2) + 1/factorial(3) + 1/factorial(4) + 1/factorial(5) # I got tired and gave up here\nprint(e)\n```\n\nOr we could write a **for loop** to do it for us.\n\n\n```python\ne = 1 # the initial value\nfor i in range(1,21): # create a variable called i, initially assign it the value of 1, then 2, then 3, ... then 20\n e = e + 1/factorial(i) # each time the loop 'goes around', execute the commands 'in the loop'\nprint(e)\n```\n\nWhat's happening above? The loop we have written is identical to the sequence of commands below\n\n\n```python\ne = 1\ni = 1\ne = e + 1/factorial(i)\ni = 2\ne = e + 1/factorial(i)\ni = 3\ne = e + 1/factorial(i)\ni = 4\ne = e + 1/factorial(i)\ni = 5\ne = e + 1/factorial(i)\ni = 6\ne = e + 1/factorial(i)\ni = 7\ne = e + 1/factorial(i)\ni = 8\ne = e + 1/factorial(i)\ni = 9\ne = e + 1/factorial(i)\ni = 10\ne = e + 1/factorial(i)\ni = 11\ne = e + 1/factorial(i)\ni = 12\ne = e + 1/factorial(i)\ni = 13\ne = e + 1/factorial(i)\ni = 14\ne = e + 1/factorial(i)\ni = 15\ne = e + 1/factorial(i)\ni = 16\ne = e + 1/factorial(i)\ni = 17\ne = e + 1/factorial(i)\ni = 18\ne = e + 1/factorial(i)\ni = 19\ne = e + 1/factorial(i)\ni = 20\ne = e + 1/factorial(i)\nprint(e)\n```\n\nbut with A LOT less repetition. Can you see which command is 'inside the loop' and gets executed over and over? Can you see which variable has its value changed with each iteration of the loop?\n\n***In the cell below, write a for loop to calculate the \"sum of squares\" of the list of pressure observations.***\n\n\n```python\na = [7,3,-2,0,4.5,9.0,-1,-1,15,0.1] # pressure deviations (in kPa), from p0 = 101 kPa\nsum_squares = 0\n# **your code here**\n```\n\n## 5 Making the computer program a little bit smart\n\nHumans are allegedly an intelligent species. One aspect of this intelligence is the ability to **see how things are and act accordingly**. What?\n\nAs an example, to cross a busy street, you first check for cars. ***If*** there is a car coming, you do not cross, ***else*** you do. \n\nWe can write this in Python.\n\n\n```python\nstreet = 'busy'\nif street == 'busy':\n print('dont cross the street')\nelse:\n print('cross the street')\n```\n\nThe `if` statement above evaluates a **condition** (essentially a question asked of Python, is the 'value' of `street` equal to `'busy'`?). \n\nIf the condition evaluates to `True`, then the command `print('dont cross the street')` is executed. If it evaluates to `'False'`, then the command `print('cross the street')` is executed instead. \n\nThe key here though is that it is **one or the other** and the outcome depends on stuff that happened earlier in the code (in this case, on the first line when I assigned a value to the variable `street`).\n\nHave another play with the example below.\n\n\n```python\nstreet = 'busy'\nattempt_to_cross = True # this is a type of variable called a 'boolean' - it is either True or False, no other options\n\nif street == 'busy' and attempt_to_cross is False: # the first condition to check\n print('dont cross, good decision')\nelif street != 'busy' and attempt_to_cross is True: # if the first condition is False, then check this one\n print('safe to cross, well done')\nelif street == 'busy' and attempt_to_cross is True: # if the first AND second conditions are False, check this one\n print('you dead')\n```\n\nIn the example above, we see that the **special statement**, `and`, allows us to evaluate two conditions at once and require that they BOTH be true. Alternatively, we could have used `or`, which allows either one, or both to be true.\n\n***Make changes to the cell above to generate a \"successful crossing\" outcome.***\n\nThe example below demonstrates different conditions and combinations of conditions:\n\n\n```python\nprint('1',True and True)\nprint('2',True and False)\nprint('3',True or False)\nprint('4',False or False)\nprint('5',not False)\nprint('6', False or not False)\nprint('6b', False or not (True or not True))\nprint('7', 3>4)\nprint('8', 3<4)\nprint('9', 4<4)\nprint('10', 4<=4)\nprint('11', 4==4)\ndensity = 2650.\nprint('12', density>2400. and density<2800.)\nprint('13', 2400. 1.e-5: # check the condition\n e = e + de # update the estimate of e\n i = i + 1 # increment the counter\n de = 1/factorial(i) # calculate a new value for de\n print('i =',i,', e =', e) # print progress so far\n \n# MAKE A CHANGE\n# - modify the loop so that it exits when e has been calculated to 6 decimal places\n# - modify the loop so that it exits when e has been calculated to 8 decimal places, or when 12 terms \n# have been calculated, whichever comes first\n```\n\n## 6 Classes, objects, attributes and methods\n\nPython is an [**object-oriented**](https://en.wikipedia.org/wiki/Object-oriented_programming) programming language. Most people initially become familiar with **procedural, structured programming**, computer code organised into a logical procession of statements, loops, control blocks and functions. We can build on that understanding and introduce the idea of **objects, with attributes and methods**.\n\nThe best introduction is perhaps a direct demonstration.\n\n**Execute the cell below to define a new *Class* for a geothermal well.**\n\n\n```python\nclass Well(object): # defining a class is similar to defining a function in that there is precise syntax\n ''' An object to represent an arbitrary Well.\n '''\n def __init__(self):\n ''' Define what properties the object should have when it is brought into existence\n '''\n self.location = [] # these are called attributes, we have defined 3: location, name and depth\n self.name = 'unnamed' # they are like variables, but they *belong* to the object\n self.depth = None # we can access and change them using the notation OBJECT.ATTRIBUTE\n```\n\nThink of the **Class** as a new \"kind\" or a \"type\" of object (along with floats, integers, strings, and arrays). Much like a function, once it is defined, we can begin to use it.\n\n\n```python\n# Create an *instance* of the Well object. A duplicate, to be modified independently of other instances.\nwell1 = Well() # note the use of brackets in creating the object\nwell2 = Well() # now we have two 'instances' of the Well object\n\nprint(well1.name, well2.name)\n```\n\nWe can modify their **attributes** in the usual way a variable is modified.\n\n\n```python\n# let's make the first object personal (change for yourself)\nwell1.location = [0.5, 8.2]\nwell1.name = 'tvz25'\nwell1.depth = 2305.\n\n# let's make the second object a beloved pet (change for yourself)\nwell2.location = [6.3, -2.4]\nwell2.name = 'tvz32'\nwell2.depth = 1680.\n\nprint(well1.name, well2.name) # verifying we have changed the attributes\nprint(well1.depth > well2.depth) # verifying attributes are subject to the usual computer arithmetic\n```\n\n#### <neat> `__repr__`\n\nTry **printing** an object directly.\n\n\n```python\nprint(well2)\n```\n\nThe standard output is not very **informative**...\n\nWe can modify this by including a **specialised method** called '__repr__' in the class definition\n\n\n```python\nclass Well(object): \n ''' An object to represent an arbitrary Well.\n '''\n def __init__(self):\n ''' Define what properties the object should have when it is brought into existence\n '''\n self.location = [] \n self.name = 'unnamed' \n self.depth = None \n def __repr__(self):\n ''' What information to print to the screen when the object is printed.\n '''\n return '{:s}'.format(self.name)\n \n# create and print the new object\nwell2 = Well()\nwell2.location = [6.3, -2.4]\nwell2.name = 'tvz32'\nwell2.depth = 1680.\nprint(well2)\n```\n\n#### </neat>\n\nAn object's attributes are **specific** to it. For example, \n\n\n```python\nprint(well1.name) # the 'name' *attribute* has been defined for the well1 object\nprint(well2.name) # the 'name' *attribute* has been defined for the well2 object\nprint(name) # 'name' on its own is a *variable* that has yet to be defined\n```\n\nIn much the same way that attributes are just variables **specific to an object**, we can define **methods**, which are functions **specific to an object**.\n\n***Execute the cell below to update the Well class with a method `bhp` that computes bottomhole pressure.***\n\n\n```python\nclass Well(object): \n ''' An object to represent an arbitrary Well.\n '''\n def __init__(self):\n ''' Define what properties the object should have when it is brought into existence\n '''\n self.location = [] \n self.name = 'unnamed' \n self.depth = None \n def __repr__(self):\n ''' What information to print to the screen when the object is printed.\n '''\n return '{:s}'.format(self.name)\n \n def bhp(self, density=1000., whp=0.1):\n ''' Computes the bottomhole pressure (in MPa) for given fluid density and wellhead pressure.\n '''\n # set gravity\n g = 9.81\n # compute pressure due to water column, in Pa\n dP = density*self.depth*g\n # convert to MPa\n dP = dP/1.e6\n # add wellhead pressure\n bhp = whp + dP\n # return value\n return bhp\n```\n\n***Execute the cell below to call the `bhp` method for a range of inputs.***\n\n\n```python\n# define a well\nwell2 = Well()\nwell2.location = [6.3, -2.4]\nwell2.name = 'tvz32'\nwell2.depth = 1680.\n\n# compute downhole pressure assuming density of 1000. and whp of 12 bar (1.2 MPa)\nbottomholepressure = well2.bhp(density=1000., whp=1.2)\nprint('at 1000 kg/m^3 and 12 bar WHP, the BHP is', bottomholepressure)\n\n# compute downhole pressure with density of 980 and atmospheric pressure (default 0.1)\nbottomholepressure = well2.bhp(density=980.)\nprint('at 980 kg/m^3 and open, the BHP is', bottomholepressure)\n\n# compute downhole pressure using all defaults\nbottomholepressure = well2.bhp()\nprint('at 1000 kg/m^3 and open, the BHP is', bottomholepressure)\n```\n\n# What now?\n\nThere you go. That's your crash course in computer coding with Python. Obviously, we're only scraping the surface, and you shouldn't expect to really feel like you \"*know what you're doing*\" until you've been writing Python for a month or so. \n\nThe rewards though. So great.\n", "meta": {"hexsha": "e5f2e022e2156293e555ad107ad98000a897cd6d", "size": 36232, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "supplementary/python101.ipynb", "max_stars_repo_name": "bryan-ruddy/ENGSCI233_2021", "max_stars_repo_head_hexsha": "97a9ede84183603ac7975d5692885921419608fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-09T02:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T02:22:42.000Z", "max_issues_repo_path": "supplementary/python101.ipynb", "max_issues_repo_name": "bryan-ruddy/ENGSCI233_2021", "max_issues_repo_head_hexsha": "97a9ede84183603ac7975d5692885921419608fa", "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": "supplementary/python101.ipynb", "max_forks_repo_name": "bryan-ruddy/ENGSCI233_2021", "max_forks_repo_head_hexsha": "97a9ede84183603ac7975d5692885921419608fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-03T09:25:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T02:15:57.000Z", "avg_line_length": 32.6414414414, "max_line_length": 467, "alphanum_fraction": 0.5601402076, "converted": true, "num_tokens": 6314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223189500989633, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.0672306666195902}} {"text": "

    Table of Contents

    \n\n\n# Question\n**Question 1.1** Write a Python Program(with class concepts) to find the area of the triangle using the below formula.

    \n\n`area = (s*(s-a)*(s-b)*(s-c)) ** 0.5`

    \n\nFunction to take the length of the sides of triangle from user should be defined in the parent class and function to calculate the area should be defined in subclass.\n\n**BreakDown points**
    \n`Class Parent : Should Read inputs from User fr the sides of triangle`
    \n`Class Child : Should Calculate the Area Of Triangle with Variables from parent`
    \n\n**Heron's Formula**\n\\begin{align}\ns = \\frac{a + b + c}{2}\n\\end{align}\n

    \n\\begin{align}\nArea Of Triangle = \\sqrt{(s*(s-a)*(s-b)*(s-c))}\n\\end{align}\n\n## Answer\n\n\n```python\n# Parent Class : Will get the input from User and display\nclass LengthOfTheSides():\n def __init__(self):\n print('Please provide length of the sides of triangle : \\n')\n self.a = float(input('side1 : '))\n self.b = float(input('side2 : '))\n self.c = float(input('side3 : '))\n \n def __repr__(self):\n return 'Provided Values are ...\\nside1 = {}, side2 = {}, side3 = {}\\n\\n'.format(str(self.a),str(self.b), str(self.c))\n\n# Child Class : Will Calculate the Area Of Triangle\nclass Area(LengthOfTheSides):\n def __init__(self):\n LengthOfTheSides.__init__(self)\n \n def AreaOfTriangle(self):\n s, a, b, c = (self.a + self.b + self.c)/2, self.a, self.b, self.c\n return (s*(s-a)*(s-b)*(s-c)) ** 0.5\n\nAreaOfTriangle = Area()\nprint('\\nArea Of Triangle : {}'.format(AreaOfTriangle.AreaOfTriangle()))\n```\n\n Please provide length of the sides of triangle : \n \n side1 : 5\n side2 : 4\n side3 : 3\n \n Area Of Triangle : 6.0\n\n\n# Question\n\n**Question 1.2** Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.\n\n## Answer\n\n\n```python\ndef filter_long_words(words_to_check, max_length):\n # Check Provided Arg[0] is List\n if not isinstance(words_to_check, list):\n raise Exception('Please enter arg[0] as list of words')\n # Check Provided Arg[1] is int\n if not isinstance(max_length, int):\n raise Exception('Please enter arg[1] as int')\n \n return [i for i in words_to_check if len(i)>max_length]\n```\n\n\n```python\n# Correct Arguments Passed\n\nfilter_long_words(['Vignesh', 'Vicky'], 5)\n```\n\n\n\n\n ['Vignesh']\n\n\n\n\n```python\n# Arg[0] is String \n\nfilter_long_words('Vignesh', 5)\n```\n\n\n```python\n# Arg[1] is String \n\nfilter_long_words(['Vignesh', 'Vicky'], \"5\")\n```\n\n# Question\n\n**Question 2.1** Write a Python program using function concept that maps list of words into a list of integers representing the lengths of the corresponding words.\n\n**Hint:** If a list [ ab,cde,erty] is passed on to the python function output should come as [2,3,4]. Here 2,3 and 4 are the lengths of the words in the list.\n\n## Answer\n\n\n```python\ndef words_to_int(words_to_check):\n # Check Provided Arg[0] is List\n if not isinstance(words_to_check, list):\n raise Exception('Please enter arg[0] as list of words')\n \n return [len(i) for i in words_to_check]\n```\n\n\n```python\nwords_to_int(['Vignesh', 'Vicky'])\n```\n\n\n\n\n [7, 5]\n\n\n\n# Question\n\n**Question 2.2** Write a Python function which takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.\n\n## Answer\n\n\n```python\ndef check_vowels(char_to_check):\n vowels = ('a', 'e', 'i', 'o', 'u')\n \n # Check Provided Arg[0] is a Single Charecter String\n if isinstance(char_to_check, str) and len(char_to_check) == 1:\n if char_to_check.lower() in vowels:\n return True\n else:\n return False\n else:\n raise Exception('Please enter arg[0] as a Single Charecter String')\n```\n\n\n```python\ncheck_vowels('V')\n```\n\n\n\n\n False\n\n\n\n\n```python\ncheck_vowels('I')\n```\n\n\n\n\n True\n\n\n", "meta": {"hexsha": "790c1ada8d04f8daf20879ad50f848003c29b2e8", "size": 15478, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Assignments/Basic-Python-Assignment-4-OOPS.ipynb", "max_stars_repo_name": "vigneshpalanivelr/MeachineLearningAI", "max_stars_repo_head_hexsha": "16741f08b8846fd27c319aff24d7e043acb843f3", "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": "Assignments/Basic-Python-Assignment-4-OOPS.ipynb", "max_issues_repo_name": "vigneshpalanivelr/MeachineLearningAI", "max_issues_repo_head_hexsha": "16741f08b8846fd27c319aff24d7e043acb843f3", "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": "Assignments/Basic-Python-Assignment-4-OOPS.ipynb", "max_forks_repo_name": "vigneshpalanivelr/MeachineLearningAI", "max_forks_repo_head_hexsha": "16741f08b8846fd27c319aff24d7e043acb843f3", "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": 35.9953488372, "max_line_length": 1352, "alphanum_fraction": 0.5742343972, "converted": true, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268346176374815, "lm_q2_score": 0.1422318931919251, "lm_q1q2_score": 0.06723066364717084}} {"text": "# pAPRika tutorial 5 - APR/Amber with Plumed restraints\n\nIn this tutorial, we will perform APR calculations for the butane (BUT)--cucurbit[6]uril (CB6) host-guest system. This is a repeat of [Tutorial 1](01-tutorial-cb6-but.ipynb) using `Plumed`-based restraints and the `AMBER` MD engine. `Plumed` is a plugin for MD codes that can analyze trajectories and perform free-energy calculations on collective variables. It is a versatile plugin that can interface with a number of MD engines. Here, we will go through the process of converting APR restraints constructed with pAPRika to a `Plumed` file and run a short calculation with `sander`.\n\n## Initialize\n\n### Before you start\n\nWe will run the simulations in this tutorial using `sander` (*Ambertools*) and `Plumed`. Both of these should be installed in your `conda` environment if you installed *pAPRika* though the `conda` route. However, for `Plumed` to work with `sander` we first need to make sure the `PLUMED_KERNEL` environment variable is loaded (the library is called `libplumedKernel.so`). *pAPRika* should load the `Plumed` kernel automatically but let's make sure it is loaded and run the cell below.\n\n\n```python\nimport os\n'PLUMED_KERNEL' in os.environ.keys()\n```\n\n\n\n\n False\n\n\n\nIf it does not exists we will load the environment in this Jupyter Notebook. Since `Plumed` is installed through `conda` the kernel will be located in your conda environment library folder. If you are running this on a Mac replace the kernel library in the cell below to `libplumedKernel.dylib`. If you compiled `Plumed` yourself and then you will need to change the path below.\n\n\n```python\nos.environ['PLUMED_KERNEL'] = f\"{os.environ['CONDA_PREFIX']}/lib/libplumedKernel.so\"\n```\n\nFor running `Plumed` with Amber outside of this notebook it might be better to export the `PLUMED_KERNEL` variable into your `.bashrc` file.\n\n**Note:** we can run `Plumed` with `AMBER` versions 18 and 20, but version 18 requires you to patch the source code first and recompile. Older versions of Amber are not supported. See the `Plumed` documentation for more details https://www.plumed.org/doc-v2.6/user-doc/html/index.html.\n\n🔵 Since we have a prepared the host-guest-dummy setup from the first tutorial, we will skip the initial tleap steps and go right into initializing the restraints.\n\n### Define names\nWe will store the files created in this tutorial in a folder called `plumed` so we don't mix files with the previous tutorial.\n\n\n```python\nbase_name = \"cb6-but-dum\"\nwork_dir = \"plumed\"\ncomplex_dir = \"complex\"\n```\n\n## Configure APR Restraints\n\n### Define anchor atoms\nSee [tutorial 1](01-tutorial-cb6-but.ipynb) for the choice of selection\n\n\n```python\n# Guest atoms\nG1 = \":BUT@C\"\nG2 = \":BUT@C3\"\n\n# Host atoms\nH1 = \":CB6@C\"\nH2 = \":CB6@C31\"\nH3 = \":CB6@C18\"\n\n# Dummy atoms\nD1 = \":DM1\"\nD2 = \":DM2\"\nD3 = \":DM3\"\n```\n\n### Determine the number of windows\nBefore we add the restraints, it is helpful to set the $\\lambda$ fractions that control the strength of the force constants during attach and release, and to define the distances for the pulling phase.\n\nThe attach fractions go from 0 to 1 and we place more points at the bottom of the range to sample the curvature of $dU/d \\lambda$. Next, we generally apply a distance restraint until the guest is ~18 Angstroms away from the host, in increments of 0.4 Angstroms. This distance should be at least twice the Lennard-Jones cutoff in the system. These values have worked well for us, but this is one aspect that should be carefully checked for new systems.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nattach_string = \"0.00 0.40 0.80 1.60 2.40 4.00 5.50 8.65 11.80 18.10 24.40 37.00 49.60 74.80 100.00\"\nattach_fractions = [float(i) / 100 for i in attach_string.split()]\n\ninitial_distance = 6.0\npull_distances = np.arange(0.0 + initial_distance, 18.0 + initial_distance, 1.0)\n\nrelease_fractions = []\n\nwindows = [len(attach_fractions), len(pull_distances), len(release_fractions)]\nprint(f\"There are {windows} windows in this attach-pull-release calculation.\")\n```\n\n There are [15, 18, 0] windows in this attach-pull-release calculation.\n\n\n### Load structure\n\n\n```python\nimport parmed as pmd\n```\n\n* Load complex structure\n\n\n```python\nstructure = pmd.load_file(\n os.path.join(complex_dir, f\"{base_name}.prmtop\"),\n os.path.join(complex_dir, f\"{base_name}.rst7\"),\n structure = True,\n) \n```\n\n### Host Static Restraints\nSee [tutorial 1](01-tutorial-cb6-but.ipynb#host_static) for an explanation of the static restraints\n\n\n```python\nimport paprika.restraints as restraints\n```\n\n\n```python\nstatic_restraints = []\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D1, H1],\n num_window_list = windows,\n ref_structure = structure,\n force_constant = 5.0,\n amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D2, D1, H1],\n num_window_list = windows,\n ref_structure = structure,\n force_constant = 100.0,\n amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D3, D2, D1, H1],\n num_window_list = windows,\n ref_structure = structure,\n force_constant = 100.0,\n amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D1, H1, H2],\n num_window_list = windows,\n ref_structure = structure,\n force_constant = 100.0,\n amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D2, D1, H1, H2],\n num_window_list = windows,\n ref_structure = structure,\n force_constant = 100.0,\n amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D1, H1, H2, H3],\n num_window_list = windows,\n ref_structure = structure,\n force_constant = 100.0,\n amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n### Guest translational and rotational restraints\nSee [tutorial 1](01-tutorial-cb6-but.ipynb#guest) for an explanation of the guest restraints\n\n\n```python\nguest_restraints = []\n```\n\n\n```python\nr = restraints.DAT_restraint()\nr.mask1 = D1\nr.mask2 = G1\nr.topology = structure\nr.auto_apr = True\nr.continuous_apr = True\nr.amber_index = True\n\nr.attach[\"target\"] = pull_distances[0] # Angstroms\nr.attach[\"fraction_list\"] = attach_fractions\nr.attach[\"fc_final\"] = 5.0 # kcal/mol/Angstroms**2\n\nr.pull[\"target_final\"] = 24.0 # Angstroms\nr.pull[\"num_windows\"] = windows[1]\n\nr.initialize()\nguest_restraints.append(r)\n```\n\n\n```python\nr = restraints.DAT_restraint()\nr.mask1 = D2\nr.mask2 = D1\nr.mask3 = G1\nr.topology = structure\nr.auto_apr = True\nr.continuous_apr = True\nr.amber_index = True\n\nr.attach[\"target\"] = 180.0 # Degrees\nr.attach[\"fraction_list\"] = attach_fractions\nr.attach[\"fc_final\"] = 100.0 # kcal/mol/radian**2\n\nr.pull[\"target_final\"] = 180.0 # Degrees\nr.pull[\"num_windows\"] = windows[1]\n\nr.initialize()\nguest_restraints.append(r)\n```\n\n\n```python\nr = restraints.DAT_restraint()\nr.mask1 = D1\nr.mask2 = G1\nr.mask3 = G2\nr.topology = structure\nr.auto_apr = True\nr.continuous_apr = True\nr.amber_index = True\n\nr.attach[\"target\"] = 180.0 # Degrees\nr.attach[\"fraction_list\"] = attach_fractions\nr.attach[\"fc_final\"] = 100.0 # kcal/mol/radian**2\n\nr.pull[\"target_final\"] = 180.0 # Degrees\nr.pull[\"num_windows\"] = windows[1]\n\nr.initialize()\nguest_restraints.append(r)\n```\n\n### Create APR windows\nWe use the guest restraints to create a list of windows with the appropriate names and then create the directories.\n\n\n```python\nfrom paprika.restraints.restraints import create_window_list\n```\n\n\n```python\nwindow_list = create_window_list(guest_restraints)\n```\n\n\n```python\nif not os.path.isdir(work_dir):\n os.makedirs(work_dir)\n \nfor window in window_list:\n folder = os.path.join(work_dir, window)\n if not os.path.isdir(folder):\n os.makedirs(os.path.join(work_dir, window))\n```\n\n### Write APR restraints to Plumed format\nIn this section we create an instance of `Plumed()` from `paprika.restraints.plumed`, which is a class to generate the `Plumed` restraint files. We need to specify the list of restraints used throughout the APR calculations and the corresponding windows list. In this tutorial we will print the **host static** restraints and the **guest** restraints. The `Plumed` class includes a method to add restraints to dummy atoms (`add_dummy_atoms_to_file`) but we will not do that here. Instead we will use the built-in position restraints feature in Amber (see [Simulation](#simulate) section below).\n\n**Note**: be careful when specifiying the force constants in `DAT_restraints`. We follow the Amber (and CHARMM) convention where the force constant is already multiplied by a factor of 1/2 but `Plumed` requires the user to specify the force constant without this factor, i.e.\n\n$$\n\\begin{align}\nU_{amber} &= K_{amber} (r-r_{0})^2 \\\\\nU_{plumed} &= \\frac{1}{2} k_{plumed} (r - r_{0})^2 \n\\end{align}\n$$\n\nthus $k_{plumed} = 2 \\times K_{amber}$. If Amber force constants was used in generating the `DAT_restraints` (the case in this tutorial) we need to set the variable `uses_legacy_k` to `True` (this is on by default).\n\n\n```python\nfrom paprika.restraints.plumed import Plumed\n```\n\n\n```python\nrestraints_list = (static_restraints + guest_restraints)\n\nplumed = Plumed()\nplumed.file_name = 'plumed.dat'\nplumed.path = work_dir\nplumed.window_list = window_list\nplumed.restraint_list = restraints_list\nplumed.uses_legacy_k = True\n\nplumed.dump_to_file()\n```\n\n## Prepare host-guest system\n\n### Translate guest molecule\nFor the attach windows, we will use the initial, bound coordinates for the host-guest complex. Only the force constants change during this phase, so a single set of coordinates is sufficient. For the pull windows, we will translate the guest to the target value of the restraint before solvation, and for the release windows, we will use the coordinates from the final pull window.\n\n\n```python\nimport shutil\n```\n\n\n```python\nfor window in window_list:\n if window[0] == \"a\":\n shutil.copy(os.path.join(complex_dir, f\"{base_name}.prmtop\"),\n os.path.join(work_dir, window, f\"{base_name}.prmtop\"))\n shutil.copy(os.path.join(complex_dir, f\"{base_name}.rst7\"),\n os.path.join(work_dir, window, f\"{base_name}.rst7\"))\n\n elif window[0] == \"p\":\n structure = pmd.load_file(\n os.path.join(complex_dir, f\"{base_name}.prmtop\"), \n os.path.join(complex_dir, f\"{base_name}.rst7\"), \n structure = True\n )\n target_difference = guest_restraints[0].phase['pull']['targets'][int(window[1:])] -\\\n guest_restraints[0].pull['target_initial']\n print(f\"In window {window} we will translate the guest {target_difference.magnitude:0.1f}.\")\n \n for atom in structure.atoms:\n if atom.residue.name == \"BUT\":\n atom.xz += target_difference.magnitude\n \n structure.save(os.path.join(work_dir, window, f\"{base_name}.prmtop\"), overwrite=True)\n structure.save(os.path.join(work_dir, window, f\"{base_name}.rst7\"), overwrite=True)\n```\n\n In window p000 we will translate the guest 0.0 Angstroms.\n In window p001 we will translate the guest 1.1 Angstroms.\n In window p002 we will translate the guest 2.1 Angstroms.\n In window p003 we will translate the guest 3.2 Angstroms.\n In window p004 we will translate the guest 4.2 Angstroms.\n In window p005 we will translate the guest 5.3 Angstroms.\n In window p006 we will translate the guest 6.4 Angstroms.\n In window p007 we will translate the guest 7.4 Angstroms.\n In window p008 we will translate the guest 8.5 Angstroms.\n In window p009 we will translate the guest 9.5 Angstroms.\n In window p010 we will translate the guest 10.6 Angstroms.\n In window p011 we will translate the guest 11.6 Angstroms.\n In window p012 we will translate the guest 12.7 Angstroms.\n In window p013 we will translate the guest 13.8 Angstroms.\n In window p014 we will translate the guest 14.8 Angstroms.\n In window p015 we will translate the guest 15.9 Angstroms.\n In window p016 we will translate the guest 16.9 Angstroms.\n In window p017 we will translate the guest 18.0 Angstroms.\n\n\n## Simulation\n\nSince we are going to run an implicit solvent simulation, we have everything ready to go. **pAPRika** has an `AMBER` module that can help setting default parameters for the simulation. There are some high level options that we set directly, like `simulation.path`, and then we call the function `config_gb_min()` to setup reasonable default simulation parameters for a minimization in the Generalized-Born ensemble. After that, we directly modify the simulation `cntrl` section to apply the positional restraints on the dummy atoms. \n\nWe will run the simulations with `sander` but it is also possible and faster to run this with `pmemd` or `pmemd.cuda` if you have them installed.\n\n**Note**: The difference here compared to [Tutorial 1](01-tutorial-cb6-but.ipynb#simulate) is that instead of specifying a `simulation.restraint_file` we will specify `simulation.plumed_file`.\n\n**Note**: as explained at the [start](#start) of this tutorial, make sure that the `PLUMED_KERNEL` environment variable is set otherwise the simulation will fail to run.\n\n\n```python\nfrom paprika.simulate import AMBER\n```\n\nInitialize logger\n\n\n```python\nimport logging\nfrom importlib import reload\nreload(logging)\n\nlogger = logging.getLogger()\nlogging.basicConfig(\n format='%(asctime)s %(message)s',\n datefmt='%Y-%m-%d %I:%M:%S %p',\n level=logging.INFO\n)\n```\n\n### Energy Minimization\nRun a quick minimization in every window. Note that we need to specify `simulation.cntrl[\"ntr\"] = 1` to enable the positional restraints on the dummy atoms.\n\n\n```python\nfor window in window_list:\n simulation = AMBER()\n simulation.executable = \"sander\"\n\n simulation.path = f\"{work_dir}/{window}/\"\n simulation.prefix = \"minimize\"\n\n simulation.topology = \"cb6-but-dum.prmtop\"\n simulation.coordinates = \"cb6-but-dum.rst7\"\n simulation.ref = \"cb6-but-dum.rst7\"\n simulation.plumed_file = \"plumed.dat\"\n\n simulation.config_gb_min()\n simulation.cntrl[\"ntr\"] = 1\n simulation.cntrl[\"restraint_wt\"] = 50.0\n simulation.cntrl[\"restraintmask\"] = \"'@DUM'\"\n\n logger.info(f\"Running minimization in window {window}...\")\n simulation.run(overwrite=True)\n```\n\n 2020-10-01 11:18:20 AM Running minimization in window a000...\n 2020-10-01 11:18:31 AM Running minimization in window a001...\n 2020-10-01 11:18:42 AM Running minimization in window a002...\n 2020-10-01 11:18:54 AM Running minimization in window a003...\n 2020-10-01 11:19:05 AM Running minimization in window a004...\n 2020-10-01 11:19:17 AM Running minimization in window a005...\n 2020-10-01 11:19:28 AM Running minimization in window a006...\n 2020-10-01 11:19:42 AM Running minimization in window a007...\n 2020-10-01 11:19:54 AM Running minimization in window a008...\n 2020-10-01 11:20:06 AM Running minimization in window a009...\n 2020-10-01 11:20:18 AM Running minimization in window a010...\n 2020-10-01 11:20:30 AM Running minimization in window a011...\n 2020-10-01 11:20:42 AM Running minimization in window a012...\n 2020-10-01 11:20:53 AM Running minimization in window a013...\n 2020-10-01 11:21:04 AM Running minimization in window p000...\n 2020-10-01 11:21:14 AM Running minimization in window p001...\n 2020-10-01 11:21:26 AM Running minimization in window p002...\n 2020-10-01 11:21:38 AM Running minimization in window p003...\n 2020-10-01 11:21:50 AM Running minimization in window p004...\n 2020-10-01 11:22:01 AM Running minimization in window p005...\n 2020-10-01 11:22:15 AM Running minimization in window p006...\n 2020-10-01 11:22:28 AM Running minimization in window p007...\n 2020-10-01 11:22:40 AM Running minimization in window p008...\n 2020-10-01 11:22:54 AM Running minimization in window p009...\n 2020-10-01 11:23:06 AM Running minimization in window p010...\n 2020-10-01 11:23:19 AM Running minimization in window p011...\n 2020-10-01 11:23:31 AM Running minimization in window p012...\n 2020-10-01 11:23:44 AM Running minimization in window p013...\n 2020-10-01 11:23:55 AM Running minimization in window p014...\n 2020-10-01 11:24:07 AM Running minimization in window p015...\n 2020-10-01 11:24:19 AM Running minimization in window p016...\n 2020-10-01 11:24:30 AM Running minimization in window p017...\n\n\n### Production Run\nHere we will skip the equilibration step and go straight to production!\n\n\n```python\nfor window in window_list:\n simulation = AMBER()\n simulation.executable = \"sander\"\n \n simulation.path = f\"{work_dir}/{window}/\"\n simulation.prefix = \"production\"\n\n simulation.topology = \"cb6-but-dum.prmtop\"\n simulation.coordinates = \"minimize.rst7\"\n simulation.ref = \"cb6-but-dum.rst7\"\n simulation.plumed_file = \"plumed.dat\"\n\n simulation.config_gb_md()\n simulation.cntrl[\"ntr\"] = 1\n simulation.cntrl[\"restraint_wt\"] = 50.0\n simulation.cntrl[\"restraintmask\"] = \"'@DUM'\"\n \n logger.info(f\"Running production in window {window}...\")\n simulation.run(overwrite=True)\n```\n\n 2020-10-01 11:12:15 AM Running production in window a000...\n 2020-10-01 11:12:25 AM Running production in window a001...\n 2020-10-01 11:12:34 AM Running production in window a002...\n 2020-10-01 11:12:44 AM Running production in window a003...\n 2020-10-01 11:12:55 AM Running production in window a004...\n 2020-10-01 11:13:06 AM Running production in window a005...\n 2020-10-01 11:13:19 AM Running production in window a006...\n 2020-10-01 11:13:29 AM Running production in window a007...\n 2020-10-01 11:13:39 AM Running production in window a008...\n 2020-10-01 11:13:49 AM Running production in window a009...\n 2020-10-01 11:13:59 AM Running production in window a010...\n 2020-10-01 11:14:10 AM Running production in window a011...\n 2020-10-01 11:14:19 AM Running production in window a012...\n 2020-10-01 11:14:29 AM Running production in window a013...\n 2020-10-01 11:14:39 AM Running production in window p000...\n 2020-10-01 11:14:49 AM Running production in window p001...\n 2020-10-01 11:14:59 AM Running production in window p002...\n 2020-10-01 11:15:10 AM Running production in window p003...\n 2020-10-01 11:15:21 AM Running production in window p004...\n 2020-10-01 11:15:33 AM Running production in window p005...\n 2020-10-01 11:15:43 AM Running production in window p006...\n 2020-10-01 11:15:55 AM Running production in window p007...\n 2020-10-01 11:16:05 AM Running production in window p008...\n 2020-10-01 11:16:18 AM Running production in window p009...\n 2020-10-01 11:16:31 AM Running production in window p010...\n 2020-10-01 11:16:45 AM Running production in window p011...\n 2020-10-01 11:16:56 AM Running production in window p012...\n 2020-10-01 11:17:05 AM Running production in window p013...\n 2020-10-01 11:17:16 AM Running production in window p014...\n 2020-10-01 11:17:26 AM Running production in window p015...\n 2020-10-01 11:17:37 AM Running production in window p016...\n 2020-10-01 11:17:49 AM Running production in window p017...\n\n\n## Analysis\n\nOnce the simulation is completed, we can using the `analysis` module to determine the binding free energy. We supply the location of the parameter information, a string or list for the file names (wildcards supported), the location of the windows, and the restraints on the guest.\n\nIn this example, we use the method `ti-block` which determines the free energy using **t**hermodynamic **i**integration and then estimates the standard error of the mean at each data point using blocking analysis. Bootstrapping it used to determine the uncertainty of the full thermodynamic integral for each phase.\n\nAfter running `compute_free_energy()`, a dictionary called `results` will be populated, that contains the free energy and SEM for each phase of the simulation.\n\n\n```python\nimport paprika.analysis as analysis\n```\n\n\n```python\nfree_energy = analysis.fe_calc()\nfree_energy.topology = \"cb6-but-dum.prmtop\"\nfree_energy.trajectory = 'production*.nc'\nfree_energy.path = work_dir\nfree_energy.restraint_list = guest_restraints\nfree_energy.collect_data()\nfree_energy.methods = ['ti-block']\nfree_energy.ti_matrix = \"full\"\nfree_energy.bootcycles = 1000\nfree_energy.compute_free_energy()\n```\n\nWe also need to calculate the free-energy cost of releasing the restraints on the guest molecule.\n\n\n```python\nfree_energy.compute_ref_state_work([\n guest_restraints[0], guest_restraints[1], None, None,\n guest_restraints[2], None\n])\n```\n\nThen we add the free-energies together and combine the uncertainties to get the binding-free energy\n\n\n```python\nbinding_affinity = -1 * (\n free_energy.results[\"attach\"][\"ti-block\"][\"fe\"] + \\\n free_energy.results[\"pull\"][\"ti-block\"][\"fe\"] + \\\n free_energy.results[\"ref_state_work\"]\n)\n\nsem = np.sqrt(\n free_energy.results[\"attach\"][\"ti-block\"][\"sem\"]**2 + \\\n free_energy.results[\"pull\"][\"ti-block\"][\"sem\"]**2\n)\n```\n\n\n```python\nprint(f\"The binding affinity of butane to cucurbit[6]uril = {binding_affinity.magnitude:0.2f} +/- {sem.magnitude:0.2f} kcal/mol\")\n```\n\n The binding affinity of butane to cucurbit[6]uril = -7.24 +/- 6.52 kcal/mol\n\n", "meta": {"hexsha": "7d061608ed020055934d24cbeb8e4d8a87af6768", "size": 33840, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/05-tutorial-cb6-but-plumed.ipynb", "max_stars_repo_name": "jaketanderson/pAPRika", "max_stars_repo_head_hexsha": "5376f44ee1f7a0785f712b3b6c7bfa4c698ca65e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-04-19T23:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T19:47:02.000Z", "max_issues_repo_path": "docs/tutorials/05-tutorial-cb6-but-plumed.ipynb", "max_issues_repo_name": "jaketanderson/pAPRika", "max_issues_repo_head_hexsha": "5376f44ee1f7a0785f712b3b6c7bfa4c698ca65e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 154, "max_issues_repo_issues_event_min_datetime": "2017-04-20T16:05:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T21:07:18.000Z", "max_forks_repo_path": "docs/tutorials/05-tutorial-cb6-but-plumed.ipynb", "max_forks_repo_name": "jaketanderson/pAPRika", "max_forks_repo_head_hexsha": "5376f44ee1f7a0785f712b3b6c7bfa4c698ca65e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-07-06T07:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T05:05:44.000Z", "avg_line_length": 33.3070866142, "max_line_length": 603, "alphanum_fraction": 0.5667553191, "converted": true, "num_tokens": 6061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.16451645880021026, "lm_q1q2_score": 0.06701304852660585}} {"text": "# Markdown 與 LaTeX簡介\n\n每個範例內容將範例語法與輸出分為不同的 Cell 放置,雙擊 Cell 也可以查看原始碼,進行進一步的研究與實驗。\n\n## 1. Markdown 主要語法\n\n### 1.1 段落和斷行\n\n_範例語法:_\n```\n前軍至夏口,周瑜問:「荊州有人在前面接否?」人報:「劉皇叔使糜竺來見都督。」瑜喚至,問勞軍如何。糜竺曰:「主公皆準備安排下了。」瑜曰:「皇叔何在?」竺曰:「在荊州城門相等,與都督把盞。」瑜曰:「今為汝家之事,出兵遠征;勞軍之禮,休得輕易。」糜竺領了言語先回。
    戰船密密排在江上,依次而進。\n```\n_輸出:(可以看到在\"戰船\"前面有換行)_\n\n前軍至夏口,周瑜問:「荊州有人在前面接否?」人報:「劉皇叔使糜竺來見都督。」瑜喚至,問勞軍如何。糜竺曰:「主公皆準備安排下了。」瑜曰:「皇叔何在?」竺曰:「在荊州城門相等,與都督把盞。」瑜曰:「今為汝家之事,出兵遠征;勞軍之禮,休得輕易。」糜竺領了言語先回。
    戰船密密排在江上,依次而進。\n\n### 1.2 標題 (Heading)\n\n_範例語法:_\n\n```\n# 主標題 (等同於 HTML `

    `)\n\n## 次標題 (等同於 `

    `)\n\n#### 第四階 (等同於 `

    `)\n\n##### 第五階 (等同於 `
    `)\n\n###### 第六階 (等同於 `
    `)\n```\n\n_輸出:_\n\n# 主標題 (等同於 HTML `

    `)\n\n## 次標題 (等同於 `

    `)\n\n#### 第四階 (等同於 `

    `)\n\n##### 第五階 (等同於 `
    `)\n\n###### 第六階 (等同於 `
    `)\n\n### 1.3 無序號列表 (Bullet list)\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### 1.4 序號列表 (Numbered list)\n\n_範例語法:_\n\n```\n1. 第一項\n2. 第二項\n3. 第三項\n```\n\n_輸出:_\n\n1. 第一項\n2. 第二項\n3. 第三項\n\n### 1.5 區塊引言 (blockquoting)\n\n_範例語法:_\n\n```\n> 卻說魯肅回見周瑜,說玄德,孔明歡喜不疑,準備出城勞軍。周瑜大笑曰:「原來今番也中了吾計!」便教魯肅稟報吳侯,並遣程普引兵接應。周瑜此時箭瘡已漸平愈,身軀無事,使甘寧為先鋒,自與徐盛,丁奉為第二;淩統,呂蒙為後隊。水陸大兵五百萬,望荊州而來。\n\n周瑜在船中,時復歡笑,以為孔明中計。\n\n> 前軍至夏口,周瑜問:「荊州有人在前面接否?」人報:「劉皇叔使糜竺來見都督。」瑜喚至,問勞軍如何。\n```\n\n_輸出:_\n\n> 卻說魯肅回見周瑜,說玄德,孔明歡喜不疑,準備出城勞軍。周瑜大笑曰:「原來今番也中了吾計!」便教魯肅稟報吳侯,並遣程普引兵接應。周瑜此時箭瘡已漸平愈,身軀無事,使甘寧為先鋒,自與徐盛,丁奉為第二;淩統,呂蒙為後隊。水陸大兵五百萬,望荊州而來。\n\n周瑜在船中,時復歡笑,以為孔明中計。\n\n> 前軍至夏口,周瑜問:「荊州有人在前面接否?」人報:「劉皇叔使糜竺來見都督。」瑜喚至,問勞軍如何。\n\n### 1.6 程式碼區塊\n\n_範例語法:_\n\n\\`\\`\\`julia\n\nprintln(\"Hello Julia\")\n\n\\`\\`\\`\n\n_輸出:_\n\n```julia\nprintln(\"Hello Julia\")\n```\n\n### 1.7 分隔線\n\n_範例語法:_\n\n```\n卻說魯肅回見周瑜,說玄德,孔明歡喜不疑,準備出城勞軍。周瑜大笑曰:「原來今番也中了吾計!」便教魯肅稟報吳侯,並遣程普引兵接應。周瑜此時箭瘡已漸平愈,身軀無事,使甘寧為先鋒,自與徐盛,丁奉為第二;淩統,呂蒙為後隊。水陸大兵五百萬,望荊州而來。周瑜在船中,時復歡笑,以為孔明中計。\n\n---\n\n前軍至夏口,周瑜問:「荊州有人在前面接否?」人報:「劉皇叔使糜竺來見都督。」瑜喚至,問勞軍如何。糜竺曰:「主公皆準備安排下了。」瑜曰:「皇叔何在?」竺曰:「在荊州城門相等,與都督把盞。」瑜曰:「今為汝家之事,出兵遠征;勞軍之禮,休得輕易。」糜竺領了言語先回。
    戰船密密排在江上,依次而進。\n```\n\n_輸出:_\n\n卻說魯肅回見周瑜,說玄德,孔明歡喜不疑,準備出城勞軍。周瑜大笑曰:「原來今番也中了吾計!」便教魯肅稟報吳侯,並遣程普引兵接應。周瑜此時箭瘡已漸平愈,身軀無事,使甘寧為先鋒,自與徐盛,丁奉為第二;淩統,呂蒙為後隊。水陸大兵五百萬,望荊州而來。周瑜在船中,時復歡笑,以為孔明中計。\n\n---\n\n前軍至夏口,周瑜問:「荊州有人在前面接否?」人報:「劉皇叔使糜竺來見都督。」瑜喚至,問勞軍如何。糜竺曰:「主公皆準備安排下了。」瑜曰:「皇叔何在?」竺曰:「在荊州城門相等,與都督把盞。」瑜曰:「今為汝家之事,出兵遠征;勞軍之禮,休得輕易。」糜竺領了言語先回。
    戰船密密排在江上,依次而進。\n\n### 1.8 超連結\n\n_範例語法:_\n\n```\n[Cupoy - 為你探索世界的新知](https://www.cupoy.com)\n```\n\n_輸出:_\n\n[Cupoy - 為你探索世界的新知](https://www.cupoy.com)\n\n### 1.9 嵌入圖片\n\n_範例語法:_\n\n```\n\n```\n\n_輸出:_\n\n\n\n### 1.10 表格\n\n_範例語法:_\n\n```\n|姓名|國家|地址|年齡|\n|---|---|---|---|\n|John Doe|中華民國台灣|台北市大安區敦化街1號|25|\n```\n\n_輸出:_\n\n|姓名|國家|地址|年齡|\n|---|---|---|---|\n|John Doe|中華民國台灣|台北市大安區敦化街1號|25|\n\n## 2. 用 LaTeX 寫數學公式\n\n### 2.1 Inline 模式\n\n_範例語法:_\n\n```\n$\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)$\n```\n\n_輸出:_\n\n$\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)$\n\n### 2.2 Block 模式\n\n_範例語法:_\n\n```\n$$\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)$$\n```\n\n_輸出:_\n\n$$\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)$$\n\n_範例語法:_\n\n```\n\\begin{equation}\n\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)\n\\end{equation}\n```\n\n_輸出:_\n\n\\begin{equation}\n\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)\n\\end{equation}\n\n_範例語法:_\n\n```\n\\begin{align}\n\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)\n\\end{align}\n```\n\n_輸出:_\n\n\\begin{align}\n\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)\n\\end{align}\n\n## 3. 結合 Markdown 和 LaTeX 數學公式\n\n_範例語法:_\n\n```\n公式 $\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)$ 是 Deep Learning 課程中常會見到的基本公式\n\n\n\n結合 Markdown 和 LaTeX 數學公式,我們可以撰寫出漂亮的文件筆記,讓學習更有效率。\n```\n\n_輸出:_\n\n公式 $\\LARGE f(\\displaystyle\\sum_i w_i x_i + b)$ 是 Deep Learning 課程中常會見到的基本公式\n\n\n\n結合 Markdown 和 LaTeX 數學公式,我們可以撰寫出漂亮的文件筆記,讓學習更有效率。\n\n\n```julia\n\n```\n", "meta": {"hexsha": "19f6937068432b598155e3b529a82d480dd8e4cc", "size": 8094, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "example/julia_002_example.ipynb", "max_stars_repo_name": "h164654156465/1st-JuliaMarathon", "max_stars_repo_head_hexsha": "f247b3bd50c15b0ca31c134e8c52d824b346ee8b", "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": "example/julia_002_example.ipynb", "max_issues_repo_name": "h164654156465/1st-JuliaMarathon", "max_issues_repo_head_hexsha": "f247b3bd50c15b0ca31c134e8c52d824b346ee8b", "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": "example/julia_002_example.ipynb", "max_forks_repo_name": "h164654156465/1st-JuliaMarathon", "max_forks_repo_head_hexsha": "f247b3bd50c15b0ca31c134e8c52d824b346ee8b", "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": 8094.0, "max_line_length": 8094, "alphanum_fraction": 0.6121818631, "converted": true, "num_tokens": 3369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.2018132246607271, "lm_q1q2_score": 0.06682434240334713}} {"text": "# Announcments\n\n* Start the CP if you haven't already\n* We have a course tutor, Brady Moore bradenm3@illinois.edu\n\n\n```python\n%matplotlib inline\n\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = (12, 9)\nplt.rcParams[\"font.size\"] = 18\n```\n\n## Binary Nuclear Reactions\n\n### Learning Objectives:\n\n- Connect concepts in particle collisions and decay to binary reactions\n- Categorize nuclear reactions using standard nomenclature\n- Apply conservation of nucleons to binary nuclear reactions\n- Formulate Q value equations for binary nuclear reactions\n- Apply conservation of energy and linear momentum to scattering\n- Apply coulombic threshold\n- Apply kinematic threshold\n- Determine when coulombic and kinematic thresholds apply or do not\n\n## Recall from Weeks 3 & 4\n\nTo acheive these objectives, we need to recall 3 major themes from weeks three and four. \n\n### 1: Compare Exothermic and Endothermic reactions\n\n- In **_exothermic_** or **_exoergic_** reactions, energy is **emitted** ($Q>0$)\n- In **_endothermic_** or **_endoergic_** reactions, energy is **absorbed** ($Q<0$)\n\n\n\n\n
    (credit: BBC)
    \n\n### 2: Relate energy and mass $E=mc^2$\n\nWhen the masses of reactions change, this is tied to a change in energy from whence we learn the Q value.\nThis change in mass is equivalent to a change in energy because **$E=mc^2$**\n\n\\begin{align}\nA + B + \\cdots &\\rightarrow C + D + \\cdots\\\\\n\\mbox{(reactants)} &\\rightarrow \\mbox{(products)}\\\\\n\\implies \\Delta M &= (\\mbox{reactants}) - (\\mbox{products})\\\\\n &= (M_A + M_B + \\cdots) - (M_C + M_D + \\cdots)\\\\\n\\implies \\Delta E &= \\left[(M_A + M_B + \\cdots) - (M_C + M_D + \\cdots)\\right]c^2\\\\\n\\end{align}\n\n\n### 3: Apply conservation of energy and momentum to scattering collisions\n\nConservation of total energy and linear momentum can inform Compton scattering reactions. X-rays scattered from electrons had a change in wavelength $\\Delta\\lambda = \\lambda' - \\lambda$ proportional to $(1-\\cos{\\theta_s})$\n\n\n\nWe used the law of cosines:\n\n\\begin{align}\np_e^2 &= p_\\lambda^2 + p_{\\lambda'}^2 - 2p_\\lambda p_{\\lambda'}\\cos{\\theta_s}\n\\end{align}\n\n\nAnd we also used conservation of energy:\n\\begin{align}\np_\\lambda c+m_ec^2 &= p_{\\lambda'}c + mc^2\\\\\n\\mbox{where }&\\\\\nm_e&=\\mbox{rest mass of the electron}\\\\\nm &= \\mbox{relativistic electron mass after scattering}\n\\end{align}\n\nCombining these with our understanding of photon energy ($E=h\\nu=pc$) gives:\n\n\\begin{align}\n\\lambda' - \\lambda &= \\frac{h}{m_ec}(1-\\cos{\\theta_s})\\\\\n\\implies \\frac{1}{E'} - \\frac{1}{E} &= \\frac{1}{m_ec^2}(1-\\cos{\\theta_s})\\\\\n\\implies E' &= \\left[\\frac{1}{E} + \\frac{1}{m_ec^2}(1-\\cos{\\theta_s})\\right]^{-1}\\\\\n\\end{align}\n\n## More Types of Reactions\n\nPreviously we were interested in fundamental particles striking one another (e.g. the electron and proton in Compton scattering) or nuclei emitting such particles (e.g. $\\beta^\\pm$ decay).\n\n**Today:** We are interested in myriad additional reactants and/or products. In particular, we're interested in:\n\n- neutron absorption and production reactions \n- _binary, two-product nuclear reactions_ in which two products emerge with new energies after the collision.\n\n## Reaction Nomenclature\n\n**Transfer Reactions:** Nucleons (1 or 2) are transferred between the projectile and product.\n\n**Scattering reactions:** The projectile and product emerge from a collision with the same identities as when they started, exchanging only kinetic energy. \n\n**Knockout reactions:** The projectile directly interacts with the target nucleus and is re-emitted **along with** nucleons from the target nucleus.\n\n**capture reactions:** The projectile is absorbed, typically exciting the nucleus. The excited nucleus may emit that energy decaying via photon emission.\n\n**nuclear photoeffect:** A photon projectile liberates a nucleon from the target nucleus.\n\n### Think Pair Share : categorize these reactions\n\nOne example of each of the above appears below. Use the definitions to categorize them.\n\n- $(n, n)$\n- $(n, \\gamma)$\n- $(n, 2n)$\n- $(\\gamma, n)$\n- $(\\alpha, n)$\n\n\n## Binary, two-product nuclear reactions\n\n**Two initial nuclei collide to form two product nuclei.**\n\n\\begin{align}\n^{A_1}_{Z_1}X_1 + ^{A_2}_{Z_2}X_2 \\longrightarrow ^{A_3}_{Z_3}X_3 + ^{A_4}_{Z_4}X_4\n\\end{align}\n\n#### Applying Conservation of Neutrons and Protons\n\nThe total number of nucleons is always conserved.\nIf the `______________` force is not involved, we can also apply this conservation separately.\n\n\nIn most binary, two-product nuclear reactions, this is the case, so the number of protons and neutrons are conserved. Thus:\n\n\\begin{align}\nZ_1 + Z_2 = Z_3 + Z_4\\\\\nA_1 + A_2 = A_3 + A_4\n\\end{align}\n\nApply this to the following:\n\n\\begin{align}\n^{3}_{1}H + ^{16}_{8}O \\longrightarrow \\left(X\\right)^* \\longrightarrow ^{16}_{7}N + ^{A_4}_{Z_4}X_4\n\\end{align}\n\n### Think Pair Share:\n\nWhat are :\n\n- $A_4$ \n- $Z_4$\n- $X_4$?\n\n- Bonus: What is $\\left(X\\right)^*$?\n\n\n#### Applying conservation of mass and energy.\n\nThe Q-value calculation is the same as it has been before. \nThe Q value represents the `________` in kinetic energy and, equivalently, a `________` in the rest masses.\n\n\\begin{align}\nQ &= E_y + E_Y − E_x − E_X \\\\\n &= (m_x + m_X − m_y − m_Y )c^2\\\\\n &= \\left(m\\left(^{A_1}_{Z_1}X_1\\right) + m\\left(^{A_2}_{Z_2}X_2\\right) - m\\left(^{A_3}_{Z_3}X_3\\right) - m\\left(^{A_4}_{Z_4}X_4\\right)\\right)c^2\\\\\n\\end{align}\n\nIf proton numbers are conserved (true for everything but electron capture or reactions involving the weak force.), we can use the approximation that $m(X) = M(X)$.\n\n\\begin{align}\nQ &= E_y + E_Y − E_x − E_X \\\\\n &= (m_x + m_X − m_y − m_Y )c^2\\\\\n &= (M_x + M_X − M_y − M_Y )c^2\\\\\n &= \\left(M\\left(^{A_1}_{Z_1}X_1\\right) + M\\left(^{A_2}_{Z_2}X_2\\right) - M\\left(^{A_3}_{Z_3}X_3\\right) - M\\left(^{A_4}_{Z_4}X_4\\right)\\right)c^2\\\\\n\\end{align}\n\n\n```python\ndef q(m_reactants, m_products):\n \"\"\"Returns Q\n \n Parameters\n ----------\n m_reactants: list (of doubles)\n the masses of the reactant atoms [amu]\n m_products : list (of doubles)\n the masses of the product atoms [amu]\n \"\"\"\n amu_to_mev = 931.5 # MeV/amu conversion\n m_difference = sum(m_reactants) - sum(m_products)\n return m_difference*amu_to_mev\n\n\n# Look up the masses:\nh_3_mass = 3.0160492675\no_16_mass = 15.9949146221\nhe_3_mass = 3.0160293097\nn_16_mass = 16.0061014\n\nm_react = [h_3_mass, o_16_mass]\nm_prods = [he_3_mass, n_16_mass]\n\nprint(\"Q: \", q(m_react, m_prods))\n```\n\n#### Applying conservation of linear momentum\n\nLet's get back to collision kinematics. \n\nFirst, we'll assume the target nucleus ($X_2$) is initially at rest.\n\n\n \n\n# Kinematic Threshold\n\nRelying on a combination of kinetic energies $E_i$ and corresponding linear momenta:\n\n\\begin{align}\np_i = \\sqrt{2m_iE_i}\n\\end{align}\n\nWe can determine that some reactions aren't possible without a certain minimum quantity of kinetic energy. \n\nThe solution to $E_3$ can become nonphysical if :\n\n- $\\cos{\\theta_3} < 0$\n- $Q < 0$\n- $m_4 - m_1 < 0$\n\n## For Exoergic Reactions ($Q>0$)\n\nFor $Q>0$ and $m_{4} > m_{1}$, $E_{3} = (a + \\sqrt{a^2+b^2})^2$ is the only real, positive, meaningful solution. \n\nThe kinetic energy of $E_3$ is, at minimum, the energy arrived at when $p_1 = 0$. Thus:\n\n\\begin{align}\nE_3 \\longrightarrow& \\frac{m_4}{m_3 + m_4}Q\\\\\n&\\mbox{ when } Q>0, p_1=0\n\\end{align}\n\nSo, no exoergic reactions are restricted by kinetics, as $Q = E_3 + E_4$, for the minimum linear momentum case, which is real and positive. \n\n## For Endoergic Reactions ($Q<0$)\nSome $Q<0$ reactions aren't possible without a certain minimum quantity of kinetic energy. \n\n\nFor $Q<0$ and $m_{4} > m_{1}$, some values of $E_{1}$ are too small to carry forward a real, positive solution. That is, the incident projectile must supply a minimum amount of kinetic energy before the reaction can occur. Without this energy, the solution for $E_3$ results in physically meaningless values. This minimum energy can be found from eqn 6.11 in your book and is :\n\n\\begin{align}\nE_1^{th,k} = -\\frac{m_3 + m_4}{m_3 + m_4 - m_1}Q.\n\\end{align}\n\nOne can often simplify this (assuming $m_i >> Q/c^2$ and $m_3 + m_4 - m_1 \\simeq m_2$) :\n\n\n\\begin{align}\nE_1^{th,k} \\simeq - \\left( 1 + \\frac{m_1}{m_2} \\right)Q.\n\\end{align}\n\n\n```python\ndef kinematic_threshold(m_1, m_3, m_4, Q):\n \"\"\"Returns the kinematic threshold energy [MeV]\n \n Parameters\n ----------\n m_1: double\n mass of incident projectile\n m_3: double\n mass of first product \n m_3: double\n mass of second product \n Q : double\n Q-value for the reaction [MeV]\n \"\"\"\n num = -(m_3 + m_4)*Q\n denom = m_3 + m_4 - m_1\n return num/denom\n\ndef kinematic_threshold_simple(m_1, m_2, Q):\n \"\"\"Returns the coulombic threshold energy [MeV]\n \n Parameters\n ----------\n m_1: double\n mass of incident projectile\n m_2: double\n mass of target \n Q : double\n Q-value for the reaction [MeV]\n \"\"\"\n to_return = -(1 + m_1/m_2)*Q\n return to_return\n```\n\n# Coulombic Threshold\n\nCoulomb forces repel a projectile if it is:\n\n- a positively charged nucleus\n- a proton\n\nThe force between the projectile (particle 1) and the target nucleus (particle 2) is :\n\n\\begin{align}\n&F_C = \\frac{Z_1Z_2e^2}{4\\pi\\epsilon_0r^2}\\\\\n\\mbox{where}&&\\\\\n&\\epsilon_0 = \\mbox{the permittivity of free space.}\n\\end{align}\n\n### Think pair share:\nWhat are the other terms in the above equation:\n\n- $Z_1$ ?\n- $Z_2$ ?\n- $e$ ?\n- $r$ ?\n\n\nBy evaluating the work function for approach to the nucleus with a coulomb barrier, we can establish that the coulombic threshold energy (in MeV) is :\n\n\\begin{align}\nE_1^{th,C} \\simeq 1.20 \\frac{Z_1Z_2}{A_1^{1/3}+A_2^{1/3}}\n\\end{align}\n\n\n```python\ndef colombic_threshold(z_1, z_2, a_1, a_2):\n \"\"\"Returns the coulombic threshold energy [MeV]\n \n Parameters\n ----------\n z_1: int\n proton number of incident projectile\n z_2: int\n proton number of target \n a_1 : int or double\n mass number of the incident projectile [amu]\n a_2 : int or double\n mass number of the target [amu]\n \"\"\"\n num = 1.20*z_1*z_2\n denom = pow(a_1, 1/3) + pow(a_2, 1/3)\n return num/denom\n```\n\n### Think Pair Share \n\nWhich thresholds apply to the below situations:\n\n- A chargeless incident particle, reaction $Q>0$\n- A chargeless incident particle, reaction $Q<0$\n- A positively charged incident particle, reaction $Q>0$\n- A positively charged incident particle, reaction $Q<0$\n\n## Overall threshold\n\nFor the case where both thresholds apply, the minimum energy for the reaction to occur is the highest of the two thresholds. \n\n\\begin{align}\n\\min{\\left(E_1^{th}\\right)}\t= \\max{\\left(E^{th,C}_1,E_1^{th,k}\\right)}.\n\\end{align}\n\n## Example\n\nTake the (p, n) reaction from $^{9}Be\\longrightarrow^{9}B$. We will need to calculate:\n\n- The Q value\n- The kinematic threshold (if it applies)\n- The coulombic threshold (if it applies)\n- Determine which one is higher\n\n\n```python\n# Q value\n# Look up the masses:\nbe_9_mass = 9.0121821\nb_9_mass = 9.0133288\nn_mass = 1.0086649158849\np_mass = 1.007825032 # hydrogen nucleus!\n\nm_react = [be_9_mass, p_mass]\nm_prods = [b_9_mass, n_mass]\n\nq_example = q(m_react, m_prods)\nprint(\"Q: \", q_example)\n```\n\n\n```python\n# Kinematic Threshold\n# Which particles were which again?\nm_1 = p_mass\nm_2 = be_9_mass\nm_3 = n_mass\nm_4 = b_9_mass\n\n# Calculate using both regular and simpler methods\nE_k_th = kinematic_threshold(m_1, m_3, m_4, q_example)\nE_k_th_simple = kinematic_threshold_simple(m_1, m_2, q_example)\nprint(\"E_k_th: \", E_k_th)\nprint(\"E_k_th (simplified): \", E_k_th_simple)\n```\n\n\n```python\n# Coulombic Threshold\n# Need some charge info and mass numbers\nz_1 = 1 # proton\nz_2 = 4 # Be\na_1 = 1 # proton\na_2 = 9 # Be\n\nE_c_th = colombic_threshold(z_1, z_2, a_1, a_2)\n\nprint(\"E_c_th: \", E_c_th)\n```\n\n\n```python\n## Which one is higher?\n\nprint(\"Total threshold: \", max(E_c_th, E_k_th))\n```\n\n# Applications: Neutron Detection\nNeutron's don't tend to directly ionize matter as they pass through. However, they can instigate nuclear reactions which produce charged products. These products, in turn, can be detected due to the ionization they create. The scheme for a Boron Trifluoride detector is below (hosted at https://www.orau.org/ptp/collection/proportional%20counters/bf3info.htm).\n\n\n\nThe wall effect results in the following spectrum (approximately):\n\n\nIn (n,p) reactions, for example, variation in emission angle of particle 3 can be used to determine the energy of the original incident neutron.\n\n# Applications: Neutron Production\nSpecific neutron energies can be targetted by collecting them at a certain angle away from the production collision.\n\n\n\n
    The accelerator and spallation target at LANSCE and other spallation experiments rely on this fact.
    \n\n\n## Two energies\n\nIn (p,n) reactions, for example, certain proton energies may result in more than one neutron energy observed at a single angle. How? \n\nRecall the equation (Shultis and Faw 6.11):\n\n\\begin{align}\n\\sqrt{E_y}=&\\sqrt{\\frac{m_xm_yE_x}{(m_y + m_Y)^2}}\\cos\\theta_y \\\\\n&\\pm \\sqrt{\\frac{m_xm_yE_x}{(m_y + m_Y)^2}\\cos^2\\theta_y + \\left[\\frac{m_Y-m_x}{(m_y + m_Y)}E_x + \\frac{m_YQ}{(m_y + m_Y)}\\right]}\n\\end{align}\n\nDr. Munk prefers this notation: \n\\begin{align}\n\\sqrt{E_3}=&\\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}}\\cos\\theta_3 \\\\\n&\\pm \\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}\\cos^2\\theta_3 + \\left[\\frac{m_4-m_1}{(m_3 + m_4)}E_1 + \\frac{m_4Q}{(m_3 + m_4)}\\right]}\n\\end{align}\n\n## Heavy Particle scattering from an electron\n\nMuch like the Compton reaction we saw between photons and electrons, we can see a similar reaction with heavy particles. Occaisionally, a heavy particle (e.g. a small nucleus, like an $\\alpha$ particle) strikes the orbital electrons in atoms of a medium.\n\nThus: particles 2 and 3 are the electron. So:\n\n\\begin{align} \nm_2 &= m_3 = m_e = \\mbox{(the electron mass)}\\\\\nE_3 &= E_e = \\mbox{(the recoil electron energy)}\\\\\nm_1 &= m_4 = \\mbox{(the mass of the heavy particle)}\\\\\nE_1 &= E_4 = \\mbox{(the kinetic energy of the incident heavy particle)}\n\\end{align}\n\nFor this scattering process, there is no change in the rest masses of the reactants, so Q = 0. \n\nWe can use the Shutlis and Faw 6.11 equation above to arrive at:\n\n\\begin{align}\n\\sqrt{E_e}=& \\frac{2}{m_4 + m_e}\\sqrt{m_4m_eE_4}\\cos{\\theta_e}\n\\end{align}\n\nWe can approximate that $m_4 >> m_e$ such that the electron recoil energy becomes:\n\n\\begin{align}\n\\implies E_e =& 4\\frac{m_e}{m_4}E_4\\cos^2{\\theta_e}\n\\end{align}\n\n## Think Pair Share\nWhat angle, $\\theta_e$, corresponds to the maximimum loss of kinetic energy by the incident heavy particle?\n\n\n\nAt $\\theta_e=0$, we find that:\n\n\\begin{align}\n(E_e)_{max} = 4\\frac{m_e}{m_4}E_4\n\\end{align}\n\n\n```python\nimport math \ndef recoil_energy(m_4, e_4, theta_e):\n m_e = 0.0005486 # amu\n num = 4*m_e*e_4*pow(math.cos(theta_e), 2)\n return num/m_4\n\n```\n\n\n```python\nth = [math.radians(-90),\n math.radians(-75),\n math.radians(-60),\n math.radians(-45),\n math.radians(-30),\n math.radians(-15),\n math.radians(0), \n math.radians(15),\n math.radians(30),\n math.radians(45),\n math.radians(60),\n math.radians(75),\n math.radians(90)]\n\nm_4 = 4.003 # alpha particle\n\nto_plot_4 = np.arange(0.,len(th))\nto_plot_10 = np.arange(0.,len(th))\n\nfor k, v in enumerate(th):\n to_plot_4[k] = (recoil_energy(m_4, 4, v))\n to_plot_10[k] = (recoil_energy(m_4, 10, v))\n\n\nplt.plot(th, to_plot_4, label=\"$4MeV$\")\nplt.plot(th, to_plot_10, label=\"$10MeV$\")\n\nplt.ylabel(\"Electron Recoil Energy ($MeV$)\")\nplt.xlabel(\"Angle (radians)\")\nplt.legend(loc=2)\n```\n\n\n```python\n\nth = 0\nm_4 = 4.003 # alpha particle\ne_4 = 4 # MeV\n\nprint(\"Max (4MeV alpha): \", recoil_energy(m_4, e_4, th))\n```\n\n## Neutron Scattering\n\n### Neutron interactions with matter.\n\n\\begin{align}\n^1_0n + {^a_z}X \\longrightarrow \n\\begin{cases}\n^1_0n + {^a_z}X & \\mbox{Elastic Scattering}\\\\\n^1_0n + \\left({^a_z}X\\right)^* & \\mbox{Inlastic Scattering}\n\\end{cases}\n\\end{align}\n\n\n\nUsing the ubiquitous equation 6.11 for a neutron scatter:\n\n\\begin{align}\n\\sqrt{E_3}=&\\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}}\\cos\\theta_3 \\\\\n&\\pm \\sqrt{\\frac{m_1m_3E_1}{(m_3 + m_4)^2}\\cos^2\\theta_3 + \\left[\\frac{m_4-m_1}{(m_3 + m_4)}E_1 + \\frac{m_4Q}{(m_3 + m_4)}\\right]}\\\\\n\\end{align}\n\nWe can define our particles as a neutron hitting a nucleus and changing in its energy.\n\n\\begin{align}\nm_1 = m_3 = m_n\\\\\nE_1 = E_n\\\\\nE_3 = E_n'\\\\\n\\end{align}\n\nSuch that:\n\n\\begin{align}\n\\sqrt{E_n'} =&\\sqrt{\\frac{m_nm_nE_n}{(m_n + m_4)^2}}\\cos\\theta_s \\\\\n&\\pm \\sqrt{\\frac{m_nm_nE_n}{(m_n + m_4)^2}\\cos^2\\theta_s + \\left[\\frac{m_4-m_n}{(m_n + m_4)}E_n + \\frac{m_4Q}{(m_n + m_4)}\\right]}\n\\end{align}\n\nWe can also agree that $m_2=m_4$, which is some nucleus with a mass that is approximately the same at the beginning and end of the scatter (approximate if the scattering is inelastic) . This gives, with some rearrangement:\n\n\\begin{align}\n\\sqrt{E_n'} &= \\frac{1}{m_4 + m_n}\\times\\\\ &\\left[\\sqrt{m_n^2E_n}\\cos{\\theta_s} \\pm \\sqrt{E(m_4^2 + m_n^2\\cos^2{\\theta_s} − m_n^2) + m_4 ( m_4 + m_n ) Q }\\right]\n\\end{align}\n\nAnd, for elastic scattering ($Q=0$):\n\n\\begin{align}\nE' = \\frac{1}{(A+1)^2}\\left[\\sqrt{E}\\cos{\\theta_s} + \\sqrt{E(A^2 - 1 + \\cos{\\theta_s}^2)}\\right]^2\n\\end{align}\n\n\n\n```python\ndef scattered_neutron_energy(A, E, th):\n \"\"\"Returns the energy of a scattered neutron [MeV]\n Parameters\n ----------\n A: int or double\n mass number of medium\n E: double\n kinetic energy of the incident neutron [MeV]\n th : double\n scattering angle, in degrees\n \"\"\"\n cos_th = math.cos(math.radians(th))\n term1 = 1/((A+1)**2)\n term2 = math.sqrt(E)*cos_th\n term3 = math.sqrt(E*(A**2 - 1 + cos_th**2))\n return term1*((term2 + term3)**2)\n```\n\n\n```python\nth = [math.radians(-90),\n math.radians(-75),\n math.radians(-60),\n math.radians(-45),\n math.radians(-30),\n math.radians(-15),\n math.radians(0), \n math.radians(15),\n math.radians(30),\n math.radians(45),\n math.radians(60),\n math.radians(75),\n math.radians(90)]\n\ne_initial = 2.0 # 2 MeV is special\na_light = 4.003 # alpha particle\na_heavy = 235.0 # uranium atom\n\nto_plot_light = np.arange(0.,len(th))\nto_plot_heavy = np.arange(0.,len(th))\n\nfor k, v in enumerate(th):\n to_plot_light[k] = (scattered_neutron_energy(a_light, e_initial, v))\n to_plot_heavy[k] = (scattered_neutron_energy(a_heavy, e_initial, v))\n\nplt.plot(th, to_plot_light, label=\"light\")\nplt.plot(th, to_plot_heavy, label=\"heavy\")\n\nplt.ylabel(\"Scattered Neutron Energy ($MeV$)\")\nplt.xlabel(\"Angle (radians)\")\nplt.legend(loc=2)\n```\n\n## Average Energy Loss\n\nFor elastic scattering (Q = 0), we see the minimum and maxium energies occur at the maximum and minimum angles. \n\n\\begin{align}\nE'_{max} &= E'(\\theta_{s,min})\\\\\n &= E'(\\theta_{s}=0)\\\\\n &= E\\\\\nE'_{min} &= E'(\\theta_{s,max})\\\\\n &= E'(\\theta_{s}=\\pi)\\\\\n &= \\frac{(A-1)^2}{(A+1)^2} E\\\\\n &\\equiv \\alpha E\\\\\n\\end{align}\n\nFor isotropic scattering, we can find the average loss:\n\n\n\\begin{align}\n(\\Delta E)_{av} &\\equiv E - E'_{av}\\\\\n&= E− 1(E+\\alpha E)\\\\\n& = 1(1- \\alpha)E\n\\end{align}\n\n\n```python\ndef alpha(a):\n \"\"\"Returns the average energy loss of a \n scattered neutron [MeV]\n Parameters\n ----------\n A: int or double\n mass number of medium\n \"\"\"\n num = (a-1)**2\n denom = (a+1)**2\n return num/denom\n \ndef average_energy_loss(A, E):\n \"\"\"Returns the average energy loss of a scattered neutron [MeV]\n Parameters\n ----------\n A: int or double\n mass number of medium\n E: double\n kinetic energy of the incident neutron [MeV]\n \"\"\"\n return 1*(1-alpha(A))*E\n```\n\n\n```python\ne_initial = np.arange(0, 2, 0.001)\n\nto_plot_light = np.arange(0.,len(e_initial))\nto_plot_heavy = np.arange(0.,len(e_initial))\n\nfor k, v in enumerate(e_initial):\n to_plot_light[k] = (average_energy_loss(a_light, v))\n to_plot_heavy[k] = (average_energy_loss(a_heavy, v))\n\nplt.plot(e_initial, to_plot_light, label=\"light atom\")\nplt.plot(e_initial, to_plot_heavy, label=\"heavy atom\")\n\nplt.ylabel(\"Average Neutron Energy Loss ($MeV$)\")\nplt.xlabel(\"Initial neutron energy ($MeV$)\")\nplt.legend(loc=2)\n```\n\n## Logarithmic Energy Loss\n\nIt turns out, on a logarithmic energy scale, a neutron loses the same amount of logarithmic energy per elastic scatter, regardless of its initial energy. So, this is a helpful term, particularly since neutron energies can range by many orders of magnitude. So, we often use 'logarithmic energy loss' when discussing this downscattering. This is also called \"lethargy\".\n\n\\begin{align}\n\\left(\\ln{(E)} - \\ln{(E')}\\right)_{av} & = \\overline{\\ln{\\left(\\frac{E}{E'}\\right)}} \\\\\n&= 1 + \\frac{\\alpha}{1-\\alpha}\\\\\n&= \\xi\\\\\n&= \\mbox{average logarithmic energy loss per elastic scatter}\\\\\n&= \\mbox{lethargy}\n\\end{align}\n\n\n```python\ndef lethargy(a): \n \"\"\"Returns the average logarithmic energy \n loss per elastic scatter\n Parameters\n ----------\n A: int or double\n mass number of medium\n \"\"\"\n return 1.0 + alpha(a)/(1-alpha(a)) \n```\n\n\n```python\na = np.arange(1, 240)\nplt.plot([lethargy(i) for i in a])\nplt.ylabel(\"$\\\\xi$\")\nplt.xlabel(\"A($amu$)\")\n\n```\n\n## Thermal Neutrons\n\n1. a fast neutron slows down\n2. may eventually come into thermal equilibrium with the medium \n3. thermal motion of atoms in medium are in Maxwellian distribution \n4. neutron may gain kinetic energy upon scattering from a rapidly moving nucleus \n5. neutron may lose energy upon scattering from a slowly moving nucleus.\n\n\n\n\nAt room temperature, 293 K:\n- the most probable kinetic energy of thermal neutrons is 0.025 eV\n- 0.025 eV corresponds to a neutron speed of about 2200 m/s.\n\n## Epithermal\n\nNeutrons that are faster than thermal neutrons, but aren't quite \"fast\" are called _epithermal_. ($0.2eV < E_{epi} < 1 MeV$)\n\n## Fast\n\n$> 1MeV$\n\n\n## Neutron Capture \n\n- Free neutrons will eventually be absorbed by a nucleus (or escape the domain of interest)\n- Neutron capture leaves the nucleus excited \n- Actually, very excited (Recall: what is a typical binding energy per nucleon?)\n- When it's released as a $\\gamma$ that energy can be very hazardous\n\nNeutron slowing down can help us to reduce very high energy $\\gamma$ emissions.\n\n## Fission Reactions\n\nSome nuclei spontaneously fission (e.g. $^{252}Cf$). However, this isn't common.\n\n\n\n\\begin{align}\n^1_0n + ^{235}_{92}U \\longrightarrow \\left( ^{236}_{92}U \\right)^*\n\\begin{cases}\n^{235}_{92}U + ^1_0n & \\mbox{Elastic Scattering}\\\\\n^{235}_{92}U + ^1_0n' + \\gamma & \\mbox{Inelastic Scattering}\\\\\n^{236}_{92}U + \\gamma & \\mbox{Radiative Capture}\\\\\n^{A_H}_{Z_H}X_H + ^{A_L}_{Z_L}X_L + ^1_0n + \\cdots & \\mbox{Fission}\n\\end{cases}\n\\end{align}\n\n# Announcements\n\n* I am modifying the schedule a bit. On Friday I will introduce different reactor types and then on Monday we are going to have a guest lecture on the nuclear fuel cycle by **Amanda Bachmann**. \n* The homework I assign on Friday will be due the Monday after spring break\n* If you wanted an adjustment on your midterm exam, you **need to email me** with the details so I can record it properly. \n* Exam 2 moved to 4/4. Syllabus updated on github. \n\n### Recall: Cross sections\n\nThe likelihood of each of these scattering events is captured by cross sections. \n\n- $\\sigma_x = $ microscopic cross section $[cm^2]$\n- $\\Sigma_x = $ macroscopic cross section $[1/length]$\n- $\\Sigma_x = N\\sigma_x $\n- $N = $ number density of target atoms $[\\#/volume]$\n\n\n### Cross sections are in units of area. Explain this to your neighbor.\n\n### What energy neutron do we prefer for fission in $^{235}U$?\n\n\nNuclei that undergo neutron induced fission can be categorized into three types:\n\n- fissile: can fission with a slow neutron ($^{235}U$, $^{233}U$, $^{239}Pu$)\n- fissionable: require high energy (>1MeV) neutron ($^{238}U$, $^{240}Pu$)\n- fertile: can be converted into fissile or fissionable nuclide (breeding reactions)\n\nKey breeding reactions are :\n\n\\begin{align}\n{^{232}_{90}}Th + ^1_0n \\longrightarrow {^{233}_{90}}Th \\overset{\\beta^-}{\\longrightarrow} {^{233}_{91}}Pa \\overset{\\beta^-}{\\longrightarrow} {^{233}_{92}}U\\\\\n{^{238}_{92}}U + ^1_0n \\longrightarrow {^{239}_{92}}U \\overset{\\beta^-}{\\longrightarrow} {^{239}_{93}}Np \\overset{\\beta^-}{\\longrightarrow} {^{239}_{94}}Pu\\\\\n\\end{align}\n\n## The fission process\n\n\\begin{align}\n^1_0n + ^{235}_{92}U \\longrightarrow \\left( ^{236}_{92}U \\right)^* \\longrightarrow X_H + X_L + \\nu_p\\left(^1_0n\\right) + \\gamma_p\n\\end{align}\n\nConserving neutrons and protons:\n\n\\begin{align}\nA_L + A_H + \\nu_p &= 236\\\\\nN_L + N_H + \\nu_p &= 144\\\\\nZ_L + Z_H &= 92\\\\\n\\end{align}\n\n\n\n## Fission Product Decay\n\nThe fission fragments end up very neutron rich.\n\n### Think Pair Share\nRecall the chart of the nuclides. How will these fission products likely decay?\n\n### Fission Spectrum\n\n$\\chi(E)$ is an empirical probability density function describing the energies of prompt fission neutrons. \n\n\\begin{align}\n\\chi (E) &= 0.453e^{-1.036E}\\sinh\\left(\\sqrt{2.29E}\\right)\\\\\n\\end{align}\n\n\n```python\nimport numpy as np\nimport math\ndef chi(energy):\n return 0.453*np.exp(-1.036*energy)*np.sinh(np.sqrt(2.29*energy))\n\nenergies = np.arange(0.0,10.0, 0.1)\n\nplt.plot(energies, chi(energies))\nplt.title(r'Prompt Neutron Energy Distribution $\\chi(E)$')\nplt.xlabel(\"Prompt Neutron Energy [MeV]\")\nplt.ylabel(\"probability\")\n```\n\n#### Questions about this plot:\n\n- What is the most likely prompt neutron energy?\n- Can you write an equation for the average neutron energy?\n- Can you write an equation for the average neutron energy?\n\n\n\n```python\nprint(max([chi(e) for e in energies]), chi(0.7))\n```\n\n#### Expectation Value\n\nRecall that the average energy will be the expectation value of the probability density function.\n\n\n\\begin{align}\n &= \\int E\\chi(E)dE\\\\\n&= E \\chi(E)\n\\end{align}\n\n\n```python\nplt.plot(energies, [chi(e)*e for e in energies])\n```\n\n## Prompt and Delayed neutrons\n\n- Most of the neutrons in fission are emitted within $10^{-14}s$. \n - **prompt** neutrons\n - $\\nu_p$\n- Some, ($<1\\%$) are produced by delayed decay of fission products. \n - **delayed** neutrons\n - $\\nu_d$\n \nWe define the delayed neutron fraction as :\n\n\\begin{align}\n\\beta \\equiv \\frac{\\nu_d}{\\nu_d + \\nu_p}\n\\end{align}\n\n## Energy from fission\n\n### Reaction Rates\n\n- The microscopic cross section is just the likelihood of the event per unit area. \n- The macroscopic cross section is just the likelihood of the event per unit area of a certain density of target isotopes.\n- The reaction rate is the macroscopic cross section times the flux of incident neutrons.\n\n\\begin{align}\nR_{i,j}(\\vec{r}) &= N_j(\\vec{r})\\int dE \\phi(\\vec{r},E)\\sigma_{i,j}(E)\\\\\nR_{i,j}(\\vec{r}) &= \\mbox{reactions of type i involving isotope j } [reactions/cm^3s]\\\\\nN_j(\\vec{r}) &= \\mbox{number of nuclei participating in the reactions } [\\#/cm^3]\\\\\nE &= \\mbox{energy} [MeV]\\\\\n\\phi(\\vec{r},E)&= \\mbox{flux of neutrons with energy E at position i } [\\#/cm^2s]\\\\\n\\sigma_{i,j}(E)&= \\mbox{cross section } [cm^2]\\\\\n\\end{align}\n\n\nThis can be written more simply as $R_x = \\Sigma_x I N$, where I is intensity of the neutron flux.\n\n\n### Source term\n\nThe source of neutrons in a reactor are the neutrons from fission. \n\n\\begin{align}\ns &=\\nu \\Sigma_f \\phi\n\\end{align}\n\nwhere\n\n\\begin{align}\ns &= \\mbox{neutrons available for next generation of fissions}\\\\\n\\nu &= \\mbox{the number born per fission}\\\\\n\\Sigma_f &= \\mbox{the number of fissions in the material}\\\\\n\\phi &= \\mbox{initial neutron flux}\n\\end{align}\n\nThis can also be written as:\n\n\\begin{align}\ns &= \\nu\\Sigma_f\\phi\\\\\n &= \\nu\\frac{\\Sigma_f}{\\Sigma_{a,fuel}}\\frac{\\Sigma_{a,fuel}}{\\Sigma_a}{\\Sigma_a} \\phi\\\\\n &= \\eta f {\\Sigma_a} \\phi\\\\\n\\eta &= \\frac{\\nu\\Sigma_f}{\\Sigma_{a,fuel}} \\\\\n &= \\mbox{number of neutrons produced per neutron absorbed by the fuel, \"neutron reproduction factor\"}\\\\\nf &= \\frac{\\Sigma_{a,fuel}}{\\Sigma_a} \\\\\n &= \\mbox{number of neutrons absorbed in the fuel per neutron absorbed anywhere, \"fuel utilization factor\"}\\\\\n\\end{align}\n\nThis absorption and flux term at the end seeks to capture the fact that some of the neutrons escape. However, if we assume an infinite reactor, we know that all the neutrons are eventually absorbed in either the fuel or the coolant, so we can normalize by $\\Sigma_a\\phi$ and therefore:\n\n\n\\begin{align}\nk_\\infty &= \\frac{\\eta f \\Sigma_a\\phi}{\\Sigma_a \\phi}\\\\\n&= \\eta f\n\\end{align}\n", "meta": {"hexsha": "5369a8c4139462fd4828264b8564c258b361bd39", "size": 44574, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10.06.1-binary_reactions/binary-reactions.ipynb", "max_stars_repo_name": "munkm/npre247", "max_stars_repo_head_hexsha": "5683fa3176e946622a31e3b207484e7ec74f8421", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-31T17:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T19:54:50.000Z", "max_issues_repo_path": "10.06.1-binary_reactions/binary-reactions.ipynb", "max_issues_repo_name": "munkm/npre247", "max_issues_repo_head_hexsha": "5683fa3176e946622a31e3b207484e7ec74f8421", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2022-01-28T20:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T17:43:54.000Z", "max_forks_repo_path": "10.06.1-binary_reactions/binary-reactions.ipynb", "max_forks_repo_name": "munkm/npre247", "max_forks_repo_head_hexsha": "5683fa3176e946622a31e3b207484e7ec74f8421", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2022-01-24T16:47:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T04:09:25.000Z", "avg_line_length": 34.7962529274, "max_line_length": 410, "alphanum_fraction": 0.5490869117, "converted": true, "num_tokens": 9189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943832145539, "lm_q2_score": 0.21469141911224196, "lm_q1q2_score": 0.06670341804253531}} {"text": "```python\n# %load /Users/facai/Study/book_notes/preconfig.py\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport numpy as np\n\nimport pandas as pd\n\nfrom IPython.display import Image\n```\n\nChapter 6 Temporal-Difference Learning\n=====================\n\nDP, TD, and Monte Carlo methods all use some variation of generalized policy iteration: primarily differences in their approaches to the prediction problem.\n\n### 6.1 TD Prediction\n\nconstant-$\\alpha$ MC: $V(S_t) \\gets V(S_t) + \\alpha \\underbrace{\\left [ G_t - V(S_t) \\right ]}_{= \\sum_{k=t}^{T-1} \\gamma^{k-1} \\theta_k}$\n\n\n\\begin{align}\n v_\\pi(s) &\\doteq \\mathbb{E}_\\pi [ G_t \\mid S_s = s] \\qquad \\text{Monte Carlo} \\\\\n &= \\mathbb{E}_\\pi [ R_{t+1} + \\gamma \\color{blue}{v_\\pi(S_{t+1})} \\mid S_t = s ] \\quad \\text{DP}\n\\end{align}\n\none-step TD, or TD(0): $V(S_t) \\gets V(S_t) + \\alpha \\left [ \\underbrace{R_{t+1} + \\gamma \\color{blue}{V(S_{t+1})} - V(S_t)}_{\\text{TD error: } \\theta_t} \\right ]$\n\nTD: samples the expected values and uses the current estimate $V$ instead of the true $v_\\pi$.\n\n\n\n```python\nImage('./res/fig6_1.png')\n```\n\n\n```python\nImage('./res/TD_0.png')\n```\n\n### 6.2 Advantages of TD Prediction Methods\n\nTD: they learn a guess from a guess - they boostrap.\n\n+ advantage:\n 1. over DP: TD do not require a model of the environment, of its reward and next-state probability distributions.\n 2. over Monte Carlo: TD are naturally implemented in an online, fully incremental fashion.\n \nTD: guarantee convergence.\n\nIn practice, TD methods have usually been found that converge faster than constant-$\\alpha$ MC methods on stochastic tasks.\n\n### 6.3 Optimality of TD(0)\n\nbatch updating: updates are made only after processing each complete batch of training data until the value function converges.\n\n+ Batch Monte Carlo methods: always find the estimates that minimize mean-squared error on the training set.\n+ Batch TD(0): always find the estimates that would be exactly correct for the maximum-likelihood model of the Markov process.\n\n### 6.4 Sarsa: On-policy TD Control\n\n$Q(S_t, A_t) \\gets Q(S_t, A_t) + \\alpha \\left [ R_{t+1} + \\gamma Q(S_{t+1}, A_{t+1}) - Q(S_t,, A_t) \\right ]$\n\n\n```python\nImage('./res/sarsa.png')\n```\n\n### 6.5 Q-learning: Off-policy TD Control\n\n\n$Q(S_t, A_t) \\gets Q(S_t, A_t) + \\alpha \\left [ R_{t+1} + \\gamma \\color{blue}{\\max_a Q(S_{t+1}, a)} - Q(S_t,, A_t) \\right ]$\n\n\n```python\nImage('./res/q_learn_off_policy.png')\n```\n\n### 6.6 Expected Sarsa\n\nuse expeteced value, how likely each action is under the current policy.\n\n\n\\begin{align}\n Q(S_t, A_t) & \\gets Q(S_t, A_t) + \\alpha \\left [ R_{t+1} + \\gamma \\color{blue}{\\mathbb{E}[Q(S_{t+1}, A_{t+1}) \\mid S_{t+1}]} - Q(S_t,, A_t) \\right ] \\\\\n & \\gets Q(S_t, A_t) + \\alpha \\left [ R_{t+1} + \\gamma \\color{blue}{\\sum_a \\pi(a \\mid S_{t+1}) Q(S_{t+1}, a)} - Q(S_t,, A_t) \\right ]\n\\end{align}\n\n+ con: additional computational cost.\n+ pro: eliminate the variance due to the random seleciton of $A_{t+1}$.\n\n### 6.7 Maximization Bias and Double Learning\n\nmaximization bias:\n+ a maximum over estimated values => an estimate of the maximum value => significant positive bias.\n\nroot of problem: using the same samples (plays) both to determine the maximizing action and to estimate its value. => divide the plays in two sets ($Q_1, Q_2$) and use them to learn two indepedent estimates. (*double learning*)\n\n\n$Q_1(S_t, A_t) \\gets Q_1(S_t, A_t) + \\alpha \\left [ R_{t+1} + \\gamma Q_2 \\left( S_{t+1}, \\operatorname{argmax}_a Q_1(S_{t+1}, a) \\right) - Q_1(S_t,, A_t) \\right ]$\n\n\n```python\nImage('./res/double_learn.png')\n```\n\n### 6.8 Games, Afterstates, and Other Special Cases\n\n\n```python\n\n```\n", "meta": {"hexsha": "7ada02683b6afc81d2997b8e0ec9cea1601857d9", "size": 404590, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Reinforcement_Learing_An_Introduction/Temporal_Difference_Learning/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "Reinforcement_Learing_An_Introduction/Temporal_Difference_Learning/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "Reinforcement_Learing_An_Introduction/Temporal_Difference_Learning/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 1444.9642857143, "max_line_length": 95910, "alphanum_fraction": 0.948777775, "converted": true, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.14223188955598276, "lm_q1q2_score": 0.06667697663118385}} {"text": "\n\n# Textual entailment classifier using an MLP plus attention \n\nIn textual entailment, \nthe input is 2 sentences (premise and hypothesis), and the output\nis a label, specifying if P entails H, P contradicts H, or neither.\n(This is also called \"natural language inference\".)\nWe use attention to align hypothesis to premise and vice versa,\nthen compare the aligned words to estimate similarity between the sentences, and pass the weighted similarities to an MLP.\n\n\nBased on sec 15.5 of http://d2l.ai/chapter_natural-language-processing-applications/natural-language-inference-attention.html\n\n\n\n\n\n\n```python\n!pip install -q flax\n```\n\n \u001b[K |████████████████████████████████| 184 kB 12.2 MB/s \n \u001b[K |████████████████████████████████| 136 kB 50.2 MB/s \n \u001b[K |████████████████████████████████| 72 kB 709 kB/s \n \u001b[?25h\n\n\n```python\nimport jax\nimport jax.numpy as jnp # JAX NumPy\n\nfrom flax import linen as nn # The Linen API\nfrom flax.training import train_state # Useful dataclass to keep train state\nimport torch\nfrom torch.utils import data # For data\n\nimport numpy as np # Ordinary NumPy\nimport optax # Optimizers\n\nimport collections\nimport re\nimport os\nimport requests\nimport zipfile\nimport tarfile\nimport hashlib\nimport time\nimport functools\nfrom typing import Any, Callable, Sequence, Tuple\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport math\nfrom IPython import display \n\nrng = jax.random.PRNGKey(0)\n!mkdir figures # for saving plots\nModuleDef = Any\n```\n\n# Data\n\nWe use SNLI (Stanford Natural Language Inference) dataset described in sec 15.4 of http://d2l.ai/chapter_natural-language-processing-applications/natural-language-inference-and-dataset.html.\n\n\n```python\n# Required functions for downloading data\n\ndef download(name, cache_dir=os.path.join('..', 'data')):\n \"\"\"Download a file inserted into DATA_HUB, return the local filename.\"\"\"\n assert name in DATA_HUB, f\"{name} does not exist in {DATA_HUB}.\"\n url, sha1_hash = DATA_HUB[name]\n os.makedirs(cache_dir, exist_ok=True)\n fname = os.path.join(cache_dir, url.split('/')[-1])\n if os.path.exists(fname):\n sha1 = hashlib.sha1()\n with open(fname, 'rb') as f:\n while True:\n data = f.read(1048576)\n if not data:\n break\n sha1.update(data)\n if sha1.hexdigest() == sha1_hash:\n return fname # Hit cache\n print(f'Downloading {fname} from {url}...')\n r = requests.get(url, stream=True, verify=True)\n with open(fname, 'wb') as f:\n f.write(r.content)\n return fname\n\ndef download_extract(name, folder=None):\n \"\"\"Download and extract a zip/tar file.\"\"\"\n fname = download(name)\n base_dir = os.path.dirname(fname)\n data_dir, ext = os.path.splitext(fname)\n if ext == '.zip':\n fp = zipfile.ZipFile(fname, 'r')\n elif ext in ('.tar', '.gz'):\n fp = tarfile.open(fname, 'r')\n else:\n assert False, 'Only zip/tar files can be extracted.'\n fp.extractall(base_dir)\n return os.path.join(base_dir, folder) if folder else data_dir \n```\n\n\n```python\nDATA_HUB = dict()\nDATA_HUB['SNLI'] = ('https://nlp.stanford.edu/projects/snli/snli_1.0.zip',\n '9fcde07509c7e87ec61c640c1b2753d9041758e4')\n\ndata_dir = download_extract('SNLI')\n```\n\n Downloading ../data/snli_1.0.zip from https://nlp.stanford.edu/projects/snli/snli_1.0.zip...\n\n\n\n```python\ndef read_snli(data_dir, is_train):\n \"\"\"Read the SNLI dataset into premises, hypotheses, and labels.\"\"\"\n def extract_text(s):\n # Remove information that will not be used by us\n s = re.sub('\\\\(', '', s)\n s = re.sub('\\\\)', '', s)\n # Substitute two or more consecutive whitespace with space\n s = re.sub('\\\\s{2,}', ' ', s)\n return s.strip()\n\n label_set = {'entailment': 0, 'contradiction': 1, 'neutral': 2}\n file_name = os.path.join(\n data_dir, 'snli_1.0_train.txt' if is_train else 'snli_1.0_test.txt')\n with open(file_name, 'r') as f:\n rows = [row.split('\\t') for row in f.readlines()[1:]]\n premises = [extract_text(row[1]) for row in rows if row[0] in label_set]\n hypotheses = [extract_text(row[2]) for row in rows if row[0] in label_set]\n labels = [label_set[row[0]] for row in rows if row[0] in label_set]\n return premises, hypotheses, labels\n```\n\nShow first 3 training examples and their labels (“0”, “1”, and “2” correspond to “entailment”, “contradiction”, and “neutral”, respectively ).\n\n\n```python\ntrain_data = read_snli(data_dir, is_train=True)\nfor x0, x1, y in zip(train_data[0][:3], train_data[1][:3], train_data[2][:3]):\n print('premise:', x0)\n print('hypothesis:', x1)\n print('label:', y)\n```\n\n premise: A person on a horse jumps over a broken down airplane .\n hypothesis: A person is training his horse for a competition .\n label: 2\n premise: A person on a horse jumps over a broken down airplane .\n hypothesis: A person is at a diner , ordering an omelette .\n label: 1\n premise: A person on a horse jumps over a broken down airplane .\n hypothesis: A person is outdoors , on a horse .\n label: 0\n\n\n\n```python\ntest_data = read_snli(data_dir, is_train=False)\nfor data in [train_data, test_data]:\n print([[row for row in data[2]].count(i) for i in range(3)])\n```\n\n [183416, 183187, 182764]\n [3368, 3237, 3219]\n\n\n\n```python\ndef tokenize(lines, token='word'):\n \"\"\"Split text lines into word or character tokens.\"\"\"\n if token == 'word':\n return [line.split() for line in lines]\n elif token == 'char':\n return [list(line) for line in lines]\n else:\n print('ERROR: unknown token type: ' + token)\n\nclass Vocab: \n \"\"\"Vocabulary for text.\"\"\"\n def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):\n if tokens is None:\n tokens = []\n if reserved_tokens is None:\n reserved_tokens = []\n # Sort according to frequencies\n counter = count_corpus(tokens)\n self.token_freqs = sorted(counter.items(), key=lambda x: x[1],\n reverse=True)\n # The index for the unknown token is 0\n self.unk, uniq_tokens = 0, [''] + reserved_tokens\n uniq_tokens += [\n token for token, freq in self.token_freqs\n if freq >= min_freq and token not in uniq_tokens]\n self.idx_to_token, self.token_to_idx = [], dict()\n for token in uniq_tokens:\n self.idx_to_token.append(token)\n self.token_to_idx[token] = len(self.idx_to_token) - 1\n\n def __len__(self):\n return len(self.idx_to_token)\n\n def __getitem__(self, tokens):\n if not isinstance(tokens, (list, tuple)):\n return self.token_to_idx.get(tokens, self.unk)\n return [self.__getitem__(token) for token in tokens]\n\n def to_tokens(self, indices):\n if not isinstance(indices, (list, tuple)):\n return self.idx_to_token[indices]\n return [self.idx_to_token[index] for index in indices]\n\ndef count_corpus(tokens): \n \"\"\"Count token frequencies.\"\"\"\n # Here `tokens` is a 1D list or 2D list\n if len(tokens) == 0 or isinstance(tokens[0], list):\n # Flatten a list of token lists into a list of tokens\n tokens = [token for line in tokens for token in line]\n return collections.Counter(tokens)\n\n```\n\n\n```python\nclass SNLIDataset(torch.utils.data.Dataset):\n \"\"\"A customized dataset to load the SNLI dataset.\"\"\"\n def __init__(self, dataset, num_steps, vocab=None):\n self.num_steps = num_steps\n all_premise_tokens = tokenize(dataset[0])\n all_hypothesis_tokens = tokenize(dataset[1])\n if vocab is None:\n self.vocab = Vocab(all_premise_tokens + all_hypothesis_tokens,\n min_freq=5, reserved_tokens=[''])\n else:\n self.vocab = vocab\n self.premises = self._pad(all_premise_tokens)\n self.hypotheses = self._pad(all_hypothesis_tokens)\n self.labels = torch.tensor(dataset[2])\n print('read ' + str(len(self.premises)) + ' examples')\n\n def _pad(self, lines):\n return torch.tensor([\n truncate_pad(self.vocab[line], self.num_steps,\n self.vocab['']) for line in lines])\n\n def __getitem__(self, idx):\n return (self.premises[idx], self.hypotheses[idx]), self.labels[idx]\n\n def __len__(self):\n return len(self.premises)\n```\n\n\n```python\ndef load_data_snli(batch_size, num_steps=50):\n \"\"\"Download the SNLI dataset and return data iterators and vocabulary.\"\"\"\n num_workers = 2\n data_dir = download_extract('SNLI')\n train_data = read_snli(data_dir, True)\n test_data = read_snli(data_dir, False)\n train_set = SNLIDataset(train_data, num_steps)\n test_set = SNLIDataset(test_data, num_steps, train_set.vocab)\n train_iter = torch.utils.data.DataLoader(train_set, batch_size,\n shuffle=True,\n num_workers=num_workers)\n test_iter = torch.utils.data.DataLoader(test_set, batch_size,\n shuffle=False,\n num_workers=num_workers)\n return train_iter, test_iter, train_set.vocab\n\ndef truncate_pad(line, num_steps, padding_token):\n \"\"\"Truncate or pad sequences.\"\"\"\n if len(line) > num_steps:\n return line[:num_steps] # Truncate\n return line + [padding_token] * (num_steps - len(line))\n```\n\n\n```python\ntrain_iter, test_iter, vocab = load_data_snli(128, 50)\nlen(vocab)\n```\n\n read 549367 examples\n read 9824 examples\n\n\n\n\n\n 18678\n\n\n\n# Model\n\nThe model is described in the book. Below we just give the code.\n\n## Attending\n\nWe define attention weights\n$$\ne_{ij} = f(a_i)^T f(b_j)\n$$\nwhere $a_i \\in R^E$ is the embedding of the $i$'th token from the premise,\n$b_j \\in R^E$ is the embedding of the $j$'th token from the hypothesis,\nand $f: R^E \\rightarrow R^H$ is an MLP that maps from the embedding space to another hidden space.\n\n\n\n\n```python\nclass mlp(nn.Module):\n num_hiddens: int\n flatten: bool\n\n @nn.compact\n def __call__(self, X, train=True):\n X = nn.Dropout(rate=0.2, deterministic=not train)(X)\n X = nn.Dense(self.num_hiddens)(X)\n X = nn.relu(X)\n if self.flatten:\n X = X.reshape((X.shape[0], -1)) # flatten\n X = nn.Dropout(rate=0.2, deterministic=not train)(X)\n X = nn.Dense(self.num_hiddens)(X)\n X = nn.relu(X)\n if self.flatten:\n X = X.reshape((X.shape[0], -1)) # flatten\n return X\n```\n\n\n```python\nclass Attend(nn.Module):\n num_hiddens: int\n\n def setup(self):\n self.f = mlp(self.num_hiddens, False)\n\n @nn.compact\n def __call__(self, A, B, train=True):\n # Shape of `A`/`B`: (`batch_size`, no. of words in sequence A/B,\n # `embed_size`)\n # Shape of `f_A`/`f_B`: (`batch_size`, no. of words in sequence A/B,\n # `num_hiddens`)\n f_A = self.f(A, train)\n f_B = self.f(B, train)\n # Shape of `e`: (`batch_size`, no. of words in sequence A,\n # no. of words in sequence B)\n e = f_A@(f_B.transpose((0, 2, 1)))\n # Shape of `beta`: (`batch_size`, no. of words in sequence A,\n # `embed_size`), where sequence B is softly aligned with each word\n # (axis 1 of `beta`) in sequence A\n beta = nn.softmax(e, axis=-1)@B\n # Shape of `alpha`: (`batch_size`, no. of words in sequence B,\n # `embed_size`), where sequence A is softly aligned with each word\n # (axis 1 of `alpha`) in sequence B\n alpha = nn.softmax(e.transpose((0, 2, 1)) , axis=-1)@A\n return beta, alpha\n```\n\n## Comparing\n\nWe concatenate word $i$ in A, $a_i$, with its \"soft counterpart\" in B, $\\beta_i$, and vice versa, and then pass this through another MLP $g$\nto get a \"comparison vector\" for each input location.\n$$\n\\begin{align}\n v_{A,i} &= g([a_i, \\beta_i]), \\; i=1,\\ldots, m \\\\\n v_{B,j} &= g([b_j, \\alpha_j]), \\; j=1,\\ldots, n\n\\end{align}\n$$\n\n\n```python\nclass Compare(nn.Module):\n num_hiddens: int\n\n def setup(self):\n self.g = mlp(self.num_hiddens, False)\n \n @nn.compact\n def __call__(self, A, B, beta, alpha, train=True):\n V_A = self.g(jnp.concatenate((A, beta), axis=2), train)\n V_B = self.g(jnp.concatenate((B, alpha), axis=2), train)\n return V_A, V_B\n```\n\n## Aggregation\n\nWe sum-pool the \"comparison vectors\" for each input sentence, and then pass the pair of poolings to yet another MLP $h$ to generate the final classification.\n\n$$\n\\begin{align}\n v_A &= \\sum_{i=1}^m v_{A,i} \\\\\n v_B &= \\sum_{j=1}^n v_{B,j} \\\\\n \\hat{y} &= h([v_A, v_B])\n\\end{align}\n$$\n\n\n\n```python\nclass Aggregate(nn.Module):\n num_hiddens: int\n num_outputs: int\n\n @nn.compact\n def __call__(self, V_A, V_B, train=True):\n # Sum up both sets of comparison vectors\n V_A = V_A.sum(axis=1)\n V_B = V_B.sum(axis=1)\n # Feed the concatenation of both summarization results into an MLP\n Y_hat = nn.Dense(self.num_outputs)(mlp(self.num_hiddens, True)(jnp.concatenate((V_A, V_B), axis=1) ,train))\n return Y_hat\n```\n\n## Putting it altogether\n\nWe use a pre-trained embedding of size E=100.\nThe $f$ (attend) function maps from $E=100$ to $H=200$ hiddens.\nThe $g$ (compare) function maps $2E=200$ to $H=200$.\nThe $h$ (aggregate) function maps $2H=400$ to 3 outputs.\n\n\n\n```python\nclass DecomposableAttention(nn.Module):\n vocab: Any\n embed_size: int\n num_hiddens: int\n embed_init: Callable\n\n def setup(self):\n self.embedding = nn.Embed(len(self.vocab), self.embed_size, embedding_init=self.embed_init)\n self.attend = Attend(self.num_hiddens)\n self.compare = Compare(self.num_hiddens)\n # There are 3 possible outputs: entailment, contradiction, and neutral\n self.aggregate = Aggregate(self.num_hiddens, 3)\n \n def __call__(self, X, train=True):\n premises, hypotheses = X\n A = self.embedding(premises)\n B = self.embedding(hypotheses)\n beta, alpha = self.attend(A, B, train)\n V_A, V_B = self.compare(A, B, beta, alpha, train)\n Y_hat = self.aggregate(V_A, V_B, train)\n return Y_hat\n```\n\n\n```python\nclass TokenEmbedding:\n \"\"\"Token Embedding.\"\"\"\n def __init__(self, embedding_name):\n self.idx_to_token, self.idx_to_vec = self._load_embedding(\n embedding_name)\n self.unknown_idx = 0\n self.token_to_idx = {\n token: idx for idx, token in enumerate(self.idx_to_token)}\n\n def _load_embedding(self, embedding_name):\n idx_to_token, idx_to_vec = [''], []\n data_dir = download_extract(embedding_name)\n # GloVe website: https://nlp.stanford.edu/projects/glove/\n # fastText website: https://fasttext.cc/\n with open(os.path.join(data_dir, 'vec.txt'), 'r') as f:\n for line in f:\n elems = line.rstrip().split(' ')\n token, elems = elems[0], [float(elem) for elem in elems[1:]]\n # Skip header information, such as the top row in fastText\n if len(elems) > 1:\n idx_to_token.append(token)\n idx_to_vec.append(elems)\n idx_to_vec = [[0] * len(idx_to_vec[0])] + idx_to_vec\n return idx_to_token, jnp.array(idx_to_vec)\n\n def __getitem__(self, tokens):\n indices = [\n self.token_to_idx.get(token, self.unknown_idx)\n for token in tokens]\n vecs = self.idx_to_vec[jnp.array(indices)]\n return vecs\n\n def __len__(self):\n return len(self.idx_to_token)\n\n```\n\n\n```python\ndef embedding_init(rng, shape, dtype):\n # get pre-trained GloVE embeddings of size 100\n# glove_embedding = TokenEmbedding('glove.6b.100d')\n# embeds = glove_embedding[vocab.idx_to_token]\n return embeds\n```\n\n\n```python\nDATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/glove.6B.100d.zip'\nDATA_HUB['glove.6b.100d'] = (DATA_URL, 'cd43bfb07e44e6f27cbcc7bc9ae3d80284fdaf5a')\n\nglove_embedding = TokenEmbedding('glove.6b.100d')\nembeds = glove_embedding[vocab.idx_to_token]\n\nembed_size, num_hiddens = 100, 200\nAttentionNetwork = functools.partial(DecomposableAttention, vocab, embed_size, num_hiddens, embedding_init) \n```\n\n Downloading ../data/glove.6B.100d.zip from http://d2l-data.s3-accelerate.amazonaws.com/glove.6B.100d.zip...\n\n\n# Training\n\n\n```python\nclass Animator:\n \"\"\"For plotting data in animation.\"\"\"\n def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,\n ylim=None, xscale='linear', yscale='linear',\n fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,\n figsize=(3.5, 2.5)):\n # Incrementally plot multiple lines\n if legend is None:\n legend = []\n display.set_matplotlib_formats('svg')\n self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize)\n if nrows * ncols == 1:\n self.axes = [self.axes,]\n # Use a lambda function to capture arguments\n self.config_axes = lambda: set_axes(self.axes[\n 0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n self.X, self.Y, self.fmts = None, None, fmts\n\n def add(self, x, y):\n # Add multiple data points into the figure\n if not hasattr(y, \"__len__\"):\n y = [y]\n n = len(y)\n if not hasattr(x, \"__len__\"):\n x = [x] * n\n if not self.X:\n self.X = [[] for _ in range(n)]\n if not self.Y:\n self.Y = [[] for _ in range(n)]\n for i, (a, b) in enumerate(zip(x, y)):\n if a is not None and b is not None:\n self.X[i].append(a)\n self.Y[i].append(b)\n self.axes[0].cla()\n for x, y, fmt in zip(self.X, self.Y, self.fmts):\n self.axes[0].plot(x, y, fmt)\n self.config_axes()\n display.display(self.fig)\n display.clear_output(wait=True)\n\nclass Timer:\n \"\"\"Record multiple running times.\"\"\"\n def __init__(self):\n self.times = []\n self.start()\n\n def start(self):\n \"\"\"Start the timer.\"\"\"\n self.tik = time.time()\n\n def stop(self):\n \"\"\"Stop the timer and record the time in a list.\"\"\"\n self.times.append(time.time() - self.tik)\n return self.times[-1]\n\n def avg(self):\n \"\"\"Return the average time.\"\"\"\n return sum(self.times) / len(self.times)\n\n def sum(self):\n \"\"\"Return the sum of time.\"\"\"\n return sum(self.times)\n\n def cumsum(self):\n \"\"\"Return the accumulated time.\"\"\"\n return np.array(self.times).cumsum().tolist()\n\nclass Accumulator:\n \"\"\"For accumulating sums over `n` variables.\"\"\"\n def __init__(self, n):\n self.data = [0.0] * n\n\n def add(self, *args):\n self.data = [a + float(b) for a, b in zip(self.data, args)]\n\n def reset(self):\n self.data = [0.0] * len(self.data)\n\n def __getitem__(self, idx):\n return self.data[idx]\n```\n\n\n```python\ndef set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):\n \"\"\"Set the axes for matplotlib.\"\"\"\n axes.set_xlabel(xlabel)\n axes.set_ylabel(ylabel)\n axes.set_xscale(xscale)\n axes.set_yscale(yscale)\n axes.set_xlim(xlim)\n axes.set_ylim(ylim)\n if legend:\n axes.legend(legend)\n axes.grid()\n```\n\n\n```python\ndef cross_entropy_loss(logits, labels) -> float:\n one_hot = jax.nn.one_hot(labels, num_classes=3)\n loss = optax.softmax_cross_entropy(logits=logits, labels=one_hot)\n return loss.sum()\n\ndef compute_metrics(logits, labels):\n \"\"\"Computes metrics and returns them.\"\"\"\n loss = cross_entropy_loss(logits, labels)\n accuracy = jnp.sum(jnp.argmax(logits, -1) == labels)\n metrics = {\n 'loss': loss,\n 'accuracy': accuracy,\n }\n return metrics\n```\n\n\n```python\ndef get_initial_params(model, rng):\n X = jnp.ones((2, 128, 50), dtype=jnp.int32)\n variables = model.init(jax.random.PRNGKey(0), X, False)\n return variables['params']\n\ndef get_train_state(rng, lr) -> train_state.TrainState:\n \"\"\"Returns a train state.\"\"\"\n model = AttentionNetwork()\n params = get_initial_params(model, rng)\n tx = optax.adam(lr)\n return train_state.TrainState.create(\n apply_fn=model.apply, params=params, tx=tx)\n```\n\n\n```python\ndef evaluate_accuracy(state: train_state.TrainState, data_iter):\n \"\"\"Compute the accuracy for a model on a dataset using a GPU.\"\"\"\n # No. of correct predictions, no. of predictions\n metric = Accumulator(2)\n for X, y in data_iter:\n X = [jnp.array(x) for x in X]\n y = jnp.array(y)\n logits = state.apply_fn({'params': state.params}, X, False)\n accuracy = jnp.sum(jnp.argmax(logits, -1) == y)\n metric.add(accuracy, y.size)\n return metric[0] / metric[1]\n```\n\n\n```python\n@jax.jit\ndef train_step(state: train_state.TrainState, dropout_rng, features, labels):\n \n \"\"\"Trains one step.\"\"\"\n def loss_fn(params):\n logits = state.apply_fn({'params': params}, features, True, rngs={'dropout': dropout_rng})\n loss = cross_entropy_loss(logits, labels)\n return loss, logits\n \n grad_fn = jax.value_and_grad(loss_fn, has_aux=True)\n (_, logits), grads = grad_fn(state.params)\n state = state.apply_gradients(grads=grads)\n metrics = compute_metrics(logits, labels)\n \n return state, metrics\n```\n\n\n```python\ndef train(train_iter, test_iter, num_epochs, lr):\n key = jax.random.PRNGKey(42)\n\n state = get_train_state(key, lr)\n\n timer, num_batches = Timer(), len(train_iter)\n animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 1], legend=['train loss', 'train acc', 'test acc'])\n\n for epoch in range(num_epochs):\n # Store training_loss, training_accuracy, num_examples, num_features\n metric = Accumulator(4)\n for i, (features, labels) in enumerate(train_iter):\n features = [jnp.array(x) for x in features]\n labels = jnp.array(labels)\n timer.start()\n state, metrics = train_step(state, key, features, labels)\n l = metrics['loss']\n acc = metrics['accuracy']\n metric.add(l, acc, labels.shape[0], labels.size)\n timer.stop()\n if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:\n animator.add(\n epoch + (i + 1) / num_batches,\n (metric[0] / metric[2], metric[1] / metric[3], None))\n # Calculate Test Accuracy\n test_acc = evaluate_accuracy(state, test_iter)\n animator.add(epoch + 1, (None, None, test_acc))\n device = jax.default_backend()\n print(f'loss {metric[0] / metric[2]:.3f}, train acc '\n f'{metric[1] / metric[3]:.3f}, test acc {test_acc:.3f}')\n print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec on '\n f'{str(device)}')\n return state\n```\n\n\n```python\nlr, num_epochs = 0.001, 4\nstate = train(train_iter, test_iter, num_epochs, lr)\n```\n\n loss 0.500, train acc 0.802, test acc 0.811\n 6486.3 examples/sec on gpu\n\n\n\n \n\n \n\n\n# Testing\n\n\n```python\ndef predict_snli(state, vocab, premise, hypothesis):\n model = AttentionNetwork()\n premise = jnp.array(vocab[premise])\n hypothesis = jnp.array(vocab[hypothesis])\n features = [premise.reshape((1, -1)), hypothesis.reshape((1, -1))]\n logits = state.apply_fn({'params': state.params}, features, False)\n label = jnp.argmax(logits)\n return 'entailment' if label == 0 else 'contradiction' if label == 1 \\\n else 'neutral'\n```\n\n\n```python\npredict_snli(state, vocab, ['he', 'is', 'good', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'contradiction'\n\n\n\n\n```python\npredict_snli(state, vocab, ['he', 'is', 'very', 'naughty', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'entailment'\n\n\n\n\n```python\npredict_snli(state, vocab, ['he', 'is', 'awful', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'entailment'\n\n\n\n\n```python\npredict_snli(state, vocab, ['he', 'is', 'handsome', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'contradiction'\n\n\n\n## Examples from training set\n\n\n```python\npredict_snli(state, vocab, \n ['a', 'person', 'on', 'a', 'horse', 'jumps', 'over', 'a', 'log' '.'],\n ['a', 'person', 'is', 'outdoors', 'on', 'a', 'horse', '.']) \n```\n\n\n\n\n 'entailment'\n\n\n\n\n```python\npredict_snli(state, vocab, \n ['a', 'person', 'on', 'a', 'horse', 'jumps', 'over', 'a', 'log' '.'],\n ['a', 'person', 'is', 'at', 'a', 'diner', 'ordering', 'an', 'omelette', '.']) \n```\n\n\n\n\n 'contradiction'\n\n\n\n\n```python\npredict_snli(state, vocab, \n ['a', 'person', 'on', 'a', 'horse', 'jumps', 'over', 'a', 'log' '.'],\n ['a', 'person', 'is', 'training', 'a', 'horse', 'for', 'a', 'competition', '.']) \n```\n\n\n\n\n 'neutral'\n\n\n", "meta": {"hexsha": "daea786e809a6cd5717604b2e3a1d82bf52db374", "size": 81552, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks-d2l/entailment_attention_mlp_jax.ipynb", "max_stars_repo_name": "patel-zeel/probml-notebooks", "max_stars_repo_head_hexsha": "1ff09bfddb2bd6b3932d81845546770e7e2fce3a", "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": "notebooks-d2l/entailment_attention_mlp_jax.ipynb", "max_issues_repo_name": "patel-zeel/probml-notebooks", "max_issues_repo_head_hexsha": "1ff09bfddb2bd6b3932d81845546770e7e2fce3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-30T20:00:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:30:42.000Z", "max_forks_repo_path": "notebooks-d2l/entailment_attention_mlp_jax.ipynb", "max_forks_repo_name": "patel-zeel/probml-notebooks", "max_forks_repo_head_hexsha": "1ff09bfddb2bd6b3932d81845546770e7e2fce3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.7973068746, "max_line_length": 31705, "alphanum_fraction": 0.5223660977, "converted": true, "num_tokens": 6717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.1666753984788992, "lm_q1q2_score": 0.06663876453680781}} {"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nPromijeni vidljivost ovdje.''')\ndisplay(tag)\n```\n\n\n\nPromijeni vidljivost ovdje.\n\n\n## Upravljanje bočnog položaja lunarnog prizemljivača\n\nOvaj primjer ilustrira razvoj regulatora (promatrača i kontrolera u formi povratne veze stanja) za upravljanje bočnim položajem lunarnog prizemljivača, počevši od jednadžbi sustava.\n\n\n\nSustav je predstavljen na gornjoj slici, njegov vertikalni spust usporen je pomoću vertikalnog potisnika koji proizvodi konstantnu silu $F$. Horizontalno kretanje može se postići laganim naginjanjem prizemljivača za kut $\\theta$; naginjanjem se stvara bočna sila koja je približno jednaka $F\\theta$. Nagib se postiže generiranjem momenta $T$ pomoću skupa upravljačkih raketa (maksimalni moment = 500 Nm). Kut nagiba mora biti unutar$\\pm15$ stupnjeva kako bi se izbjeglo opasno povećanje brzine vertikalnog spusta. Izmjerene veličine su bočni položaj i brzina. Pretpostavlja se da je atmosferski otpor zanemariv, a vrijednosti parametara navedene su u donjoj tablici.\n\n| Parametar | Vrijednost |\n|-----------|-------------------------------:|\n|$m$ | 1000 kg |\n|$J$ | 1000 kg$\\text{m}^2$ |\n|$F$ | 1500 N |\n\nCilj dizajna upravljačkog sustava je postići sljedeće performanse za regulaciju vodoravnog položaja $z$:\n1. Maksimalno prekoračenje od 30%.\n2. Vrijeme smirivanja (za 5% pojasa tolerancije) manje od 15 sekundi.\n3. Kut $\\theta$ uvijek unutar svojih granica za željenu maksimalnu bočnu promjenu od 10 metara.\n4. Nulta pogreška kao odziv na naredbeni korak.\n\nJednadžbe sustava su:\n\n\n\\begin{cases}\nJ\\ddot{\\theta}=T \\\\\nm\\ddot{z}=F\\theta\n\\end{cases}\ni definiranjem $\\textbf{x}=[x_1,x_2,x_3,x_4]^T=[z,\\dot{z},\\theta,\\dot{\\theta}]^T$ kao vektora stanja te $u=T$ kao ulaza, u formi prostora stanja dobivamo:\n\n\\begin{cases}\n\\dot{\\textbf{x}}=\\underbrace{\\begin{bmatrix}0&1&0&0 \\\\ 0&0&F/m&0 \\\\ 0&0&0&1 \\\\ 0&0&0&0\\end{bmatrix}}_{A}\\textbf{x}+\\underbrace{\\begin{bmatrix}0\\\\0\\\\0\\\\1/J\\end{bmatrix}}_{B}u \\\\ \\\\\n\\textbf{y}=\\underbrace{\\begin{bmatrix}1&0&0&0 \\\\ 0&1&0&0\\end{bmatrix}}_{C}\\textbf{x}.\n\\end{cases}\n\n### Dizajn kontrolera\nKako bi postigli nultu pogrešku za odziv na referentni korak, sustav se proširuje dodavanjem novog stanja $\\dot{x_5}=y_1-y_d$ gdje je $y_1$ izmjereni bočni položaj, a $y_d$ je vrijednost željenog položaja. Stoga je prošireni sustav:\n\n\\begin{cases}\n\\dot{\\textbf{x}_a}=\\underbrace{\\begin{bmatrix}0&1&0&0&0 \\\\ 0&0&F/m&0&0 \\\\ 0&0&0&1&0 \\\\ 0&0&0&0&0 \\\\ 1&0&0&0&0 \\end{bmatrix}}_{A_a}\\textbf{x}_a+\\underbrace{\\begin{bmatrix} 0&0\\\\0&0\\\\0&0\\\\1/J&0\\\\0&-1 \\end{bmatrix}}_{B_a}\\underbrace{\\begin{bmatrix} u\\\\y_d \\end{bmatrix}}_{u_a} \\\\ \\\\\n\\textbf{y}_a=\\underbrace{\\begin{bmatrix}1&0&0&0&0\\\\0&1&0&0&0\\\\0&0&0&0&1\\end{bmatrix}}_{C_a}\\textbf{x}_a\n\\end{cases}\n\nkoji se može kontrolirati (upravljiv) s prvim stupcem od $B_a$, tako da je moguće koristiti metodu postavljanja polova. Imajte na umu da je, kako bi se održala osmotrivost sustava, dodan red u matrici $C$ jer je poznato novo stanje $x_5$.\n\nMatrica pojačanja $K_a$ koja zadovoljava sve zadane uvjete je:\n$$\nK_a=\\begin{bmatrix}2225.0&6244.0&13861.0&5275.0&316.0\\end{bmatrix}\n$$\nčime se polovi od $(A_a-B_aK_a)$ pozicioniraju na $-0.28$, $-2.24+2.23i$, $-2.24-2.23i$, $-0.26+0.32i$ i $-0.26-0.32i$.\n\n### Dizajn promatrača\nSustav je osmotriv, a, budući da se mjere tri stanja, moguće je dizajnirati promatrač s reduciranim stanjima (za $\\theta$ i $\\dot{\\theta}$) koji ima strukturu:\n$$\n\\dot{\\hat{\\textbf{v}}}=(A_{11}+L_aA_{21})\\hat{\\textbf{v}}+(A_{12}+L_aA_{22}-A_{11}L_a-L_aA_{21}L_a)\\textbf{y}_a+(B_1+L_aB_2)u_a,\n$$\ngdje je\n$$\nT^{-1}A_aT=\\begin{bmatrix}A_{11}&A_{12} \\\\ A_{21}&A_{22}\\end{bmatrix}, \n\\quad T^{-1}B_a=\\begin{bmatrix}B_1 \\\\ B_2\\end{bmatrix}, \n\\quad \\overline{\\textbf{x}_a}=T^{-1}\\textbf{x}_a=\\begin{bmatrix}V \\\\ C\\end{bmatrix}\\textbf{x}_a, \n\\quad V=\\begin{bmatrix}0&0&1&0&0 \\\\ 0&0&0&1&0\\end{bmatrix}, \n\\quad \\hat{\\textbf{x}_a}=\\begin{bmatrix}\\hat{\\textbf{v}}-L_a\\textbf{y}_a \\\\ \\textbf{y}_a\\end{bmatrix}.\n$$\n\nOdabir svojstvenih vrijednosti promatrača vrši se na način da dinamika pogrešaka konvergira brže od dinamike sustava specificirane zahtjevima. Svojstvene vrijednosti odabrane za $A_{11}+L_aA_{21}$ su $\\lambda_i=-10$ rad/s, $i=1,2$ uz\n$$ L_a=\\begin{bmatrix}0&-\\frac{40}{3}&0 \\\\ 0&-\\frac{200}{3}&0\\end{bmatrix} $$\n\n\n\n### Kako koristiti ovaj interaktivni primjer?\nUčinkovitost sustava možete provjeriti s razvijenim regulatorom i izravno modificirati kontroler i/ili promatrač. Simulacija započinje početnom pogreškom promatrača.\n\n\n```python\n#Preparatory Cell \n\n%matplotlib notebook\nimport control as ctrl\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\nimport matplotlib.transforms as transforms\nimport matplotlib.lines as lines\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(ctrl.StateSpace):\n def __init__(self,*args):\n #call base class init constructor\n ctrl.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# Define matrixes\n\nA = numpy.matrix('0 1 0 0; 0 0 1.5 0; 0 0 0 1; 0 0 0 0')\nB = numpy.matrix('0;0;0;0.001')\nC = numpy.matrix('1 0 0 0; 0 1 0 0')\nAa = numpy.matrix('0 1 0 0 0; 0 0 1.5 0 0; 0 0 0 1 0; 0 0 0 0 0; 1 0 0 0 0')\nBa = numpy.matrix('0 0;0 0;0 0;0.001 0;0 -1')\nCa = numpy.matrix('1 0 0 0 0; 0 1 0 0 0; 0 0 0 0 1')\nKa1 = numpy.matrix('[2225.0, 6244.0, 13861.0, 5275.0, 316.0') #318.9333 835 2012.5 2000 59.6\nTa = (numpy.matrix('0 0 1 0 0; 0 0 0 1 0; 1 0 0 0 0;0 1 0 0 0; 0 0 0 0 1'))**(-1)\nAr = Ta**(-1)*Aa*Ta\nBr = Ta**(-1)*Ba\nA11 = Ar[0:2,0:2]\nA12 = Ar[0:2,2:5]\nA21 = Ar[2:5,0:2]\nA22 = Ar[2:5,2:5]\nB1 = Br[0:2,:]\nB2 = Br[2:5,:]\nLa1 = numpy.matrix([[0, -4*10/3, 0],[0, -3/8*(-4*10/3)**2, 0]])\nX0a = numpy.matrix('0;0;0;0;0;0;0;0;0;0;0.002;0.002;0;0;0;0;0;0.002;0.002;0;0;0;0;0')\n# X0a = numpy.matrix('0;0;0;0;0')\n# V0 = numpy.matrix('0;0')\n```\n\n\n```python\n# Define matrixes widget\nKaw = matrixWidget(1,5)\nLaw = matrixWidget(2,3)\neig1 = matrixWidget(1,1)\neig2 = matrixWidget(2,1)\neig3 = matrixWidget(2,1)\neig4 = matrixWidget(1,1)\neig5 = matrixWidget(1,1)\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\n\nYdw = widgets.FloatSlider(\n value=10,\n min=0,\n max=10.0,\n step=0.1,\n description='$y_d$:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.1f',\n )\n\n# Init matrix widgets\nKaw.setM(Ka1) \nLaw.setM(La1)\n#[-0.6,-0.5-0.35j,-0.5+0.35j,-0.2-0.6j,-0.2+0.6j]\neig1.setM(numpy.matrix([-0.28]))\neig2.setM(numpy.matrix([[-2.24],[-2.23]]))\neig3.setM(numpy.matrix([[-0.26],[-0.32]])) \neig4.setM(numpy.matrix([-1])) \neig5.setM(numpy.matrix([-1])) \neig1o.setM(numpy.matrix([-10])) \neig2o.setM(numpy.matrix([[-10],[0]])) \n```\n\n\n```python\n# Support functions\n# Simulation function\ndef simulation(Aa, Baa, Ca, A11, A12, A21, A22, B1, B2, La, Ka, Ta):\n Aa, Baa, Ca = sym.Matrix(Aa), sym.Matrix(Baa), sym.Matrix(Ca)\n A11, A12, A21, A22 = sym.Matrix(A11), sym.Matrix(A12), sym.Matrix(A21), sym.Matrix(A22)\n B1, B2 = sym.Matrix(B1), sym.Matrix(B2)\n La, Ka = sym.Matrix(La), sym.Matrix(Ka)\n Ta = sym.Matrix(Ta)\n sysS = sss(Aa, Baa, Ca, sym.zeros(3,2))\n sysX = sss(Aa, Baa, sym.eye(5), sym.zeros(5,2))\n sysO1 = sss((A11+La*A21), (B1+La*B2).row_join(A12+La*A22-A11*La-La*A21*La), sym.eye(2), sym.zeros(2,5))\n sysO2 = ctrl.append(sysO1, sysS)\n sysO3 = ctrl.connect(sysO2, [[3, 3], [4, 4], [5, 5]], [1, 2, 6, 7], [1, 2, 3, 4, 5])\n sysO = sss(sysO3.A,\n sysO3.B*sym.eye(2).col_join(sym.eye(2)),\n Ta*(sym.eye(2).row_join(-La)).col_join(sym.zeros(3, 2).row_join(sym.eye(3)))*sysO3.C,\n sym.zeros(5,2))\n sysU = sss(sysO.A, sysO.B, -Ka*sysO.C, sym.zeros(1,2))\n sysT = ctrl.append(sysS, sysX, sysO, sysU)\n sysT1 = ctrl.connect(sysT, [[1, 14], [3, 14], [5, 14], [7, 14]], [2, 4, 6, 8], [i for i in range(1, 15)])\n sys = sss(sysT1.A, sysT1.B*sym.Matrix([1, 1, 1, 1]), sysT1.C, sym.zeros(14, 1))\n return sys\n\n# check functions\ndef eigen_choice(selc,selo):\n if selc == '0 kompleksnih svojstvenih vrijednosti':\n eig2.children[1].children[0].disabled = True\n eig3.children[1].children[0].disabled = True\n eig3.children[0].children[0].disabled = False\n eig4.children[0].children[0].disabled = False\n eig5.children[0].children[0].disabled = False\n eigc = 0\n if selc == '2 kompleksne svojstvene vrijednosti':\n eig2.children[1].children[0].disabled = False\n eig3.children[1].children[0].disabled = True\n eig3.children[0].children[0].disabled = True\n eig4.children[0].children[0].disabled = False\n eig5.children[0].children[0].disabled = False\n eigc = 2\n if selc == '4 kompleksne svojstvene vrijednosti':\n eig2.children[1].children[0].disabled = False\n eig3.children[1].children[0].disabled = False\n eig3.children[0].children[0].disabled = False\n eig4.children[0].children[0].disabled = True\n eig5.children[0].children[0].disabled = True\n eigc = 4\n if selo == '0 kompleksnih svojstvenih vrijednosti':\n eig1o.children[0].children[0].disabled = False\n eig2o.children[1].children[0].disabled = True\n eigo = 0\n if selo == '2 kompleksne svojstvene vrijednosti':\n eig1o.children[0].children[0].disabled = True\n eig2o.children[1].children[0].disabled = False\n eigo = 2\n return (eigc, eigo)\n\ndef method_choice(selm):\n if selm == 'Postavi Ka i La':\n method = 1\n selc.disabled = True\n selo.disabled = True\n if selm == 'Postavi svojstvene vrijednosti':\n method = 2\n selc.disabled = False\n selo.disabled = False\n return method\n\n# Animation functions\ndef fun_animation(index):\n global Ydw, yout, T\n yd = Ydw.value\n frame = 1\n \n linez.set_data(T[0:index*frame],yd*yout[0][0:index*frame])\n linezv.set_data(T[0:index*frame],yd*yout[1][0:index*frame])\n lined.set_data(T,[yd for i in range(0,len(T))])\n lineu.set_data(T[0:index*frame],yd*yout[13][0:index*frame])\n linelimu1.set_data(T,[500 for j in range(0,len(T))])\n linelimu2.set_data(T,[-500 for j in range(0,len(T))])\n linethetaest.set_data(T[0:index*frame],yd*yout[10][0:index*frame]*180/numpy.pi)\n linetheta.set_data(T[0:index*frame],yd*yout[5][0:index*frame]*180/numpy.pi)\n \n \n rotation_transform.clear().translate(yd*yout[0][index*frame]*numpy.cos(float(yd*yout[6][index*frame])), yd*yout[0][index*frame]*numpy.sin(float(yd*yout[6][index*frame]))).rotate(float(-yd*yout[6][index*frame]))\n \n return (linez,linezv,lined,lineu,linelimu1,linelimu2,linethetaest,linetheta)\n\ndef anim_init():\n linez.set_data([], [])\n linezv.set_data([], [])\n lined.set_data([], [])\n lineu.set_data([], [])\n linelimu1.set_data([], [])\n linelimu2.set_data([], [])\n linethetaest.set_data([], [])\n linetheta.set_data([], [])\n return (linez,linezv,lined,lineu,linelimu1,linelimu2,linethetaest,linetheta)\n\n```\n\n\n```python\n# Main cell\n# Data\nglobal yd, T, yout\nyd = 10.\nT = []\nyout = []\n\n# Figures\nfig = plt.figure(num='Simulacija sustava za upravljanje bočnog položaja lunarnog prizemljivača')\nfig.set_size_inches((9.8, 6))\nfig.set_tight_layout(True)\n\nax0 = fig.add_subplot(221)\nax0.set_title('Lunarni prizemljivač')\nax0.set_xlim(-12,12)\nax0.set_ylim(-4,4)\nax0.grid()\n# ax0.axis('off')\n\nax1 = fig.add_subplot(222)\nlinez = ax1.plot([],[])[0]\nlinezv = ax1.plot([],[])[0]\nlined = ax1.plot([],[])[0]\nax1.set_title('Bočni položaj i brzina')\nax1.set_xlabel('$t$ [s]')\nax1.set_ylabel('y [m], $\\dot y$ [m/s]')\nax1.set_xlim([0,17])\nax1.axvline(x=0,color='black',linewidth=0.8)\nax1.axhline(y=0,color='black',linewidth=0.8)\nax1.grid()\nax1.legend(['Nočni položaj','Bočna brzina','Željena vrijednost'])\n\nax2 = fig.add_subplot(223)\nlineu = ax2.plot([],[])[0]\nlinelimu1 = ax2.plot([],[],'r')[0]\nlinelimu2 = ax2.plot([],[],'r')[0]\nax2.set_title('Ulazni moment T')\nax2.set_xlabel('$t$ [s]')\nax2.set_ylabel('$T$ [Nm]')\nax2.set_xlim([0,17])\nax2.axvline(x=0,color='black',linewidth=0.8)\nax2.axhline(y=0,color='black',linewidth=0.8)\nax2.grid()\nax2.legend(['T','Limit'])\n\nax3 = fig.add_subplot(224)\nlinethetaest = ax3.plot([],[])[0]\nlinetheta = ax3.plot([],[])[0]\nax3.set_title(r'$\\theta_{est}$ vs $\\theta$')\nax3.set_xlabel('$t$ [s]')\nax3.set_ylabel(r'$\\theta$ [deg]')\nax3.axvline(x=0,color='black',linewidth=0.8)\nax3.axhline(y=0,color='black',linewidth=0.8)\nax3.set_xlim([0,17])\nax3.grid()\n\n# Patches\nrotation_transform = transforms.Affine2D()\ncircle = patches.Circle((0, 0.6), fill=True, radius=0.5, ec='black', fc='gray', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nrect = patches.Rectangle((-1, -0.4), 2, 0.5, fill=True, ec='black', fc='gray', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\npoly = patches.Polygon(numpy.stack(([-0.25, -0.15, 0.15, 0.25], [-0.8, -0.4, -0.4, -0.8])).T, \n closed=True, fill=True, ec='black', fc='black', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nlleg = patches.Rectangle((-1, -1.2), 0.05, 1, angle=-15, fill=True, ec='black', fc='black', lw=1, zorder=10, \n transform=rotation_transform + ax0.transData)\nrleg = patches.Rectangle((1, -1.2), 0.05, 1, angle=15, fill=True, ec='black', fc='black', lw=1, zorder=10, \n transform=rotation_transform + ax0.transData)\nlfoot = patches.Rectangle((-1.1, -1.2), 0.2, 0.05, fill=True, ec='black', fc='black', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nrfoot = patches.Rectangle((0.9, -1.2), 0.2, 0.05, fill=True, ec='black', fc='black', lw=1, zorder=20, \n transform=rotation_transform + ax0.transData)\nax0.add_patch(circle)\nax0.add_patch(rect)\nax0.add_patch(poly)\nax0.add_patch(lleg)\nax0.add_patch(rleg)\nax0.add_patch(lfoot)\nax0.add_patch(rfoot)\nplt.show()\n\n# Functions\ndef main_function(Ka,La,Ydw,eig1,eig2,eig3,eig4,eig5,eig1o,eig2o,selm,selc,selo,DW):\n global T, yout, yd, Aa, Ba, A11, A21\n method = method_choice(selm)\n eigc, eigo = eigen_choice(selc,selo)\n yd = Ydw\n ax1.set_ylim([-0.1*yd,yd*1.5])\n ax2.set_ylim([-51*yd,51*yd])\n ax3.set_ylim([-15,15])\n \n if method == 1: #Setted matrix gain\n sol = numpy.linalg.eig((Aa-Ba[:,0]*Ka))\n print('Svojstvene vrijednosti od Aa su: '+str(round(sol[0][0],3))+', '+str(round(sol[0][1],3))+', '+str(round(sol[0][2],3))+', '+str(round(sol[0][3],3))+' i '+str(round(sol[0][4],3)))\n sol = numpy.linalg.eig(A11+La*A21)\n print('Svojstvene vrijednosti od A11+La*A21 su: '+str(round(sol[0][0],3))+' i '+str(round(sol[0][1],3))) \n sys = simulation(Aa, Ba, Ca, A11, A12, A21, A22, B1, B2, La, Ka, Ta)\n T = numpy.linspace(0, 17, 100)\n T, yout = ctrl.step_response(sys, T, X0a)\n if method == 2: #Setted eigenvalues\n if eigc == 0:\n Ka = ctrl.acker(Aa, Ba[:,0], [eig1[0,0], eig2[0,0], eig3[0,0], eig4[0,0], eig5[0,0]])\n Kaw.setM(Ka)\n if eigc == 2:\n Ka = ctrl.acker(Aa, Ba[:,0], [eig1[0,0], numpy.complex(eig2[0,0],eig2[1,0]), numpy.complex(eig2[0,0],-eig2[1,0]), eig4[0,0], eig5[0,0]])\n Kaw.setM(Ka)\n if eigc == 4:\n Ka = ctrl.acker(Aa, Ba[:,0], [eig1[0,0], numpy.complex(eig2[0,0],eig2[1,0]), numpy.complex(eig2[0,0],-eig2[1,0]), numpy.complex(eig3[0,0],eig3[1,0]), numpy.complex(eig3[0,0],-eig3[1,0])])\n Kaw.setM(Ka)\n if eigo == 0:\n La = numpy.matrix([[0, 2*eig1o[0,0]/3 + 2*eig2o[0,0]/3, 0], [0, -2*eig1o[0,0]*eig2o[0,0]/3, 0]])\n Law.setM(La) \n if eigo == 2:\n La = numpy.matrix([[0, 2*numpy.complex(eig2o[0,0],eig2o[1,0])/3 + 2*numpy.complex(eig2o[0,0],-eig2o[1,0])/3, 0], [0, -2*numpy.complex(eig2o[0,0],eig2o[1,0])*numpy.complex(eig2o[0,0],-eig2o[1,0])/3, 0]])\n Law.setM(La)\n sol = numpy.linalg.eig((Aa-Ba[:,0]*Ka))\n print('Svojstvene vrijednosti od Aa su: '+str(round(sol[0][0],3))+', '+str(round(sol[0][1],3))+', '+str(round(sol[0][2],3))+', '+str(round(sol[0][3],3))+' i '+str(round(sol[0][4],3)))\n sol = numpy.linalg.eig(A11+La*A21)\n print('Svojstvene vrijednosti od A11+La*A21 su: '+str(round(sol[0][0],3))+' i '+str(round(sol[0][1],3))) \n sys = simulation(Aa, Ba, Ca, A11, A12, A21, A22, B1, B2, La, Ka, Ta)\n T = numpy.linspace(0, 17, 100)\n T, yout = ctrl.step_response(sys, T, X0a)\n\nani = animation.FuncAnimation(fig, fun_animation, init_func=anim_init, frames=100, repeat=True, interval=170, blit=True)\n\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= ['Postavi Ka i La', 'Postavi svojstvene vrijednosti'],\n value= 'Postavi Ka i La',\n description='',\n disabled=False\n)\n\n# Define the number of complex eigenvalues for the controller\nselc = widgets.Dropdown(\n options= ['0 kompleksnih svojstvenih vrijednosti', '2 kompleksne svojstvene vrijednosti', '4 kompleksne svojstvene vrijednosti'],\n value= '4 kompleksne svojstvene vrijednosti',\n description='Aa:',\n disabled=False\n)\n\n# Define the number of complex eigenvalues for the observer\nselo = widgets.Dropdown(\n options= ['0 kompleksnih svojstvenih vrijednosti', '2 kompleksne svojstvene vrijednosti'],\n value= '0 kompleksnih svojstvenih vrijednosti',\n description='Aobs:',\n disabled=False\n)\n\nalltogether = widgets.VBox([\n widgets.HBox([\n selm,\n selc,\n selo\n ]),\n widgets.Label('',border=3),\n widgets.HBox([\n widgets.Label('Ka:',border=3),\n Kaw,\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n widgets.Label('La:',border=3),\n Law\n ]),\n widgets.Label('',border=3),\n widgets.HBox([\n widgets.Label('Svojstvene vrijednosti od Aa:',border=3),\n eig1, eig2, eig3, eig4, eig5,\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n widgets.Label('Svojstvene vrijednosti od Aobs:',border=3),\n eig1o, eig2o\n ]),\n widgets.Label('',border=3),\n widgets.HBox([\n Ydw,\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n widgets.Label('',border=3),\n START\n ])\n])\n\nout = widgets.interactive_output(main_function,{'Ka':Kaw, 'La':Law, 'Ydw':Ydw, 'eig1':eig1, 'eig2':eig2, \n 'eig3':eig3, 'eig4':eig4, 'eig5':eig5,\n 'eig1o':eig1o, 'eig2o':eig2o,\n 'selm':selm, 'selc':selc, 'selo':selo, 'DW':DW})\ndisplay(out, alltogether)\n```\n\n\n \n\n\n\n\n\n\n\n Output()\n\n\n\n VBox(children=(HBox(children=(Dropdown(options=('Postavi Ka i La', 'Postavi svojstvene vrijednosti'), value='P…\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "41612d6b44a302f241f539a5f0e2119290fb1d8c", "size": 458406, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_hr/examples/04/SS-38-Upravljanje_bocnog_polozaja_lunarnog_prizemljivaca.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_hr/examples/04/SS-38-Upravljanje_bocnog_polozaja_lunarnog_prizemljivaca.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_hr/examples/04/SS-38-Upravljanje_bocnog_polozaja_lunarnog_prizemljivaca.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": 46.6381117102, "max_line_length": 119991, "alphanum_fraction": 0.6853313438, "converted": true, "num_tokens": 8262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.14608725076600915, "lm_q1q2_score": 0.06621577725368845}} {"text": "\n\n

    Processamento de Linguagem Natural

    \n
    Gustavo C. A Corradi
    \n\n
    @gustavocorradi, @data4sci
    \n\n# Lesson I - Text representation\n\nIn this lesson we will see in some details how we can best represent text in our application. Let's start by importing the modules we will be using:\n\n\n```python\nimport string\nfrom collections import Counter\nfrom pprint import pprint\nimport gzip\nimport matplotlib.pyplot as plt \nimport numpy as np\n\n%matplotlib inline\n```\n\nWe choose a well known nursery rhyme, that has the added distinction of having been the first audio ever recorded, to be the short snippet of text that we will use in our examples:\n\n\n```python\ntext = \"\"\"Mary had a little lamb, little lamb,\n little lamb. Mary had a little lamb\n whose fleece was white as snow.\n And everywhere that Mary went\n Mary went, Mary went. Everywhere\n that Mary went,\n The lamb was sure to go\"\"\"\n```\n\n## Tokenization\n\nThe first step in any analysis is to tokenize the text. What this means is that we will extract all the individual words in the text. For the sake of simplicity, we will assume that our text is well formed and that our words are delimited either by white space or punctuation characters.\n\n\n```python\ndef extract_words(text):\n temp = text.split() # Split the text on whitespace\n text_words = []\n\n for word in temp:\n # Remove any punctuation characters present in the beginning of the word\n while word[0] in string.punctuation:\n word = word[1:]\n\n # Remove any punctuation characters present in the end of the word\n while word[-1] in string.punctuation:\n word = word[:-1]\n\n # Append this word into our list of words.\n text_words.append(word.lower())\n \n return text_words\n```\n\nAfter this step we now have our text represented as an array of individual, lowercase, words:\n\n\n```python\ntext_words = extract_words(text)\nprint(text_words)\n```\n\n ['mary', 'had', 'a', 'little', 'lamb', 'little', 'lamb', 'little', 'lamb', 'mary', 'had', 'a', 'little', 'lamb', 'whose', 'fleece', 'was', 'white', 'as', 'snow', 'and', 'everywhere', 'that', 'mary', 'went', 'mary', 'went', 'mary', 'went', 'everywhere', 'that', 'mary', 'went', 'the', 'lamb', 'was', 'sure', 'to', 'go']\n\n\nAs we saw during the video, this is a wasteful way to represent text. We can be much more efficient by representing each word by a number\n\n\n```python\nword_dict = {}\nword_list = []\nvocabulary_size = 0\ntext_tokens = []\n\nfor word in text_words:\n # If we are seeing this word for the first time, create an id for it and added it to our word dictionary\n if word not in word_dict:\n word_dict[word] = vocabulary_size\n word_list.append(word)\n vocabulary_size += 1\n \n # add the token corresponding to the current word to the tokenized text.\n text_tokens.append(word_dict[word])\n```\n\nWhen we were tokenizing our text, we also generated a dictionary **word_dict** that maps words to integers and a **word_list** that maps each integer to the corresponding word.\n\n\n```python\nprint(\"Word list:\", word_list, \"\\n\\n Word dictionary:\")\npprint(word_dict)\n```\n\n Word list: ['mary', 'had', 'a', 'little', 'lamb', 'whose', 'fleece', 'was', 'white', 'as', 'snow', 'and', 'everywhere', 'that', 'went', 'the', 'sure', 'to', 'go'] \n \n Word dictionary:\n {'a': 2,\n 'and': 11,\n 'as': 9,\n 'everywhere': 12,\n 'fleece': 6,\n 'go': 18,\n 'had': 1,\n 'lamb': 4,\n 'little': 3,\n 'mary': 0,\n 'snow': 10,\n 'sure': 16,\n 'that': 13,\n 'the': 15,\n 'to': 17,\n 'was': 7,\n 'went': 14,\n 'white': 8,\n 'whose': 5}\n\n\nThese two datastructures already proved their usefulness when we converted our text to a list of tokens.\n\n\n```python\nprint(text_tokens)\n```\n\n [0, 1, 2, 3, 4, 3, 4, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 14, 0, 14, 0, 14, 12, 13, 0, 14, 15, 4, 7, 16, 17, 18]\n\n\nUnfortunately, while this representation is convenient for memory reasons it has some severe limitations. Perhaps the most important of which is the fact that computers naturally assume that numbers can be operated on mathematically (by addition, subtraction, etc) in a way that doesn't match our understanding of words.\n\n## One-hot encoding\n\nOne typical way of overcoming this difficulty is to represent each word by a one-hot encoded vector where every element is zero except the one corresponding to a specific word.\n\n\n```python\ndef one_hot(word, word_dict):\n \"\"\"\n Generate a one-hot encoded vector corresponding to *word*\n \"\"\"\n \n vector = np.zeros(len(word_dict))\n vector[word_dict[word]] = 1\n \n return vector\n```\n\nSo, for example, the word \"fleece\" would be represented by:\n\n\n```python\nfleece_hot = one_hot(\"fleece\", word_dict)\nprint(fleece_hot)\n```\n\n [0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n\n\nThis vector has every element set to zero, except element 6, since:\n\n\n```python\nprint(word_dict[\"fleece\"])\nfleece_hot[6] == 1\n```\n\n 6\n\n\n\n\n\n True\n\n\n\n## Bag of words\n\nWe can now use the one-hot encoded vector for each word to produce a vector representation of our original text, by simply adding up all the one-hot encoded vectors:\n\n\n```python\ntext_vector1 = np.zeros(vocabulary_size)\n\nfor word in text_words:\n hot_word = one_hot(word, word_dict)\n text_vector1 += hot_word\n \nprint(text_vector1)\n```\n\n [6. 2. 2. 4. 5. 1. 1. 2. 1. 1. 1. 1. 2. 2. 4. 1. 1. 1. 1.]\n\n\nIn practice, we can also easily skip the encoding step at the word level by using the *word_dict* defined above:\n\n\n```python\ntext_vector = np.zeros(vocabulary_size)\n\nfor word in text_words:\n text_vector[word_dict[word]] += 1\n \nprint(text_vector)\n```\n\n [6. 2. 2. 4. 5. 1. 1. 2. 1. 1. 1. 1. 2. 2. 4. 1. 1. 1. 1.]\n\n\nNaturally, this approach is completely equivalent to the previous one and has the added advantage of being more efficient in terms of both speed and memory requirements.\n\nThis is known as the __bag of words__ representation of the text. It should be noted that these vectors simply contains the number of times each word appears in our document, so we can easily tell that the word *mary* appears exactly 6 times in our little nursery rhyme.\n\n\n```python\ntext_vector[word_dict[\"mary\"]]\n```\n\n\n\n\n 6.0\n\n\n\nA more pythonic (and efficient) way of producing the same result is to use the standard __Counter__ module:\n\n\n```python\nword_counts = Counter(text_words)\npprint(word_counts)\n```\n\n Counter({'mary': 6,\n 'lamb': 5,\n 'little': 4,\n 'went': 4,\n 'had': 2,\n 'a': 2,\n 'was': 2,\n 'everywhere': 2,\n 'that': 2,\n 'whose': 1,\n 'fleece': 1,\n 'white': 1,\n 'as': 1,\n 'snow': 1,\n 'and': 1,\n 'the': 1,\n 'sure': 1,\n 'to': 1,\n 'go': 1})\n\n\nFrom which we can easily generate the __text_vector__ and __word_dict__ data structures:\n\n\n```python\nitems = list(word_counts.items())\n\n# Extract word dictionary and vector representation\nword_dict2 = dict([[items[i][0], i] for i in range(len(items))])\ntext_vector2 = [items[i][1] for i in range(len(items))]\n```\n\nAnd let's take a look at them:\n\n\n```python\nprint(\"Text vector:\", text_vector2, \"\\n\\nWord dictionary:\")\npprint(word_dict2)\n```\n\n Text vector: [6, 2, 2, 4, 5, 1, 1, 2, 1, 1, 1, 1, 2, 2, 4, 1, 1, 1, 1] \n \n Word dictionary:\n {'a': 2,\n 'and': 11,\n 'as': 9,\n 'everywhere': 12,\n 'fleece': 6,\n 'go': 18,\n 'had': 1,\n 'lamb': 4,\n 'little': 3,\n 'mary': 0,\n 'snow': 10,\n 'sure': 16,\n 'that': 13,\n 'the': 15,\n 'to': 17,\n 'was': 7,\n 'went': 14,\n 'white': 8,\n 'whose': 5}\n\n\nThe results using this approach are slightly different than the previous ones, because the words are mapped to different integer ids but the corresponding values are the same:\n\n\n```python\nfor word in word_dict.keys():\n if text_vector[word_dict[word]] != text_vector2[word_dict2[word]]:\n print(\"Error!\")\n```\n\nAs expected, there are no differences!\n\n## Term Frequency\n\nThe bag of words vector representation introduced above relies simply on the frequency of occurence of each word. Following a long tradition of giving fancy names to simple ideas, this is known as __Term Frequency__.\n\nIntuitively, we expect the the frequency with which a given word is mentioned should correspond to the relevance of that word for the piece of text we are considering. For example, **Mary** is a pretty important word in our little nursery rhyme and indeed it is the one that occurs the most often:\n\n\n```python\nsorted(items, key=lambda x:x[1], reverse=True)\n```\n\n\n\n\n [('mary', 6),\n ('lamb', 5),\n ('little', 4),\n ('went', 4),\n ('had', 2),\n ('a', 2),\n ('was', 2),\n ('everywhere', 2),\n ('that', 2),\n ('whose', 1),\n ('fleece', 1),\n ('white', 1),\n ('as', 1),\n ('snow', 1),\n ('and', 1),\n ('the', 1),\n ('sure', 1),\n ('to', 1),\n ('go', 1)]\n\n\n\nHowever, it's hard to draw conclusions from such a small piece of text. Let us consider a significantly larger piece of text, the first 100 MB of the english Wikipedia from: http://mattmahoney.net/dc/textdata. For the sake of convenience, text8.gz has been included in this repository in the **data/** directory. We start by loading it's contents into memory as an array of words:\n\n\n```python\ndata = []\n\nfor line in gzip.open(\"data/text8.gz\", 'rt'):\n data.extend(line.strip().split())\n```\n\nNow let's take a look at the most common words in this large corpus:\n\n\n```python\ncounts = Counter(data)\n\nsorted_counts = sorted(list(counts.items()), key=lambda x:x[1], reverse=True)\n\nfor word, count in sorted_counts[:10]:\n print(word, count)\n```\n\n the 1061396\n of 593677\n and 416629\n one 411764\n in 372201\n a 325873\n to 316376\n zero 264975\n nine 250430\n two 192644\n\n\nSurprisingly, we find that the most common words are not particularly meaningful. Indeed, this is a common occurence in Natural Language Processing. The most frequent words are typically auxiliaries required due to gramatical rules.\n\nOn the other hand, there is also a large number of words that occur very infrequently as can be easily seen by glancing at the word freqency distribution.\n\n\n```python\ndist = Counter(counts.values())\ndist = list(dist.items())\ndist.sort(key=lambda x:x[0])\ndist = np.array(dist)\n\nnorm = np.dot(dist.T[0], dist.T[1])\n\nplt.loglog(dist.T[0], dist.T[1]/norm)\nplt.xlabel(\"count\")\nplt.ylabel(\"P(count)\")\nplt.title(\"Word frequency distribution\")\n```\n\n## Stopwords\n\nOne common technique to simplify NLP tasks is to remove what are known as Stopwords, words that are very frequent but not meaningful. If we simply remove the most common 100 words, we significantly reduce the amount of data we have to consider while losing little information.\n\n\n```python\nstopwords = set([word for word, count in sorted_counts[:100]])\n\nclean_data = []\n\nfor word in data:\n if word not in stopwords:\n clean_data.append(word)\n\nprint(\"Original size:\", len(data))\nprint(\"Clean size:\", len(clean_data))\nprint(\"Reduction:\", 1-len(clean_data)/len(data))\n```\n\n Original size: 17005207\n Clean size: 9006229\n Reduction: 0.470384041782026\n\n\nWow, our dataset size was reduced almost in half!\n\nIn practice, we don't simply remove the most common words in our corpus but rather a manually curate list of stopwords. Lists for dozens of languages and applications can easily be found online.\n\n## Term Frequency/Inverse Document Frequency\n\nOne way of determining of the relative importance of a word is to see how often it appears across multiple documents. Words that are relevant to a specific topic are more likely to appear in documents about that topic and much less in documents about other topics. On the other hand, less meaningful words (like **the**) will be common across documents about any subject.\n\nTo measure the document frequency of a word we will need to have multiple documents. For the sake of simplicity, we will treat each sentence of our nursery rhyme as an individual document:\n\n\n```python\ncorpus_text = text.split('.')\ncorpus_words = []\n\nfor document in corpus_text:\n doc_words = extract_words(document)\n corpus_words.append(doc_words)\n```\n\nNow our corpus is represented as a list of word lists, where each list is just the word representation of the corresponding sentence:\n\n\n```python\npprint(corpus_words)\n```\n\n [['mary', 'had', 'a', 'little', 'lamb', 'little', 'lamb', 'little', 'lamb'],\n ['mary',\n 'had',\n 'a',\n 'little',\n 'lamb',\n 'whose',\n 'fleece',\n 'was',\n 'white',\n 'as',\n 'snow'],\n ['and', 'everywhere', 'that', 'mary', 'went', 'mary', 'went', 'mary', 'went'],\n ['everywhere',\n 'that',\n 'mary',\n 'went',\n 'the',\n 'lamb',\n 'was',\n 'sure',\n 'to',\n 'go']]\n\n\nLet us now calculate the number of documents in which each word appears:\n\n\n```python\ndocument_count = {}\n\nfor document in corpus_words:\n word_set = set(document)\n \n for word in word_set:\n document_count[word] = document_count.get(word, 0) + 1\n\npprint(document_count)\n```\n\n {'a': 2,\n 'and': 1,\n 'as': 1,\n 'everywhere': 2,\n 'fleece': 1,\n 'go': 1,\n 'had': 2,\n 'lamb': 3,\n 'little': 2,\n 'mary': 4,\n 'snow': 1,\n 'sure': 1,\n 'that': 2,\n 'the': 1,\n 'to': 1,\n 'was': 2,\n 'went': 2,\n 'white': 1,\n 'whose': 1}\n\n\nAs we can see, the word __Mary__ appears in all 4 of our documents, making it useless when it comes to distinguish between the different sentences. On the other hand, words like __white__ which appear in only one document are very discriminative. Using this approach we can define a new quantity, the ___Inverse Document Frequency__ that tells us how frequent a word is across the documents in a specific corpus:\n\n\n```python\ndef inv_doc_freq(corpus_words):\n number_docs = len(corpus_words)\n \n document_count = {}\n\n for document in corpus_words:\n word_set = set(document)\n\n for word in word_set:\n document_count[word] = document_count.get(word, 0) + 1\n \n IDF = {}\n \n for word in document_count:\n IDF[word] = np.log(number_docs/document_count[word])\n \n \n return IDF\n```\n\nWhere we followed the convention of using the logarithm of the inverse document frequency. This has the numerical advantage of avoiding to have to handle small fractional numbers. \n\nWe can easily see that the IDF gives a smaller weight to the most common words and a higher weight to the less frequent:\n\n\n```python\nIDF = inv_doc_freq(corpus_words)\n\npprint(IDF)\n```\n\n {'a': 0.6931471805599453,\n 'and': 1.3862943611198906,\n 'as': 1.3862943611198906,\n 'everywhere': 0.6931471805599453,\n 'fleece': 1.3862943611198906,\n 'go': 1.3862943611198906,\n 'had': 0.6931471805599453,\n 'lamb': 0.28768207245178085,\n 'little': 0.6931471805599453,\n 'mary': 0.0,\n 'snow': 1.3862943611198906,\n 'sure': 1.3862943611198906,\n 'that': 0.6931471805599453,\n 'the': 1.3862943611198906,\n 'to': 1.3862943611198906,\n 'was': 0.6931471805599453,\n 'went': 0.6931471805599453,\n 'white': 1.3862943611198906,\n 'whose': 1.3862943611198906}\n\n\nAs expected **Mary** has the smallest weight of all words 0, meaning that it is effectively removed from the dataset. You can consider this as a way of implicitly identify and remove stopwords. In case you do want to keep even the words that appear in every document, you can just add a 1. to the argument of the logarithm above:\n\n\\begin{equation}\n\\log\\left[1+\\frac{N_d}{N_d\\left(w\\right)}\\right]\n\\end{equation}\n\nWhen we multiply the term frequency of each word by it's inverse document frequency, we have a good way of quantifying how relevant a word is to understand the meaning of a specific document.\n\n\n```python\ndef tf_idf(corpus_words):\n IDF = inv_doc_freq(corpus_words)\n \n TFIDF = []\n \n for document in corpus_words:\n TFIDF.append(Counter(document))\n \n for document in TFIDF:\n for word in document:\n document[word] = document[word]*IDF[word]\n \n return TFIDF\n```\n\n\n```python\ntf_idf(corpus_words)\n```\n\n\n\n\n [Counter({'mary': 0.0,\n 'had': 0.6931471805599453,\n 'a': 0.6931471805599453,\n 'little': 2.0794415416798357,\n 'lamb': 0.8630462173553426}),\n Counter({'mary': 0.0,\n 'had': 0.6931471805599453,\n 'a': 0.6931471805599453,\n 'little': 0.6931471805599453,\n 'lamb': 0.28768207245178085,\n 'whose': 1.3862943611198906,\n 'fleece': 1.3862943611198906,\n 'was': 0.6931471805599453,\n 'white': 1.3862943611198906,\n 'as': 1.3862943611198906,\n 'snow': 1.3862943611198906}),\n Counter({'and': 1.3862943611198906,\n 'everywhere': 0.6931471805599453,\n 'that': 0.6931471805599453,\n 'mary': 0.0,\n 'went': 2.0794415416798357}),\n Counter({'everywhere': 0.6931471805599453,\n 'that': 0.6931471805599453,\n 'mary': 0.0,\n 'went': 0.6931471805599453,\n 'the': 1.3862943611198906,\n 'lamb': 0.28768207245178085,\n 'was': 0.6931471805599453,\n 'sure': 1.3862943611198906,\n 'to': 1.3862943611198906,\n 'go': 1.3862943611198906})]\n\n\n\nNow we finally have a vector representation of each of our documents that takes the informational contributions of each word into account. Each of these vectors provides us with a unique representation of each document, in the context (corpus) in which it occurs, making it posssible to define the similarity of two documents, etc.\n\n## Porter Stemmer\n\nThere is still, however, one issue with our approach to representing text. Since we treat each word as a unique token and completely independently from all others, for large documents we will end up with many variations of the same word such as verb conjugations, the corresponding adverbs and nouns, etc. \n\nOne way around this difficulty is to use stemming algorithm to reduce words to their root (or stem) version. The most famous Stemming algorithm is known as the **Porter Stemmer** and was introduced by Martin Porter in 1980 [Program 14, 130 (1980)](https://dl.acm.org/citation.cfm?id=275705)\n\nThe algorithm starts by defining consonants (C) and vowels (V):\n\n\n```python\nV = set('aeiouy')\nC = set('bcdfghjklmnpqrstvwxz')\n```\n\nThe stem of a word is what is left of that word after a speficic ending has been removed. A function to do this is easy to implement:\n\n\n```python\ndef get_stem(suffix, word):\n \"\"\"\n Extract the stem of a word\n \"\"\"\n \n if word.lower().endswith(suffix.lower()): # Case insensitive comparison\n return word[:-len(suffix)]\n\n return None\n```\n\nIt also defines words (or stems) to be sequences of vowels and consonants of the form:\n\n\\begin{equation}\n[C](VC)^m[V]\n\\end{equation}\n\nwhere $m$ is called the **measure** of the word and [] represent optional sections. \n\n\n```python\ndef measure(orig_word):\n \"\"\"\n Calculate the \"measure\" m of a word or stem, according to the Porter Stemmer algorthim\n \"\"\"\n \n word = orig_word.lower()\n\n optV = False\n optC = False\n VC = False\n m = 0\n\n pos = 0\n\n # We can think of this implementation as a simple finite state machine\n # looks for sequences of vowels or consonants depending of the state\n # in which it's in, while keeping track of how many VC sequences it\n # has encountered.\n # The presence of the optional V and C portions is recorded in the\n # optV and optC booleans.\n \n # We're at the initial state.\n # gobble up all the optional consonants at the beginning of the word\n while pos < len(word) and word[pos] in C:\n pos += 1\n optC = True\n\n while pos < len(word):\n # Now we know that the next state must be a vowel\n while pos < len(word) and word[pos] in V:\n pos += 1\n optV = True\n\n # Followd by a consonant\n while pos < len(word) and word[pos] in C:\n pos += 1\n optV = False\n \n # If a consonant was found, then we matched VC\n # so we should increment m by one. Otherwise, \n # optV remained true and we simply had a dangling\n # V sequence.\n if not optV:\n m += 1\n\n return m\n```\n\nLet's consider a simple example. The word __crepusculars__ should have measure 4:\n\n[cr] (ep) (usc) (ul) (ars)\n\nand indeed it does.\n\n\n```python\nword = \"crepusculars\"\nprint(measure(word))\n```\n\n 4\n\n\nThe Porter algorithm sequentially applies a series of transformation rules over a series of 5 steps (step 1 is divided in 3 substeps and step 5 in 2). The rules are only applied if a certain condition is true. \n\nIn addition to possibily specifying a requirement on the measure of a word, conditions can make use of different boolean functions as well: \n\n\n```python\ndef ends_with(char, stem):\n \"\"\"\n Checks the ending of the word\n \"\"\"\n return stem[-1] == char\n\ndef double_consonant(stem):\n \"\"\"\n Checks the ending of a word for a double consonant\n \"\"\"\n if len(stem) < 2:\n return False\n\n if stem[-1] in C and stem[-2] == stem[-1]:\n return True\n\n return False\n\ndef contains_vowel(stem):\n \"\"\"\n Checks if a word contains a vowel or not\n \"\"\"\n return len(set(stem) & V) > 0 \n```\n\nFinally, we define a function to apply a specific rule to a word or stem:\n\n\n```python\ndef apply_rule(condition, suffix, replacement, word):\n \"\"\"\n Apply Porter Stemmer rule.\n if \"condition\" is True replace \"suffix\" by \"replacement\" in \"word\"\n \"\"\"\n \n stem = get_stem(suffix, word)\n\n if stem is not None and condition is True:\n # Remove the suffix\n word = stem\n\n # Add the replacement suffix, if any\n if replacement is not None:\n word += replacement\n\n return word\n```\n\nNow we can see how rules can be applied. For example, this rule, from step 1b is successfully applied to __pastered__:\n\n\n```python\nword = \"plastered\"\nsuffix = \"ed\"\nstem = get_stem(suffix, word)\napply_rule(contains_vowel(stem), suffix, None, word)\n```\n\n\n\n\n 'plaster'\n\n\n\nWhile try applying the same rule to **bled** will fail to pass the condition resulting in no change.\n\n\n```python\nword = \"bled\"\nsuffix = \"ed\"\nstem = get_stem(suffix, word)\napply_rule(contains_vowel(stem), suffix, None, word)\n```\n\n\n\n\n 'bled'\n\n\n\nFor a more complex example, we have, in Step 4:\n\n\n```python\nword = \"adoption\"\nsuffix = \"ion\"\nstem = get_stem(suffix, word)\napply_rule(measure(stem) > 1 and (ends_with(\"s\", stem) or ends_with(\"t\", stem)), suffix, None, word)\n```\n\n\n\n\n 'adopt'\n\n\n\nIn total, the Porter Stemmer algorithm (for the English language) applies several dozen rules (see https://tartarus.org/martin/PorterStemmer/def.txt for a complete list). Implementing all of them is both tedious and error prone, so we abstain from providing a full implementation of the algorithm here. High quality implementations can be found in all major NLP libraries such as [NLTK](http://www.nltk.org/howto/stem.html).\n\nThe dificulties of defining matching rules to arbitrary text cannot be fully resolved without the use of Regular Expressions (typically implemented as Finite State Machines like our __measure__ implementation above), a more advanced topic that is beyond the scope of this course.\n", "meta": {"hexsha": "dd7db4ffe060a8630ed22b0bd836009752c84ebd", "size": 68974, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NLP_1.ipynb", "max_stars_repo_name": "gustavocac/FromScratch", "max_stars_repo_head_hexsha": "999f728759cbcf5362168cac2d2beeecafdf2791", "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": "NLP_1.ipynb", "max_issues_repo_name": "gustavocac/FromScratch", "max_issues_repo_head_hexsha": "999f728759cbcf5362168cac2d2beeecafdf2791", "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": "NLP_1.ipynb", "max_forks_repo_name": "gustavocac/FromScratch", "max_forks_repo_head_hexsha": "999f728759cbcf5362168cac2d2beeecafdf2791", "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": 38.8804960541, "max_line_length": 15334, "alphanum_fraction": 0.5707223012, "converted": true, "num_tokens": 6518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.13846178523628042, "lm_q1q2_score": 0.06598806929356016}} {"text": "# The Jupyter Notebook \n\nIt is a **```web application```** that allows you to create and share documents that contain \n- live code\n- equations\n- visualizations\n- explanatory text\n\n\n\n

    Table of Contents

    \n\n\n\n```python\n# my first python script\nprint(\"hello world! \\n I am Cheng-Jun Wang.\")\n```\n\n hello world! \n I am Cheng-Jun Wang.\n\n\nUses include: \n- data cleaning and transformation, \n- numerical simulation, \n- statistical modeling, \n- machine learning \n- and much more.\n\n\n\n```python\nprint('hello world')\n```\n\n hello world\n\n\n\n```python\n1 + 1\n```\n\n\n\n\n 2\n\n\n\n$E = MC^2$\n\n\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align}\n\n# 搜狗输入法表情和符号\n\n- ∫ ∑ ※ ➕➖✖️➗ ❎ √ ×\n- 😪😠😡😎☺️😁📚🌲\n- 👌👍👎👂👃👀✋❌💰🌂\n- 0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣②🔟 \n- 🐶🐱🐔🐷🐖🐴🐎🐂🐑🐯🐧🐺🐒🐵🐻🐦🐲\n- 💻 🌈🌎☁️❄️🏃♀👩👱✨\n- 🆚🔥🌹✈️🌉🎄\n\n(✿◡‿◡)害羞 ⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄ d=====( ̄▽ ̄*)b厉害 \n\n我是我,不一样花火。~( ̄▽ ̄~)(~ ̄▽ ̄)~ 矜持 \n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nxi = [1, 2, 3, 4, 5]\ny = [3, 5, 9, 13, 16]\n\nplt.plot(xi, y, 'g-s')\nplt.xlabel('$x_i$', fontsize = 20)\nplt.ylabel('$y$', fontsize = 20)\nplt.title('$Scatter\\,Plot$', fontsize = 20)\nplt.show()\n```\n\n# 一级标题\n## 二级标题\n[复旦大学](http://www.fdu.edu.cn)是一个*非常棒*的大学!\n\n1. point 1\n1. point 2\n1. point 3\n\n# 运行C代码\n\nC functions are typically split into header files (.h) where things are declared but not defined, and implementation files (.c) where they are defined. http://people.duke.edu/~ccc14/sta-663/CrashCourseInC.html#a-tutorial-example-coding-a-fibonacci-function-in-c\n\n\n```python\n%%file hello.c\n#include \n\nint main() {\n printf(\"Hello, world!\");\n}\n```\n\n Overwriting hello.c\n\n\n\n```python\n! gcc hello.c -o hello # 编译\n```\n\n xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun\r\n\n\n\n```python\n! ./hello # 执行\n```\n\n Hello, world!\n\n# Jupyter 魔术命令 \n\n\n```python\n%lsmagic \n```\n\n\n\n\n Available line magics:\n %alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode\n \n Available cell magics:\n %%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile\n \n Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n> pip install version_information\n\n\n```python\n!pip install version_information\n```\n\n Requirement already satisfied: version_information in /Users/datalab/Applications/anaconda/lib/python3.5/site-packages (1.0.3)\n \u001b[33mYou are using pip version 19.0.3, however version 19.1.1 is available.\n You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\n# install version_information in the terminal first.\n%reload_ext version_information\n%version_information numpy, matplotlib, pandas, scipy, statsmodels\n```\n\n\n\n\n
    SoftwareVersion
    Python3.5.4 64bit [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]
    IPython6.2.1
    OSDarwin 18.6.0 x86_64 i386 64bit
    numpy1.16.3
    matplotlib3.0.1
    pandas0.23.4
    scipy1.1.0
    statsmodels0.9.0
    Fri Jun 07 14:29:42 2019 CST
    \n\n\n\n# END\n\nThis is the end.\n\n\n```python\n\n```\n", "meta": {"hexsha": "975ecc6596347fbc40b364675ae545b34335b776", "size": 32583, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/01.jupyter_notebook.ipynb", "max_stars_repo_name": "computational-class/cjc", "max_stars_repo_head_hexsha": "1569ce7a7a85571bd2e399ab20fb950d7f8963b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65, "max_stars_repo_stars_event_min_datetime": "2017-04-06T01:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T15:30:30.000Z", "max_issues_repo_path": "code/01.jupyter_notebook.ipynb", "max_issues_repo_name": "AnxietyVendor/cjc", "max_issues_repo_head_hexsha": "4bfd22ea4f360a803093a95bd9b1a2d497b7200a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2017-05-12T10:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-17T13:13:22.000Z", "max_forks_repo_path": "code/01.jupyter_notebook.ipynb", "max_forks_repo_name": "AnxietyVendor/cjc", "max_forks_repo_head_hexsha": "4bfd22ea4f360a803093a95bd9b1a2d497b7200a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48, "max_forks_repo_forks_event_min_datetime": "2017-03-22T02:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-16T03:08:47.000Z", "avg_line_length": 44.210312076, "max_line_length": 13464, "alphanum_fraction": 0.6948101771, "converted": true, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.18713267762907493, "lm_q1q2_score": 0.06590845999551023}} {"text": "|

    Name

    |

    Date

    |\n| ---------------------------------------------------| ------------------------------------- |\n|

    Diaaeldin SHALABY

    | 18.06.2021 |\n\n

    Hands-on AI II

    \n

    Unit 7 — Introduction to Reinforcement Learning (Assignment)

    \n\nAuthors: B. Schäfl, S. Lehner, J. Brandstetter
    \nDate: 11-06-2021\n\nThis file is part of the \"Hands-on AI II\" lecture material. The following copyright statement applies to all code within this file.\n\nCopyright statement:
    \nThis material, no matter whether in printed or electronic form, may be used for personal and non-commercial educational use only. Any reproduction of this manuscript, no matter whether as a whole or in parts, no matter whether in printed or in electronic form, requires explicit prior acceptance of the authors.\n\n

    Table of contents

    \n
      \n
    1. Dissection of an Environment
    2. \n
        \n
      1. States and actions
      2. \n
      \n
    3. Tackling the Environment with Random Exploration
    4. \n
        \n
      1. Implementing random search
      2. \n
      3. The problem with random search
      4. \n
      \n
    5. Tackling the Environment with $Q$-Learning
    6. \n
        \n
      1. First approach of learning a $Q$-table
      2. \n
      3. The problem with missing exploration
      4. \n
      5. Evaluate the agent's performance
      6. \n
      7. The role of randomness in the environment
      8. \n
      \n
    \n\n

    How to use this notebook

    \nThis notebook is designed to run from start to finish. There are different tasks (displayed in orange boxes) which require your contribution (in form of code, plain text, ...). Most/All of the supplied functions are imported from the file u7_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\n

    Setting up notebook ... finished.

    \n\n\n\n\n

    Module versions

    \nAs mentioned in the introductory slides, specific minimum versions of Python itself as well as of used modules is recommended.\n\n\n```python\nu7.check_module_versions()\n```\n\n Installed Python version: 3.8 (✓)\n Installed numpy version: 1.19.1 (✓)\n Installed pandas version: 1.1.3 (✓)\n Installed PyTorch version: 1.7.1 (✓)\n Installed scikit-learn version: 0.23.2 (✓)\n Installed scipy version: 1.5.0 (✓)\n Installed matplotlib version: 3.3.1 (✓)\n Installed seaborn version: 0.11.0 (✓)\n Installed PIL version: 8.0.0 (✓)\n Installed rdkit version: 2020.09.1 (✓)\n Installed gym version: 0.18.3 (✓)\n\n\n

    Dissection of an Environment

    \n

    All 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

    \n Winter is here. You and your friends were tossing around a frisbee at the park when you made a wild throw that left the frisbee out in the middle of the lake. The water is mostly frozen, but there are a few holes where the ice has melted. If you step into one of those holes, you'll fall into the freezing water. At this time, there's an international frisbee shortage, so it's absolutely imperative that you navigate across the lake and retrieve the disc. However, the ice is slippery, so you won't always move in the direction you intend.\n

    \n\n\n

    There are four types of surfaces described in this environment:\n

      \n
    • S $\\rightarrow$ starting point (safe)
    • \n
    • F $\\rightarrow$ frozen surface (safe)
    • \n
    • H $\\rightarrow$ hole (fall to your doom)
    • \n
    • G $\\rightarrow$ goal (frisbee location)
    • \n
    \n\n\nIf not already done, more information on how to install and import the gym module is available in the lecture's notebook.

    \n\n
    \n Execute the notebook until here and try to solve the following tasks:\n
      \n
    • Create a new instance of FrozenLakeEnv with the seed set to 42 and render the current state in a human-readable way.
    • \n
    • Gather and print the amount of different actions as well as states of the FrozenLakeEnv instance. Discuss the results.
    • \n
    • Display the reward table entry for the current state. Discuss the different elements of the resulting dictionary.
    • \n
    \n
    \n\n\n```python\nenviroment_lake = u7.FrozenLakeEnv()\nu7.set_environment_seed(environment=enviroment_lake, seed=42)\n```\n\n\n```python\nenviroment_lake.render(mode=r'human')\ncurrent_state_id = enviroment_lake.s\nprint(f'Current state ID: {current_state_id}')\n```\n\n \n \u001b[41mS\u001b[0mFFF\n FHFH\n FFFH\n HFFG\n Current state ID: 0\n\n\n

    The 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\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    StepDescription
    0Choose a random action with respect to the current state.
    1Execute previously chosen action and transition into a new state.
    2Repeat the previous steps as long as the current episode is still ongoing.
    \n\nFor such an approach to be at least remotely applicable, the number of possible actions and states is of utter importance. Otherwise, we are lost in the depth of combinatorial explosion. The property 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\n

    Each entry of the reward table contains a dictionary of the form s: {a: [] for a in range(nA)} for s in range(nS).\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    ElementDescription
    nS=nrows*ncolsThe number of possible moves.
    nA=4Number of surfaces. [S,F,H,G]
    aPotential state based on the surface of the next move.

    \n\n

    Tackling the Environment with Random Exploration

    \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

      \n
    • I $\\rightarrow$ choose a random action with respect to the current state.
    • \n
    • II $\\rightarrow$ execute previously chosen action and transition into a new state.
    • \n
    • III $\\rightarrow$ if the episode is finished, but the goal not reached, reset the position of the disc retrieving entity.
    • \n
    \n\nThis procedure is repeated as long as the task is not solved or a defined maximum of steps is reached, whatever triggers first (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\n
    \n Execute the notebook until here and try to solve the following tasks:\n
      \n
    • Implement the random search algorithm as outlined above (equivalently to the one discussed during the exercise).
    • \n
    • Apply your random search implementation on a freshly seeded FrozenLakeEnv instance, with an animation delay of $0.1$.
    • \n
    • How many steps are necessary to reach the goal at least once and how often did an involuntary dive happen?
    • \n
    \n
    \n\n\n```python\ndef apply_random_search(environment: u7.FrozenLakeEnv, animate: bool = False,\n delay: float = 0.01, max_steps: int = 1000) -> Tuple[int, int, Dict[str, Any]]:\n \"\"\"\n Solve specified environment by applying random search.\n \n :param environment: the environment on which to apply random search\n :param animate: animate the random search process\n :param delay: the minimum delay in milliseconds between each rendered frame (ignored if not animated)\n :param max_steps: maximum amount of steps to perform\n :return: amount of steps performed, involuntary dives and captured frames\n \"\"\"\n num_steps, num_penalties, final_reward, captured_frames = 0, 0, 0, []\n\n # : repeat random search procedure as long as the episode is still ongoing.\n \n u7.set_environment_seed(environment=enviroment_lake, seed=42)\n \n done = False\n while not done:\n if num_steps == max_steps:\n break\n\n # : choose a random action with respect to the current state.\n current_action = environment.action_space.sample()\n\n # : execute previously chosen action and transition into a new state.\n current_state, current_reward, done, info = environment.step(current_action)\n\n # Update counter for inflicted penalties.\n final_reward += current_reward\n if current_reward <= 0:\n num_penalties += 1\n num_steps += 1\n \n\n # Save rendering of current state.\n captured_frames.append({\n r'frame': environment.render(mode=r'ansi'),\n r'state': current_state,\n r'action': current_action,\n r'reward': current_reward\n })\n \n # Optionally display current state.\n if animate:\n display.clear_output(wait=True)\n print(captured_frames[-1][r'frame'])\n print(f'Step No.: {num_steps}'\n f'\\nState ID: {current_state}'\n f'\\nAction ID: {current_action}'\n f'\\nReward: {current_reward}')\n time.sleep(delay)\n \n if not done and current_reward == 0:\n enviroment_lake.reset()\n \n return num_steps, num_penalties, final_reward, captured_frames\n```\n\n\n```python\nu7.set_environment_seed(environment=enviroment_lake, seed=42)\nnum_steps, num_penalties, final_reward, _ = apply_random_search(\n environment=enviroment_lake,\n animate=True,\n delay=0.1\n)\n```\n\n (Right)\n S\u001b[41mF\u001b[0mFF\n FHFH\n FFFH\n HFFG\n \n Step No.: 1000\n State ID: 1\n Action ID: 2\n Reward: 0.0\n\n\nUnfortunatly the function did not find a solution.\n\n

    To 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

      \n
    • Repeat the previous random search procedure a specified amount of times.
    • \n
    • Aggregate the results of each run for later analysis.
    • \n
    • Visualise the aggegrated results using box- and swarm-plots.
    • \n
    \nOnce again, we are setting the random seed, but take care of setting it outside the loop, otherwise the same result is reported with each iteration (and an aggregation of the results would not give us any more insights).

    \n\n
    \n Execute the notebook until here and try to solve the following tasks:\n
      \n
    • Conduct a random search experiment as outlined above, using $100$ repetitions and the random seed set to $42$.
    • \n
    • Interpret the visualization (e.g. the span of the boxes) and keep the scaling of the x-axis in mind.
    • \n
    • In comparison with the Taxi-v3 environment, what might be the problem with FrozenLakeEnv w.r.t. random exploration?
    • \n
    \n
    \n\n\n```python\nu7.set_environment_seed(environment=enviroment_lake, seed=42)\nnum_steps_total, num_penalties_total, final_reward_total = [], [], []\nnum_repetitions = 100\n\n# Collect information over multiple repetitions.\nfor repetition in range(num_repetitions):\n enviroment_lake.reset()\n num_steps, num_penalties, final_reward, _ = apply_random_search(environment=enviroment_lake)\n num_steps_total.append(num_steps)\n num_penalties_total.append(num_penalties)\n final_reward_total.append(final_reward)\n\n# Combine collected information to a data frame for further downstream analysis.\ncollected_experiment_info = pd.DataFrame(zip(\n num_steps_total, num_penalties_total, final_reward_total\n), columns=(r'Steps performed', r'Penalties inflicted', r'Final reward'))\n```\n\n\n```python\n# Set default plotting style.\nsns.set()\n\n# Visualize aggregated results of the random search procedure.\nfig, ax = plt.subplots(nrows=1, ncols=1, squeeze=False, figsize=(20, 7))\nax[0, 0].set_xscale(r'symlog')\n_ = sns.boxplot(data=collected_experiment_info, ax=ax[0, 0], orient=r'h')\n_ = sns.swarmplot(data=collected_experiment_info, ax=ax[0, 0], color=r'0.3', orient=r'h')\n```\n\n

    Tackling the Environment with $Q$-Learning

    \n

    In a simplified version of $Q$-learning, the $\\boldsymbol{Q}$-value\n\\begin{equation}\n Q(s,a)\n\\end{equation}

    \n\n

    is 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\n

    We 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\n

    The $\\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\n

    Previously, 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

      \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.\n
    \n\nThis procedure is repeated for as many episodes as specified (VI).

    \n\n
    \n Execute the notebook until here and try to solve the following tasks:\n
      \n
    • Implement $Q$-learning as outlined above (equivalently to the one discussed during the exercise).
    • \n
    • Apply $Q$-learning on a freshly seeded FrozenLakeEnv instance for $10^4$ episodes, with $10^3$ delay steps and $\\alpha{}=0.1$.
    • \n
    • Interpret the visualization of the resulting $Q$-table. What do you observe?
    • \n
    \n
    \n\n
    \n The following code snippet is taken from the accompanying exercise notebook. You do not need to modify it for this assignment.\n
    \n\n\n```python\ndef visualize_q_table(q_table: np.ndarray, title: str = r'') -> None:\n \"\"\"\n Visualize Q-table using a heatmap plot.\n \n :param q_table: Q-table to visualize\n :return: None\n \"\"\"\n sns.set()\n fig, ax = plt.subplots(nrows=1, ncols=1, squeeze=False, figsize=(20, 7))\n _ = sns.heatmap(data=q_table, ax=ax[0, 0])\n _ = ax[0, 0].set(xlabel=r'Action', ylabel=r'State', title=title)\n display.clear_output(wait=True)\n display.display(fig)\n plt.close(fig=fig)\n\n\ndef apply_q_learning(environment: u7.FrozenLakeEnv, num_episodes: int = 1000, alpha: float = 0.1,\n animate: bool = False, delay_steps: int = 100) -> np.ndarray:\n \"\"\"\n Solve specified environment by applying Q-learning.\n \n :param environment: the environment on which to apply Q-learning\n :param num_episodes: the total amount of episodes used to adapt the Q-table\n :param alpha: the learning rate to be applied by Q-learning\n :param animate: animate the Q-learning process\n :param delay_steps: the steps between each Q-table visualization (ignored if not animated)\n \"\"\"\n q_table = np.zeros(shape=(environment.observation_space.n, environment.action_space.n))\n \n # : repeat Q-learning as long as the total amount of episodes is not yet reached.\n for episode in range(num_episodes):\n state = environment.reset()\n \n done = False\n while not done:\n \n # : choose next action according to current Q-table.\n action = np.argmax(q_table[state]) \n \n # : go from the current state to the next by applying chosen action.\n next_state, reward, done, info = environment.step(action)\n \n # : from all possible Q-values w.r.t. the new state, select the highest.\n next_max = np.max(q_table[next_state])\n \n # : update the Q-table accordingly.\n old_value = q_table[state, action]\n new_value = (1 - alpha) * old_value + alpha * (reward + next_max)\n q_table[state, action] = new_value\n\n # : update the next step with the current one.\n state = next_state\n \n # Optionally visualize the current Q-table.\n if animate and any(((episode + 1) % delay_steps == 0, (episode + 1) == num_episodes)):\n visualize_q_table(q_table=q_table, title=f'Episode {episode + 1}')\n \n return q_table\n```\n\n\n```python\nu7.set_environment_seed(environment=enviroment_lake, seed=42)\nq_table = apply_q_learning(\n environment=enviroment_lake,\n num_episodes=10000,\n alpha=0.1,\n animate=True,\n delay_steps=1000\n)\n```\n\nI obsere that it's all the same color which indicates that it's the same level.\n\n

    Very 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

      \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

    \n\n
    \n Execute the notebook until here and try to solve the following tasks:\n
      \n
    • Modify the $Q$-learning implementation from the previous tasks as outlined above (mark the corresponding code sections).
    • \n
    • Apply $Q$-learning on a freshly seeded FrozenLakeEnv instance for $10^4$ episodes, with $10^3$ delay steps and $\\alpha{}=0.1$.
    • \n
    • Interpret the visualization of the resulting $Q$-table. What do you observe (compare with the previous visualization)?
    • \n
    \n
    \n\n\n```python\ndef apply_q_learning(environment: u7.FrozenLakeEnv, num_episodes: int = 1000, alpha: float = 0.1,\n animate: bool = False, delay_steps: int = 100, threshold: float = 0.125) -> np.ndarray:\n \"\"\"\n Solve specified environment by applying Q-learning.\n \n :param environment: the environment on which to apply Q-learning\n :param num_episodes: the total amount of episodes used to adapt the Q-table\n :param alpha: the learning rate to be applied by Q-learning\n :param animate: animate the Q-learning process\n :param delay_steps: the steps between each Q-table visualization (ignored if not animated)\n :param threshold: threshold for randomly sampling next action\n :return: adapted Q-table\n \"\"\"\n import random\n \n q_table = np.zeros(shape=(environment.observation_space.n, environment.action_space.n))\n \n # : repeat Q-learning as long as the total amount of episodes is not yet reached.\n for episode in range(num_episodes):\n state = environment.reset()\n \n done = False\n while not done:\n rnd_num = random.uniform(0, 1)\n action = np.argmax(q_table[state]) \n \n if rnd_num < 0.1:\n action = environment.action_space.sample()\n else: \n action = np.argmax(q_table[state])\n\n # : go from the current state to the next by applying chosen action.\n next_state, reward, done, info = environment.step(action)\n\n \n # : from all possible Q-values w.r.t. the new state, select the highest.\n next_max = np.max(q_table[next_state])\n \n # : update the Q-table accordingly.\n old_value = q_table[state, action]\n new_value = (1 - alpha) * old_value + alpha * (reward + next_max)\n q_table[state, action] = new_value\n\n # : update the next step with the current one.\n state = next_state\n \n # Optionally visualize the current Q-table.\n if animate and any(((episode + 1) % delay_steps == 0, (episode + 1) == num_episodes)):\n visualize_q_table(q_table=q_table, title=f'Episode {episode + 1}')\n \n return q_table\n```\n\n\n```python\nu7.set_environment_seed(environment=enviroment_lake, seed=42)\nq_table = apply_q_learning(\n environment=enviroment_lake,\n num_episodes=10000,\n alpha=0.1,\n animate=True,\n delay_steps=1000\n)\n\n```\n\n
    \n Execute the notebook until here and try to solve the following tasks:\n
      \n
    • Implement a function for applying a pre-trained $Q$-table on a FrozenLakeEnv instance (like discussed during class).
    • \n
    • Conduct a $Q$-table guided search on a freshly seeded FrozenLakeEnv instance, with an animation delay of $0.1$.
    • \n
    • How many steps are necessary to reach the goal at least once and how often did an involuntary dive happen?
    • \n
    \n
    \n\n\n```python\ndef apply_q_table(environment: u7.FrozenLakeEnv, q_table: np.ndarray, animate: bool = False,\n delay: float = 0.01, max_steps: int = 1000) -> Tuple[int, int, Dict[str, Any]]:\n \"\"\"\n Solve specified environment by applying specified Q-table.\n \n :param environment: the environment on which to apply Q-table guided search\n :param q_table: the Q-table used during Q-table guided search\n :param animate: animate the Q-table guided search process\n :param delay: the minimum delay in milliseconds between each rendered frame (ignored if not animated)\n :param max_steps: maximum amount of steps to perform\n :return: amount of steps performed, involuntary dives and captured frames\n \"\"\"\n raise NotImplementedError(r'Exchange this error with your implementation.')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n
    \n Execute the notebook until here and try to solve the following tasks:\n
      \n
    • Conduct a $Q$-table guided search experiment as outlined previously, using $100$ repetitions and the random seed set to $42$.
    • \n
    • Interpret the visualization (e.g. the span of the boxes) and keep the scaling of the x-axis in mind.
    • \n
    • In comparison with the random search experiment, how does the $Q$-table guided search perform? Discuss the results.
    • \n
    \n
    \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9ce83cdd8bd042710819c955832afdb53c707454", "size": 107148, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Introduction to Reinforcement Learning.ipynb", "max_stars_repo_name": "diaa-shalaby/AI-microprojects", "max_stars_repo_head_hexsha": "536e72ddbf0bc329603d1428c1b6149afa4cadad", "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": "Introduction to Reinforcement Learning.ipynb", "max_issues_repo_name": "diaa-shalaby/AI-microprojects", "max_issues_repo_head_hexsha": "536e72ddbf0bc329603d1428c1b6149afa4cadad", "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": "Introduction to Reinforcement Learning.ipynb", "max_forks_repo_name": "diaa-shalaby/AI-microprojects", "max_forks_repo_head_hexsha": "536e72ddbf0bc329603d1428c1b6149afa4cadad", "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": 111.7288842544, "max_line_length": 24024, "alphanum_fraction": 0.8206126106, "converted": true, "num_tokens": 7563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27202453929068215, "lm_q2_score": 0.2422056341953392, "lm_q1q2_score": 0.06588587605559464}} {"text": "Probabilistic Programming and Bayesian Methods for Hackers \n========\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n#### Looking for a printed version of Bayesian Methods for Hackers?\n\n_Bayesian Methods for Hackers_ is now a published book by Addison-Wesley, available on [Amazon](http://www.amazon.com/Bayesian-Methods-Hackers-Probabilistic-Addison-Wesley/dp/0133902838)! \n\n\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assumes that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json, matplotlib\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials) / 2, 2, k + 1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials) - 1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$ pass. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2 * p / (1 + p), color=\"#348ABD\", lw=3)\n# plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2 * (0.2) / 1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Is my code bug-free?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1. / 3, 2. / 3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.ylim(0,1)\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n#### Expected Value\nExpected value (EV) is one of the most important concepts in probability. The EV for a given probability distribution can be described as \"the mean value in the long run for many repeated samples from that distribution.\" To borrow a metaphor from physics, a distribution's EV acts like its \"center of mass.\" Imagine repeating the same experiment many times over, and taking the average over each outcome. The more you repeat the experiment, the closer this average will become to the distributions EV. (side note: as the number of repeated experiments goes to infinity, the difference between the average outcome and the EV becomes arbitrarily small.)\n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots, \\; \\; \\lambda \\in \\mathbb{R}_{>0} $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1. / l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0, 1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```python\nimport pymc as pm\n\nalpha = 1.0 / count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = pm.Exponential(\"lambda_1\", alpha)\nlambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\ntau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```python\nprint(\"Random output:\", tau.random(), tau.random(), tau.random())\n```\n\n Random output: 64 5 12\n\n\n\n```python\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. Deterministic functions will be covered in Chapter 2. \n\n\n```python\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n# Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n [-----------------100%-----------------] 40000 of 40000 complete in 6.5 sec\n\n\n```python\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```python\nfigsize(12.5, 10)\n# histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data) - 20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n# type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n# type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n# type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "1f52b4f4e0bb074a841362e736059c91aa289416", "size": 544517, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_stars_repo_name": "markmorrison95/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "fb261006b30ec176f081761610bf93d3208ab8cf", "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": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_issues_repo_name": "markmorrison95/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "fb261006b30ec176f081761610bf93d3208ab8cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_forks_repo_name": "markmorrison95/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "fb261006b30ec176f081761610bf93d3208ab8cf", "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": 479.3283450704, "max_line_length": 191279, "alphanum_fraction": 0.8119140449, "converted": true, "num_tokens": 11683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776780354463427, "lm_q2_score": 0.22815649166448124, "lm_q1q2_score": 0.06565609247073742}} {"text": "```python\n# %load /Users/facai/Study/book_notes/preconfig.py\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\n#sns.set(font='SimHei')\nplt.rcParams['axes.grid'] = False\n\n#from IPython.display import SVG\ndef show_image(filename, figsize=None, res_dir=True):\n if figsize:\n plt.figure(figsize=figsize)\n\n if res_dir:\n filename = './res/{}'.format(filename)\n\n plt.imshow(plt.imread(filename))\n```\n\nChapter 7 Regularization for Deep Learning\n==========================================\n\nthe best fitting model is a large model that has been regularized appropriately.\n\n### 7.1 Parameter Norm Penalties\n\n\\begin{equation}\n \\tilde{J}(\\theta; X, y) = J(\\theta; X, y) + \\alpha \\Omega(\\theta)\n\\end{equation}\n\nwhere $\\Omega(\\theta)$ is a paramter norm penalty.\n\ntypically, penalizes **only the weights** of the affine transformation at each layer and leaves the biases unregularized.\n\n\n#### 7.1.1 $L^2$ Parameter Regularization\n\n\n#### 7.1.2 $L^1$ Regularization\n\nThe sparsity property induced by $L^1$ regularization => feature selection\n\n### 7.2 Norm Penalties as Constrained Optimization\n\nconstrain $\\Omega(\\theta)$ to be less than some constant $k$:\n\n\\begin{equation}\n \\mathcal{L}(\\theta, \\alpha; X, y) = J(\\theta; X, y) + \\alpha(\\Omega(\\theta) - k)\n\\end{equation}\n\nIn practice, column norm limitation is always implemented as an explicit constraint with reprojection.\n\n### 7.3 Regularization and Under-Constrained Problems\n\nregularized matrix is guarantedd to be invertible.\n\n\n### 7.4 Dataset Augmentation\n\ncreate fake data:\n\n+ transform\n+ inject noise\n\n\n### 7.5 Noise Robustness\n\n+ add noise to data\n+ add noise to weight (Bayesian: variable distributaion): \n is equivalent with an additional regularization term.\n+ add noise to output target: label smooothing\n\n\n### 7.6 Semi-Supervised Learning\n\nGoal: learn a representation so that example from the same class have similar representations.\n\n\n### 7.7 Multi-Task Learning\n\n1. Task-specific paramters\n2. Generic parameters\n\n\n```python\nshow_image(\"fig7_2.png\")\n```\n\n### 7.8 Early Stopping\n\nrun it until the ValidationSetError has not imporved for some amount of time.\n\nUse the parameters of the lowest ValidationSetError during the whole train.\n\n\n```python\nshow_image(\"fig7_3.png\", figsize=[10, 8])\n```\n\n### 7.9 Parameter Tying adn Parameter Sharing\n\n+ regularized the paramters of one model (supervised) to be close to model (unsupervised)\n+ to force sets of parameters to be equal: parameter sharing => convolutional neural networks.\n\n### 7.10 Sparse Representations\n\nplace a penalty on the activations of the units in a neural network, encouraging their activations to be sparse.\n\n\n### 7.11 Bagging and Other Ensemble Methods\n\n### 7.12 Dropout\n\nincrease the size of the model when using dropout.\n\nsmall samples, dropout is less effective.\n\n\n### 7.13 Adversarial Training\n\n\n```python\nshow_image(\"fig7_8.png\", figsize=[10, 8])\n```\n\n### 7.14 Tangent Distance, Tangent Prop, and Manifold Tangent Classifier\n\n\n```python\n\n```\n", "meta": {"hexsha": "86d383efd41216fb8be78bbfd9ecd1af965ccd22", "size": 308505, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "deep_learning/Regularization_for_Deep_Learning/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "deep_learning/Regularization_for_Deep_Learning/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "deep_learning/Regularization_for_Deep_Learning/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 1177.5, "max_line_length": 184956, "alphanum_fraction": 0.9460559796, "converted": true, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771175, "lm_q2_score": 0.13846179590164853, "lm_q1q2_score": 0.06544860512298327}} {"text": "# The Jupyter notebook\n\n[IPython](https://ipython.org) provides a **kernel** for [Jupyter](https://jupyter.org).\nJupyter is the name for this notebook interface,\nand the document format.\n\n\n\n\nNotebooks can contain [Markdown](https://help.github.com/articles/markdown-basics/) like this cell here,\nas well as mathematics rendered with [mathjax](https://mathjax.org):\n\n$$\n\\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} =\n1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}\n{1+\\frac{e^{-8\\pi}} {1+\\ldots} } } } \n$$\n\n\n```python\n!head -n 32 \"Intro to IPython.ipynb\"\n```\n\n[nbviewer](https://nbviewer.org) is a service that renders notebooks to HTML,\nfor sharing and reading notebooks on the Internet.\n\n[This notebook](https://nbviewer.jupyter.org/github/minrk/inf3331-ipython/blob/master/Intro%20to%20IPython.ipynb) on nbviewer.\n\nYou can also convert notebooks to HTML and other formats locally with `jupyter nbconvert`.\n\n# IPython: beyond plain Python\n\nFollow along: https://github.com/minrk/inf3331-ipython\n\nWhen executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to make the interactive experience more fluid and efficient.\n\n## First things first: running code, getting help\n\nIn the notebook, to run a cell of code, hit `Shift-Enter`. This executes the cell and puts the cursor in the next cell below, or makes a new one if you are at the end. Alternately, you can use:\n \n- `Alt-Enter` (or `option-Enter`) to force the creation of a new cell unconditionally (useful when inserting new content in the middle of an existing notebook).\n- `Control-Enter` executes the cell and keeps the cursor in the same cell, useful for quick experimentation of snippets that you don't need to keep permanently.\n\n\n```python\nprint(\"Hi\")\n```\n\n\n```python\nimport time\n\nfor i in range(10):\n print(i, end=' ')\n time.sleep(1)\n```\n\n\n```python\ni\n```\n\nGetting help:\n\n\n```python\n?\n```\n\nTyping `object_name?` will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructor details for classes.\n\n\n```python\nimport collections\ncollections.namedtuple?\n```\n\n\n```python\n# copy/paste an example\n\n```\n\n\n```python\ncollections.Counter??\n```\n\n\n```python\nc = collections.Counter('abcdeabcdabcaba')\n```\n\n\n```python\nc.most_common?\n```\n\n\n```python\nc.most_common(2)\n```\n\nwith '\\*', you can do a wildcard search:\n\n\n```python\n*int*?\n```\n\n\n```python\nimport numpy as np\nnp.*array*?\n```\n\nAn IPython quick reference card:\n\n\n```python\n%quickref\n```\n\n## Tab completion\n\nTab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type `object_name.` to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.\n\n\n```python\nnp.array_equal\n```\n\n## The interactive workflow: input, output, history\n\n\n```python\n2+10\n```\n\n\n```python\n_+10\n```\n\nYou can suppress the storage and rendering of output if you append `;` to the last cell (this comes in handy when plotting with matplotlib, for example):\n\n\n```python\n10+20;\n```\n\n\n```python\n_\n```\n\nThe output is stored in `_N` and `Out[N]` variables:\n\n\n```python\nOut[19]\n```\n\n`%history` lets you view and search your history\n\n\n```python\n%history -n 1-5\n```\n\n**Exercise**\n\nUsing this info, how could we write the last 10 lines of history to a file with `%history`? What would be the first thing to try?\n\n\n```python\n\n```\n\n## Accessing the underlying operating system\n\n[open myfile](myfile.py)\n\n\n```python\n!cat myfile.py\n```\n\n\n```python\nimport os\nprint(os.getcwd())\n```\n\n\n```python\nimport subprocess\np = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)\nstdout, _ = p.communicate()\nprint(stdout.decode())\n```\n\n\n```python\n!pwd\n```\n\n\n```python\n!ls -la\n```\n\n\n```python\nls\n```\n\n\n```python\nfiles = !ls\nprint(\"My current directory's files:\")\nprint(files)\n```\n\n\n```python\nfor f in files:\n print(f)\n```\n\n\n```python\n!echo $files\n```\n\n\n```python\n!echo {files[0].upper()}\n```\n\nNote that all this is available even in multiline blocks:\n\n\n```python\nimport os\nfor i,f in enumerate(files):\n if f.endswith('ipynb'):\n !echo {\"%02d\" % i} - \"{os.path.splitext(f)[0]}\"\n else:\n print(f'-- {os.path.splitext(f)[0]}')\n```\n\n## Beyond Python: magic functions\n\nThe IPyhton 'magic' functions are a set of commands, invoked by prepending one or two `%` signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with `--` and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold:\n \n- To provide an orthogonal namespace for controlling IPython itself and exposing other system-oriented functionality.\n\n- To expose a calling mode that requires minimal verbosity and typing while working interactively. Thus the inspiration taken from the classic Unix shell style for commands.\n\nLine vs cell magics:\n\n\n```python\n%timeit list(range(1000))\n```\n\n\n```python\n%%timeit\nlist(range(10))\nlist(range(100))\n```\n\n\n```python\n%%html\nsome bold text\n```\n\nLine magics can be used even inside code blocks:\n\n\n```python\nfor i in range(1, 4):\n size = i*100\n print('size:', size, end=' ')\n %timeit list(range(size))\n```\n\n\n```python\n%timeit time.sleep(0.1)\n```\n\n\n```python\n%timeit?\n```\n\nMagics can do anything they want with their input, so it doesn't have to be valid Python:\n\n\n```bash\n%%bash\necho \"My shell is:\" $SHELL\necho \"My disk usage is:\"\ndf -h\n```\n\nAnother interesting cell magic: create any file you want locally from the notebook:\n\n\n```python\n%%writefile test.txt\nThis is a test file!\nIt can contain anything I want...\n\nAnd more...\n```\n\n\n```python\n!cat test.txt\n```\n\nLet's see what other magics are currently defined in the system:\n\n\n```python\n%lsmagic\n```\n\n\n```python\nimport math\nmath.pi\n```\n\n\n```python\n%precision 1\nmath.pi\n```\n\n\n```python\nnp.random.random(10)\n```\n\n\n```python\n%precision?\n```\n\n## Running normal Python code: execution and errors\n\nNot only can you input normal Python code, you can even paste straight from a Python or IPython shell session:\n\n\n```python\n>>> # Fibonacci series:\n... # the sum of two elements defines the next\n... a, b = 0, 1\n>>> while b < 10:\n... print(b)\n... a, b = b, a + b\n\n```\n\nAnd when your code produces errors, you can control how they are displayed with the `%xmode` magic:\n\n\n```python\n%%writefile mod.py\n\ndef f(x):\n return 1.0/(x-1)\n\ndef g(y):\n return f(y+1)\n```\n\nNow let's call the function `g` with an argument that would produce an error:\n\n\n```python\nimport mod\nmod.g(0)\n```\n\n\n```python\n%xmode verbose\n```\n\n\n```python\nmod.g(0)\n```\n\n## Raw Input in the notebook\n\nSince 1.0 the IPython notebook web application support `raw_input` which for example allow us to invoke the `%debug` magic in the notebook:\n\n\n```python\n%debug\n```\n\nDon't foget to exit your debugging session. Raw input can of course be use to ask for user input:\n\n\n```python\ncolour = input('What is your favourite colour? ')\nprint('colour is:', colour)\n```\n\n## Running code in other languages with special `%%` magics\n\n\n```perl\n%%perl\n@months = (\"July\", \"August\", \"September\");\nprint $months[0];\n```\n\n\n```ruby\n%%ruby\nname = \"world\"\nputs \"Hello #{name.capitalize}!\"\n```\n\n## Plotting in the notebook\n\nThis magic configures matplotlib to render its figures inline:\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nx = np.linspace(0, 2*np.pi, 300)\ny = np.sin(x**2)\nplt.plot(x, y)\nplt.title(\"A little chirp\")\nfig = plt.gcf() # let's keep the figure object around for later...\n```\n\n### Widgets\n\n\n```python\nfrom ipywidgets import interact\n\n@interact\ndef show_args(num=5, text='hello', check=True):\n print(locals())\n```\n\n\n```python\nimport sympy\nfrom sympy import Symbol, Eq, factor\nx = Symbol('x')\nsympy.init_printing(use_latex='mathjax')\nx\n```\n\n\n```python\n@interact(n=(1,21))\ndef factorit(n):\n return Eq(x**n-1, factor(x**n-1))\n```\n\n\n```python\n@interact(T=(0.0,10), ω=(-1., 10.), n=(5, 512))\ndef plot_sin(T, ω, n):\n t = np.linspace(0, T, n)\n y = np.sin(ω * t)\n plt.plot(t, y)\n\n```\n", "meta": {"hexsha": "aae2f203c1bd0a5107063ecc1f2f5238528d5e16", "size": 20404, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Intro to IPython.ipynb", "max_stars_repo_name": "minrk/inf3331-h15", "max_stars_repo_head_hexsha": "31053fadc73f4e5c52994245d342960be04d4baf", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Intro to IPython.ipynb", "max_issues_repo_name": "minrk/inf3331-h15", "max_issues_repo_head_hexsha": "31053fadc73f4e5c52994245d342960be04d4baf", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Intro to IPython.ipynb", "max_forks_repo_name": "minrk/inf3331-h15", "max_forks_repo_head_hexsha": "31053fadc73f4e5c52994245d342960be04d4baf", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0039215686, "max_line_length": 357, "alphanum_fraction": 0.5142128994, "converted": true, "num_tokens": 2212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.17328819739040088, "lm_q1q2_score": 0.06542334193759698}} {"text": "#
    Financial Economics HW_03
    \n\n**
    11510691 程远星$\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\plim}{plim}\n\\newcommand{\\ffrac}{\\displaystyle \\frac}\n\\newcommand{\\d}[1]{\\displaystyle{#1}}\n\\newcommand{\\space}{\\text{ }}\n\\newcommand{\\bspace}{\\;\\;\\;\\;}\n\\newcommand{\\bbspace}{\\;\\;\\;\\;\\;\\;\\;\\;}\n\\newcommand{\\QQQ}{\\boxed{?\\:}}\n\\newcommand{\\void}{\\left.\\right.}\n\\newcommand{\\Tran}[1]{{#1}^{\\mathrm{T}}}\n\\newcommand{\\CB}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\SB}[1]{\\left[ #1 \\right]}\n\\newcommand{\\P}[1]{\\left( #1 \\right)}\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\n\\newcommand{\\norm}[1]{\\left\\| #1 \\right\\|}\n\\newcommand{\\given}[1]{\\left. #1 \\right|}\n\\newcommand{\\using}[1]{\\stackrel{\\mathrm{#1}}{=}}\n\\newcommand{\\asim}{\\overset{\\text{a}}{\\sim}}\n\\newcommand{\\RR}{\\mathbb{R}}\n\\newcommand{\\EE}{\\mathbb{E}}\n\\newcommand{\\II}{\\mathbb{I}}\n\\newcommand{\\NN}{\\mathbb{N}}\n\\newcommand{\\ZZ}{\\mathbb{Z}}\n\\newcommand{\\QQ}{\\mathbb{Q}}\n\\newcommand{\\PP}{\\mathbb{P}}\n\\newcommand{\\AcA}{\\mathcal{A}}\n\\newcommand{\\FcF}{\\mathcal{F}}\n\\newcommand{\\AsA}{\\mathscr{A}}\n\\newcommand{\\FsF}{\\mathscr{F}}\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\I}[1]{\\mathrm{I}\\left( #1 \\right)}\n\\newcommand{\\N}[1]{\\mathcal{N}\\left( #1 \\right)}\n\\newcommand{\\Exp}[1]{\\mathrm{E}\\left[ #1 \\right]}\n\\newcommand{\\Var}[1]{\\mathrm{Var}\\left[ #1 \\right]}\n\\newcommand{\\Avar}[1]{\\mathrm{Avar}\\left[ #1 \\right]}\n\\newcommand{\\Cov}[1]{\\mathrm{Cov}\\left( #1 \\right)}\n\\newcommand{\\Corr}[1]{\\mathrm{Corr}\\left( #1 \\right)}\n\\newcommand{\\ExpH}{\\mathrm{E}}\n\\newcommand{\\VarH}{\\mathrm{Var}}\n\\newcommand{\\AVarH}{\\mathrm{Avar}}\n\\newcommand{\\CovH}{\\mathrm{Cov}}\n\\newcommand{\\CorrH}{\\mathrm{Corr}}\n\\newcommand{\\ow}{\\text{otherwise}}\n\\newcommand{\\FSD}{\\text{FSD}}\n\\void^\\dagger$
    **\n\n## Question 8.1\n\n$\\bspace$We first write $n$ Eular equations\n\n$$u_0'\\P{e_0 - \\Tran S \\theta} S_k = \\sum_{\\omega \\in\\Omega} \\pi_\\omega u_1'\\P{e_{1\\omega} + X_{\\omega,\\cdot} \\theta} X_{\\omega,k},\\bspace k = 1,2,\\dots,n$$\n\n$\\bspace$whose solution $\\theta$ is the optimal portfolio. The fact that $\\tilde r_i$ are $i.i.d.$ implies that the preceding equation can be rewritten as, after letting $e_{1\\omega} = 0$\n\n$$\\begin{align}u_0'\\P{e_0 - \\Tran S \\theta} S_k &= \\Exp{u_1'\\P{\\SB{S_1+S_1\\cdot\\tilde r_1,S_2+S_2\\cdot\\tilde r_2, \\cdots, S_n + S_n\\cdot\\tilde r_n}\\theta\\:} \\cdot S_k\\P{1+\\tilde r_k}}\\\\\nu_0'\\P{e_0 - \\Tran S \\theta}&= \\Exp{u_1'\\P{\\SB{S_1+S_1\\cdot\\tilde r_1,S_2+S_2\\cdot\\tilde r_2, \\cdots, S_n + S_n\\cdot\\tilde r_n}\\theta\\:}} \\cdot \\Exp{1+\\tilde r_k}\n\\end{align}$$\n\n$\\bspace$And now if we consider the variance, unbalanced allocation of securities will lead to higher covariance, and so is the variance, consequently. So the optimal portfolio is to find a $\\theta^*$ such that \n\n$$\\theta = \\theta^*\\cdot \\iota$$\n\n## Question 8.2\n\n$\\P{1}$\n\n$\\bspace$Suppose we put $y\\cdot w$ money in risk security and the rest in risk free security, then we write\n\n$$\\tilde w = y\\cdot w \\P{1+\\tilde r} + \\P{1-y}w\\P{1+r_F} = w\\P{1+r_F + y\\P{\\tilde r-r_F}}$$\n\n$\\bspace$With this we rewrite the optimization problem:\n\n$$\\begin{array}{cc}\n\\d{\\max_y} & \\Exp{w\\P{1+r_F + y\\P{\\tilde r-r_F}} - \\ffrac{1}{2}aw^2\\P{1+r_F + y\\P{\\tilde r-r_F}}^2}\n\\end{array}$$\n\n$\\bspace$And take the derivative on $y$ we have the first order condition:\n\n$$\\begin{align}\n\\ffrac{\\partial \\Exp{\\tilde w - \\ffrac{1}{2}a\\tilde w^2}}{\\partial y} &= \\Exp{w\\P{\\tilde r - r_F} - \\ffrac{1}{2} aw^2\\cdot 2\\P{1+r_F + y\\P{\\tilde r - r_F}}\\P{\\tilde r - r_F}}\\\\\n&= w\\P{\\Exp{\\tilde r} - r_F} - aw^2\\P{\\P{1+r_F}\\P{\\Exp{\\tilde r} - r_F} + y\\P{r_F^2 - 2r_F\\Exp{\\tilde r} + \\Exp{\\tilde r^2}}}\\\\\n&= w\\P{\\bar r - r_F} - aw^2\\P{\\P{1+r_F}\\P{\\bar r - r_F} + y\\P{r_F^2 - 2r_F\\bar r + \\bar r^2 + \\sigma^2}}=0\\\\\n\\Rightarrow y &= \\ffrac{\\ffrac{\\bar r - r_F}{aw} - \\P{1+r_F}\\P{\\bar r - r_F}}{\\P{\\bar r - r_F}^2 + \\sigma^2} = \\ffrac{\\P{\\bar r - r_F}\\P{1-aw\\P{1+r_F}}}{aw\\P{\\P{\\bar r - r_F}^2 + \\sigma^2}}\n\\end{align}$$\n\n$\\P{2}$\n\n$\\bspace$Here we give the intuitive answers.\n\n- $r_F$ and $y$ are negatively correlated, because agent will tend to put more money in risk free security given they can get more interest\n- $\\bar r$ and $y$ are positively correlated, because agent will tend to put more money in risk security given they can get more interest, in a probabilistic sense\n- $\\sigma$ and $y$ are negatively correlated, because rational agent will withdraw money from risk security given higher risk, or volatility\n- $a$ and $y$ are negatively correlated, not only can be seen from the explicit expression of $y$, but also the meaning of $a$. Given a increase in $a$ the absolute risk aversion $A\\P{w} = \\ffrac{a}{1-aw}$ increases meaning that the agent tend to withdraw some money from the risk security.\n\n## Question 8.3\n\n$\\P 1$\n\n$\\bspace$The optimization problem is now\n\n$$\\begin{array}{cc}\n\\d{\\max_y} & \\Exp{ -\\exp\\CB{-aw\\P{1+r_F + y\\P{\\tilde r-r_F}}}}\n\\end{array}$$\n\n$\\bspace$We first simplify this expression\n\n$$\\begin{align}\n\\Exp{ -\\exp\\CB{-aw\\P{1+r_F + y\\P{\\tilde r-r_F}}}} &= -\\exp\\CB{-aw\\P{1+r_F-yr_F}}\\Exp{\\exp\\CB{-awy \\tilde r}}\\\\\n&= -\\exp\\CB{-aw\\P{1+r_F-yr_F}} \\cdot \\exp\\CB{-\\mu \\cdot awy + \\ffrac{\\sigma^2}{2}\\P{awy}^2}\\\\\n&= -\\exp\\CB{-aw\\P{1+r_F} + aw\\P{r_F - \\mu}y + \\ffrac{\\sigma^2}{2}\\P{aw}^2y^2}\n\\end{align}$$\n\n$\\bspace$Since $\\exp\\CB{-aw\\P{1+r_F}}$ is positive we have the simplified optimization problem\n\n$$\\begin{array}{cc}\n\\d{\\max_y} & -\\exp\\CB{aw\\P{r_F - \\mu}y + \\ffrac{\\sigma^2}{2}\\P{aw}^2y^2}\n\\end{array}$$\n\n$\\bspace$And take the derivative on $y$ we have the first order condition:\n\n$$\\begin{align}\n\\ffrac{\\partial \\P{-\\exp\\CB{aw\\P{r_F - \\mu}y + \\ffrac{\\sigma^2}{2}\\P{aw}^2y^2}}}{\\partial y} &= -\\exp\\CB{aw\\P{r_F - \\mu}y + \\ffrac{\\sigma^2}{2}\\P{aw}^2y^2}\\cdot\\P{aw\\P{r_F - \\mu} + \\sigma^2\\P{aw}^2y} = 0\\\\\n\\Rightarrow \\P{aw\\P{r_F - \\mu} + \\sigma^2\\P{aw}^2y}&=0 \\Rightarrow y = \\ffrac{\\mu - r_F}{\\sigma^2aw}\n\\end{align}$$\n\n$\\P{2}$\n\n$\\bspace$Here we give the intuitive answers.\n\n- $r_F$ and $y$ are negatively correlated, because agent will tend to put more money in risk free security given they can get more interest\n- $\\mu$ and $y$ are positively correlated, because agent will tend to put more money in risk security given they can get more interest, in a probabilistic sense\n- $\\sigma$ and $y$ are negatively correlated, because rational agent will withdraw money from risk security given higher risk, or volatility\n- $a$ and $y$ are negatively correlated, not only can be seen from the explicit expression of $y$, but also the meaning of $a$. Given a increase in $a$ the absolute risk aversion $A\\P{w} = a$ increases meaning that the agent tend to withdraw some money from the risk security.\n\n## Question 9.1\n\n$\\bspace\\newcommand{\\FSD}{\\text{FSD}}\n\\newcommand{\\SSD}{\\text{SSD}}$Consider first stochastic dominance, $A\\not\\succsim_{\\FSD} B$ if $u\\P x = x^3$, nor $B\\not\\succsim_{\\FSD} A$ if $u\\P x = x+1$.\n\n$\\bspace$Then the second stochastic dominance, using the theorem, we let $d=1$ and define $\\tilde e$\n\n$$\\begin{array}{c|cccc}\n& \\omega_1 & \\omega_2 &\\omega_3&\\omega_4\\\\\\hline\n\\tilde e & 0.4 & 0.3 & -0.3 & -0.4\\\\\np & 0.25 & 0.25 & 0.25 & 0.25\\\\\n\\tilde x_A & 1.5 & 1.5 & 1.7 & 1.7\n\\end{array}$$\n\n$$\\begin{align}\n\\Exp{\\tilde e \\mid x_A} &= \\sum_{i} \\tilde e_i \\cdot p\\P{\\tilde e_i\\mid x_{A,i}}\\\\\n&= 0.4\\times0.25 + 0.3 \\times 0.25 - 0.3 \\times 0.25 - 0.4 \\times 0.25 = 0\n\\end{align}$$\n\n$\\bspace$So $A\\succsim_{\\SSD} B$.\n\n## Question 9.2\n\n$\\P{\\text a.1}$\n\n$$\\bspace \\tilde r_B = \\tilde x + \\tilde e = 1 \\cdot \\tilde r_A + \\tilde e \\Rightarrow \\tilde x_B = 1 \\cdot \\tilde x_A + \\tilde e $$\n\n$\\bspace$And due to the independency, $\\Exp{\\tilde e\\mid \\tilde x_A} = \\Exp{\\tilde e} = 0$, thus $A\\succsim_{\\void_\\SSD} B$.\n\n$\\P{\\text a.2}$\n\n$$\\begin{align}\n\\Exp{u\\P{\\tilde w}} &= \\Exp{u\\P{a\\P{1+\\tilde r_A} + \\P{1-a}\\P{1+\\tilde r_B}}}\\\\\n&= \\Exp{u\\P{1+ a\\P{\\tilde x - \\tilde x - \\tilde e} + \\tilde x + \\tilde e}}\\\\\n&= \\Exp{u\\P{1+\\P{1-a}\\tilde e + \\tilde x}}\n\\end{align}$$\n\n$\\bspace$Since $\\Exp{\\tilde e} = 0$, we take the derivative on $a$ and have the following:\n\n$$\\begin{align}\n\\ffrac{\\partial^2 \\Exp{u\\P{\\tilde w}}}{\\partial a^2} &=\\Exp{u''\\P{1+\\P{1-a}\\tilde e + \\tilde x}\\tilde e^2}\\leq 0\\\\\n\\ffrac{\\partial \\Exp{u\\P{\\tilde w}}}{\\partial a} &= \\Exp{-u'\\P{1+\\P{1-a}\\tilde e + \\tilde x}\\tilde e}\\\\\n&= \\sum_{e<0}e\\cdot P\\CB{\\tilde e = e}\\cdot u'\\P{1+\\P{1-a}e + \\tilde x} + \\sum_{e>0}e\\cdot P\\CB{\\tilde e = e}\\cdot u'\\P{1+\\P{1-a}e + \\tilde x}\\\\\n&\\geq \\sum_{e<0}e\\cdot P\\CB{\\tilde e = e}\\cdot u'\\P{1+\\P{1-a}\\cdot 0 + \\tilde x} + \\sum_{e>0}e\\cdot P\\CB{\\tilde e = e}\\cdot u'\\P{1+\\P{1-a}\\cdot 0 + \\tilde x}\\\\\n& = u'\\P{1 + \\tilde x}\\cdot\\Exp{\\tilde e} = 0\n\\end{align}$$\n\n$\\bspace$Thus $\\Exp{u\\P{\\tilde w}}$ gets to its maximum at $a=1$. The conclusion is same when $\\tilde e$ is continuous.\n\n$\\P{\\text b.1}$\n\n$\\bspace$With the same reasoning, we can prove that $A\\succsim_{\\void_\\SSD} B$.\n\n$\\P{\\text b.2}$\n\n$\\bspace$Now $\\Exp{u\\P{\\tilde w}} = \\Exp{u\\P{a\\tilde x + \\P{1-a}\\P{\\tilde y + \\tilde e}}} = \\Exp{u\\P{\\tilde y + \\tilde e + a\\P{\\tilde x - \\tilde y - \\tilde e}}}$. Still we have its second order direvative on $a$ positive. Then\n\n$$\\begin{align}\n\\ffrac{\\partial \\Exp{u\\P{\\tilde w}}}{\\partial a} &= \\Exp{u'\\P{\\tilde y + \\tilde e + a\\P{\\tilde x - \\tilde y - \\tilde e}}\\P{\\tilde x - \\tilde y - \\tilde e}}\\\\\n\\end{align}$$\n\n$\\bspace$At $a = 0.5$, this equals to $\\Exp{u'\\P{a\\P{\\tilde x + \\tilde y + \\tilde e}}\\P{\\tilde x - \\tilde y - \\tilde e}} = -\\Exp{u'\\P{a\\P{\\tilde x + \\tilde y + \\tilde e}}\\tilde e}$, with the same form we've proved in $\\P{\\text a.2}$. Thus $\\given{\\ffrac{\\partial \\Exp{u\\P{\\tilde w}}}{\\partial a}}_{a=0.5}\\geq0$. In order to reach the maximum, we have now $a>0.5$.\n\n$\\P{\\text{c}}$\n\n$\\bspace$The result is intuitively obvious. In $\\P{\\text a}$, $\\tilde r_B$ has got a higher volatility than $\\tilde r_A$, so the optimal strategy is to ignore asset $B$. In $\\P{\\text b}$, we know that in probabilistic sense asset $A$ has a lower volatility than asset $B$, thus, we put more money in $A$ and consequently $a>0.5$.\n\n## Question 9.5\n\n$\\bspace$Using $Theorem\\space 9.5$, when all $\\tilde r_n$ are $i.i.d.$, whatever preference you have, the portfolio you hold is equivelent to a equal-weight portfolio. Thus the utility function of any agent, say $k$, can now be linearly transformed to the utility function of any other agent, say $j$, meaning that the utility functions of all agents, are equivalent, in linear sense. So then we have single fund separation.\n\n## Question 9.6\n\n$\\P{1}$\n\n$\\bspace$The weights on all $N$ risky securities are $\\alpha = \\SB{a_1;a_2;\\cdots;a_N}$. Then we write\n\n$$\\tilde w = w\\P{1+r_F} + \\sum_{i=1}^N a_i\\P{\\tilde r_i - r_F} = w\\P{1+r_F} + \\Tran\\alpha\\P{\\tilde r - r_F\\cdot \\iota}$$\n\n$\\bspace$We then take the derivative on $\\alpha$ to derive the first order condition\n\n$\\begin{align}\n&\\ffrac{\\partial \\Exp{\\tilde w - \\ffrac{1}{2}a\\tilde w^2}}{\\partial \\alpha}\\\\ \n=\\;& \\ffrac{\\partial \\Exp{w\\P{1+r_F} + \\Tran{\\P{\\tilde r - r_F\\cdot\\iota}}\\alpha - \\ffrac{1}{2}a \\P{w^2\\P{1+r_F}^2 + \\Tran\\alpha\\P{\\tilde r - r_F\\cdot\\iota} \\Tran{\\P{\\tilde r - r_F\\cdot\\iota}}\\alpha + 2w\\P{1+r_F}\\Tran{\\P{\\tilde r - r_F\\cdot\\iota}}\\alpha}}}{\\partial \\alpha}\\\\\n=\\;& \\Exp{\\Tran{\\P{\\tilde r - r_F\\cdot\\iota}} - \\ffrac{1}{2} a\\Tran\\alpha\\P{\\P{\\tilde r - r_F\\cdot\\iota}\\Tran{\\P{\\tilde r - r_F\\cdot\\iota}} + \\P{\\tilde r - r_F\\cdot\\iota}\\Tran{\\P{\\tilde r - r_F\\cdot\\iota}}} - aw\\P{1+r_F}\\Tran{\\P{\\tilde r - r_F\\cdot\\iota}}}\\\\\n=\\;& \\Exp{\\Tran{\\P{\\tilde r - r_F\\cdot\\iota}}\\P{1 - aw\\P{1+r_F}}- a\\Tran\\alpha\\P{\\P{\\tilde r - r_F\\cdot\\iota}\\Tran{\\P{\\tilde r - r_F\\cdot\\iota}}}}\\\\\n=\\;& \\Tran{\\P{\\bar r - r_F \\cdot \\iota}}\\P{1-aw\\P{1+r_F}} - a\\Tran\\alpha \\Sigma = 0\n\\end{align}$\n\n$\\bspace$So that $\\alpha = \\ffrac{1-aw\\P{1+r_F}}{a} \\Sigma^{-1}\\P{\\bar r - r_F \\cdot \\iota}$\n\n$\\P{2}$\n\n$\\bspace$From $Theorem\\space 9.6$, the assertion is obviously true. And the proof is given in Chapter 12, so...\n\n***\n", "meta": {"hexsha": "e66b1d90fa7ac1b3df45ca9b7257c7dbd923c2c7", "size": 15847, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FinMath/Financial Economics/HW/HW_03.ipynb", "max_stars_repo_name": "XavierOwen/Notes", "max_stars_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-27T10:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T03:11:58.000Z", "max_issues_repo_path": "FinMath/Financial Economics/HW/HW_03.ipynb", "max_issues_repo_name": "XavierOwen/Notes", "max_issues_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "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": "FinMath/Financial Economics/HW/HW_03.ipynb", "max_forks_repo_name": "XavierOwen/Notes", "max_forks_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:57:23.000Z", "avg_line_length": 51.9573770492, "max_line_length": 433, "alphanum_fraction": 0.5223070613, "converted": true, "num_tokens": 4803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.18010666188603547, "lm_q1q2_score": 0.06537317197356454}} {"text": "```javascript\n%%javascript\n MathJax.Hub.Config({\n TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n });\n```\n\n\n \n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n
    ''')\n```\n\n\n\n\n\n
    \n\n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n\n\n\n''')\n```\n\n\n\n\n\n\n\n\n\n\n\n\n# Benchmark Problem 7: MMS Allen-Cahn\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''{% include jupyter_benchmark_table.html num=\"[7]\" revision=0 %}''')\n```\n\n\n\n\n{% include jupyter_benchmark_table.html num=\"[7]\" revision=0 %}\n\n\n\n* [Overview](#Overview)\n* [Governing equation and manufactured solution](#Governing-equation-and-manufactured-solution)\n* [Domain geometry, boundary conditions, initial conditions, and stopping condition](#Domain-geometry,-boundary-conditions,-initial-conditions,-and-stopping-condition)\n* [Parameter values](#Parameter-values)\n* [Benchmark simulation instructions](#Benchmark-simulation-instructions)\n * [Part (a)](#Part-%28a%29)\n * [Part (b)](#Part-%28b%29)\n * [Part (c)](#Part-%28c%29)\n* [Results](#Results)\n* [Feedback](#Feedback)\n* [Appendix](#Appendix)\n * [Computer algebra systems](#Computer-algebra-systems)\n * [Source equation](#Source-equation)\n * [Code](#Code)\n\n\nSee the journal publication entitled [\"Benchmark problems for numerical implementations of phase field models\"][benchmark_paper] for more details about the benchmark problems. Furthermore, read [the extended essay][benchmarks] for a discussion about the need for benchmark problems.\n\n[benchmarks]: ../\n[benchmark_paper]: http://dx.doi.org/10.1016/j.commatsci.2016.09.022\n\n# Overview\n\nThe Method of Manufactured Solutions (MMS) is a powerful technique for verifying the accuracy of a simulation code. In the MMS, one picks a desired solution to the problem at the outset, the \"manufactured solution\", and then determines the governing equation that will result in that solution. With the exact analytical form of the solution in hand, when the governing equation is solved using a particular simulation code, the deviation from the expected solution can be determined exactly. This deviation can be converted into an error metric to rigously quantify the error for a calculation. This error can be used to determine the order of accuracy of the simulation results to verify simulation codes. It can also be used to compare the computational efficiency of different codes or different approaches for a particular code at a certain level of error. Furthermore, the spatial/temporal distribution can give insight into the conditions resulting in the largest error (high gradients, changes in mesh resolution, etc.).\n\nAfter choosing a manufactured solution, the governing equation must be modified to force the solution to equal the manufactured solution. This is accomplished by taking the nominal equation that is to be solved (e.g. Allen-Cahn equation, Cahn-Hilliard equation, Fick's second law, Laplace equation) and adding a source term. This source term is determined by plugging the manufactured solution into the nominal governing equation and setting the source term equal to the residual. Thus, the manufactured solution satisfies the MMS governing equation (the nominal governing equation plus the source term). A more detailed discussion of MMS can be found in [the report by Salari and Knupp][mms_report].\n\nIn this benchmark problem, the objective is to use the MMS to rigorously verify phase field simulation codes and then provide a basis of comparison for the computational performance between codes and for various settings for a single code, as discussed above. To this end, the benchmark problem was chosen as a balance between two factors: simplicity, to minimize the development effort required to solve the benchmark, and transferability to a real phase field system of physical interest. \n\n[mms_report]: http://prod.sandia.gov/techlib/access-control.cgi/2000/001444.pdf\n\n# Governing equation and manufactured solution\nFor this benchmark problem, we use a simple Allen-Cahn equation as the governing equation\n\n$$\\begin{equation}\n\\frac{\\partial \\eta}{\\partial t} = - \\left[ 4 \\eta \\left(\\eta - 1 \\right) \\left(\\eta-\\frac{1}{2} \\right) - \\kappa \\nabla^2 \\eta \\right] + S(x,y,t) \n\\end{equation}$$\n\nwhere $S(x,y,t)$ is the MMS source term and $\\kappa$ is a constant parameter (the gradient energy coefficient). \n\nThe manufactured solution, $\\eta_{sol}$ is a hyperbolic tangent function, shifted to vary between 0 and 1, with the $x$ position of the middle of the interface ($\\eta_{sol}=0.5$) given by the function $\\alpha(x,t)$:\n\n$$\\begin{equation}\n\\eta_{sol}(x,y,t) = \\frac{1}{2}\\left[ 1 - \\tanh\\left( \\frac{y-\\alpha(x,t)}{\\sqrt{2 \\kappa}} \\right) \\right] \n\\end{equation}$$\n\n$$\\begin{equation}\n\\alpha(x,t) = \\frac{1}{4} + A_1 t \\sin\\left(B_1 x \\right) + A_2 \\sin \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\nwhere $A_1$, $B_1$, $A_2$, $B_2$, and $C_2$ are constant parameters. \n\nThis manufactured solution is an equilbrium solution of the governing equation, when $S(x,y,t)=0$ and $\\alpha(x,t)$ is constant. The closeness of this manufactured solution to a solution of the nominal governing equation increases the likihood that the behavior of simulation codes when solving this benchmark problem is representive of the solution of the regular Allen-Cahn equation (i.e. without the source term). The form of $\\alpha(x,t)$ was chosen to yield complex behavior while still retaining a (somewhat) simple functional form. The two spatial sinusoidal terms introduce two controllable length scales to the interfacial shape. Summing them gives a \"beat\" pattern with a period longer than the period of either individual term, permitting a domain size that is larger than the wavelength of the sinusoids without a repeating pattern. The temporal sinusoidal term introduces a controllable time scale to the interfacial shape in addition to the phase transformation time scale, while the linear temporal dependence of the other term ensures that the sinusoidal term can go through multiple periods without $\\eta_{sol}$ repeating itself.\n\nInserting the manufactured solution into the governing equation and solving for $S(x,y,t)$ yields:\n\n$$\\begin{equation}\nS(x,y,t) = \\frac{\\text{sech}^2 \\left[ \\frac{y-\\alpha(x,t)}{\\sqrt{2 \\kappa}} \\right]}{4 \\sqrt{\\kappa}} \\left[-2\\sqrt{\\kappa} \\tanh \\left[\\frac{y-\\alpha(x,t)}{\\sqrt{2 \\kappa}} \\right] \\left(\\frac{\\partial \\alpha(x,t)}{\\partial x} \\right)^2+\\sqrt{2} \\left[ \\frac{\\partial \\alpha(x,t)}{\\partial t}-\\kappa \\frac{\\partial^2 \\alpha(x,t)}{\\partial x^2} \\right] \\right]\n\\end{equation}$$\n\nwhere $\\alpha(x,t)$ is given above and where:\n\n$$\\begin{equation}\n\\frac{\\partial \\alpha(x,t)}{\\partial x} = A_1 B_1 t \\cos\\left(B_1 x\\right) + A_2 B_2 \\cos \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\n$$\\begin{equation}\n\\frac{\\partial^2 \\alpha(x,t)}{\\partial x^2} = -A_1 B_1^2 t \\sin\\left(B_1 x\\right) - A_2 B_2^2 \\sin \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\n$$\\begin{equation}\n\\frac{\\partial \\alpha(x,t)}{\\partial t} = A_1 \\sin\\left(B_1 x\\right) + A_2 C_2 \\cos \\left(B_2 x + C_2 t \\right)\n\\end{equation}$$\n\n#### *N.B.*: Don't transcribe these equations. Please download the appropriate files from the [Appendix](#Appendix).\n\n# Domain geometry, boundary conditions, initial conditions, and stopping condition\nThe domain geometry is a rectangle that spans [0, 1] in $x$ and [0, 0.5] in $y$. This elongated domain was chosen to allow multiple peaks and valleys in $\\eta_{sol}$ without stretching the interface too much in the $y$ direction (which causes the thickness of the interface to change) or having large regions where $\\eta_{sol}$ never deviates from 0 or 1. Periodic boundary conditions are applied along the $x = 0$ and the $x = 1$ boundaries to accomodate the periodicity of $\\alpha(x,t)$. Dirichlet boundary conditions of $\\eta$ = 0 and $\\eta$ = 1 are applied along the $y = 0$ and the $y = 0.5$ boundaries, respectively. These boundary conditions are chosen to be consistent with $\\eta_{sol}(x,y,t)$. The initial condition is the manufactured solution at $t = 0$:\n\n$$\n\\begin{equation}\n\\eta_{sol}(x,y,0) = \\frac{1}{2}\\left[ 1 - \\tanh\\left( \\frac{y-\\left(\\frac{1}{4}+A_2 \\sin(B_2 x) \\right)}{\\sqrt{2 \\kappa}} \\right) \\right] \n\\end{equation}\n$$\n\nThe stopping condition for all calculations is when t = 8 time units, which was chosen to let $\\alpha(x,t)$ evolve substantially, while still being slower than the characteristic time for the phase evolution (determined by the CFL condition for a uniform mesh with a reasonable level of resolution of $\\eta_{sol}$).\n\n# Parameter values\nThe nominal parameter values for the governing equation and manufactured solution are given below. The value of $\\kappa$ will change in Part (b) in the following section and the values of $\\kappa$ and $C_2$ will change in Part (c).\n\n| Parameter | Value |\n|-----------|-------|\n| $\\kappa$ | 0.0004|\n| $A_1$ | 0.0075|\n| $B_1$ | 0.03 |\n| $A_2$ | 8.0 |\n| $B_2$ | 22.0 |\n| $C_2$ | 0.0625|\n\n# Benchmark simulation instructions\nThis section describes three sets of tests to conduct using the MMS problem specified above. The primary purpose of the first test is provide a computationally inexpensive problem to verify a simulation code. The second and third tests are more computationally demanding and are primarily designed to serve as a basis for performance comparisons.\n\n## Part (a)\nThe objective of this test is to verify the accuracy of your simulation code in both time and space. Here, we make use of convergence tests, where either the mesh size (or grid point spacing) or the time step size is systematically changed to determine the response of the error to these quantities. Once a convergence test is completed the order of accuracy can be calculated from the result. The order of accuracy can be compared to the theoretical order of accuracy for the numerical method employed in the simulation. If the two match (to a reasonable degree), then one can be confident that the simulation code is working as expected. The remainder of this subsection will give instructions for convergence tests for this MMS problem.\n\nImplement the MMS problem specified above using the simulation code of your choice. Perform a spatial convergence test by running the simulation for a variety of mesh sizes. For each simulation, determine the discrete $L_2$ norm of the error at $t=8$:\n\n$$\\begin{equation}\n L_2 = \\sqrt{\\sum\\limits_{x,y}\\left(\\eta^{t=8}_{x,y} - \\eta_{sol}(x,y,8)\\right)^2 \\Delta x \\Delta y}\n\\end{equation}$$\n\nFor all of these simulations, verify that the time step is small enough that any temporal error is much smaller that the total error. This can be accomplished by decreasing the time step until it has minimal effect on the error. Ensure that at least three simulation results have $L_2$ errors in the range $[5\\times10^{-3}, 1\\times10^{-4}]$, attempting to cover as much of that range as possible/practical. This maximum and minimum errors in the range roughly represent a poorly resolved simulation and a very well-resolved simulation.\n\nFor at least three simulations that have $L_2$ errors in the range $[5\\times10^{-3}, 1\\times10^{-4}]$, save the effective mesh size and $L_2$ error in a CSV or JSON file. Upload this file to the PFHub website as a 2D data set with the effective mesh size as the x-axis column and the $L_2$ error as the y-axis column. Calculate the effective element size as the square root of the area of the finest part of the mesh for nonuniform meshes. For irregular meshes with continous distributions of element sizes, approximate the effective mesh size as the average of the square root of the area of the smallest 5% of the elements.\n\nNext, confirm that the observed order of accuracy is approximately equal to the expected value. Calculate the order of accuracy, $p$, with a least squares fit of the following function:\n\n$$\\begin{equation}\n \\log(E)=p \\log(R) + b\n\\end{equation}$$\n\nwhere $E$ is the $L_2$ error, $R$ is the effective element size, and b is an intercept. Deviations of ±0.2 or more from the theoretical value are to be expected (depending on the range of errors considered and other factors).\n\nFinally, perform a similar convergence test, but for the time step, systematically changing the time step and recording the $L_2$ error. Use a time step that does not vary over the course of any single simulation. Verify that the spatial discretization error is small enough that it does not substantially contribute to the total error. Once again, ensure that at least three simulations have $L_2$ errors in the range $[5\\times10^{-3}, 1\\times10^{-4}]$, attempting to cover as much of that range as possible/practical. Save the effective mesh size and $L_2$ error for each individual simulation in a CSV or JSON file. [Upload this file to the PFHub website](https://pages.nist.gov/pfhub/simulations/upload_form/) as a 2D data set with the time step size as the x-axis column and the $L_2$ error as the y-axis column. Confirm that the observed order of accuracy is approximately equal to the expected value.\n\n## Part (b)\nNow that your code has been verified in (a), the objective of this part is to determine the computational performance of your code at various levels of error. These results can then be used to objectively compare the performance between codes or settings within the same code. To make the problem more computationally demanding and stress solvers more than in (a), decrease $\\kappa$ by a factor of $256$ to $1.5625\\times10^{-6}$. This change will reduce the interfacial thickness by a factor of $16$.\n\nRun a series of simulations, attempting to optimize solver parameters (mesh, time step, tolerances, etc.) to minimize the required computational resources for at least three levels of $L_2$ error in range $[5\\times10^{-3}, 1\\times10^{-5}]$. Use the same CPU and processor type for all simulations. For the best of these simulations, save the wall time, number of computing cores, maximum memory usage, and $L_2$ error for each individual simulation in a CSV or JSON file. [Upload this to the PFHub website](https://pages.nist.gov/pfhub/simulations/upload_form/) as a 3D data set with the wall time as the x-axis column, the number of computing cores as the y-axis column, and the $L_2$ error as the z-axis column. (The PFHub upload system is currently limited to three columns of data. Once this constraint is relaxed, the maximum memory usage data will be incorporated as well.)\n\n\n\n## Part (c)\nThis final part is designed to stress time integrators even further by increasing the rate of change of $\\alpha(x,t)$. Increase $C_2$ to $0.5$. Keep $\\kappa= 1.5625\\times10^{-6}$ from (b).\n\nRepeat the process from (b), uploading the wall time, number of computing cores, processor speed, maximum memory usage, and $L_2$ error at $t=8$ to the PFHub website.\n\n# Results\nResults from this benchmark problem are displayed on the [simulation result page]({{ site.baseurl }}/simulations) for different codes.\n\n# Feedback\nFeedback on this benchmark problem is appreciated. If you have questions, comments, or seek clarification, please contact the [CHiMaD phase field community](https://pages.nist.gov/chimad-phase-field/community/) through the [Gitter chat channel](https://gitter.im/usnistgov/chimad-phase-field) or by [email](https://pages.nist.gov/chimad-phase-field/mailing_list/). If you found an error, please file an [issue on GitHub](https://github.com/usnistgov/chimad-phase-field/issues/new).\n\n# Appendix\n\n## Computer algebra systems\nRigorous verification of software frameworks using MMS requires posing the equation and manufacturing the solution with as much complexity as possible. This can be straight-forward, but interesting equations produce complicated source terms. To streamline the MMS workflow, it is strongly recommended that you use a CAS such as SymPy, Maple, or Mathematica to generate source equations and turn it into executable code automatically. For accessibility, we will use [SymPy](http://www.sympy.org/), but so long as vector calculus is supported, and CAS will do.\n\n## Source term\n\n\n```python\nfrom sympy import Symbol, symbols, simplify\nfrom sympy import Eq, sin, cos, cosh, sinh, tanh, sqrt\nfrom sympy.physics.vector import divergence, gradient, ReferenceFrame, time_derivative\nfrom sympy.printing import pprint\nfrom sympy.abc import kappa, S, t, x, y\n\n# Spatial coordinates: x=R[0], y=R[1], z=R[2]\nR = ReferenceFrame('R')\n\n# sinusoid amplitudes\nA1, A2 = symbols('A1 A2')\nB1, B2 = symbols('B1 B2')\nC1, C2 = symbols('C1 C2')\n\n# Define interface offset (alpha)\nalpha = (1/4 + A1 * t * sin(B1 * R[0]) \n + A2 * sin(B2 * R[0] + C2 * t)\n ).subs({R[0]: x, R[1]: y})\n\n# Define the solution equation (eta) \neta = (1/2 * (1 - tanh((R[1] - alpha) /\n sqrt(2*kappa)))\n ).subs({R[0]: x, R[1]: y})\n\n# Compute the initial condition\neta0 = eta.subs({t: 0, R[0]: x, R[1]: y})\n\n# Compute the source term from the equation of motion\nS = simplify(time_derivative(eta, R)\n + 4 * eta * (eta - 1) * (eta - 1/2)\n - divergence(kappa * gradient(eta, R), R)\n ).subs({R[0]: x, R[1]: y})\n```\n\n\n```python\npprint(Eq(symbols('alpha'), alpha))\n```\n\n α = A₁⋅t⋅sin(B₁⋅x) + A₂⋅sin(B₂⋅x + C₂⋅t) + 0.25\n\n\n\n```python\npprint(Eq(symbols('eta'), eta))\n```\n\n ⎛√2⋅(-A₁⋅t⋅sin(B₁⋅x) - A₂⋅sin(B₂⋅x + C₂⋅t) + y - 0.25)⎞ \n η = - 0.5⋅tanh⎜─────────────────────────────────────────────────────⎟ + 0.5\n ⎝ 2⋅√κ ⎠ \n\n\n\n```python\npprint(Eq(symbols('eta0'), eta0))\n```\n\n ⎛√2⋅(-A₂⋅sin(B₂⋅x) + y - 0.25)⎞ \n η₀ = - 0.5⋅tanh⎜─────────────────────────────⎟ + 0.5\n ⎝ 2⋅√κ ⎠ \n\n\n\n```python\npprint(Eq(symbols('S'), S))\n```\n\n ⎛ ⎛√2⋅(A₁⋅t⋅sin(B₁⋅x) + A₂⋅sin(B₂⋅x + C₂⋅t) - y + 0.25)⎞ \n ⎜0.5⋅√κ⋅tanh⎜────────────────────────────────────────────────────⎟ - 0.25⋅\n ⎝ ⎝ 2⋅√κ ⎠ \n S = ──────────────────────────────────────────────────────────────────────────\n \n \n ⎞ ⎛ 2⎛√2⋅(A₁⋅t⋅sin(B₁⋅x) + A₂⋅sin\n √2⋅(A₁⋅sin(B₁⋅x) + A₂⋅C₂⋅cos(B₂⋅x + C₂⋅t))⎟⋅⎜tanh ⎜───────────────────────────\n ⎠ ⎝ ⎝ 2⋅√\n ──────────────────────────────────────────────────────────────────────────────\n √κ \n \n (B₂⋅x + C₂⋅t) - y + 0.25)⎞ ⎞\n ─────────────────────────⎟ - 1⎟\n κ ⎠ ⎠\n ───────────────────────────────\n \n\n\n## Code\n\n### Python\n\nCopy the first cell under Source Term directly into your program.\nFor a performance boost, convert the expressions into lambda functions:\n```python\nfrom sympy.utilities.lambdify import lambdify\n\napy = lambdify([x, y], alpha, modules='sympy')\nepy = lambdify([x, y], eta, modules='sympy')\nipy = lambdify([x, y], eta0, modules='sympy')\nSpy = lambdify([x, y], S, modules='sympy')\n```\n#### *N.B.*: You may need to add coefficients to the variables list.\n\n### C\n\n\n```python\nfrom sympy.utilities.codegen import codegen\n\n[(c_name, c_code), (h_name, c_header)] = codegen([('alpha', alpha),\n ('eta', eta),\n ('eta0', eta0),\n ('S', S)],\n language='C', prefix='MMS', project='PFHub')\nprint(c_code)\n```\n\n /******************************************************************************\n * Code generated with sympy 1.1.1 *\n * *\n * See http://www.sympy.org/ for more information. *\n * *\n * This file is part of 'PFHub' *\n ******************************************************************************/\n #include \"MMS.h\"\n #include \n \n double alpha(double A1, double A2, double B1, double B2, double C2, double t, double x) {\n \n double alpha_result;\n alpha_result = A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) + 0.25;\n return alpha_result;\n \n }\n \n double eta(double A1, double A2, double B1, double B2, double C2, double kappa, double t, double x, double y) {\n \n double eta_result;\n eta_result = -0.5*tanh((1.0L/2.0L)*sqrt(2)*(-A1*t*sin(B1*x) - A2*sin(B2*x + C2*t) + y - 0.25)/sqrt(kappa)) + 0.5;\n return eta_result;\n \n }\n \n double eta0(double A2, double B2, double kappa, double x, double y) {\n \n double eta0_result;\n eta0_result = -0.5*tanh((1.0L/2.0L)*sqrt(2)*(-A2*sin(B2*x) + y - 0.25)/sqrt(kappa)) + 0.5;\n return eta0_result;\n \n }\n \n double S(double A1, double A2, double B1, double B2, double C2, double kappa, double t, double x, double y) {\n \n double S_result;\n S_result = (0.5*sqrt(kappa)*tanh((1.0L/2.0L)*sqrt(2)*(A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25)/sqrt(kappa)) - 0.25*sqrt(2)*(A1*sin(B1*x) + A2*C2*cos(B2*x + C2*t)))*(pow(tanh((1.0L/2.0L)*sqrt(2)*(A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25)/sqrt(kappa)), 2) - 1)/sqrt(kappa);\n return S_result;\n \n }\n \n\n\n### C++\n\n\n```python\nfrom sympy.printing.cxxcode import cxxcode\n```\n\n\n```python\nprint(\"α:\")\ncxxcode(alpha)\n```\n\n α:\n\n\n\n\n\n 'A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) + 0.25'\n\n\n\n\n```python\nprint(\"η:\")\ncxxcode(eta)\n```\n\n η:\n\n\n\n\n\n '-0.5*tanh((1.0L/2.0L)*std::sqrt(2)*(-A1*t*sin(B1*x) - A2*sin(B2*x + C2*t) + y - 0.25)/std::sqrt(kappa)) + 0.5'\n\n\n\n\n```python\nprint(\"η₀:\")\ncxxcode(eta0)\n```\n\n η₀:\n\n\n\n\n\n '-0.5*tanh((1.0L/2.0L)*std::sqrt(2)*(-A2*sin(B2*x) + y - 0.25)/std::sqrt(kappa)) + 0.5'\n\n\n\n\n```python\nprint(\"S:\")\ncxxcode(S)\n```\n\n S:\n\n\n\n\n\n '(0.5*std::sqrt(kappa)*tanh((1.0L/2.0L)*std::sqrt(2)*(A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25)/std::sqrt(kappa)) - 0.25*std::sqrt(2)*(A1*sin(B1*x) + A2*C2*cos(B2*x + C2*t)))*(std::pow(tanh((1.0L/2.0L)*std::sqrt(2)*(A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25)/std::sqrt(kappa)), 2) - 1)/std::sqrt(kappa)'\n\n\n\n### Fortran\n\n\n```python\nfrom sympy.printing import fcode\n```\n\n\n```python\nprint(\"α:\")\nfcode(alpha)\n```\n\n α:\n\n\n\n\n\n ' A1*t*sin(B1*x) + A2*sin(B2*x + C2*t) + 0.25d0'\n\n\n\n\n```python\nprint(\"η:\")\nfcode(eta)\n```\n\n η:\n\n\n\n\n\n ' -0.5d0*tanh(0.707106781186548d0*kappa**(-0.5d0)*(-A1*t*sin(B1*x) -\\n @ A2*sin(B2*x + C2*t) + y - 0.25d0)) + 0.5d0'\n\n\n\n\n```python\nprint(\"η₀:\")\nfcode(eta0)\n```\n\n η₀:\n\n\n\n\n\n ' -0.5d0*tanh(0.707106781186548d0*kappa**(-0.5d0)*(-A2*sin(B2*x) + y\\n @ - 0.25d0)) + 0.5d0'\n\n\n\n\n```python\nprint(\"S:\")\nfcode(S)\n```\n\n S:\n\n\n\n\n\n ' (0.5d0*sqrt(kappa)*tanh(0.707106781186548d0*kappa**(-0.5d0)*(A1*t*\\n @ sin(B1*x) + A2*sin(B2*x + C2*t) - y + 0.25d0)) - 0.25d0*sqrt(\\n @ 2.0d0)*(A1*sin(B1*x) + A2*C2*cos(B2*x + C2*t)))*(tanh(\\n @ 0.707106781186548d0*kappa**(-0.5d0)*(A1*t*sin(B1*x) + A2*sin(B2*x\\n @ + C2*t) - y + 0.25d0))**2 - 1)/sqrt(kappa)'\n\n\n\n### Julia\n\n\n```python\nfrom sympy.printing import julia_code\n```\n\n\n```python\nprint(\"α:\")\njulia_code(alpha)\n```\n\n α:\n\n\n\n\n\n 'A1.*t.*sin(B1.*x) + A2.*sin(B2.*x + C2.*t) + 0.25'\n\n\n\n\n```python\nprint(\"η:\")\njulia_code(eta)\n```\n\n η:\n\n\n\n\n\n '-0.5*tanh(sqrt(2)*(-A1.*t.*sin(B1.*x) - A2.*sin(B2.*x + C2.*t) + y - 0.25)./(2*sqrt(kappa))) + 0.5'\n\n\n\n\n```python\nprint(\"η₀:\")\njulia_code(eta0)\n```\n\n η₀:\n\n\n\n\n\n '-0.5*tanh(sqrt(2)*(-A2.*sin(B2.*x) + y - 0.25)./(2*sqrt(kappa))) + 0.5'\n\n\n\n\n```python\nprint(\"S:\")\njulia_code(S)\n```\n\n S:\n\n\n\n\n\n '(0.5*sqrt(kappa).*tanh(sqrt(2)*(A1.*t.*sin(B1.*x) + A2.*sin(B2.*x + C2.*t) - y + 0.25)./(2*sqrt(kappa))) - 0.25*sqrt(2)*(A1.*sin(B1.*x) + A2.*C2.*cos(B2.*x + C2.*t))).*(tanh(sqrt(2)*(A1.*t.*sin(B1.*x) + A2.*sin(B2.*x + C2.*t) - y + 0.25)./(2*sqrt(kappa))).^2 - 1)./sqrt(kappa)'\n\n\n\n### Mathematica\n\n\n```python\nfrom sympy.printing import mathematica_code\n```\n\n\n```python\nprint(\"α:\")\nmathematica_code(alpha)\n```\n\n α:\n\n\n\n\n\n 'A1*t*Sin[B1*x] + A2*Sin[B2*x + C2*t] + 0.25'\n\n\n\n\n```python\nprint(\"η:\")\nmathematica_code(eta)\n```\n\n η:\n\n\n\n\n\n '-0.5*Tanh[(1/2)*2^(1/2)*(-A1*t*Sin[B1*x] - A2*Sin[B2*x + C2*t] + y - 0.25)/kappa^(1/2)] + 0.5'\n\n\n\n\n```python\nprint(\"η₀:\")\nmathematica_code(eta0)\n```\n\n η₀:\n\n\n\n\n\n '-0.5*Tanh[(1/2)*2^(1/2)*(-A2*Sin[B2*x] + y - 0.25)/kappa^(1/2)] + 0.5'\n\n\n\n\n```python\nprint(\"S:\")\nmathematica_code(S)\n```\n\n S:\n\n\n\n\n\n '(0.5*kappa^(1/2)*Tanh[(1/2)*2^(1/2)*(A1*t*Sin[B1*x] + A2*Sin[B2*x + C2*t] - y + 0.25)/kappa^(1/2)] - 0.25*2^(1/2)*(A1*Sin[B1*x] + A2*C2*Cos[B2*x + C2*t]))*(Tanh[(1/2)*2^(1/2)*(A1*t*Sin[B1*x] + A2*Sin[B2*x + C2*t] - y + 0.25)/kappa^(1/2)]^2 - 1)/kappa^(1/2)'\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "cbf099b9d7fbc519c00c5b6085c2d0d20f2ab358", "size": 40238, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "benchmarks/benchmark7.ipynb", "max_stars_repo_name": "stvdwtt/chimad-phase-field", "max_stars_repo_head_hexsha": "cf0c0b923b7dcfd8eb5785fb778438387194920d", "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": "benchmarks/benchmark7.ipynb", "max_issues_repo_name": "stvdwtt/chimad-phase-field", "max_issues_repo_head_hexsha": "cf0c0b923b7dcfd8eb5785fb778438387194920d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-12T21:47:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-26T16:45:15.000Z", "max_forks_repo_path": "benchmarks/benchmark7.ipynb", "max_forks_repo_name": "stvdwtt/chimad-phase-field", "max_forks_repo_head_hexsha": "cf0c0b923b7dcfd8eb5785fb778438387194920d", "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": 34.9591659427, "max_line_length": 1161, "alphanum_fraction": 0.5381977235, "converted": true, "num_tokens": 7667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.16885694586780495, "lm_q1q2_score": 0.06499508914498427}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\n# Write your imports here\nimport numpy as np\n```\n\n# High-School Maths Exercise\n## Getting to Know Jupyter Notebook. Python Libraries and Best Practices. Basic Workflow\n\n### Problem 1. Markdown\nJupyter Notebook is a very light, beautiful and convenient way to organize your research and display your results. Let's play with it for a while.\n\nFirst, you can double-click each cell and edit its content. If you want to run a cell (that is, execute the code inside it), use Cell > Run Cells in the top menu or press Ctrl + Enter.\n\nSecond, each cell has a type. There are two main types: Markdown (which is for any kind of free text, explanations, formulas, results... you get the idea), and code (which is, well... for code :D).\n\nLet me give you a...\n#### Quick Introduction to Markdown\n##### Text and Paragraphs\nThere are several things that you can do. As you already saw, you can write paragraph text just by typing it. In order to create a new paragraph, just leave a blank line. See how this works below:\n```\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n```\n**Result:**\n\nThis is some text.\nThis text is on a new line, but it will continue the same paragraph (so you can make your paragraphs more easily readable by just continuing on a new line, or just go on and on like this one line is ever continuing).\n\nThis text is displayed in a new paragraph.\n\nAnd this is yet another paragraph.\n\n##### Headings\nThere are six levels of headings. Level one is the highest (largest and most important), and level 6 is the smallest. You can create headings of several types by prefixing the header line with one to six \"#\" symbols (this is called a pound sign if you are ancient, or a sharp sign if you're a musician... or a hashtag if you're too young :D). Have a look:\n```\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n```\n\n**Result:**\n\n# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n\nIt is recommended that you have **only one** H1 heading - this should be the header of your notebook (or scientific paper). Below that, you can add your name or just jump to the explanations directly.\n\n##### Emphasis\nYou can create emphasized (stonger) text by using a **bold** or _italic_ font. You can do this in several ways (using asterisks (\\*) or underscores (\\_)). In order to \"escape\" a symbol, prefix it with a backslash (\\). You can also strike thorugh your text in order to signify a correction.\n```\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not \\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n```\n\n**Result:**\n\n**bold** __bold__\n*italic* _italic_\n\nThis is \\*\\*not\\*\\* bold.\n\nI ~~didn't make~~ a mistake.\n\n##### Lists\nYou can add two types of lists: ordered and unordered. Lists can also be nested inside one another. To do this, press Tab once (it will be converted to 4 spaces).\n\nTo create an ordered list, just type the numbers. Don't worry if your numbers are wrong - Jupyter Notebook will create them properly for you. Well, it's better to have them properly numbered anyway...\n```\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n```\n\n**Result:**\n1. This is\n2. A list\n10. With many\n9. Items\n 1. Some of which\n 2. Can\n 3. Be nested\n42. You can also\n * Mix \n * list\n * types\n \nTo create an unordered list, type an asterisk, plus or minus at the beginning:\n```\n* This is\n* An\n + Unordered\n - list\n```\n\n**Result:**\n* This is\n* An\n + Unordered\n - list\n \n##### Links\nThere are many ways to create links but we mostly use one of them: we present links with some explanatory text. See how it works:\n```\nThis is [a link](http://google.com) to Google.\n```\n\n**Result:**\n\nThis is [a link](http://google.com) to Google.\n\n##### Images\nThey are very similar to links. Just prefix the image with an exclamation mark. The alt(ernative) text will be displayed if the image is not available. Have a look (hover over the image to see the title text):\n```\n\n```\n\n**Result:**\n\n\n\nIf you want to resize images or do some more advanced stuff, just use HTML. \n\nDid I mention these cells support HTML, CSS and JavaScript? Now I did.\n\n##### Tables\nThese are a pain because they need to be formatted (somewhat) properly. Here's a good [table generator](http://www.tablesgenerator.com/markdown_tables). Just select File > Paste table data... and provide a tab-separated list of values. It will generate a good-looking ASCII-art table for you.\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**Result:**\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##### Code\nJust use triple backtick symbols. If you provide a language, it will be syntax-highlighted. You can also use inline code with single backticks.\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 \n \n \n \n
    \n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
    \n\nThe `IonDevice` represents a trapped ion quantum computer with all-to-all qubit connectivity. The number of qubits as well as the duration of gates and measurements are specified by the user when creating an ion device.\n\nTwo-qubit gates are implemented by an Ising-type coupling known as the *Mølmer–Sørensen* gate. The Mølmer–Sørensen gate couples ions through the shared motional modes of the ion chain. The ion motion and internal state decouples at the end of each gate. The `IonDevice` class assumes this decoupling is perfect and does not explicitly model the ion motion. \n\n\n```\ntry:\n import cirq\nexcept ImportError:\n print(\"installing cirq...\")\n !pip install cirq --quiet\n print(\"installed cirq.\")\n import cirq\n\nimport numpy as np\n```\n\n## Defining an `IonDevice`\n\nTo define an `IonDevice`, we specify\n\n- The set of qubits in the device,\n- The duration of single-qubit gates,\n- The duration of two-qubit gates, and\n- The duration of measurement gates.\n\nThe code below creates an `IonDevice` with four qubits in a linear array. The durations we use for each type of gate are reasonable order-of-magnitude estimates, though they will differ for different trapped ion computers.\n\n\n```\n\"\"\"Create an IonDevice.\"\"\"\nion_device = cirq.IonDevice(\n qubits=cirq.LineQubit.range(4),\n oneq_gates_duration=cirq.Duration(micros=10),\n twoq_gates_duration=cirq.Duration(micros=200),\n measurement_duration=cirq.Duration(micros=100)\n)\n```\n\nWe can view some properties of the `ion_device` as shown below.\n\n\n```\n\"\"\"View some properties of the device.\"\"\"\n# Display the ion device.\nprint(\"Ion Device:\\n\", ion_device)\n\n# Get all qubits in the device.\nprint(\"\\nQubits in the IonDevice:\\n\", sorted(ion_device.qubits))\n\n# Get a qubit at a certain position (if present).\npos = 2\nprint(f\"\\nQubit at position {pos}:\\n\", ion_device.at(pos))\n```\n\n Ion Device:\n 0───1───2───3\n \n Qubits in the IonDevice:\n [cirq.LineQubit(0), cirq.LineQubit(1), cirq.LineQubit(2), cirq.LineQubit(3)]\n \n Qubit at position 2:\n 2\n\n\n## Native Gate Set\n\nAn `IonDevice` can implement single-qubit rotations about the $X$, $Y$, and $Z$ axes of the Bloch sphere: namely, `cirq.rx`, `cirq.ry`, and `cirq.rz`. \n\nAn `IonDevice` can implement the two-qubit Mølmer–Sørensen gate, a rotation about the $XX$ axis in the two-qubit Bloch sphere defined as\n\n\\begin{equation}\n \\exp(-i t XX) = \\left[ \\begin{matrix}\n \\cos t & 0 & 0 & -i \\sin t \\\\\n 0 & \\cos t & -i \\sin t & 0 \\\\\n 0 & -i \\sin t & \\cos t & 0 \\\\\n -i \\sin t & 0 & 0 & \\cos t\n \\end{matrix} \\right] .\n\\end{equation}\n\nThe Mølmer–Sørensen gate is defined in Cirq as `cirq.ms`.\n\nOne can check if a given gate is valid with `IonDevice.validate_gate`. This method raises an error if the gate is invalid (not supported by the device) and does nothing if the gate is valid (supported by the device).\n\n\n```\n\"\"\"Check if gates are valid. Invalid gates raise a ValueError.\"\"\"\n# Single-qubit X rotation of any angle is supported.\nion_device.validate_gate(cirq.rx(np.pi / 7))\n\n# Single-qubit Z rotation of any angle is supported.\nion_device.validate_gate(cirq.rz(np.pi / 5))\n\n# Mølmer–Sørensen gate of any angle is supported.\nion_device.validate_gate(cirq.ms(np.pi / 4))\n```\n\nOne can also validate operations and circuits with `IonDevice.validate_operation` and `IonDevice.validate_circuit`, respectively.\n\nWe can get the duration of valid operations as follows.\n\n\n```\n\"\"\"Get the duration of valid operations.\"\"\"\n# Duration of a single-qubit operation.\nion_device.duration_of(cirq.ry(np.pi / 2).on(ion_device.at(0)))\n```\n\n\n\n\n cirq.Duration(micros=10)\n\n\n\n## Decomposing Operations and Circuits\n\nOperations which are not valid on the device can be decomposed into a set of valid operations. For example, a CNOT gate is not supported but can be implemented with the following decomposition.\n\n\n```\n\"\"\"Decompose a CNOT operation into valid IonDevice operations.\"\"\"\n# Get a CNOT operation.\nop = cirq.CNOT(ion_device.at(0), ion_device.at(1))\n\n# Decompose it for the IonDevice.\nion_device_ops = cirq.ConvertToIonGates().convert_one(op)\n\n# Print the sequence of operations to implement a CNOT.\nprint(\"Sequence of IonDevice operations for a CNOT:\\n\")\nprint(cirq.Circuit(ion_device_ops))\n```\n\n Sequence of IonDevice operations for a CNOT:\n \n 0: ───Ry(0.5π)───MS(0.25π)───Rx(-0.5π)───Ry(-0.5π)───\n │\n 1: ──────────────MS(0.25π)───Rx(-0.5π)───────────────\n\n\nCircuits can also be decomposed in a similar manner using `IonDevice.decompose_circuit`.\n\n\n```\n\"\"\"Decompose a circuit into IonDevice operations.\"\"\"\n# Example circuit to decompose.\ncircuit = cirq.Circuit(\n cirq.H(cirq.LineQubit(0)),\n cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(1)),\n cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(2))\n)\n\n# Display it.\nprint(\"Circuit to decompose:\\n\")\nprint(circuit)\n\n# Decompose the circuit.\nion_device_circuit = ion_device.decompose_circuit(circuit)\n\n# Display the decomposed circuit.\nprint(\"\\nIonDevice circuit:\\n\")\nprint(ion_device_circuit)\n```\n\n Circuit to decompose:\n \n 0: ───H───@───@───\n │ │\n 1: ───────X───┼───\n │\n 2: ───────────X───\n \n IonDevice circuit:\n \n 0: ───PhX(1)───────────MS(0.25π)───PhX(1)^0.5───────────MS(0.25π)───PhX(-0.5)^0.5───S^-1───\n │ │\n 1: ────────────────────MS(0.25π)───PhX(1)^0.5───────────┼──────────────────────────────────\n │\n 2: ─────────────────────────────────────────────────────MS(0.25π)───PhX(1)^0.5─────────────\n\n", "meta": {"hexsha": "784cc9660a9a3188d6006aadc27b228f604ebda4", "size": 11964, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/educators/ion_device.ipynb", "max_stars_repo_name": "pavoljuhas/Cirq", "max_stars_repo_head_hexsha": "b6d6577be61d216ce2f29f8c64ae5879cf3087d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T22:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T22:17:39.000Z", "max_issues_repo_path": "docs/tutorials/educators/ion_device.ipynb", "max_issues_repo_name": "pavoljuhas/Cirq", "max_issues_repo_head_hexsha": "b6d6577be61d216ce2f29f8c64ae5879cf3087d5", "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/ion_device.ipynb", "max_forks_repo_name": "pavoljuhas/Cirq", "max_forks_repo_head_hexsha": "b6d6577be61d216ce2f29f8c64ae5879cf3087d5", "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": 29.4679802956, "max_line_length": 364, "alphanum_fraction": 0.5443831494, "converted": true, "num_tokens": 1953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12940271984052937, "lm_q1q2_score": 0.06470135992026468}} {"text": "

    Dinámica

    \n

    Capítulo 1: Cinemática y Cinética de partículas

    \n

    Movimiento rectilíneo

    \n

    2021/02

    \n

    MEDELLÍN - COLOMBIA

    \n\n\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***Docente:*** Carlos Alberto Álvarez Henao, I.C. D.Sc.\n\n***e-mail:*** carlosalvarezh@gmail.com\n\n***skype:*** carlos.alberto.alvarez.henao\n\n***Linkedin:*** https://www.linkedin.com/in/carlosalvarez5/\n\n***github:*** https://github.com/carlosalvarezh/Dinamica\n\n***Herramienta:*** [Jupyter](http://jupyter.org/)\n\n***Kernel:*** Python 3.9\n\n\n***\n\n

    Tabla de Contenidos

    \n\n\n

    \n \n

    \n\n
    Fuente: Engineer4Free
    \n\n\n***Introducción***\n\nEstas notas son extraídas principalmente de los textos de Dinámica de [Hibbeler](https://www.pearson.com/us/higher-education/product/Hibbeler-Engineering-Mechanics-Dynamics-14th-Edition/9780133915389.html) y [Beer&Johnston](https://www.amazon.com/Vector-Mechanics-Engineers-Ferdinand-Beer/dp/0077402324), así como también de la revisión de extensa literatura en internet. Las referencias se indicarán en cada apartado. Se hace uso de la herramienta [Jupyter Notebook](https://jupyter.org/) empleando el lenguaje de programación [python](https://python.org/) en la versión estable más reciente\n\n\n\n## Dinámica\n\nParte de la física que estudia la relación existente entre las fuerzas que actúan sobre un cuerpo y los efectos que se producirán sobre el movimiento de ese cuerpo.\n\n

    \n \n

    \n\n
    Fuente: Engineer4Free
    \n\n\n### Ubicación de la dinámica en la Física\n\n\n

    \n \n

    \n\n
    Fuente: Wikisabio
    \n\n\n### Definiciones\n\n- ***Mecánica:*** Se ocupa del estado de reposo o movimiento de cuerpos sometidos a la acción de fuerzas.\n\n\n- ***Estática:*** Se ocupa del equilibrio de un cuerpo que está en reposo o que se mueve con velocidad constante. \n\n\n- ***Dinámica:*** Se ocupa del movimiento acelerado de un cuerpo. \n\n\n- ***Cinemática:*** Trata sólo los aspectos geométricos del movimiento.\n\n\n- ***Cinética:*** Analiza las fuerzas que provocan el movimiento.\n\n\nPara desarrollar estos principios, primero se analizará la dinámica de una partícula, y a continuación se abordarán temas de dinámica de un cuerpo rígido en dos y luego en tres dimensiones.\n\n### Estrategia para la solución de problemas\n\n- Lea el problema con cuidado y trate de correlacionar la situación física real con la teoría que haya estudiado.\n\n\n- Trace todos los diagramas necesarios y tabule los datos del problema.\n\n\n- Establezca un sistema de coordenadas y aplique los principios pertinentes, casi siempre en forma matemática.\n\n\n- Resuelva de manera algebraica las ecuaciones necesarias hasta donde sea práctico; luego, utilice un conjunto consistente de unidades y complete la solución numéricamente. Reporte la respuesta sin más cifras significativas que la precisión de los datos dados.\n\n\n- Estudie la respuesta con juicio técnico y sentido común para determinar si parece o no razonable.\n\n\n- Una vez completadas las soluciones, repase el problema. Trate de pensar en otras formas de obtener la misma solución.\n\n\n## Cinemática rectilínea - Movimiento continuo\n\n### Consideraciones\n\n

    \n \n

    \n\n
    Fuente: Pinterest
    \n\n\n- Los cuerpos se consideran de tamaño finito, como partícula, y el movimiento del cuerpo como un todo se caracteriza por el movimiento de su centro de masa, sin rotación.\n\n\n- Se considera la partícula con masa, y su tamaño y forma son indiferentes.\n\n\n- Se presenta la partícula moviéndose a lo largo de una trayectoria rectilínea.\n\n\n- La cinemática de una partícula se caracteriza al especificar, en cualquier instante, su posición, desplazamiento, velocidad y aceleración.\n\n### Posició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\n\n
    \n\n\n\n

    El 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\nVamos a resolver el ejemplo de dos formas: Analítica y computacionalmente.\n\n\n***Solución analítica:***\n\n- ***Sistema de coordenadas:*** Se establece el sistema de coordenadas en sentido horizontal, con origen en el punto $O$, positivo a la derecha.\n\n\n- ***Posición:*** como la velocidad es una función del tiempo, $\\textbf{v}=f(t)$, la posición se determina de la [(Ec1.3)](#Ec1_3). Reemplazando\n\n$$\\textbf{v}=3t^2 + 2t=\\frac{ds}{dt}$$\n\nrealizando la separación de variables e integrando el espacio, $s$, entre $0$ y $s$ y el tiempo, $t$, entre $0$ y $t$:\n\n$$\\int_0^s ds=\\int_0^t(3t^2+2t)dt$$\n\n$$\\left. s\\right|_0^s= \\left. t^3+t^2 \\right|_0^t$$\n\ncuando $t=3 s$\n\n$$s(3)=3^3+3^2 =36 pies$$\n\n\n- ***Aceleración***\nLa aceleración también es función del tiempo y se determina de ecuación [(Ec1.5)](#Ec1_5).\n\n$$\\textbf{a}=\\frac{d(3t^2 + 2t)}{dt}=\\frac{d\\textbf{v}}{dt}$$\n\nrealizando la separación de variables e integrando:\n\n$$\\textbf{a}=6t+2$$\n\ncuando $t=3 s$\n\n$$a(3)=6(3)+2=20 \\text{pies/s}^2$$ \n\n***Solución computacional:***\n\nAhora vamos a resolver el ejemplo computacionalmente empleando el módulo [`sympy`](https://www.sympy.org/en/index.html) de `python`. Primero, se carga el módulo de cálculo simbólico, que nos permitirá obtener expresiones analíticas de la posición y la aceleración, que serán evaluadas en el tiempo solicitado. Para la impresión de algunos resultados de forma analítica se empleará el módulo [`mathjax`](https://www.mathjax.org/).\n\n\n```python\nfrom sympy import *\nt = symbols('t')\ninit_printing(use_latex='mathjax')\n```\n\nGeneramos una expresión para la función velocidad, como fue dada en el enunciado\n\n\n```python\ndef v(t):\n \n \"\"\"\n Función velocidad\n función para determinar la velocidad en función del tiempo, t.\n \n Input:\n Cadena de caracteres en donde t es la varible.\n \n Output:\n Cadena de caracteres.\n \n Ejemplo:\n 3 * t**2 + 2 * t\n \"\"\"\n\n # Ingresando la función a través del teclado (descomentar las dos líneas siguientes y comentar la última línea)\n #veloc = input(\"Ingrese la función correspondiente a la velocidad, v(t): \")\n #return veloc\n\n # escribiendo la función directamente dentro del módulo (comentar las dos líneas anteriores)\n return 3 * t**2 + 2 * t\n```\n\n\n```python\nhelp(v)\n```\n\nVisualizando la integral de la velocidad a ser calculada de forma analítica\n\n\n```python\nIntegral(v(t),(t,0,t))\n```\n\nIntegrando analíticamente la expresión de la velocidad, para obtener una expresión de la posición:\n\n\n```python\npos = integrate(v(t),(t,0,t))\npos\n```\n\nEvaluando la expresión del espacio obtenida con la integración, en $t=3s$\n\n\n```python\nprint(\"La posición que tendrá el vehículo despues de 3 seg será de {0} pies\".format(pos.subs(t,3)))\n```\n\nAhora vamos a determinar una expresión para la aceleración, derivando la expresión dada de la velocidad \n\n\n```python\nacel = diff(v(t),t)\nprint(acel)\n```\n\nPor último, evaluamos la expresión de la aceleración obtenida con la derivada de la velociad respecto al tiempo, en $t=3s$\n\n\n```python\nprint(\"La aceleración del vehículo después de 3 seg es {0} pies/s^2\".format(acel.subs(t,3)))\n```\n\nCompactando en una única celda el código visto:\n\n\n```python\nfrom sympy import *\nt = symbols('t')\n\n# definición de la función a evaluar\ndef v(t):\n return 3 * t**2 + 2 * t\n\n# posición\npos = integrate(v(t),(t,0,t))\nprint(\"La posición que tendrá el vehículo despues de 3 seg será de {0} pies\".format(pos.subs(t,3)))\n\n# aceleración\nacel = diff(v(t),t)\nprint(\"La aceleración del vehículo después de 3 seg es {0} pies/s^2\".format(acel.subs(t,3)))\n```\n\n#### Altura máxima cohete\n\n \n \n\n\n\n
    \n\n

    Durante 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\nIgual que el ejemplo anterior, se dará solución analítica y computacional.\n\n\n***Solución analítica:***\n\n- ***Sistema de coordenadas:*** Se establecerá el origen de coordenadas a nivel del suelo. \n\n\n- ***Altura máxima:*** Del enunciado se establece que el cohete está a una distancia de $s_A=40m$ del suelo, con una velocidad $v_A = +75m/s$ cuando el motor falla, que es cuando se empieza a tomar el tiempo, es decir, $t=0$. La aceleración que experimenta el cohete es debida a la gravedad, $a_c=-9.81m/s^2$ (negativa pues actúa en sentido contrario al desplazamiento y velocidad). Como la aceleración es constante, la posición y velocidad del cohete se pueden relacionar directamente mediante la [Ec. 1.9](#Ec1_9), donde $A$ y $B$ son los puntos inicial y final (de máxima altura) respectivamente.\n\n$$v_B^2=v_A^2+2a_c(s_B-s_A)$$\n\nLa velocidad en el punto $B$ es cero. Reemplazando valores se tiene:\n\n$$0=(75m/s)^2+2(-9.81m/s^2)(s_B-40m)$$\n\ny despejando para el valor de $s_B$\n\n$$s_B=327m$$\n\n\n- ***Velocidad:*** La velocidad final del cohete (justo antes de chocar con la tierra), punto $C$, también se puede determinar de la [Ec. 1.9](#Ec1_9). En este caso el punto $B$ será el inicial.\n\n$$v_C^2=v_B^2+2a_c(s_C-s_B)$$\n\nLa velocidad en el punto $B$ y la distancia en el punto $C$ son cero. Reemplazando valores se tiene:\n\n$$v_C=\\pm \\sqrt{(0)^2+2(-9.81m/s^2)(0-327m)}$$\n\ny calculando para el valor de $v_C$\n\n$$v_C=-80.1m/s$$\n\nSe selecciona la raíz negativa pues el cohete está descendiendo.\n\n\n***Solución computacional:*** Se deja al estudiante intentar una solución empleando programación con `python`.\n\n#### Partícula en campo magnético\n\n \n \n\n\n\n
    \n\n

    Una 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\n***Solución analítica:***\n\n- ***Sistema de coordenadas:*** Positivo hacia abájo (dirección del desplazamiento)\n\n\n- ***Velocidad:*** Como la aceleración es dada en función del espacio, $a=f(s)$, podemos deivar la ecuación de la velocidad a partir de la [Ec. 1.6](#Ec1_6), con condiciones iniciales $v=0$ en $s=0.1m$, entonces:\n\n$$vdv=ads$$\n\nintegrando a ambos lados, con los límites de integración correspondientes, se tien:\n\n$$\\int_0^v vdv=\\int_{0.1}^s 4s ds$$\n\n$$\\left. \\frac{1}{2}v^2 \\right |_0^v = \\left . \\frac{4}{2} s^2 \\right|_{0.1}^s$$\n\n$$v=\\pm 2 \\sqrt{(s^2-0.01)} m/s$$\n\nevaluando en $s=200 mm = 0.2 m$ se tiene\n\n$$v_B=0.346 m/s=346 mm/s$$\n\nse escoge la raíz positiva pues va en la dirección del movimiento.\n\n\n- ***Tiempo:*** El tiempo de desplazamiento de $C$ a $B$ se obtiene de la [Ec. 1.3](#Ec1_3). Reemplazando la expresión del espacio, cuando $s=0.1m$ en $t=0$\n\n$$ds=vdt=\\pm 2 \\sqrt{(s^2-0.01)}dt$$\n\nintegrando\n\n$$\\int_{0.1}^s \\frac{ds}{2 \\sqrt{s^2-0.01}}=\\int_0^t dt$$\n\n$$\\left. Ln \\left( 2 \\sqrt{s^2-0.01} + s \\right) \\right|_{0.1}^s=\\left. t \\right|_0^t$$\n\n$$Ln \\left( 2 \\sqrt{s^2-0.01} + s \\right) +2.303 = t$$\n\nevaluando en $s=0.2 m$\n\n$$t=\\frac{Ln \\left( 2 \\sqrt{(0.2)^2-0.01} + 0.2 \\right) +2.303 }{2}=0.658s$$\n\n***Solución computacional***\n\n- ***Velocidad:***\n\nAhora vamos a plantear la solución computacional como en el primer ejemplo. Para encontrar una expresión analítica para la velocidad debemos integrar la ecuacíón $vdv=ads$. \n\n\n```python\nfrom sympy import *\nt, x = symbols('t x')\na, v, s = symbols('a v s') #, cls = Function)\ninit_printing(use_latex='mathjax')\n```\n\nEn este ejemplo se ofrece una función para la aceleración dada por $a=(4s) m/s$. Generaremos una variable en python para la aceleración\n\n\n```python\na = 4 * s\n```\n\nintegrando a ambos lados de la ecuación\n\n\n```python\nveloc = Eq(integrate(v, (v, 0, v)), integrate(a, (s, 0.1, s)))\nveloc\n```\n\nResolviendo para la variable $v$\n\n\n```python\nveloc = solve(veloc,v)\nveloc\n```\n\nevaluando en $s=0.2 m$, para la raíz positiva (posición 1 de la lista), se tiene\n\n\n```python\nprint(\"La velocidad de caída de la partícula es {0:3.0f} mm/s\".format(veloc[1].subs(s,0.2)*1000))\n```\n\n- ***tiempo:*** Siguiendo lo presentado en la solución analítica\n\n\n```python\nspace = Eq(integrate(1/(veloc[1]),(s, 0.1, s)), integrate(1, (t, 0, t)))\nspace\n```\n\n\n```python\ntime = solve(space,t)\ntime\n```\n\n\n```python\nprint(\"El tiempo de caída de la partícula es {0:3.3f} s\".format(time[0].subs(s,0.2)))\n```\n\n## Cinemática rectilínea: Movimiento variable\n\nCuando el movimiento de una partícula es variable, su *posición*, *velocidad* y *aceleración* no pueden describirse mediante una sola función matemática continua a lo largo de toda la trayectoria. En su lugar, se requerirá una serie de funciones para especificar el movimiento en diferentes intervalos. Por eso, conviene representar el movimiento como una gráfica. Si se puede trazar una gráfica del movimiento que relacione dos de las variables $s$, $v$, $a$, $t$, entonces esta gráfica puede utilizarse para construir gráficas subsecuentes que relacionen otras dos variables, puesto que las variables están relacionadas por las relaciones diferenciales $v = ds/dt$, $a=dv/dt$ o $ads=vdv$. Con frecuencia ocurren varias situaciones.\n\n### Gráficas de $s-t$, $v-t$ y $a-t$\n\n \n \n\n\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\n \n \n\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\n \n \n\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\n \n \n\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\n### Gráficas de $v-s$ y $a-s$\n\n \n \n\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\n \n \n\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### Ejemplos\n\n#### Desplazamiento en bicicleta\n\n \n \n\n\n\n
    \n\n

    Una 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***Solución analítica:***\n\n \n \n\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 \n \n\n\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***Solución computacional:***\n\nIgual que en los primeros ejemplos, se empleará el módulo `sympy` de `python` para realizar los cálculos correspondientes, de forma computacional.\n\n\n```python\nfrom sympy import *\nimport seaborn as sns\nt = symbols('t')\ninit_printing(use_latex='mathjax')\n```\n\n\n```python\n# definición de las funciones a evaluar\ndef s1(t):\n return t**2\n\ndef s2(t):\n return 20 * t - 100\n```\n\n\n```python\n# Gráfica s-t\nsns.set()\nsns.set_style(\"whitegrid\", {'grid.linestyle': '--'})\nplot((s1(t), (t,0,10)), (s2(t), (t,10,30)));\n```\n\n\n```python\n#Gráfica v-t\nplot((diff(s1(t),t), (t,0,10)), (diff(s2(t),t), (t,10,30)));\n```\n\n\n```python\n#Gráfica a-t\nplot((diff(s1(t),t,2), (t,0,10)), (diff(s2(t),t,2), (t,10,30)));\n```\n\n[nbviewer](https://nbviewer.jupyter.org/github/carlosalvarezh/Dinamica/blob/main/C01_CinematicaCineticaParticulas.ipynb)\n", "meta": {"hexsha": "e66e532e174cbb3b72a4e0065dddaa6879b63930", "size": 57030, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "C01_CinematicaCineticaParticulas_MovRectilineo.ipynb", "max_stars_repo_name": "carlosalvarezh/Dinamica", "max_stars_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "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": "C01_CinematicaCineticaParticulas_MovRectilineo.ipynb", "max_issues_repo_name": "carlosalvarezh/Dinamica", "max_issues_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "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": "C01_CinematicaCineticaParticulas_MovRectilineo.ipynb", "max_forks_repo_name": "carlosalvarezh/Dinamica", "max_forks_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-28T18:47:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T18:47:37.000Z", "avg_line_length": 37.9693741678, "max_line_length": 5003, "alphanum_fraction": 0.5884446782, "converted": true, "num_tokens": 12271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.22270012850745968, "lm_q1q2_score": 0.0640859295502975}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n```\n\n\n```python\nfrom plotnine import *\n```\n\n\n```python\nclass theme_fs(theme_light):\n \"\"\"\n A theme similar to :class:`theme_linedraw` but with light grey\n lines and axes to direct more attention towards the data.\n Parameters\n ----------\n base_size : int, optional\n Base font size. All text sizes are a scaled versions of\n the base font size. Default is 11.\n base_family : str, optional\n Base font family.\n \"\"\"\n\n def __init__(self, base_size=11, base_family='DejaVu Sans'):\n theme_light.__init__(self, base_size, base_family)\n self.add_theme(theme(\n axis_ticks=element_line(color='#DDDDDD', size=0.5),\n panel_border=element_rect(fill='None', color='#838383',\n size=1),\n strip_background=element_rect(\n fill='#DDDDDD', color='#838383', size=1),\n strip_text_x=element_text(color='black'),\n strip_text_y=element_text(color='black', angle=-90),\n legend_key=element_blank(),\n ), inplace=True)\n```\n\n\n```python\ndf = pd.read_csv('./data/settles.acl16.learning_traces.13m.csv.gz')\ndf['delta_days'] = df['delta'].apply(lambda d: d / (60 * 60 * 24))\n```\n\n\n```python\n# df = df.head(3000)\n```\n\n\n```python\n(\n ggplot(df)\n + geom_bar(\n aes(x='p_recall'),\n stat=stat_bin(bins=100),\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df)\n + geom_bar(\n aes(x='delta_days'),\n stat=stat_bin(bins=100),\n fill='blue',\n alpha=0.5\n )\n + scale_y_log10()\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df.loc[df.delta_days < 50])\n + geom_bar(\n aes(x='delta_days'),\n stat=stat_bin(bins=100),\n fill='blue',\n alpha=0.5\n )\n + scale_y_log10()\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df)\n + geom_bar(\n aes(x='history_seen'),\n stat=stat_bin(bins=100),\n fill='blue',\n alpha=0.5\n )\n + scale_y_log10()\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df.loc[df.history_seen < 50])\n + geom_bar(\n aes(x='history_seen'),\n stat=stat_bin(bins=50),\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df)\n + geom_bar(\n aes(x='history_correct'),\n stat=stat_bin(bins=100),\n fill='blue',\n alpha=0.5\n )\n + scale_y_log10()\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df.loc[df.history_correct < 50])\n + geom_bar(\n aes(x='history_correct'),\n stat=stat_bin(bins=50),\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df)\n + geom_bar(\n aes(x='session_seen'),\n stat=stat_bin(bins=15),\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n)\n```\n\n\n```python\n(\n ggplot(df)\n + geom_bar(\n aes(x='session_correct'),\n stat=stat_bin(bins=15),\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n)\n```\n\n\n```python\ndef _bin_p_recall(group):\n return pd.DataFrame([{'p_recall': group.p_recall.mean()}])\n(\n ggplot(\n df.groupby(\n pd.qcut(df.delta_days, 20)\n ).apply(_bin_p_recall).reset_index()\n )\n + geom_bar(\n aes(x='delta_days', y='p_recall', ymin=0.75, ymax=1.0),\n stat='identity',\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n + theme(\n axis_text_x=element_text(rotation=90)\n )\n)\n```\n\n## reliability diagram, expected calibration error\n\nIn multi-class classification setting, the general idea of calibration is that confidence should match accuracy, i.e. when the model is 60% confidence, the probability of it being correct should be 60%.\n\nreliability diagram: bin validation examples by predicted probability, then calculate the average accuracy within each bin, plot average accuracy against confidence. ideal calibration should be a diagonal line.\n\nexpected calibration error (ECE): the difference in expectation between confidence and accuracy is\n$$\\mathbb{E}_{\\hat{P}}[|\\mathbb{P}(\\hat{Y}=Y|\\hat{P}=p)-p)|$$\nThis can be approximated by a weighted average of bins' accuracy - confidence difference (the gap showns as red bars in reliability diagrams)\n$$\\text{ECE}=\\sum_{i}\\frac{|B_i|}{n}|\\text{acc}(B_m)-\\text{conf}(B_m)|$$\n\n\n```python\nresults = pd.read_csv('./results/hlr.settles.acl16.learning_traces.13m.preds', delimiter='\\t')\n```\n\n\n```python\ndef _bin_prediction(group):\n return pd.DataFrame([{'prediction': group.pp.mean()}])\n\n(\n ggplot(\n results.groupby(\n pd.cut(results.p, 20)\n ).apply(_bin_prediction).reset_index()\n )\n + geom_bar(\n aes(x='p', y='prediction'),\n stat='identity',\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n + theme(\n axis_text_x=element_text(rotation=90)\n )\n)\n```\n\n\n```python\ndef _bin_rmse(group):\n return pd.DataFrame([{\n 'rmse': ((group.pp - group.p) ** 2).mean() ** (1/2)\n }])\n\n(\n ggplot(\n results.groupby(\n pd.cut(results.pp, 20)\n ).apply(_bin_rmse).reset_index()\n )\n + geom_bar(\n aes(x='pp', y='rmse'),\n stat='identity',\n fill='blue',\n alpha=0.5\n )\n + theme_fs()\n + theme(\n axis_text_x=element_text(rotation=90)\n )\n)\n```\n\nWhen our model directly predicts the probability, instead of using ECE, we can directly measure the miscalibration\n$$\\text{ECE}=\\sum_i\\frac{|B_i|}{n}|\\text{precition}(B_i) - \\text{ground_truth}(B_i)|$$\n\n\n```python\ndef _bin_miscalibration(group):\n return pd.DataFrame([{\n 'miscalibration': (group.pp - group.p).abs().mean(),\n 'prediction': group.pp.mean(),\n 'ground_truth': group.p.mean()\n }])\n\nmiscalibration = results.groupby(pd.cut(results.p, 16)).apply(_bin_miscalibration).reset_index()\n\nprint('expected calibration error', miscalibration.miscalibration.mean())\n\n(\n ggplot(miscalibration)\n + geom_bar(\n aes(x='p', y='ground_truth'),\n stat='identity',\n fill='blue',\n alpha=1.0\n )\n + geom_bar(\n aes(x='p', y='prediction'),\n stat='identity',\n fill='red',\n color='red',\n alpha=0.3\n )\n + theme_fs()\n + theme(\n axis_text_x=element_text(rotation=90)\n )\n)\n```\n\n## Half-life regression (HLR)\n\nshort-hand for each record \\begin{align}<\\cdot>&=<\\Delta,x,P[\\text{recall}]\\in[0,1]>\\\\&=<\\Delta,x,y\\in\\{0,1\\}>\\end{align}\n\nRegression against recall probability $$l_\\text{recall}(<\\cdot>;\\theta)=(p-f_\\theta(x,\\Delta))^2$$\n\nRegression against back-solved half-life $$l_\\text{half-life}(<\\cdot>;\\theta)=(\\frac{-\\Delta}{\\log_2{p}}-f_\\theta(x,\\Delta))^2$$\n\nBinary recall classification $$l_\\text{binary}(<\\cdot>;\\theta)=\\text{xent}(f_\\theta(x,\\Delta),y)$$\n\nAssume that half-life increases exponentially with each repeated exposure, with a linear approximator, you get $f_\\theta(x,\\Delta)=2^{\\theta\\cdot x}$. Use this parameterization with regression against both recall probability and back-solved half-life, you get Settles' formulation:\n$$l(<\\cdot>; \\theta)=(p-2^{\\frac{\\Delta}{2^{\\theta\\cdot x}}})^2+\\alpha(\\frac{\\Delta}{\\log_2(p)}-2^{\\theta\\cdot{x}})^2+\\lambda|\\theta|_2^2$$\n\nNote that this formulation incorporates two heuristics\n1. the memory strength follows an exponential forgetting curve, hence the half-life\n2. half-life increases exponentially with number of repetitions\n\nBut in their code the `history_seen` and `history_seen_correct` feature are squre-rooted, so essentially throwing away the second heuristic.\n\n\n```python\nsplitpoint = int(0.9 * len(df))\ntrain_df, test_df = df.iloc[:splitpoint], df.iloc[splitpoint:]\n```\n\n\n```python\ndf1 = pd.DataFrame({\n 'pp': results.pp.tolist(),\n 'hh': results.hh.tolist(),\n 'p': results.p.tolist(),\n 'h': results.h.tolist(),\n 'history_seen': test_df.history_seen.tolist(),\n 'history_correct': test_df.history_correct.tolist(),\n 'session_seen': test_df.session_seen.tolist(),\n 'session_correct': test_df.session_correct.tolist(),\n 'delta_days': test_df.delta_days.tolist(),\n})\n```\n\n\n```python\ndef _bin_delta(group):\n return pd.DataFrame([{\n 'prediction': group.pp.mean(),\n 'ground_truth': group.p.mean(),\n 'delta': group.delta_days.mean(),\n }])\n\n(\n ggplot(\n df1.groupby(\n pd.cut(df1.delta_days, 16)\n ).apply(_bin_delta).reset_index()\n )\n + geom_bar(\n aes(x='delta', y='ground_truth'),\n stat='identity',\n fill='blue',\n alpha=0.3\n )\n + geom_bar(\n aes(x='delta', y='prediction'),\n stat='identity',\n fill='red',\n color='red',\n alpha=0.3\n )\n + theme_fs()\n + theme(\n axis_text_x=element_text(rotation=90)\n )\n)\n```\n\n\n```python\ndef _bin_history_seen(group):\n return pd.DataFrame([{\n 'prediction': group.pp.mean(),\n 'ground_truth': group.p.mean(),\n 'seen': group.history_seen.mean(),\n }])\n\n_df1 = df1.loc[df1.history_seen < 100]\n\n(\n ggplot(\n _df1.groupby(\n pd.cut(_df1.history_seen, 30)\n ).apply(_bin_history_seen).reset_index()\n )\n + geom_bar(\n aes(x='seen', y='ground_truth'),\n stat='identity',\n fill='blue',\n alpha=0.3\n )\n + geom_bar(\n aes(x='seen', y='prediction'),\n stat='identity',\n fill='red',\n color='red',\n alpha=0.3\n )\n + theme_fs()\n + theme(\n axis_text_x=element_text(rotation=90)\n )\n)\n```\n\nThere are several knobs to be tweaked in the general formulation:\n- labels: derived $p$, binary $y$\n- linear, nn\n- on/off: exponentially increased half-life\n- on/off: loss wrt back-solved half-life (from derived $p$)\n\n\n```python\n\n```\n", "meta": {"hexsha": "60442a2a44607a55d84271ad0f3c49e6fa26e03a", "size": 359002, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "analysis.ipynb", "max_stars_repo_name": "ihsgnef/duolingo-halflife-regression", "max_stars_repo_head_hexsha": "01c7895eee0450462b5277a055d2ae1de58f1be5", "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": "analysis.ipynb", "max_issues_repo_name": "ihsgnef/duolingo-halflife-regression", "max_issues_repo_head_hexsha": "01c7895eee0450462b5277a055d2ae1de58f1be5", "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": "analysis.ipynb", "max_forks_repo_name": "ihsgnef/duolingo-halflife-regression", "max_forks_repo_head_hexsha": "01c7895eee0450462b5277a055d2ae1de58f1be5", "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": 382.3237486688, "max_line_length": 48140, "alphanum_fraction": 0.9328053883, "converted": true, "num_tokens": 2670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.1384617834587191, "lm_q1q2_score": 0.06383320546797798}} {"text": "```python\n#format the book\n%matplotlib inline\nfrom __future__ import division, print_function\nimport sys;sys.path.insert(0,'..')\nfrom book_format import load_style;load_style('..')\n```\n\n\n\n\n\n\n\n\n\n\n# Computing and plotting PDFs of discrete data\n\nSo let's investigate how to compute and plot probability distributions.\n\n\nFirst, let's make some data according to a normal distribution. We use `numpy.random.normal` for this. The parameters are not well named. `loc` is the mean of the distribution, and `scale` is the standard deviation. We can call this function to create an arbitrary number of data points that are distributed according to that mean and std.\n\n\n```python\nimport numpy as np\nimport numpy.random as random\n\nmean = 3\nstd = 2\n\ndata = random.normal(loc=mean, scale=std, size=50000)\nprint(len(data))\nprint(data.mean())\nprint(data.std())\n```\n\n 50000\n 3.00067325106\n 2.00433280075\n\n\nAs you can see from the print statements we got 5000 points that have a mean very close to 3, and a standard deviation close to 2.\n\nWe can plot this Gaussian by using `scipy.stats.norm` to create a frozen function that we will then use to compute the pdf (probability distribution function) of the Gaussian.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n\ndef plot_normal(xs, mean, std, **kwargs):\n norm = stats.norm(mean, std)\n plt.plot(xs, norm.pdf(xs), **kwargs)\n\nxs = np.linspace(-5, 15, num=200)\nplot_normal(xs, mean, std, color='k')\n```\n\nBut we really want to plot the PDF of the discrete data, not the idealized function.\n\nThere are a couple of ways of doing that. First, we can take advantage of `matplotlib`'s `hist` method, which computes a histogram of a collection of data. Normally `hist` computes the number of points that fall in a bin, like so:\n\n\n```python\nplt.hist(data, bins=200)\nplt.show()\n```\n\nthat is not very useful to us - we want the PDF, not bin counts. Fortunately `hist` includes a `normed` parameter which will plot the PDF for us.\n\n\n```python\nplt.hist(data, bins=200, normed=True)\nplt.show()\n```\n\nI may not want bars, so I can specify the `histtype` as 'step' to get a line.\n\n\n```python\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nplt.show()\n```\n\nTo be sure it is working, let's also plot the idealized Gaussian in black.\n\n\n```python\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nnorm = stats.norm(mean, std)\nplt.plot(xs, norm.pdf(xs), color='k', lw=2)\nplt.show()\n```\n\nThere is another way to get the approximate distribution of a set of data. There is a technique called *kernel density estimate* that uses a kernel to estimate the probability distribution of a set of data. SciPy implements it with the function `gaussian_kde`. Do not be mislead by the name - Gaussian refers to the type of kernel used in the computation. This works for any distribution, not just Gaussians. In this section we have a Gaussian distribution, but soon we will not, and this same function will work.\n\n\n```python\nkde = stats.gaussian_kde(data)\n\nxs = np.linspace(-5, 15, num=200)\nplt.plot(xs, kde(xs))\nplt.show()\n```\n\n## Monte Carlo Simulations\n\n\nWe (well I) want to do this sort of thing because I want to use monte carlo simulations to compute distributions. It is easy to compute Gaussians when they pass through linear functions, but difficult to impossible to compute them analytically when passed through nonlinear functions. Techniques like particle filtering handle this by taking a large sample of points, passing them through a nonlinear function, and then computing statistics on the transformed points. Let's do that.\n\nWe will start with the linear function $f(x) = 2x + 12$ just to prove to ourselves that the code is working. I will alter the mean and std of the data we are working with to help ensure the numbers that are output are unique It is easy to be fooled, for example, if the formula multipies x by 2, the mean is 2, and the std is 2. If the output of something is 4, is that due to the multication factor, the mean, the std, or a bug? It's hard to tell. \n\n\n```python\ndef f(x):\n return 2*x + 12\n\nmean = 1.\nstd = 1.4\ndata = random.normal(loc=mean, scale=std, size=50000)\n\nd_t = f(data) # transform data through f(x)\n\nplt.hist(data, bins=200, normed=True, histtype='step', lw=2)\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\n\nplt.ylim(0, .35)\nplt.show()\nprint('mean = {:.2f}'.format(d_t.mean()))\nprint('std = {:.2f}'.format(d_t.std()))\n```\n\nThis is what we expected. The input is the Gaussian $\\mathcal{N}(\\mu=1, \\sigma=1.4)$, and the function is $f(x) = 2x+12$. Therefore we expect the mean to be shifted to $f(\\mu) = 2*1+12=14$. We can see from the plot and the print statement that this is what happened. \n\nBefore I go on, can you explain what happened to the standard deviation? You may have thought that the new $\\sigma$ should be passed through $f(x)$ like so $2(1.4) + 12=14.81$. But that is not correct - the standard deviation is only affected by the multiplicative factor, not the shift. If you think about that for a moment you will see it makes sense. We multiply our samples by 2, so they are twice as spread out as before. Standard deviation is a measure of how spread out things are, so it should also double. It doesn't matter if we then shift that distribution 12 places, or 12 million for that matter - the spread is still twice the input data.\n\n\n\n## Nonlinear Functions\n\nNow that we believe in our code, lets try it with nonlinear functions.\n\n\n```python\ndef f2(x):\n return (np.cos((1.5*x + 2.1))) * np.sin(0.3*x) - 1.6*x\n\nd_t = f2(data)\nplt.subplot(121)\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\n\nplt.subplot(122)\nkde = stats.gaussian_kde(d_t)\nxs = np.linspace(-10, 10, 200)\nplt.plot(xs, kde(xs), 'k')\nplot_normal(xs, d_t.mean(), d_t.std(), color='g', lw=3)\nplt.show()\nprint('mean = {:.2f}'.format(d_t.mean()))\nprint('std = {:.2f}'.format(d_t.std()))\n```\n\nHere I passed the data through the nonlinear function $f(x) = \\cos(1.5x+2.1)\\sin(\\frac{x}{3}) - 1.6x$. That function is quite close to linear, but we can see how much it alters the pdf of the sampled data. \n\nThere is a lot of computation going on behind the scenes to transform 50,000 points and then compute their PDF. The Extended Kalman Filter (EKF) gets around this by linearizing the function at the mean and then passing the Gaussian through the linear equation. We saw above how easy it is to pass a Gaussian through a linear function. So lets try that.\n\nWe can linearize this by taking the derivative of the function at x. We can use sympy to get the derivative. \n\n\n```python\nimport sympy\nx = sympy.symbols('x')\nf = sympy.cos(1.5*x+2.1) * sympy.sin(x/3) - 1.6*x\ndfx = sympy.diff(f, x)\ndfx\n```\n\n\n\n\n -1.5*sin(x/3)*sin(1.5*x + 2.1) + cos(x/3)*cos(1.5*x + 2.1)/3 - 1.6\n\n\n\nWe can now compute the slope of the function by evaluating the derivative at the mean.\n\n\n```python\nm = dfx.subs(x, mean)\nm\n```\n\n\n\n\n -1.66528051815545\n\n\n\nThe equation of a line is $y=mx+b$, so the new standard deviation should be $~1.67$ times the input std. We can compute the new mean by passing it through the original function because the linearized function is just the slope of f(x) evaluated at the mean. The slope is a tangent that touches the function at $x$, so both will return the same result. So, let's plot this and compare it to the results from the monte carlo simulation.\n\n\n```python\nplt.hist(d_t, bins=200, normed=True, histtype='step', lw=2)\nplot_normal(xs, f2(mean), abs(float(m)*std), color='k', lw=3, label='EKF')\nplot_normal(xs, d_t.mean(), d_t.std(), color='r', lw=3, label='MC')\nplt.legend()\nplt.show()\n```\n\nWe can see from this that the estimate from the EKF (in red) is not exact, but it is not a bad approximation either. \n", "meta": {"hexsha": "ac4fe9949702070b78d7d586f8f6e5668d92d9fe", "size": 152666, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_stars_repo_name": "VladPodilnyk/Kalman-and-Bayesian-Filters-in-Python", "max_stars_repo_head_hexsha": "1b47e2c27ea0a007e8c36d9f6d453c47402b3615", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-23T05:00:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-18T13:27:02.000Z", "max_issues_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_issues_repo_name": "VladPodilnyk/Kalman-and-Bayesian-Filters-in-Python", "max_issues_repo_head_hexsha": "1b47e2c27ea0a007e8c36d9f6d453c47402b3615", "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": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_forks_repo_name": "VladPodilnyk/Kalman-and-Bayesian-Filters-in-Python", "max_forks_repo_head_hexsha": "1b47e2c27ea0a007e8c36d9f6d453c47402b3615", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-10T18:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T02:17:23.000Z", "avg_line_length": 208.8454172367, "max_line_length": 20664, "alphanum_fraction": 0.886418718, "converted": true, "num_tokens": 3428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.06377875534175452}} {"text": "```python\n# File Authorship Information\n__author__ = \"\"\"Matteo Lulli, Luca Biferale, Giacomo Falcucci, \n Mauro Sbragaglia and Xiaowen Shan\"\"\"\n__copyright__ = \"\"\"Copyright 2020-2021, Matteo Lulli, Luca Biferale, \nGiacomo Falcucci, Mauro Sbragaglia and Xiaowen Shan, idea.deploy\"\"\"\n__license__ = \"\"\"Permission is hereby granted, free of charge, \nto any person obtaining a copy of this software and associated \ndocumentation files (the \"Software\"), to deal in the Software \nwithout restriction, including without limitation the rights to \nuse, copy, modify, merge, publish, distribute, sublicense, \nand/or sell copies of the Software, \nand to permit persons to whom the Software is furnished to do so, \nsubject to the following conditions:\nThe above copyright notice and this permission notice shall be \nincluded in all copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES \nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \nDEALINGS IN THE SOFTWARE.\"\"\"\n__maintainer__ = \"Matteo Lulli\"\n__email__ = \"matteo.lulli@gmail.com\"\n__status__ = \"Development\"\n```\n\n\n```python\n# Development cell\n%load_ext autoreload\n%autoreload 2\n```\n\n# Structure and Isotropy of Lattice Pressure Tensors for Multi-range Potentials\n\nAuthors: Matteo Lulli (1), Luca Biferale (2), Giacomo Falcucci (3), Mauro Sbragaglia (2) and Xiaowen Shan (1)\n\n(1) Department of Mechanics and Aerospace Engineering, Southern University of Science and Technology, Shenzhen, Guangdong 518055, China\n\n(2) Department of Physics \\& INFN, University of Rome \\\"Tor Vergata\\\", Via della Ricerca Scientifica 1, 00133, Rome, Italy.\n\n(3) Department of Enterprise Engineering \\\"Mario Lucertini\\\", University of Rome \\\"Tor Vergata\\\", Via del Politecnico 1, 00133 Rome, Italy; John A. Paulson School of Engineering and Applied Physics, *Harvard University*, 33 Oxford Street, 02138 Cambridge, Massachusetts, USA.\n\n**Abstract:**\n We systematically analyze the tensorial structure of the lattice pressure tensors for a class of multiphase lattice Boltzmann models (LBM) with multi-range interactions. Due to lattice discrete effects, we show that the built-in isotropy properties of the lattice interaction forces are not necessarily mirrored in the corresponding lattice pressure tensor. We therefore outline a new procedure to retrieve the desired isotropy in the lattice pressure tensors via a suitable choice of multi-range potentials. The newly obtained LBM forcing schemes are tested via numerical simulations of non-ideal equilibrium interfaces and are shown to yield weaker and less spatially extended spurious currents with respect to previous higher order forcing schemes obtained by forcing isotropy requirements only.\n \nThe paper has been published on [https://journals.aps.org/pre/abstract/10.1103/PhysRevE.103.063309](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.103.063309) and can also be retreived on the arXiv [https://arxiv.org/abs/2009.12522](https://arxiv.org/abs/2009.12522)\n\n# Reproducibility\n\nThis document is intended for those interested readers who want to reproduce the results published on [https://journals.aps.org/pre/abstract/10.1103/PhysRevE.103.063309](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.103.063309) and on the arXiv [https://arxiv.org/abs/2009.12522](https://arxiv.org/abs/2009.12522). In the present case the computational resources needed should be available in general. \n\nNext development steps will include a class to measure the time required by each cell and output it in a .json file which can be sent to [matteo.lulli@gmail.com](mailto:matteo.lulli@gmail.com) so that average execution times will be availble and organized according to the hardware.\n\nEach subsection can be executed independently and reproduce the results which will be stored locally in the directory 'reproduced-data', so that the data will be generated only once.\n\nPlots can also be generated using the same scripts employed for the figures of the paper. Since there are some issues in executing these scripts in the Jupyter environment we include them as separated files which are called from the cells themselves. **In order to reproduce the plots a working 'latex' installation is necessary to be present on the system.**\n\nThis file will be kept updated for new local features and developments in the parent project [**idea.deploy**](https://github.com/lullimat/idea.deploy)\n\nThis file is supposed to be pulled from the repository [https://github.com/lullimat/arXiv-2009.12522](https://github.com/lullimat/arXiv-2009.12522), from within the \"papers\" directory the [**idea.deploy**](https://github.com/lullimat/idea.deploy) project.\n\n## Details\n\n- **The simulations cells for Figure 3 and Figure 4 generate ALL the data discussed in the paper**\n- Each simulation cell can run independently on the other\n- Only one architecture and device can be chosen in order to reproduce all the figures. This will become more general in a future release\n\n# Paper Results\nUsing the next subsections/cells it is possible to reproduce all the results and plots reported in the paper.\n\n## Content of Table I\nIn the next cell we compute the values displayed in Table I of the manuscript.\n\n\n```python\n# Folding Comment: click on the arrow to unfold the content of this cell\nimport sys\nsys.path.append(\"../../\")\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom IPython.display import display\n\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\n\ndef GetIsotropyCoefficients(stencil, weights_list = None):\n '''\n GetIsotropyCoefficients: \n function for printing the isotropy coefficients\n for a give stencil and an arbitrary set of weights\n compatibly with the stencil. If no set of weights\n is provided the solution already provided by the \n stencil class is used\n '''\n if weights_list is None:\n weights_list = stencil.w_sol[0]\n \n print(\"Isotropy Constants\")\n # stencil.e_expr\n for elem in [2, 4]:\n _swap_sym = sp_symbols('e_{' + str(elem) + '}')\n display(_swap_sym)\n display(stencil.e_expr[elem])\n _value = stencil.e_expr[elem]\n \n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n display(_value)\n print()\n \ndef GetIsotropyConditions(stencil, order, weights_list = None):\n '''\n GetIsotropyConditions: \n function for printing the isotropy conditions\n for a given stencil and an arbitrary set of weights\n compatibly with the stencil. If no set of weights\n is provided the solution already provided by the \n stencil class is used\n '''\n if weights_list is None:\n weights_list = stencil.w_sol[0]\n \n print(\"Isotropy Conditions\")\n\n _swap_sym = sp_symbols('I_{' + str(order) + '\\,0}')\n display(_swap_sym)\n display(stencil.B2n_expr[order][0])\n _value = stencil.B2n_expr[order][0]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n display(_value)\n print()\n \n for i in range(len(stencil.B2q_expr[order])):\n _swap_sym = sp_symbols('I_{' + str(order) + '\\,' + str(i + 1) + '}')\n display(_swap_sym)\n display(stencil.B2q_expr[order][i])\n _value = stencil.B2q_expr[order][i]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n display(_value)\n print() \n \ndef GetVarepsilon(stencil):\n '''\n GetVarepsilon: \n function for printing the value of \\varepsilon\n the 5 weights expression is assumed\n ''' \n w1, w2, w4, w5, w8, w9, w10 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8) w(9) w(10)\")\n w13, w16, w17 = sp_symbols(\"w(13) w(16) w(17)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8, w9, w10, w13, w16, w17]\n \n eps_expr = \\\n (48*w4 + 96*w5 + 96*w8 + 288*w9 + 576*w10 + 704*w13 + 960*w16 + 1920*w17)/\\\n (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8 + 342*w9 + \n 696*w10 + 812*w13 + 1056*w16 + 2124*w17)\n \n for i in range(10 - len(stencil.w_sol[0])):\n eps_expr = eps_expr.subs(w_sym_list[len(stencil.w_sol[0]) + i], 0)\n \n display(eps)\n display(eps_expr)\n \n weights_list = None\n if len(stencil.w_sol[0]) != 10:\n len_diff = 10 - len(stencil.w_sol[0])\n if len_diff < 0:\n raise Exception(\"The number of weights must be 7 at most!\")\n weights_list = stencil.w_sol[0] + [0 for i in range(len_diff)]\n else:\n weights_list = stencil.w_sol[0]\n \n _value = eps_expr\n for w_i in range(len(w_sym_list)):\n _value = _value.subs(w_sym_list[w_i], \n weights_list[w_i])\n display(_value)\n print()\n \ndef GetLambdaChiI(stencil):\n '''\n GetLambdaChiI:\n unction for printing the value of \\chi_I, \\Lambda_I\n the 5 weights expression is assumed\n '''\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n chi_i, lambda_i = sp_symbols('\\\\chi_I \\\\Lambda_I')\n w_sym_list = [w1, w2, w4, w5, w8]\n \n chi_i_expr = 2*w4 - 8*w8 - w5\n lambda_i_expr = sp_Rational('1/2')*w1 - 2*w2 + 6*w4 - 24*w8 - 6*w5\n \n weights_list = None\n if len(stencil.w_sol[0]) != 5:\n len_diff = 5 - len(stencil.w_sol[0])\n if len_diff < 0:\n raise Exception(\"The number of weights must be 5 at most!\")\n weights_list = stencil.w_sol[0] + [0 for i in range(len_diff)]\n else:\n weights_list = stencil.w_sol[0]\n \n display(lambda_i)\n display(lambda_i_expr)\n _value = lambda_i_expr\n for w_i in range(len(w_sym_list)):\n _value = _value.subs(w_sym_list[w_i], \n weights_list[w_i])\n display(_value)\n print() \n \n display(chi_i)\n display(chi_i_expr)\n _value = chi_i_expr\n for w_i in range(len(w_sym_list)):\n _value = _value.subs(w_sym_list[w_i], \n weights_list[w_i])\n display(_value)\n print() \n \n'''\nGetting usual weights\n'''\n\nif True:\n '''\n E^6_F2P6\n '''\n S5_E6_P2F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4])\n S5_E6_P2F6.GetWolfEqs()\n S5_E6_P2F6.GetTypEqs()\n S5_E6_P2F6_W = S5_E6_P2F6.FindWeights()\n\n '''\n E^8_F2P8\n '''\n S5_E8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n S5_E8_P2F8_W = S5_E8_P2F8.FindWeights()\n\n '''\n E^10_F2P10\n '''\n S5_E10_P2F10 = SCFStencils(E = BasisVectors(x_max = 3), \n len_2s = [1, 2, 4, 5, 8, 9, 10])\n S5_E10_P2F10_W = S5_E10_P2F10.FindWeights()\n\n '''\n E^12_F2P12\n '''\n S5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\n S5_E12_P2F12_W = S5_E12_P2F12.FindWeights()\n\n'''\nGetting new weights: always up to w(8)\n'''\nif True:\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8]\n \n eps_expr = (48*w4 + 96*w5 + 96*w8)\n eps_expr /= (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8)\n\n chi_i_expr = 2*w4 - 8*w8 - w5\n\n '''\n E^6_F4P6\n '''\n S5_E6_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E6_P4F6.GetWolfEqs()\n S5_E6_P4F6.GetTypEqs()\n\n cond_e4 = S5_E6_P4F6.e_expr[4] - sp_Rational('2/5')\n cond_e2 = S5_E6_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('2/17')\n cond_chi_i = chi_i_expr\n\n S5_E6_P4F6_eqs = [cond_e2,\n cond_eps, \n cond_chi_i, \n S5_E6_P4F6.typ_eq_s[4][0],\n S5_E6_P4F6.typ_eq_s[6][0]]\n\n S5_E6_P4F6_W = S5_E6_P4F6.FindWeights(S5_E6_P4F6_eqs)\n\n '''\n E^8_P4F6\n '''\n S5_E8_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E8_P4F6.GetWolfEqs()\n S5_E8_P4F6.GetTypEqs()\n\n cond_e4 = S5_E8_P4F6.e_expr[4] - sp_Rational('4/7')\n cond_e2 = S5_E8_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('10/31')\n cond_chi_i = chi_i_expr\n\n S5_E8_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E8_P4F6.typ_eq_s[4][0],\n S5_E8_P4F6.typ_eq_s[6][0]]\n\n S5_E8_P4F6_W = S5_E8_P4F6.FindWeights(S5_E8_P4F6_eqs)\n\n '''\n E^10_P4F6\n '''\n S5_E10_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E10_P4F6.GetWolfEqs()\n S5_E10_P4F6.GetTypEqs()\n\n cond_e4 = S5_E10_P4F6.e_expr[4] - sp_Rational('12/17')\n cond_e2 = S5_E10_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('38/89')\n cond_chi_i = chi_i_expr\n\n S5_E10_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E10_P4F6.typ_eq_s[4][0],\n S5_E10_P4F6.typ_eq_s[6][0]]\n\n S5_E10_P4F6_W = S5_E10_P4F6.FindWeights(S5_E10_P4F6_eqs)\n\n '''\n E^12_P4F6\n '''\n S5_E12_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E12_P4F6.GetWolfEqs()\n S5_E12_P4F6.GetTypEqs()\n\n cond_e4 = S5_E12_P4F6.e_expr[4] - sp_Rational(120, 143)\n cond_e2 = S5_E12_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational(136774, 271813)\n cond_chi_i = chi_i_expr\n\n S5_E12_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i,\n S5_E12_P4F6.typ_eq_s[4][0], \n S5_E12_P4F6.typ_eq_s[6][0]]\n\n S5_E12_P4F6_W = S5_E12_P4F6.FindWeights(S5_E12_P4F6_eqs)\n\n'''\nPrinting\n'''\n\nE6_P2F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P2\\,F6}\")\nE8_P2F8_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P2\\,F8}\")\nE10_P2F10_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P2\\,F10}\")\nE12_P2F12_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P2\\,F12}\")\n\nE6_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P4\\,F6}\")\nE8_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P4\\,F6}\")\nE10_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P4\\,F6}\")\nE12_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P4\\,F6}\")\n\ndisplay(E6_P2F6_sym)\nprint(\"Weights: \", S5_E6_P2F6_W)\nGetIsotropyCoefficients(S5_E8_P2F8, weights_list = S5_E6_P2F6_W + [0,0])\nGetVarepsilon(S5_E6_P2F6)\nGetLambdaChiI(S5_E6_P2F6)\nGetIsotropyConditions(S5_E6_P2F6, order = 4)\nGetIsotropyConditions(S5_E6_P2F6, order = 6)\n\nprint(\"-------------------------------------------------------------------------\")\n\ndisplay(E6_P4F6_sym)\nprint(\"Weights: \", S5_E6_P4F6_W)\nGetIsotropyCoefficients(S5_E6_P4F6)\nGetVarepsilon(S5_E6_P4F6)\nGetLambdaChiI(S5_E6_P4F6)\nGetIsotropyConditions(S5_E6_P4F6, order = 4)\nGetIsotropyConditions(S5_E6_P4F6, order = 6)\n\nprint(\"=========================================================================\")\n\ndisplay(E8_P2F8_sym)\nprint(\"Weights: \", S5_E8_P2F8_W)\nGetIsotropyCoefficients(S5_E8_P2F8)\nGetVarepsilon(S5_E8_P2F8)\nGetLambdaChiI(S5_E8_P2F8)\nGetIsotropyConditions(S5_E8_P2F8, order = 4)\nGetIsotropyConditions(S5_E8_P2F8, order = 6)\n\nprint(\"-------------------------------------------------------------------------\")\n\ndisplay(E8_P4F6_sym)\nprint(\"Weights: \", S5_E8_P4F6_W)\nGetIsotropyCoefficients(S5_E8_P4F6)\nGetVarepsilon(S5_E8_P4F6)\nGetLambdaChiI(S5_E8_P4F6)\nGetIsotropyConditions(S5_E8_P4F6, order = 4)\nGetIsotropyConditions(S5_E8_P4F6, order = 6)\n\nprint(\"=========================================================================\")\n\ndisplay(E10_P2F10_sym)\nprint(\"Weights: \", S5_E10_P2F10_W)\nGetIsotropyCoefficients(S5_E10_P2F10)\nGetVarepsilon(S5_E10_P2F10)\nGetIsotropyConditions(S5_E10_P2F10, order = 4)\nGetIsotropyConditions(S5_E10_P2F10, order = 6)\n\nprint(\"-------------------------------------------------------------------------\")\n\ndisplay(E10_P4F6_sym)\nprint(\"Weights: \", S5_E10_P4F6_W)\nGetIsotropyCoefficients(S5_E10_P4F6)\nGetVarepsilon(S5_E10_P4F6)\nGetLambdaChiI(S5_E10_P4F6)\nGetIsotropyConditions(S5_E10_P4F6, order = 4)\nGetIsotropyConditions(S5_E10_P4F6, order = 6)\n\nprint(\"=========================================================================\")\n\ndisplay(E12_P2F12_sym)\nprint(\"Weights: \", S5_E12_P2F12_W)\nGetIsotropyCoefficients(S5_E12_P2F12)\nGetVarepsilon(S5_E12_P2F12)\nGetIsotropyConditions(S5_E12_P2F12, order = 4)\nGetIsotropyConditions(S5_E12_P2F12, order = 6)\n\nprint(\"-------------------------------------------------------------------------\")\n\ndisplay(E12_P4F6_sym)\nprint(\"Weights: \", S5_E12_P4F6_W)\nGetIsotropyCoefficients(S5_E12_P4F6)\nGetVarepsilon(S5_E12_P4F6)\nGetLambdaChiI(S5_E12_P4F6)\nGetIsotropyConditions(S5_E12_P4F6, order = 4)\nGetIsotropyConditions(S5_E12_P4F6, order = 6)\n```\n\n## Content of Table II\nIn the next cell we compute the values displayed in Table II of the manuscript.\n\n\n```python\n# Folding Comment: click on the arrow to unfold the content of this cell\nimport sys\nsys.path.append(\"../../\")\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom IPython.display import display\n\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\n\nw1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\neps = sp_symbols('\\\\varepsilon')\nw_sym_list = [w1, w2, w4, w5, w8]\n\neps_expr = (48*w4 + 96*w5 + 96*w8)\neps_expr /= (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8)\n\nchi_i_expr = 2*w4 - 8*w8 - w5\n\nchi_i, lambda_i = sp_symbols('\\\\chi_I \\\\Lambda_I')\nI40, I60 = sp_symbols('I_{4\\,0} I_{6\\,0}')\n\n\nE6_P2F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P2\\,F6}\")\nE8_P2F8_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P2\\,F8}\")\nE10_P2F10_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P2\\,F10}\")\nE12_P2F12_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P2\\,F12}\")\n\nE6_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P4\\,F6}\")\nE8_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P4\\,F6}\")\nE10_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P4\\,F6}\")\nE12_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P4\\,F6}\")\n\n'''\nGetting usual weights\n'''\n\n'''\nE^6_F2P6\n'''\nS5_E6_P2F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4])\nS5_E6_P2F6_W = S5_E6_P2F6.FindWeights()\n\n'''\nE^8_F2P8\n'''\nS5_E8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\nS5_E8_P2F8_W = S5_E8_P2F8.FindWeights()\n\n'''\nE^10_F2P10\n'''\nS5_E10_P2F10 = SCFStencils(E = BasisVectors(x_max = 3), \n len_2s = [1, 2, 4, 5, 8, 9, 10])\nS5_E10_P2F10_W = S5_E10_P2F10.FindWeights()\n\n'''\nE^12_F2P12\n'''\nS5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\nS5_E12_P2F12_W = S5_E12_P2F12.FindWeights()\n\n\n'''\nfirst: E6_P2F6\n'''\n\ndisplay(E6_P2F6_sym)\nprint(\"Weights: \", S5_E6_P2F6_W)\nprint()\n\nprint(\"-------------------------------------------------------------------------\")\n\n'''\nsecond: E6_P4F6\n'''\nif True:\n S5_E6_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E6_P4F6.GetWolfEqs()\n S5_E6_P4F6.GetTypEqs()\n\n cond_e4 = S5_E6_P4F6.e_expr[4] - sp_Rational('2/5')\n cond_e2 = S5_E6_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('2/17')\n cond_chi_i = chi_i_expr\n\n S5_E6_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E6_P4F6.typ_eq_s[4][0],\n S5_E6_P4F6.typ_eq_s[6][0]]\n\n\n\n print(\"System of equations:\")\n display(S5_E6_P4F6.e_sym[2])\n display(cond_e2)\n print()\n display(eps)\n display(cond_eps)\n print()\n display(chi_i)\n display(cond_chi_i)\n print()\n display(I40)\n display(S5_E6_P4F6.typ_eq_s[4][0])\n print()\n display(I60)\n display(S5_E6_P4F6.typ_eq_s[6][0])\n print()\n\n S5_E6_P4F6_W = S5_E6_P4F6.FindWeights(S5_E6_P4F6_eqs)\n\ndisplay(E6_P4F6_sym)\nprint(\"Weights: \", S5_E6_P4F6_W)\n\nprint(\"=========================================================================\")\n\n'''\nthird: E8_P2F8\n'''\n\ndisplay(E8_P2F8_sym)\nprint(\"Weights: \", S5_E8_P2F8_W)\nprint()\n\nprint(\"-------------------------------------------------------------------------\")\n\n'''\nfourth: E8_P4F6\n'''\nif True:\n S5_E8_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E8_P4F6.GetWolfEqs()\n S5_E8_P4F6.GetTypEqs()\n\n print(\"System of equations:\")\n cond_e2 = S5_E8_P4F6.e_expr[2] - 1\n display(S5_E8_P4F6.e_sym[2])\n display(cond_e2)\n print()\n cond_eps = eps_expr - sp_Rational('10/31')\n display(eps)\n display(cond_eps)\n print()\n cond_chi_i = chi_i_expr\n display(chi_i)\n display(cond_chi_i)\n print()\n cond_I40 = S5_E8_P4F6.typ_eq_s[4][0]\n display(I40)\n display(cond_I40)\n print()\n cond_I60 = S5_E8_P4F6.typ_eq_s[6][0]\n display(I60)\n display(cond_I60)\n print()\n\n S5_E8_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n cond_I40, \n cond_I60]\n\n S5_E8_P4F6_W = S5_E8_P4F6.FindWeights(S5_E8_P4F6_eqs)\n\ndisplay(E8_P4F6_sym)\nprint(\"Weights: \", S5_E8_P4F6_W)\n\nprint(\"=========================================================================\")\n\n'''\nfifth: E10_P2F10\n'''\n\ndisplay(E10_P2F10_sym)\nprint(\"Weights: \", S5_E10_P2F10_W)\nprint()\n\nprint(\"-------------------------------------------------------------------------\")\n\n'''\nsixth: E10_P4F6\n'''\nif True:\n S5_E10_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E10_P4F6.GetWolfEqs()\n S5_E10_P4F6.GetTypEqs()\n\n print(\"System of equations:\")\n cond_e2 = S5_E10_P4F6.e_expr[2] - 1\n display(S5_E10_P4F6.e_sym[2])\n display(cond_e2)\n print()\n cond_eps = eps_expr - sp_Rational('38/89')\n display(eps)\n display(cond_eps)\n print()\n cond_chi_i = chi_i_expr\n display(chi_i)\n display(cond_chi_i)\n print()\n cond_I40 = S5_E10_P4F6.typ_eq_s[4][0]\n display(I40)\n display(cond_I40)\n print()\n cond_I60 = S5_E10_P4F6.typ_eq_s[6][0]\n display(I60)\n display(cond_I60)\n print()\n\n S5_E10_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n cond_I40, \n cond_I60]\n\n S5_E10_P4F6_W = S5_E10_P4F6.FindWeights(S5_E10_P4F6_eqs)\n\ndisplay(E10_P4F6_sym)\nprint(\"Weights: \", S5_E10_P4F6_W)\n\nprint(\"=========================================================================\")\n\n'''\nseventh: E12_P2F12\n'''\n\ndisplay(E12_P2F12_sym)\nprint(\"Weights: \", S5_E12_P2F12_W)\nprint()\n\nprint(\"-------------------------------------------------------------------------\")\n\n'''\neighth: E12_P4F6\n'''\nif True:\n S5_E12_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E12_P4F6.GetWolfEqs()\n S5_E12_P4F6.GetTypEqs()\n\n print(\"System of equations:\")\n cond_e2 = S5_E12_P4F6.e_expr[2] - 1\n display(S5_E12_P4F6.e_sym[2])\n display(cond_e2)\n print()\n cond_eps = eps_expr - sp_Rational(136774, 271813)\n display(eps)\n display(cond_eps)\n print()\n cond_chi_i = chi_i_expr\n display(chi_i)\n display(cond_chi_i)\n print()\n cond_I40 = S5_E12_P4F6.typ_eq_s[4][0]\n display(I40)\n display(cond_I40)\n print()\n cond_I60 = S5_E12_P4F6.typ_eq_s[6][0]\n display(I60)\n display(cond_I60)\n print()\n\n S5_E12_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n cond_I40, \n cond_I60]\n\n S5_E12_P4F6_W = S5_E12_P4F6.FindWeights(S5_E12_P4F6_eqs)\n\ndisplay(E12_P4F6_sym)\nprint(\"Weights: \", S5_E12_P4F6_W)\n\nprint(\"=========================================================================\")\n```\n\n## Simulations: Hardware Selection\nIn the following cells you are required to make a choice for the hardware to employ for the simulations. At the moment you need to stick to a given choice in order to visualize all the results. A more elastic management will be provided in future releases.\n\n**These are the only cells in the notebook that have a \"global\" character, i.e. they are needed by the rest of the notebook for the simulations cell to run.**\n\nBy executing (shift-enter) the cell below, the hardware present in your system will be listed\n\n\n```python\n# Display Hardware (click the arrow to unfold)\nimport sys\nsys.path.append(\"../../\")\n\nfrom idpy.IdpyCode import IdpyHardware\n\nIdpyHardware()\n```\n\n**To repdroduce the results you need hardware that support OpenCL with 64bits floating point variables (indicated by 'Double : 63') and/or CUDA.**\n\nThe variable \"preferred_lang\" can be set as\n- OCL_T for OpenCL\n- CUDA_T for CUDA\n\nThe variable \"preferred_device\" need to be set to the number matching the 64-bits floating point precision requirement discussed above.\n\nThe variable \"preferred_kind\" can be used only with OCL_T and can be set as\n- \"gpu\" for selecting GPU devices\n- \"cpu\" for selecting CPU devices\n\nIt also possible to run the simulations on 32-bits floating point variables, however the results will not match those presented in the paper.\n\n\n```python\n# Language imports (click on left arrow to unfold)\nimport sys\nsys.path.append(\"../../\")\n\nfrom idpy.IdpyCode import CUDA_T, OCL_T, idpy_langs_sys\n```\n\n\n```python\npreferred_lang, preferred_device, preferred_kind = OCL_T, 0, \"cpu\"\n```\n\n\n```python\n# Setting up global variables (click on left arrow to unfold)\nimport sys\nsys.path.append(\"../../\")\n\nfrom idpy.IdpyCode import CUDA_T, OCL_T, idpy_langs_sys\n\ndevice = None\nif preferred_device is None:\n device = 0\nelse:\n device = preferred_device\n\nlang = None\nif preferred_lang is None:\n if idpy_langs_sys[CUDA_T]:\n lang = CUDA_T\n elif idpy_langs_sys[OCL_T]:\n lang = OCL_T\nelse:\n lang = preferred_lang\n \nif lang is None:\n raise Exception(\"It seems idpy is not correctly initialized\", \n \"Did you source the virtual environment before opening the notebook?\", \n \"(idpy-load; ipdy-jupyter; then follow the instructions)\")\n\ndev_kind = None\nif preferred_kind is None:\n dev_kind = \"gpu\"\nelse:\n dev_kind = preferred_kind\n \ndevice_str = None\nif lang == OCL_T:\n from idpy.OpenCL.OpenCL import OpenCL\n ocl = OpenCL()\n gpus_list = ocl.DiscoverGPUs()\n cpus_list = ocl.DiscoverCPUs()\n if dev_kind == \"cpu\":\n device_str = str(cpus_list[device]['Name']) + \"_\" + str(cpus_list[device]['DrvVersion']) \n device_str = device_str.replace(\" \", \"_\").replace(\"(\", \"_\").replace(\")\", \"_\")\n device_str = device_str.replace(\",\", \"_\").replace(\".\", \"_\").replace(\":\", \"_\")\n device_str = device_str.replace(\"@\", \"at\")\n device_str = device_str.replace(\"{\", \"_\").replace(\"}\", \"_\")\n if dev_kind == \"gpu\":\n device_str = str(gpus_list[device]['Name']) + \"_\" + str(gpus_list[device]['DrvVersion']) \n device_str = device_str.replace(\" \", \"_\").replace(\"(\", \"_\").replace(\")\", \"_\")\n device_str = device_str.replace(\",\", \"_\").replace(\".\", \"_\").replace(\":\", \"_\")\n device_str = device_str.replace(\"@\", \"at\")\n device_str = device_str.replace(\"{\", \"_\").replace(\"}\", \"_\")\n \nif lang == CUDA_T:\n from idpy.CUDA.CUDA import CUDA\n cu = CUDA()\n gpus_list = cu.DiscoverGPUs()\n device_str = str(gpus_list[device]['Name']) + \"_\" + str(gpus_list[device]['DrvVersion']) \n device_str = device_str.replace(\" \", \"_\").replace(\"(\", \"_\").replace(\")\", \"_\")\n device_str = device_str.replace(\",\", \"_\").replace(\".\", \"_\").replace(\":\", \"_\")\n device_str = device_str.replace(\"@\", \"at\")\n device_str = device_str.replace(\"{\", \"_\").replace(\"}\", \"_\")\n```\n\n## Figure 3\n\nThe simulation cell for this figure generates all the data needed for the curved interface results. For the flat interface use the (faster) simulation cells in Figure 4.\n\n**Execution times for the cell below**\n\n*Cached Equilibrium Densities*\n\n**0 d, 7 h, 18 m, 33 s, CUDA, GeForce GTX 1070 (64-bits), Ryzen 5 3500X (6-Core) Processor**\n\n*Uncached Equilibrium Densities*\n\n**0 d, 7 h, 22 m, 32 s, OpenCL, AMD Radeon RX 590 (64-bits), Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz**\n\n\n```python\n# Droplets Simulations for the Laplace data and velocity fields (click arrow to unfold)\nimport time\nstart = time.time()\n\nimport sys\nsys.path.append(\"../../\")\n\n########################################################################\n\nfrom pathlib import Path\nreproduced_results = Path(\"reproduced-results\")\nif not reproduced_results.is_dir():\n reproduced_results.mkdir()\n\nfrom sympy import exp as sp_exp\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom sympy import lambdify as sp_lambdify\nfrom IPython.display import display\nimport numpy as np\n\nfrom idpy.LBM.SCThermo import ShanChen\nfrom idpy.Utils.ManageData import ManageData\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\nfrom idpy.LBM.LBM import XIStencils\n\nfrom idpy.LBM.SCThermo import ShanChanEquilibriumCache\nfrom idpy.LBM.LBM import ShanChenMultiPhase, CheckUConvergence\nfrom idpy.IdpyCode import IdpyMemory\n\ndef GetE2(stencil):\n weights_list = stencil.w_sol[0]\n _value = stencil.e_expr[2]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n return _value\n\n'''\nHere we declare the symbol for the density as 'n'\nand define the pseudo-potential\n'''\n\nn = sp_symbols('n')\npsis = [sp_exp(-1/n), 1 - sp_exp(-n)]\npsi_codes = {psis[0]: 'exp((NType)(-1./ln))', \n psis[1]: '1. - exp(-(NType)ln)',}\n\nGs = {psis[0]: [-2.6, -3.1, -3.6], \n psis[1]: [-1.4, -1.6, -1.75]}\n\nE6_P2F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P2\\,F6}\")\nE8_P2F8_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P2\\,F8}\")\nE10_P2F10_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P2\\,F10}\")\nE12_P2F12_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P2\\,F12}\")\nE6_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P4\\,F6}\")\nE8_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P4\\,F6}\")\nE10_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P4\\,F6}\")\nE12_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P4\\,F6}\")\n\n'''\nGetting usual weights\n'''\n\nif True:\n '''\n E^6_F2P6\n '''\n S5_E6_P2F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4])\n S5_E6_P2F6_W = S5_E6_P2F6.FindWeights()\n\n '''\n E^8_F2P8\n '''\n S5_E8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n S5_E8_P2F8_W = S5_E8_P2F8.FindWeights()\n\n '''\n E^10_F2P10\n '''\n S5_E10_P2F10 = SCFStencils(E = BasisVectors(x_max = 3), \n len_2s = [1, 2, 4, 5, 8, 9, 10])\n S5_E10_P2F10_W = S5_E10_P2F10.FindWeights()\n\n '''\n E^12_F2P12\n '''\n S5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\n S5_E12_P2F12_W = S5_E12_P2F12.FindWeights()\n\n'''\nGetting new weights: always up to w(8)\n'''\nif True:\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8]\n\n chi_i_expr = 2*w4 - 8*w8 - w5\n eps_expr = (48*w4 + 96*w5 + 96*w8)\n eps_expr /= (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8) \n \n '''\n E^6_F4P6\n '''\n S5_E6_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E6_P4F6.GetWolfEqs()\n S5_E6_P4F6.GetTypEqs()\n\n cond_e4 = S5_E6_P4F6.e_expr[4] - sp_Rational('2/5')\n cond_e2 = S5_E6_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('2/17')\n cond_chi_i = chi_i_expr\n\n S5_E6_P4F6_eqs = [cond_e2,\n cond_eps, \n cond_chi_i, \n S5_E6_P4F6.typ_eq_s[4][0],\n S5_E6_P4F6.typ_eq_s[6][0]]\n\n S5_E6_P4F6_W = S5_E6_P4F6.FindWeights(S5_E6_P4F6_eqs)\n\n '''\n E^8_P4F6\n '''\n S5_E8_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E8_P4F6.GetWolfEqs()\n S5_E8_P4F6.GetTypEqs()\n\n cond_e4 = S5_E8_P4F6.e_expr[4] - sp_Rational('4/7')\n cond_e2 = S5_E8_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('10/31')\n cond_chi_i = chi_i_expr\n\n S5_E8_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E8_P4F6.typ_eq_s[4][0],\n S5_E8_P4F6.typ_eq_s[6][0]]\n\n S5_E8_P4F6_W = S5_E8_P4F6.FindWeights(S5_E8_P4F6_eqs)\n\n '''\n E^10_P4F6\n '''\n S5_E10_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E10_P4F6.GetWolfEqs()\n S5_E10_P4F6.GetTypEqs()\n\n cond_e4 = S5_E10_P4F6.e_expr[4] - sp_Rational('12/17')\n cond_e2 = S5_E10_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('38/89')\n cond_chi_i = chi_i_expr\n\n S5_E10_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E10_P4F6.typ_eq_s[4][0],\n S5_E10_P4F6.typ_eq_s[6][0]]\n\n S5_E10_P4F6_W = S5_E10_P4F6.FindWeights(S5_E10_P4F6_eqs)\n\n '''\n E^12_P4F6\n '''\n S5_E12_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E12_P4F6.GetWolfEqs()\n S5_E12_P4F6.GetTypEqs()\n\n cond_e4 = S5_E12_P4F6.e_expr[4] - sp_Rational(120, 143)\n cond_e2 = S5_E12_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational(136774, 271813)\n cond_chi_i = chi_i_expr\n\n S5_E12_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i,\n S5_E12_P4F6.typ_eq_s[4][0], \n S5_E12_P4F6.typ_eq_s[6][0]]\n\n S5_E12_P4F6_W = S5_E12_P4F6.FindWeights(S5_E12_P4F6_eqs)\n\n'''\nDefining output files: Flat interface\n'''\n\nstencil_string = {E6_P2F6_sym: 'E6_P2F6', \n E6_P4F6_sym: 'E6_P4F6', \n E8_P2F8_sym: 'E8_P2F8', \n E8_P4F6_sym: 'E8_P4F6', \n E10_P2F10_sym: 'E10_P2F10', \n E10_P4F6_sym: 'E10_P4F6', \n E12_P2F12_sym: 'E12_P2F12', \n E12_P4F6_sym: 'E12_P4F6'}\n\nstencil_dict = {E6_P2F6_sym: S5_E6_P2F6, \n E6_P4F6_sym: S5_E6_P4F6, \n E8_P2F8_sym: S5_E8_P2F8, \n E8_P4F6_sym: S5_E8_P4F6, \n E10_P2F10_sym: S5_E10_P2F10, \n E10_P4F6_sym: S5_E10_P4F6, \n E12_P2F12_sym: S5_E12_P2F12, \n E12_P4F6_sym: S5_E12_P4F6}\n\nstencil_sym_list = [E6_P2F6_sym, E6_P4F6_sym, \n E8_P2F8_sym, E8_P4F6_sym, \n E10_P2F10_sym, E10_P4F6_sym, \n E12_P2F12_sym, E12_P4F6_sym]\n\n#stencil_sym_list = [E12_P2F12_sym, E12_P4F6_sym]\n\ndef LaplaceFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_laplace\")\n\ndef DropletsFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_droplets\")\n\ndef StencilPsiKey(stencil_sym, psi):\n return str(stencil_sym) + \"_\" + str(psi)\n\nlaplace_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[1]),\n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[1])}\n\ndroplets_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[0]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[0]),\n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[1]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[1])}\n\n\nfrom idpy.Utils.ManageData import ManageData\n'''\nSimulations Loop\n'''\nfor _psi in psis:\n print(\"The pseudo-potential is: \")\n display(_psi)\n for _G in Gs[_psi]:\n print(\"Coupling Constant G: \", _G)\n for stencil_sym in stencil_sym_list:\n display(stencil_sym)\n _stencil = stencil_dict[stencil_sym]\n _data_out_laplace = ManageData(dump_file = laplace_files[StencilPsiKey(stencil_sym, _psi)])\n _data_out_droplets = ManageData(dump_file = droplets_files[StencilPsiKey(stencil_sym, _psi)]) \n \n _e2_swap = GetE2(_stencil)\n print(\"e2: \", _e2_swap)\n \n # [127, 159, 191, 223, 255, 287, 319, 351]\n for L in [127, 159, 191, 223, 255, 287, 319, 351]:\n print(\"L: \", L, \"R: \", L/5.)\n\n _data_key = str(_G) + \"_\" + str(L)\n\n _is_data_there_laplace = False\n if _data_out_laplace.Read():\n print(\"File \", laplace_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_laplace = _data_key in _data_out_laplace.WhichData()\n\n if _is_data_there_laplace:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(laplace_files[StencilPsiKey(stencil_sym, _psi)])\n print() \n \n _is_data_there_droplets = False\n if L in [255, 351]:\n if _data_out_droplets.Read():\n print(\"File \", droplets_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_droplets = _data_key in _data_out_droplets.WhichData()\n\n if _is_data_there_droplets:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(droplets_files[StencilPsiKey(stencil_sym, _psi)])\n print()\n else:\n _is_data_there_droplets = True\n\n \n\n if not _is_data_there_laplace or not _is_data_there_droplets:\n print(\"Data is not there...\")\n print(\"Preparing the simulation...\")\n print()\n _lbm = ShanChenMultiPhase(lang = lang, \n dim_sizes = (L, L), \n xi_stencil = XIStencils['D2Q9'], \n f_stencil = _stencil.PushStencil(), \n psi_code = psi_codes[_psi], \n psi_sym = _psi,\n SC_G = _G, tau = 1., \n device = device, \n cl_kind = dev_kind, \n optimizer_flag = True)\n\n print(\"----------------------------------------------------\")\n print(\"\\nComputing/Retrieving flat mechanical equilibrium densities...\")\n print(\"psi: \", _psi, \"G: \", _G, \"Ws: \", _stencil.w_sol[0])\n\n _sc_eq_cache = ShanChanEquilibriumCache(stencil = _stencil, \n psi_f = _psi, G = _G, \n c2 = XIStencils['D2Q9']['c2'])\n\n _eq_params = _sc_eq_cache.GetFromCache()\n print(\"...done!\\n\")\n print(\"The mechanical equilibrium densities are:\")\n print(\"n_g (gas): \", _eq_params['n_g'], \n \", n_l (liq): \", _eq_params['n_l'])\n print(\"Surface tension: \", _eq_params['sigma_f'])\n print(\"(G_c, n_c) (crtitcal G and n): \", (_eq_params['G_c'], \n _eq_params['n_c']))\n print()\n print(\"Initializing flat interface\")\n\n _lbm.InitRadialInterface(n_g = _eq_params['n_g'], n_l = _eq_params['n_l'], \n R = L/5., full_flag = True)\n\n print(\"Running the simulation...\")\n\n\n _lbm.MainLoop(range(0, 2**22, 2**14),\n convergence_functions = [CheckUConvergence])\n\n '''\n Getting average density, inner and outer density for\n computing the Gibbs radius\n '''\n \n _n_ave = IdpyMemory.Sum(_lbm.sims_idpy_memory['n'])/(L*L)\n _n = _lbm.sims_idpy_memory['n'].D2H()\n _n = _n.reshape(np.flip(_lbm.sims_vars['dim_sizes']))\n \n _center = tuple(_lbm.sims_vars['dim_center'])\n _n_in = _n[_center]\n _n_out = _n[(L - 1, L - 1)]\n \n _R_Gibbs = L*np.sqrt((_n_ave - _n_out)/(np.pi * (_n_in - _n_out)))\n \n def BulkP(n_value, _e2):\n _psi_f = sp_lambdify(n, _psi)\n p = n_value * XIStencils['D2Q9']['c2']\n p += 0.5 * _G * _e2 * (_psi_f(n_value)) ** 2\n return p\n \n _p_in, _p_out = BulkP(_n_in, _e2_swap), BulkP(_n_out, _e2_swap)\n _delta_p = _p_in - _p_out\n \n print(\"L: \", L, \"Start R: \", L/5., \"R_Gibbs: \", _R_Gibbs)\n print(\"Estimated surface tension: \", _delta_p * _R_Gibbs)\n print(\"Analytic surface tension: \", _eq_params['sigma_f'])\n \n _dict_out = {'delta_p': _delta_p, \n 'R_Gibbs': _R_Gibbs}\n \n if not _is_data_there_laplace:\n _data_out_laplace.PushData(data = _dict_out, key = _data_key)\n _data_out_laplace.Dump()\n \n if not _is_data_there_droplets:\n _u = _lbm.sims_idpy_memory['u'].D2H() \n _data_out_droplets.PushData(data = _u, key = _data_key)\n _data_out_droplets.Dump() \n\n print(\"Ending and deleting LB simulation object\")\n _lbm.End()\n del _lbm\n print()\n print()\n \nend = time.time()\ndef PrintElapsedTime(lapse):\n _n_sec_min, _n_min_hrs = 60, 60\n _n_sec_hrs, _n_hrs_day = _n_min_hrs * _n_sec_min, 24\n _n_sec_day = _n_hrs_day * _n_sec_hrs\n \n print(int(end - start)//_n_sec_day, \"d, \",\n (int(end - start)//_n_sec_hrs)%_n_hrs_day, \"h, \",\n (int(end - start)//_n_sec_min)%_n_min_hrs, \"m, \", \n int(end - start)% _n_sec_min, \"s\")\n\nPrintElapsedTime(start - end)\n```\n\n\n```python\n# Figure 3 (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_3.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 3 (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_3.png\")\n```\n\n## Figure 4\n\nThe simulation cell for this figure generates all the data needed for the flat interface results. For the curved interface use the (faster) simulation cells in Figure 3.\n\n*Uncached Equilibrium Densities*\n\n**0 d, 0 h, 27 m, 2 s, OpenCL, Apple M1 CPU (64-bits)**\n\n**0 d, 0 h, 54 m, 36 s, CUDA, GeForce GTX 1070 (64-bits), Ryzen 5 3500X (6-Core) Processor**\n\n**0 d, 0 h, 36 m, 25 s, OpenCL, AMD Radeon RX 590 (64-bits), Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz**\n\n*Cached Equilibrium Densities*\n\n**0 d, 0 h, 8 m, 20 s, OpenCL, AMD Radeon RX 590 (64-bits), Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz**\n\n\n```python\n# Flat Interfaces Simulations for the profiles comparison (click arrow to unfold)\nimport time\n\nimport sys\nsys.path.append(\"../../\")\n\n########################################################################\n\nfrom pathlib import Path\nreproduced_results = Path(\"reproduced-results\")\nif not reproduced_results.is_dir():\n reproduced_results.mkdir()\n\nfrom sympy import exp as sp_exp\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom IPython.display import display\nimport numpy as np\n\nfrom idpy.LBM.SCThermo import ShanChen\nfrom idpy.Utils.ManageData import ManageData\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\nfrom idpy.LBM.LBM import XIStencils\n\nfrom idpy.LBM.SCThermo import ShanChanEquilibriumCache\nfrom idpy.LBM.LBM import ShanChenMultiPhase, CheckUConvergence\n\ndef GetE2(stencil):\n weights_list = stencil.w_sol[0]\n _value = stencil.e_expr[2]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n return _value\n\n'''\nHere we declare the symbol for the density as 'n'\nand define the pseudo-potential\n'''\n\nn = sp_symbols('n')\npsis = [sp_exp(-1/n), 1 - sp_exp(-n)]\npsi_codes = {psis[0]: 'exp((NType)(-1./ln))', \n psis[1]: '1. - exp(-(NType)ln)',}\n\nGs = {psis[0]: [-2.6, -3.1, -3.6], \n psis[1]: [-1.4, -1.6, -1.75]}\n\nE6_P2F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P2\\,F6}\")\nE8_P2F8_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P2\\,F8}\")\nE10_P2F10_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P2\\,F10}\")\nE12_P2F12_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P2\\,F12}\")\nE6_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P4\\,F6}\")\nE8_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P4\\,F6}\")\nE10_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P4\\,F6}\")\nE12_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P4\\,F6}\")\n\n'''\nGetting usual weights\n'''\n\nif True:\n '''\n E^6_F2P6\n '''\n S5_E6_P2F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4])\n S5_E6_P2F6_W = S5_E6_P2F6.FindWeights()\n\n '''\n E^8_F2P8\n '''\n S5_E8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n S5_E8_P2F8_W = S5_E8_P2F8.FindWeights()\n\n '''\n E^10_F2P10\n '''\n S5_E10_P2F10 = SCFStencils(E = BasisVectors(x_max = 3), \n len_2s = [1, 2, 4, 5, 8, 9, 10])\n S5_E10_P2F10_W = S5_E10_P2F10.FindWeights()\n\n '''\n E^12_F2P12\n '''\n S5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\n S5_E12_P2F12_W = S5_E12_P2F12.FindWeights()\n\n'''\nGetting new weights: always up to w(8)\n'''\nif True:\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8]\n\n chi_i_expr = 2*w4 - 8*w8 - w5\n eps_expr = (48*w4 + 96*w5 + 96*w8)\n eps_expr /= (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8)\n \n '''\n E^6_F4P6\n '''\n S5_E6_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E6_P4F6.GetWolfEqs()\n S5_E6_P4F6.GetTypEqs()\n\n cond_e4 = S5_E6_P4F6.e_expr[4] - sp_Rational('2/5')\n cond_e2 = S5_E6_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('2/17')\n cond_chi_i = chi_i_expr\n\n S5_E6_P4F6_eqs = [cond_e2,\n cond_eps, \n cond_chi_i, \n S5_E6_P4F6.typ_eq_s[4][0],\n S5_E6_P4F6.typ_eq_s[6][0]]\n\n S5_E6_P4F6_W = S5_E6_P4F6.FindWeights(S5_E6_P4F6_eqs)\n\n '''\n E^8_P4F6\n '''\n S5_E8_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E8_P4F6.GetWolfEqs()\n S5_E8_P4F6.GetTypEqs()\n\n cond_e4 = S5_E8_P4F6.e_expr[4] - sp_Rational('4/7')\n cond_e2 = S5_E8_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('10/31')\n cond_chi_i = chi_i_expr\n\n S5_E8_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E8_P4F6.typ_eq_s[4][0],\n S5_E8_P4F6.typ_eq_s[6][0]]\n\n S5_E8_P4F6_W = S5_E8_P4F6.FindWeights(S5_E8_P4F6_eqs)\n\n '''\n E^10_P4F6\n '''\n S5_E10_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E10_P4F6.GetWolfEqs()\n S5_E10_P4F6.GetTypEqs()\n\n cond_e4 = S5_E10_P4F6.e_expr[4] - sp_Rational('12/17')\n cond_e2 = S5_E10_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('38/89')\n cond_chi_i = chi_i_expr\n\n S5_E10_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E10_P4F6.typ_eq_s[4][0],\n S5_E10_P4F6.typ_eq_s[6][0]]\n\n S5_E10_P4F6_W = S5_E10_P4F6.FindWeights(S5_E10_P4F6_eqs)\n\n '''\n E^12_P4F6\n '''\n S5_E12_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E12_P4F6.GetWolfEqs()\n S5_E12_P4F6.GetTypEqs()\n\n cond_e4 = S5_E12_P4F6.e_expr[4] - sp_Rational(120, 143)\n cond_e2 = S5_E12_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational(136774, 271813)\n cond_chi_i = chi_i_expr\n\n S5_E12_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i,\n S5_E12_P4F6.typ_eq_s[4][0], \n S5_E12_P4F6.typ_eq_s[6][0]]\n\n S5_E12_P4F6_W = S5_E12_P4F6.FindWeights(S5_E12_P4F6_eqs)\n\n'''\nDefining output files: Flat interface\n'''\n\nstencil_string = {E6_P2F6_sym: 'E6_P2F6', \n E6_P4F6_sym: 'E6_P4F6', \n E8_P2F8_sym: 'E8_P2F8', \n E8_P4F6_sym: 'E8_P4F6', \n E10_P2F10_sym: 'E10_P2F10', \n E10_P4F6_sym: 'E10_P4F6', \n E12_P2F12_sym: 'E12_P2F12', \n E12_P4F6_sym: 'E12_P4F6'}\n\nstencil_dict = {E6_P2F6_sym: S5_E6_P2F6, \n E6_P4F6_sym: S5_E6_P4F6, \n E8_P2F8_sym: S5_E8_P2F8, \n E8_P4F6_sym: S5_E8_P4F6, \n E10_P2F10_sym: S5_E10_P2F10, \n E10_P4F6_sym: S5_E10_P4F6, \n E12_P2F12_sym: S5_E12_P2F12, \n E12_P4F6_sym: S5_E12_P4F6}\n\nstencil_sym_list = [E6_P2F6_sym, E6_P4F6_sym, \n E8_P2F8_sym, E8_P4F6_sym,\n E10_P2F10_sym, E10_P4F6_sym,\n E12_P2F12_sym, E12_P4F6_sym]\n\ndef FlatFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_flat_profile\")\n\ndef StencilPsiKey(stencil_sym, psi):\n return str(stencil_sym) + \"_\" + str(psi)\n\nflat_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / FlatFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / FlatFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / FlatFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / FlatFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / FlatFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / FlatFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / FlatFileName(E8_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / FlatFileName(E8_P4F6_sym, psis[1]), \n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / FlatFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / FlatFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / FlatFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / FlatFileName(E10_P4F6_sym, psis[1]), \n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / FlatFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / FlatFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / FlatFileName(E12_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / FlatFileName(E12_P4F6_sym, psis[1])}\n\nfrom idpy.Utils.ManageData import ManageData\n\n'''\nSimulations Loop\n'''\nstart = time.time()\n\nfor _psi in psis:\n print(\"The pseudo-potential is: \")\n display(_psi)\n for _G in Gs[_psi]:\n print(\"Coupling Constant G: \", _G)\n for stencil_sym in stencil_sym_list:\n display(stencil_sym)\n _stencil = stencil_dict[stencil_sym]\n _data_out = ManageData(dump_file = flat_files[StencilPsiKey(stencil_sym, _psi)])\n\n _data_key = _G\n _e2_swap = GetE2(_stencil)\n\n _is_data_there = False\n if _data_out.Read():\n print(\"File \", flat_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there = _data_key in _data_out.WhichData()\n\n if _is_data_there:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(flat_files[StencilPsiKey(stencil_sym, _psi)])\n print()\n\n if not _is_data_there:\n print(\"Data is not there...\")\n print(\"Preparing the simulation...\")\n print()\n _lbm = ShanChenMultiPhase(lang = lang, \n dim_sizes = (100, 4), \n xi_stencil = XIStencils['D2Q9'], \n f_stencil = _stencil.PushStencil(), \n psi_code = psi_codes[_psi],\n psi_sym = _psi,\n SC_G = _G, tau = 1., \n device = device, \n cl_kind = dev_kind, \n optimizer_flag = False)\n\n print(\"----------------------------------------------------\")\n print(\"\\nComputing/Retrieving flat mechanical equilibrium densities...\")\n print(\"psi: \", _psi, \"G: \", _G, \"Ws: \", _stencil.w_sol[0])\n\n _sc_eq_cache = ShanChanEquilibriumCache(stencil = _stencil, \n psi_f = _psi, G = _G, \n c2 = XIStencils['D2Q9']['c2'])\n\n _eq_params = _sc_eq_cache.GetFromCache()\n print(\"...done!\\n\")\n print(\"The mechanical equilibrium densities are:\")\n print(\"n_g (gas): \", _eq_params['n_g'], \n \", n_l (liq): \", _eq_params['n_l'])\n print(\"Surface tension: \", _eq_params['sigma_f'])\n print(\"(G_c, n_c) (crtitcal G and n): \", (_eq_params['G_c'], \n _eq_params['n_c']))\n print()\n print(\"Initializing flat interface\")\n\n '''\n _width: an arbitrary value\n '''\n _width = 41.36574669941303\n _width = 50\n\n _lbm.InitFlatInterface(n_g = _eq_params['n_g'], n_l = _eq_params['n_l'], \n width = _width, \n direction = 0, full_flag = False)\n\n print(\"Running the simulation...\")\n\n\n _lbm.MainLoop(range(0, 2**20, 2**14),\n convergence_functions = [CheckUConvergence])\n\n '''\n Getting a line from the density field\n '''\n _n = _lbm.sims_idpy_memory['n'].D2H()\n _n = _n.reshape(np.flip(_lbm.sims_vars['dim_sizes']))[0,:]\n _data_out.PushData(data = _n, key = _data_key)\n _data_out.Dump()\n\n print(\"Ending and deleting LB simulation object\")\n _lbm.End()\n del _lbm\n print()\n print()\n \nend = time.time()\ndef PrintElapsedTime(lapse):\n _n_sec_min, _n_min_hrs = 60, 60\n _n_sec_hrs, _n_hrs_day = _n_min_hrs * _n_sec_min, 24\n _n_sec_day = _n_hrs_day * _n_sec_hrs\n \n print(int(end - start)//_n_sec_day, \"d, \",\n (int(end - start)//_n_sec_hrs)%_n_hrs_day, \"h, \",\n (int(end - start)//_n_sec_min)%_n_min_hrs, \"m, \", \n int(end - start)% _n_sec_min, \"s\")\n\nPrintElapsedTime(start - end)\n```\n\n\n```python\n# Figure 4 (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_4.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 4 (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_4.png\")\n```\n\n## Figure 5\n\n*Uncached Equilibrium Densities*\n\n**0 d, 0 h, 22 m, 27 s, OpenCL, AMD Radeon RX 590 (64-bits), Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz**\n\n*Cached Equilibrium Densities*\n\n**0 d, 0 h, 16 m, 21 s, OpenCL, AMD Radeon RX 590 (64-bits), Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz**\n\n\n```python\n# Droplets Simulations for the Laplace data and velocity fields (click arrow to unfold)\nimport time\nstart = time.time()\n\nimport sys\nsys.path.append(\"../../\")\n\n########################################################################\n\nfrom pathlib import Path\nreproduced_results = Path(\"reproduced-results\")\nif not reproduced_results.is_dir():\n reproduced_results.mkdir()\n\nfrom sympy import exp as sp_exp\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom sympy import lambdify as sp_lambdify\nfrom IPython.display import display\nimport numpy as np\n\nfrom idpy.LBM.SCThermo import ShanChen\nfrom idpy.Utils.ManageData import ManageData\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\nfrom idpy.LBM.LBM import XIStencils\n\nfrom idpy.LBM.SCThermo import ShanChanEquilibriumCache\nfrom idpy.LBM.LBM import ShanChenMultiPhase, CheckUConvergence\nfrom idpy.IdpyCode import IdpyMemory\n\ndef GetE2(stencil):\n weights_list = stencil.w_sol[0]\n _value = stencil.e_expr[2]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n return _value\n\n'''\nHere we declare the symbol for the density as 'n'\nand define the pseudo-potential\n'''\n\nn = sp_symbols('n')\npsis = [sp_exp(-1/n), 1 - sp_exp(-n)]\npsi_codes = {psis[0]: 'exp((NType)(-1./ln))', \n psis[1]: '1. - exp(-(NType)ln)',}\n\nGs = {psis[0]: [-2.6, -3.1, -3.6], \n psis[1]: [-1.4, -1.6, -1.75]}\n\nE6_P2F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P2\\,F6}\")\nE8_P2F8_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P2\\,F8}\")\nE10_P2F10_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P2\\,F10}\")\nE12_P2F12_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P2\\,F12}\")\nE6_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P4\\,F6}\")\nE8_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P4\\,F6}\")\nE10_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P4\\,F6}\")\nE12_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P4\\,F6}\")\n\n'''\nGetting usual weights\n'''\n\nif True:\n '''\n E^6_F2P6\n '''\n S5_E6_P2F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4])\n S5_E6_P2F6_W = S5_E6_P2F6.FindWeights()\n\n '''\n E^8_F2P8\n '''\n S5_E8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n S5_E8_P2F8_W = S5_E8_P2F8.FindWeights()\n\n '''\n E^10_F2P10\n '''\n S5_E10_P2F10 = SCFStencils(E = BasisVectors(x_max = 3), \n len_2s = [1, 2, 4, 5, 8, 9, 10])\n S5_E10_P2F10_W = S5_E10_P2F10.FindWeights()\n\n '''\n E^12_F2P12\n '''\n S5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\n S5_E12_P2F12_W = S5_E12_P2F12.FindWeights()\n\n'''\nGetting new weights: always up to w(8)\n'''\nif True:\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8]\n\n chi_i_expr = 2*w4 - 8*w8 - w5\n eps_expr = (48*w4 + 96*w5 + 96*w8)\n eps_expr /= (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8) \n \n '''\n E^6_F4P6\n '''\n S5_E6_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E6_P4F6.GetWolfEqs()\n S5_E6_P4F6.GetTypEqs()\n\n cond_e4 = S5_E6_P4F6.e_expr[4] - sp_Rational('2/5')\n cond_e2 = S5_E6_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('2/17')\n cond_chi_i = chi_i_expr\n\n S5_E6_P4F6_eqs = [cond_e2,\n cond_eps, \n cond_chi_i, \n S5_E6_P4F6.typ_eq_s[4][0],\n S5_E6_P4F6.typ_eq_s[6][0]]\n\n S5_E6_P4F6_W = S5_E6_P4F6.FindWeights(S5_E6_P4F6_eqs)\n\n '''\n E^8_P4F6\n '''\n S5_E8_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E8_P4F6.GetWolfEqs()\n S5_E8_P4F6.GetTypEqs()\n\n cond_e4 = S5_E8_P4F6.e_expr[4] - sp_Rational('4/7')\n cond_e2 = S5_E8_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('10/31')\n cond_chi_i = chi_i_expr\n\n S5_E8_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E8_P4F6.typ_eq_s[4][0],\n S5_E8_P4F6.typ_eq_s[6][0]]\n\n S5_E8_P4F6_W = S5_E8_P4F6.FindWeights(S5_E8_P4F6_eqs)\n\n '''\n E^10_P4F6\n '''\n S5_E10_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E10_P4F6.GetWolfEqs()\n S5_E10_P4F6.GetTypEqs()\n\n cond_e4 = S5_E10_P4F6.e_expr[4] - sp_Rational('12/17')\n cond_e2 = S5_E10_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('38/89')\n cond_chi_i = chi_i_expr\n\n S5_E10_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E10_P4F6.typ_eq_s[4][0],\n S5_E10_P4F6.typ_eq_s[6][0]]\n\n S5_E10_P4F6_W = S5_E10_P4F6.FindWeights(S5_E10_P4F6_eqs)\n\n '''\n E^12_P4F6\n '''\n S5_E12_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E12_P4F6.GetWolfEqs()\n S5_E12_P4F6.GetTypEqs()\n\n cond_e4 = S5_E12_P4F6.e_expr[4] - sp_Rational(120, 143)\n cond_e2 = S5_E12_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational(136774, 271813)\n cond_chi_i = chi_i_expr\n\n S5_E12_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i,\n S5_E12_P4F6.typ_eq_s[4][0], \n S5_E12_P4F6.typ_eq_s[6][0]]\n\n S5_E12_P4F6_W = S5_E12_P4F6.FindWeights(S5_E12_P4F6_eqs)\n\n'''\nDefining output files: Flat interface\n'''\n\nstencil_string = {E6_P2F6_sym: 'E6_P2F6', \n E6_P4F6_sym: 'E6_P4F6', \n E8_P2F8_sym: 'E8_P2F8', \n E8_P4F6_sym: 'E8_P4F6', \n E10_P2F10_sym: 'E10_P2F10', \n E10_P4F6_sym: 'E10_P4F6', \n E12_P2F12_sym: 'E12_P2F12', \n E12_P4F6_sym: 'E12_P4F6'}\n\nstencil_dict = {E6_P2F6_sym: S5_E6_P2F6, \n E6_P4F6_sym: S5_E6_P4F6, \n E8_P2F8_sym: S5_E8_P2F8, \n E8_P4F6_sym: S5_E8_P4F6, \n E10_P2F10_sym: S5_E10_P2F10, \n E10_P4F6_sym: S5_E10_P4F6, \n E12_P2F12_sym: S5_E12_P2F12, \n E12_P4F6_sym: S5_E12_P4F6}\n\nstencil_sym_list = [E6_P2F6_sym, E6_P4F6_sym, \n E8_P2F8_sym, E8_P4F6_sym, \n E10_P2F10_sym, E10_P4F6_sym, \n E12_P2F12_sym, E12_P4F6_sym]\n\n#stencil_sym_list = [E12_P2F12_sym, E12_P4F6_sym]\n\ndef LaplaceFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_laplace\")\n\ndef DropletsFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_droplets\")\n\ndef StencilPsiKey(stencil_sym, psi):\n return str(stencil_sym) + \"_\" + str(psi)\n\nlaplace_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[1]),\n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[1])}\n\ndroplets_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[0]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[0]),\n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[1]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[1])}\n\nfrom idpy.Utils.ManageData import ManageData\n'''\nSimulation Loop\n'''\nfor _psi in psis[0:1]:\n print(\"The pseudo-potential is: \")\n display(_psi)\n for _G in Gs[_psi][-1:]:\n print(\"Coupling Constant G: \", _G)\n for stencil_sym in stencil_sym_list:\n display(stencil_sym)\n _stencil = stencil_dict[stencil_sym]\n _data_out_laplace = ManageData(dump_file = laplace_files[StencilPsiKey(stencil_sym, _psi)])\n _data_out_droplets = ManageData(dump_file = droplets_files[StencilPsiKey(stencil_sym, _psi)]) \n \n _e2_swap = GetE2(_stencil)\n print(\"e2: \", _e2_swap)\n \n for L in [255]:\n print(\"L: \", L, \"R: \", L/5.)\n\n _data_key = str(_G) + \"_\" + str(L)\n\n _is_data_there_laplace = False\n if _data_out_laplace.Read():\n print(\"File \", laplace_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_laplace = _data_key in _data_out_laplace.WhichData()\n\n if _is_data_there_laplace:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(laplace_files[StencilPsiKey(stencil_sym, _psi)])\n print() \n \n _is_data_there_droplets = False\n if L in [255, 351]:\n if _data_out_droplets.Read():\n print(\"File \", droplets_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_droplets = _data_key in _data_out_droplets.WhichData()\n\n if _is_data_there_droplets:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(droplets_files[StencilPsiKey(stencil_sym, _psi)])\n print()\n else:\n _is_data_there_droplets = True\n\n \n\n if not _is_data_there_laplace or not _is_data_there_droplets:\n print(\"Data is not there...\")\n print(\"Preparing the simulation...\")\n print()\n _lbm = ShanChenMultiPhase(lang = lang, \n dim_sizes = (L, L), \n xi_stencil = XIStencils['D2Q9'], \n f_stencil = _stencil.PushStencil(), \n psi_code = psi_codes[_psi],\n psi_sym = _psi,\n SC_G = _G, tau = 1., \n device = device, \n cl_kind = dev_kind, \n optimizer_flag = True)\n\n print(\"----------------------------------------------------\")\n print(\"\\nComputing/Retrieving flat mechanical equilibrium densities...\")\n print(\"psi: \", _psi, \"G: \", _G, \"Ws: \", _stencil.w_sol[0])\n\n _sc_eq_cache = ShanChanEquilibriumCache(stencil = _stencil, \n psi_f = _psi, G = _G, \n c2 = XIStencils['D2Q9']['c2'])\n\n _eq_params = _sc_eq_cache.GetFromCache()\n print(\"...done!\\n\")\n print(\"The mechanical equilibrium densities are:\")\n print(\"n_g (gas): \", _eq_params['n_g'], \n \", n_l (liq): \", _eq_params['n_l'])\n print(\"Surface tension: \", _eq_params['sigma_f'])\n print(\"(G_c, n_c) (crtitcal G and n): \", (_eq_params['G_c'], \n _eq_params['n_c']))\n print()\n print(\"Initializing flat interface\")\n\n _lbm.InitRadialInterface(n_g = _eq_params['n_g'], n_l = _eq_params['n_l'], \n R = L/5., full_flag = True)\n\n print(\"Running the simulation...\")\n\n\n _lbm.MainLoop(range(0, 2**22, 2**14),\n convergence_functions = [CheckUConvergence])\n\n '''\n Getting average density, inner and outer density for\n computing the Gibbs radius\n '''\n \n _n_ave = IdpyMemory.Sum(_lbm.sims_idpy_memory['n'])/(L*L)\n _n = _lbm.sims_idpy_memory['n'].D2H()\n _n = _n.reshape(np.flip(_lbm.sims_vars['dim_sizes']))\n \n _center = tuple(_lbm.sims_vars['dim_center'])\n _n_in = _n[_center]\n _n_out = _n[(L - 1, L - 1)]\n \n _R_Gibbs = L*np.sqrt((_n_ave - _n_out)/(np.pi * (_n_in - _n_out)))\n \n def BulkP(n_value, _e2):\n _psi_f = sp_lambdify(n, _psi)\n p = n_value * XIStencils['D2Q9']['c2']\n p += 0.5 * _G * _e2 * (_psi_f(n_value)) ** 2\n return p\n \n _p_in, _p_out = BulkP(_n_in, _e2_swap), BulkP(_n_out, _e2_swap)\n _delta_p = _p_in - _p_out\n \n print(\"L: \", L, \"Start R: \", L/5., \"R_Gibbs: \", _R_Gibbs)\n print(\"Estimated surface tension: \", _delta_p * _R_Gibbs)\n print(\"Analytic surface tension: \", _eq_params['sigma_f'])\n \n _dict_out = {'delta_p': _delta_p, \n 'R_Gibbs': _R_Gibbs}\n \n if not _is_data_there_laplace:\n _data_out_laplace.PushData(data = _dict_out, key = _data_key)\n _data_out_laplace.Dump()\n \n if not _is_data_there_droplets:\n _u = _lbm.sims_idpy_memory['u'].D2H() \n _data_out_droplets.PushData(data = _u, key = _data_key)\n _data_out_droplets.Dump() \n\n print(\"Ending and deleting LB simulation object\")\n _lbm.End()\n del _lbm\n print()\n print()\n \nend = time.time()\ndef PrintElapsedTime(lapse):\n _n_sec_min, _n_min_hrs = 60, 60\n _n_sec_hrs, _n_hrs_day = _n_min_hrs * _n_sec_min, 24\n _n_sec_day = _n_hrs_day * _n_sec_hrs\n \n print(int(end - start)//_n_sec_day, \"d, \",\n (int(end - start)//_n_sec_hrs)%_n_hrs_day, \"h, \",\n (int(end - start)//_n_sec_min)%_n_min_hrs, \"m, \", \n int(end - start)% _n_sec_min, \"s\")\n\nPrintElapsedTime(start - end)\n```\n\n### Figure 5 (a) \\& (b)\n\n\n```python\n# Figure 5 (a), (b) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_5_ab.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 5 (a), (b) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_5_ab.png\")\n```\n\n### Figure 5 (c) \\& (d)\n\n\n```python\n# Figure 5 (c), (d) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_5_cd.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 5 (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_5_cd.png\")\n```\n\n### Figure 5 (e) \\& (f)\n\n\n```python\n# Figure 5 (e), (f) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_5_ef.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 5 (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_5_ef.png\")\n```\n\n### Figure 5 (g) \\& (h)\n\n\n```python\n# Figure 5 (g), (h) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_5_gh.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 5 (g), (h) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_5_gh.png\")\n```\n\n## Figure 6\n\n*Uncached Equilibrium Densities*\n\n**0 d, 0 h, 38 m, 3 s, OpenCL, AMD Radeon RX 590 (64-bits), Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz**\n\n\n```python\n# Droplets Simulations for the Laplace data and velocity fields (click arrow to unfold)\nimport time\nstart = time.time()\n\nimport sys\nsys.path.append(\"../../\")\n\n########################################################################\n\nfrom pathlib import Path\nreproduced_results = Path(\"reproduced-results\")\nif not reproduced_results.is_dir():\n reproduced_results.mkdir()\n\nfrom sympy import exp as sp_exp\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom sympy import lambdify as sp_lambdify\nfrom IPython.display import display\nimport numpy as np\n\nfrom idpy.LBM.SCThermo import ShanChen\nfrom idpy.Utils.ManageData import ManageData\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\nfrom idpy.LBM.LBM import XIStencils\n\nfrom idpy.LBM.SCThermo import ShanChanEquilibriumCache\nfrom idpy.LBM.LBM import ShanChenMultiPhase, CheckUConvergence\nfrom idpy.IdpyCode import IdpyMemory\n\ndef GetE2(stencil):\n weights_list = stencil.w_sol[0]\n _value = stencil.e_expr[2]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n return _value\n\n'''\nHere we declare the symbol for the density as 'n'\nand define the pseudo-potential\n'''\n\nn = sp_symbols('n')\npsis = [sp_exp(-1/n), 1 - sp_exp(-n)]\npsi_codes = {psis[0]: 'exp((NType)(-1./ln))', \n psis[1]: '1. - exp(-(NType)ln)',}\n\nGs = {psis[0]: [-2.6, -3.1, -3.6], \n psis[1]: [-1.4, -1.6, -1.75]}\n\nE6_P2F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P2\\,F6}\")\nE8_P2F8_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P2\\,F8}\")\nE10_P2F10_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P2\\,F10}\")\nE12_P2F12_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P2\\,F12}\")\nE6_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P4\\,F6}\")\nE8_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P4\\,F6}\")\nE10_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P4\\,F6}\")\nE12_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P4\\,F6}\")\n\n'''\nGetting usual weights\n'''\n\nif True:\n '''\n E^6_F2P6\n '''\n S5_E6_P2F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4])\n S5_E6_P2F6_W = S5_E6_P2F6.FindWeights()\n\n '''\n E^8_F2P8\n '''\n S5_E8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n S5_E8_P2F8_W = S5_E8_P2F8.FindWeights()\n\n '''\n E^10_F2P10\n '''\n S5_E10_P2F10 = SCFStencils(E = BasisVectors(x_max = 3), \n len_2s = [1, 2, 4, 5, 8, 9, 10])\n S5_E10_P2F10_W = S5_E10_P2F10.FindWeights()\n\n '''\n E^12_F2P12\n '''\n S5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\n S5_E12_P2F12_W = S5_E12_P2F12.FindWeights()\n\n'''\nGetting new weights: always up to w(8)\n'''\nif True:\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8]\n\n chi_i_expr = 2*w4 - 8*w8 - w5\n eps_expr = (48*w4 + 96*w5 + 96*w8)\n eps_expr /= (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8) \n \n '''\n E^6_F4P6\n '''\n S5_E6_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E6_P4F6.GetWolfEqs()\n S5_E6_P4F6.GetTypEqs()\n\n cond_e4 = S5_E6_P4F6.e_expr[4] - sp_Rational('2/5')\n cond_e2 = S5_E6_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('2/17')\n cond_chi_i = chi_i_expr\n\n S5_E6_P4F6_eqs = [cond_e2,\n cond_eps, \n cond_chi_i, \n S5_E6_P4F6.typ_eq_s[4][0],\n S5_E6_P4F6.typ_eq_s[6][0]]\n\n S5_E6_P4F6_W = S5_E6_P4F6.FindWeights(S5_E6_P4F6_eqs)\n\n '''\n E^8_P4F6\n '''\n S5_E8_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E8_P4F6.GetWolfEqs()\n S5_E8_P4F6.GetTypEqs()\n\n cond_e4 = S5_E8_P4F6.e_expr[4] - sp_Rational('4/7')\n cond_e2 = S5_E8_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('10/31')\n cond_chi_i = chi_i_expr\n\n S5_E8_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E8_P4F6.typ_eq_s[4][0],\n S5_E8_P4F6.typ_eq_s[6][0]]\n\n S5_E8_P4F6_W = S5_E8_P4F6.FindWeights(S5_E8_P4F6_eqs)\n\n '''\n E^10_P4F6\n '''\n S5_E10_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E10_P4F6.GetWolfEqs()\n S5_E10_P4F6.GetTypEqs()\n\n cond_e4 = S5_E10_P4F6.e_expr[4] - sp_Rational('12/17')\n cond_e2 = S5_E10_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('38/89')\n cond_chi_i = chi_i_expr\n\n S5_E10_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E10_P4F6.typ_eq_s[4][0],\n S5_E10_P4F6.typ_eq_s[6][0]]\n\n S5_E10_P4F6_W = S5_E10_P4F6.FindWeights(S5_E10_P4F6_eqs)\n\n '''\n E^12_P4F6\n '''\n S5_E12_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E12_P4F6.GetWolfEqs()\n S5_E12_P4F6.GetTypEqs()\n\n cond_e4 = S5_E12_P4F6.e_expr[4] - sp_Rational(120, 143)\n cond_e2 = S5_E12_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational(136774, 271813)\n cond_chi_i = chi_i_expr\n\n S5_E12_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i,\n S5_E12_P4F6.typ_eq_s[4][0], \n S5_E12_P4F6.typ_eq_s[6][0]]\n\n S5_E12_P4F6_W = S5_E12_P4F6.FindWeights(S5_E12_P4F6_eqs)\n\n'''\nDefining output files: Flat interface\n'''\n\nstencil_string = {E6_P2F6_sym: 'E6_P2F6', \n E6_P4F6_sym: 'E6_P4F6', \n E8_P2F8_sym: 'E8_P2F8', \n E8_P4F6_sym: 'E8_P4F6', \n E10_P2F10_sym: 'E10_P2F10', \n E10_P4F6_sym: 'E10_P4F6', \n E12_P2F12_sym: 'E12_P2F12', \n E12_P4F6_sym: 'E12_P4F6'}\n\nstencil_dict = {E6_P2F6_sym: S5_E6_P2F6, \n E6_P4F6_sym: S5_E6_P4F6, \n E8_P2F8_sym: S5_E8_P2F8, \n E8_P4F6_sym: S5_E8_P4F6, \n E10_P2F10_sym: S5_E10_P2F10, \n E10_P4F6_sym: S5_E10_P4F6, \n E12_P2F12_sym: S5_E12_P2F12, \n E12_P4F6_sym: S5_E12_P4F6}\n\nstencil_sym_list = [E6_P2F6_sym, E6_P4F6_sym, \n E8_P2F8_sym, E8_P4F6_sym, \n E10_P2F10_sym, E10_P4F6_sym, \n E12_P2F12_sym, E12_P4F6_sym]\n\n#stencil_sym_list = [E12_P2F12_sym, E12_P4F6_sym]\n\ndef LaplaceFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_laplace\")\n\ndef DropletsFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_droplets\")\n\ndef StencilPsiKey(stencil_sym, psi):\n return str(stencil_sym) + \"_\" + str(psi)\n\nlaplace_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[1]),\n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[1])}\n\ndroplets_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[0]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[0]),\n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[1]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[1])}\n\nfrom idpy.Utils.ManageData import ManageData\n'''\nSimulation Loop\n'''\nfor _psi in psis:\n print(\"The pseudo-potential is: \")\n display(_psi)\n for _G in Gs[_psi][-1:]:\n print(\"Coupling Constant G: \", _G)\n for stencil_sym in stencil_sym_list:\n display(stencil_sym)\n _stencil = stencil_dict[stencil_sym]\n _data_out_laplace = ManageData(dump_file = laplace_files[StencilPsiKey(stencil_sym, _psi)])\n _data_out_droplets = ManageData(dump_file = droplets_files[StencilPsiKey(stencil_sym, _psi)]) \n \n _e2_swap = GetE2(_stencil)\n print(\"e2: \", _e2_swap)\n \n for L in [255]:\n print(\"L: \", L, \"R: \", L/5.)\n\n _data_key = str(_G) + \"_\" + str(L)\n\n _is_data_there_laplace = False\n if _data_out_laplace.Read():\n print(\"File \", laplace_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_laplace = _data_key in _data_out_laplace.WhichData()\n\n if _is_data_there_laplace:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(laplace_files[StencilPsiKey(stencil_sym, _psi)])\n print() \n \n _is_data_there_droplets = False\n if L in [255, 351]:\n if _data_out_droplets.Read():\n print(\"File \", droplets_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_droplets = _data_key in _data_out_droplets.WhichData()\n\n if _is_data_there_droplets:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(droplets_files[StencilPsiKey(stencil_sym, _psi)])\n print()\n else:\n _is_data_there_droplets = True\n\n \n\n if not _is_data_there_laplace or not _is_data_there_droplets:\n print(\"Data is not there...\")\n print(\"Preparing the simulation...\")\n print()\n _lbm = ShanChenMultiPhase(lang = lang, \n dim_sizes = (L, L), \n xi_stencil = XIStencils['D2Q9'], \n f_stencil = _stencil.PushStencil(), \n psi_code = psi_codes[_psi],\n psi_sym = _psi,\n SC_G = _G, tau = 1., \n device = device, \n cl_kind = dev_kind, \n optimizer_flag = True)\n\n print(\"----------------------------------------------------\")\n print(\"\\nComputing/Retrieving flat mechanical equilibrium densities...\")\n print(\"psi: \", _psi, \"G: \", _G, \"Ws: \", _stencil.w_sol[0])\n\n _sc_eq_cache = ShanChanEquilibriumCache(stencil = _stencil, \n psi_f = _psi, G = _G, \n c2 = XIStencils['D2Q9']['c2'])\n\n _eq_params = _sc_eq_cache.GetFromCache()\n print(\"...done!\\n\")\n print(\"The mechanical equilibrium densities are:\")\n print(\"n_g (gas): \", _eq_params['n_g'], \n \", n_l (liq): \", _eq_params['n_l'])\n print(\"Surface tension: \", _eq_params['sigma_f'])\n print(\"(G_c, n_c) (crtitcal G and n): \", (_eq_params['G_c'], \n _eq_params['n_c']))\n print()\n print(\"Initializing flat interface\")\n\n _lbm.InitRadialInterface(n_g = _eq_params['n_g'], n_l = _eq_params['n_l'], \n R = L/5., full_flag = True)\n\n print(\"Running the simulation...\")\n\n\n _lbm.MainLoop(range(0, 2**22, 2**14),\n convergence_functions = [CheckUConvergence])\n\n '''\n Getting average density, inner and outer density for\n computing the Gibbs radius\n '''\n \n _n_ave = IdpyMemory.Sum(_lbm.sims_idpy_memory['n'])/(L*L)\n _n = _lbm.sims_idpy_memory['n'].D2H()\n _n = _n.reshape(np.flip(_lbm.sims_vars['dim_sizes']))\n \n _center = tuple(_lbm.sims_vars['dim_center'])\n _n_in = _n[_center]\n _n_out = _n[(L - 1, L - 1)]\n \n _R_Gibbs = L*np.sqrt((_n_ave - _n_out)/(np.pi * (_n_in - _n_out)))\n \n def BulkP(n_value, _e2):\n _psi_f = sp_lambdify(n, _psi)\n p = n_value * XIStencils['D2Q9']['c2']\n p += 0.5 * _G * _e2 * (_psi_f(n_value)) ** 2\n return p\n \n _p_in, _p_out = BulkP(_n_in, _e2_swap), BulkP(_n_out, _e2_swap)\n _delta_p = _p_in - _p_out\n \n print(\"L: \", L, \"Start R: \", L/5., \"R_Gibbs: \", _R_Gibbs)\n print(\"Estimated surface tension: \", _delta_p * _R_Gibbs)\n print(\"Analytic surface tension: \", _eq_params['sigma_f'])\n \n _dict_out = {'delta_p': _delta_p, \n 'R_Gibbs': _R_Gibbs}\n \n if not _is_data_there_laplace:\n _data_out_laplace.PushData(data = _dict_out, key = _data_key)\n _data_out_laplace.Dump()\n \n if not _is_data_there_droplets:\n _u = _lbm.sims_idpy_memory['u'].D2H() \n _data_out_droplets.PushData(data = _u, key = _data_key)\n _data_out_droplets.Dump() \n\n print(\"Ending and deleting LB simulation object\")\n _lbm.End()\n del _lbm\n print()\n print()\n \nend = time.time()\ndef PrintElapsedTime(lapse):\n _n_sec_min, _n_min_hrs = 60, 60\n _n_sec_hrs, _n_hrs_day = _n_min_hrs * _n_sec_min, 24\n _n_sec_day = _n_hrs_day * _n_sec_hrs\n \n print(int(end - start)//_n_sec_day, \"d, \",\n (int(end - start)//_n_sec_hrs)%_n_hrs_day, \"h, \",\n (int(end - start)//_n_sec_min)%_n_min_hrs, \"m, \", \n int(end - start)% _n_sec_min, \"s\")\n\nPrintElapsedTime(start - end)\n```\n\n### Figure 6 (a), (b), (c) and (d)\n\n\n```python\n# Figure 6 (a), (b), (c) and (d) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run \"figure_6_abcd.py\" {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 6 (a), (b), (c) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_6_abcd.png\")\n```\n\n### Figure 6 (e), (f), (g) and (h)\n\n\n```python\n# Figure 6 (e), (f), (g) and (h) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run \"figure_6_efgh.py\" {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 6 (e), (f), (g), (h) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_6_efgh.png\")\n```\n\n## Figure 7\n\n*Cached Equilibrium Densities*\n\n**0 d, 1 h, 9 m, 59 s, OpenCL, AMD Radeon RX 590 (64-bits), Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz**\n\n\n```python\n# Droplets Simulations for the Laplace data and velocity fields (click arrow to unfold)\nimport time\nstart = time.time()\n\nimport sys\nsys.path.append(\"../../\")\n\n########################################################################\n\nfrom pathlib import Path\nreproduced_results = Path(\"reproduced-results\")\nif not reproduced_results.is_dir():\n reproduced_results.mkdir()\n\nfrom sympy import exp as sp_exp\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom sympy import lambdify as sp_lambdify\nfrom IPython.display import display\nimport numpy as np\n\nfrom idpy.LBM.SCThermo import ShanChen\nfrom idpy.Utils.ManageData import ManageData\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\nfrom idpy.LBM.LBM import XIStencils\n\nfrom idpy.LBM.SCThermo import ShanChanEquilibriumCache\nfrom idpy.LBM.LBM import ShanChenMultiPhase, CheckUConvergence\nfrom idpy.IdpyCode import IdpyMemory\n\ndef GetE2(stencil):\n weights_list = stencil.w_sol[0]\n _value = stencil.e_expr[2]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n return _value\n\n'''\nHere we declare the symbol for the density as 'n'\nand define the pseudo-potential\n'''\n\nn = sp_symbols('n')\npsis = [sp_exp(-1/n), 1 - sp_exp(-n)]\npsi_codes = {psis[0]: 'exp((NType)(-1./ln))', \n psis[1]: '1. - exp(-(NType)ln)',}\n\nGs = {psis[0]: [-2.6, -3.1, -3.6], \n psis[1]: [-1.4, -1.6, -1.75]}\n\nE6_P2F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P2\\,F6}\")\nE8_P2F8_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P2\\,F8}\")\nE10_P2F10_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P2\\,F10}\")\nE12_P2F12_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P2\\,F12}\")\nE6_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(6)}_{P4\\,F6}\")\nE8_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(8)}_{P4\\,F6}\")\nE10_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(10)}_{P4\\,F6}\")\nE12_P4F6_sym = sp_symbols(\"\\\\boldsymbol{E}^{(12)}_{P4\\,F6}\")\n\n'''\nGetting usual weights\n'''\n\nif True:\n '''\n E^6_F2P6\n '''\n S5_E6_P2F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4])\n S5_E6_P2F6_W = S5_E6_P2F6.FindWeights()\n\n '''\n E^8_F2P8\n '''\n S5_E8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n S5_E8_P2F8_W = S5_E8_P2F8.FindWeights()\n\n '''\n E^10_F2P10\n '''\n S5_E10_P2F10 = SCFStencils(E = BasisVectors(x_max = 3), \n len_2s = [1, 2, 4, 5, 8, 9, 10])\n S5_E10_P2F10_W = S5_E10_P2F10.FindWeights()\n\n '''\n E^12_F2P12\n '''\n S5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\n S5_E12_P2F12_W = S5_E12_P2F12.FindWeights()\n\n'''\nGetting new weights: always up to w(8)\n'''\nif True:\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8]\n\n chi_i_expr = 2*w4 - 8*w8 - w5\n eps_expr = (48*w4 + 96*w5 + 96*w8)\n eps_expr /= (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8) \n \n '''\n E^6_F4P6\n '''\n S5_E6_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E6_P4F6.GetWolfEqs()\n S5_E6_P4F6.GetTypEqs()\n\n cond_e4 = S5_E6_P4F6.e_expr[4] - sp_Rational('2/5')\n cond_e2 = S5_E6_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('2/17')\n cond_chi_i = chi_i_expr\n\n S5_E6_P4F6_eqs = [cond_e2,\n cond_eps, \n cond_chi_i, \n S5_E6_P4F6.typ_eq_s[4][0],\n S5_E6_P4F6.typ_eq_s[6][0]]\n\n S5_E6_P4F6_W = S5_E6_P4F6.FindWeights(S5_E6_P4F6_eqs)\n\n '''\n E^8_P4F6\n '''\n S5_E8_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E8_P4F6.GetWolfEqs()\n S5_E8_P4F6.GetTypEqs()\n\n cond_e4 = S5_E8_P4F6.e_expr[4] - sp_Rational('4/7')\n cond_e2 = S5_E8_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('10/31')\n cond_chi_i = chi_i_expr\n\n S5_E8_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E8_P4F6.typ_eq_s[4][0],\n S5_E8_P4F6.typ_eq_s[6][0]]\n\n S5_E8_P4F6_W = S5_E8_P4F6.FindWeights(S5_E8_P4F6_eqs)\n\n '''\n E^10_P4F6\n '''\n S5_E10_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E10_P4F6.GetWolfEqs()\n S5_E10_P4F6.GetTypEqs()\n\n cond_e4 = S5_E10_P4F6.e_expr[4] - sp_Rational('12/17')\n cond_e2 = S5_E10_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational('38/89')\n cond_chi_i = chi_i_expr\n\n S5_E10_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i, \n S5_E10_P4F6.typ_eq_s[4][0],\n S5_E10_P4F6.typ_eq_s[6][0]]\n\n S5_E10_P4F6_W = S5_E10_P4F6.FindWeights(S5_E10_P4F6_eqs)\n\n '''\n E^12_P4F6\n '''\n S5_E12_P4F6 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\n S5_E12_P4F6.GetWolfEqs()\n S5_E12_P4F6.GetTypEqs()\n\n cond_e4 = S5_E12_P4F6.e_expr[4] - sp_Rational(120, 143)\n cond_e2 = S5_E12_P4F6.e_expr[2] - 1\n cond_eps = eps_expr - sp_Rational(136774, 271813)\n cond_chi_i = chi_i_expr\n\n S5_E12_P4F6_eqs = [cond_e2, \n cond_eps, \n cond_chi_i,\n S5_E12_P4F6.typ_eq_s[4][0], \n S5_E12_P4F6.typ_eq_s[6][0]]\n\n S5_E12_P4F6_W = S5_E12_P4F6.FindWeights(S5_E12_P4F6_eqs)\n\n'''\nDefining output files: Flat interface\n'''\n\nstencil_string = {E6_P2F6_sym: 'E6_P2F6', \n E6_P4F6_sym: 'E6_P4F6', \n E8_P2F8_sym: 'E8_P2F8', \n E8_P4F6_sym: 'E8_P4F6', \n E10_P2F10_sym: 'E10_P2F10', \n E10_P4F6_sym: 'E10_P4F6', \n E12_P2F12_sym: 'E12_P2F12', \n E12_P4F6_sym: 'E12_P4F6'}\n\nstencil_dict = {E6_P2F6_sym: S5_E6_P2F6, \n E6_P4F6_sym: S5_E6_P4F6, \n E8_P2F8_sym: S5_E8_P2F8, \n E8_P4F6_sym: S5_E8_P4F6, \n E10_P2F10_sym: S5_E10_P2F10, \n E10_P4F6_sym: S5_E10_P4F6, \n E12_P2F12_sym: S5_E12_P2F12, \n E12_P4F6_sym: S5_E12_P4F6}\n\nstencil_sym_list = [E6_P2F6_sym, E6_P4F6_sym, \n E8_P2F8_sym, E8_P4F6_sym, \n E10_P2F10_sym, E10_P4F6_sym, \n E12_P2F12_sym, E12_P4F6_sym]\n\n#stencil_sym_list = [E12_P2F12_sym, E12_P4F6_sym]\n\ndef LaplaceFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_laplace\")\n\ndef DropletsFileName(stencil_sym, psi):\n psi_str = str(psi).replace(\"/\", \"_\").replace(\"-\", \"_\")\n psi_str = psi_str.replace(\" \", \"_\")\n psi_str = psi_str.replace(\"(\", \"\").replace(\")\",\"\")\n lang_str = str(lang) + \"_\" + device_str\n\n return (lang_str + stencil_string[stencil_sym] + \"_\" + \n psi_str + \"_droplets\")\n\ndef StencilPsiKey(stencil_sym, psi):\n return str(stencil_sym) + \"_\" + str(psi)\n\nlaplace_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E10_P4F6_sym, psis[1]),\n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / LaplaceFileName(E12_P4F6_sym, psis[1])}\n\ndroplets_files = \\\n {StencilPsiKey(E6_P2F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[0]), \n StencilPsiKey(E6_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[0]), \n StencilPsiKey(E8_P2F8_sym, psis[0]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[0]), \n StencilPsiKey(E8_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[0]),\n StencilPsiKey(E10_P2F10_sym, psis[0]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[0]), \n StencilPsiKey(E10_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[0]), \n StencilPsiKey(E12_P2F12_sym, psis[0]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[0]), \n StencilPsiKey(E12_P4F6_sym, psis[0]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[0]),\n StencilPsiKey(E6_P2F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P2F6_sym, psis[1]), \n StencilPsiKey(E6_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E6_P4F6_sym, psis[1]), \n StencilPsiKey(E8_P2F8_sym, psis[1]): reproduced_results / DropletsFileName(E8_P2F8_sym, psis[1]), \n StencilPsiKey(E8_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E8_P4F6_sym, psis[1]),\n StencilPsiKey(E10_P2F10_sym, psis[1]): reproduced_results / DropletsFileName(E10_P2F10_sym, psis[1]), \n StencilPsiKey(E10_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E10_P4F6_sym, psis[1]), \n StencilPsiKey(E12_P2F12_sym, psis[1]): reproduced_results / DropletsFileName(E12_P2F12_sym, psis[1]), \n StencilPsiKey(E12_P4F6_sym, psis[1]): reproduced_results / DropletsFileName(E12_P4F6_sym, psis[1])}\n\nfrom idpy.Utils.ManageData import ManageData\n'''\nSimulation Loop\n'''\nfor _psi in psis:\n print(\"The pseudo-potential is: \")\n display(_psi)\n for _G in Gs[_psi][-1:]:\n print(\"Coupling Constant G: \", _G)\n for stencil_sym in stencil_sym_list:\n display(stencil_sym)\n _stencil = stencil_dict[stencil_sym]\n _data_out_laplace = ManageData(dump_file = laplace_files[StencilPsiKey(stencil_sym, _psi)])\n _data_out_droplets = ManageData(dump_file = droplets_files[StencilPsiKey(stencil_sym, _psi)]) \n \n _e2_swap = GetE2(_stencil)\n print(\"e2: \", _e2_swap)\n \n for L in [255, 351]:\n print(\"L: \", L, \"R: \", L/5.)\n\n _data_key = str(_G) + \"_\" + str(L)\n\n _is_data_there_laplace = False\n if _data_out_laplace.Read():\n print(\"File \", laplace_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_laplace = _data_key in _data_out_laplace.WhichData()\n\n if _is_data_there_laplace:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(laplace_files[StencilPsiKey(stencil_sym, _psi)])\n print() \n \n _is_data_there_droplets = False\n if L in [255, 351]:\n if _data_out_droplets.Read():\n print(\"File \", droplets_files[StencilPsiKey(stencil_sym, _psi)], \"exists!\")\n print(\"Checking if data is there...\")\n _is_data_there_droplets = _data_key in _data_out_droplets.WhichData()\n\n if _is_data_there_droplets:\n print(\"Data Found! No need to run the simulation\")\n print(\"To perform the simulation again remove the file:\")\n print(droplets_files[StencilPsiKey(stencil_sym, _psi)])\n print()\n else:\n _is_data_there_droplets = True\n\n \n\n if not _is_data_there_laplace or not _is_data_there_droplets:\n print(\"Data is not there...\")\n print(\"Preparing the simulation...\")\n print()\n _lbm = ShanChenMultiPhase(lang = lang, \n dim_sizes = (L, L), \n xi_stencil = XIStencils['D2Q9'], \n f_stencil = _stencil.PushStencil(), \n psi_code = psi_codes[_psi],\n psi_sym = _psi,\n SC_G = _G, tau = 1., \n device = device, \n cl_kind = dev_kind, \n optimizer_flag = True)\n\n print(\"----------------------------------------------------\")\n print(\"\\nComputing/Retrieving flat mechanical equilibrium densities...\")\n print(\"psi: \", _psi, \"G: \", _G, \"Ws: \", _stencil.w_sol[0])\n\n _sc_eq_cache = ShanChanEquilibriumCache(stencil = _stencil, \n psi_f = _psi, G = _G, \n c2 = XIStencils['D2Q9']['c2'])\n\n _eq_params = _sc_eq_cache.GetFromCache()\n print(\"...done!\\n\")\n print(\"The mechanical equilibrium densities are:\")\n print(\"n_g (gas): \", _eq_params['n_g'], \n \", n_l (liq): \", _eq_params['n_l'])\n print(\"Surface tension: \", _eq_params['sigma_f'])\n print(\"(G_c, n_c) (crtitcal G and n): \", (_eq_params['G_c'], \n _eq_params['n_c']))\n print()\n print(\"Initializing flat interface\")\n\n _lbm.InitRadialInterface(n_g = _eq_params['n_g'], n_l = _eq_params['n_l'], \n R = L/5., full_flag = True)\n\n print(\"Running the simulation...\")\n\n\n _lbm.MainLoop(range(0, 2**22, 2**14),\n convergence_functions = [CheckUConvergence])\n\n '''\n Getting average density, inner and outer density for\n computing the Gibbs radius\n '''\n \n _n_ave = IdpyMemory.Sum(_lbm.sims_idpy_memory['n'])/(L*L)\n _n = _lbm.sims_idpy_memory['n'].D2H()\n _n = _n.reshape(np.flip(_lbm.sims_vars['dim_sizes']))\n \n _center = tuple(_lbm.sims_vars['dim_center'])\n _n_in = _n[_center]\n _n_out = _n[(L - 1, L - 1)]\n \n _R_Gibbs = L*np.sqrt((_n_ave - _n_out)/(np.pi * (_n_in - _n_out)))\n \n def BulkP(n_value, _e2):\n _psi_f = sp_lambdify(n, _psi)\n p = n_value * XIStencils['D2Q9']['c2']\n p += 0.5 * _G * _e2 * (_psi_f(n_value)) ** 2\n return p\n \n _p_in, _p_out = BulkP(_n_in, _e2_swap), BulkP(_n_out, _e2_swap)\n _delta_p = _p_in - _p_out\n \n print(\"L: \", L, \"Start R: \", L/5., \"R_Gibbs: \", _R_Gibbs)\n print(\"Estimated surface tension: \", _delta_p * _R_Gibbs)\n print(\"Analytic surface tension: \", _eq_params['sigma_f'])\n \n _dict_out = {'delta_p': _delta_p, \n 'R_Gibbs': _R_Gibbs}\n \n if not _is_data_there_laplace:\n _data_out_laplace.PushData(data = _dict_out, key = _data_key)\n _data_out_laplace.Dump()\n \n if not _is_data_there_droplets:\n _u = _lbm.sims_idpy_memory['u'].D2H() \n _data_out_droplets.PushData(data = _u, key = _data_key)\n _data_out_droplets.Dump() \n\n print(\"Ending and deleting LB simulation object\")\n _lbm.End()\n del _lbm\n print()\n print()\n \nend = time.time()\ndef PrintElapsedTime(lapse):\n _n_sec_min, _n_min_hrs = 60, 60\n _n_sec_hrs, _n_hrs_day = _n_min_hrs * _n_sec_min, 24\n _n_sec_day = _n_hrs_day * _n_sec_hrs\n \n print(int(end - start)//_n_sec_day, \"d, \",\n (int(end - start)//_n_sec_hrs)%_n_hrs_day, \"h, \",\n (int(end - start)//_n_sec_min)%_n_min_hrs, \"m, \", \n int(end - start)% _n_sec_min, \"s\")\n\nPrintElapsedTime(start - end)\n```\n\n### Figure 7 (a) and (b)\n\n\n```python\n# Figure 7 (a) and (b) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_7_ab.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 7 (a), (b) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_7_ab.png\")\n```\n\n### Figure 7 (c) and (d)\n\n\n```python\n# Figure 7 (c) and (d) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_7_cd.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 7 (c), (d) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_7_cd.png\")\n```\n\n### Figure 7 (e) and (f)\n\n\n```python\n# Figure 7 (e) and (f) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_7_ef.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 7 (e), (f) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\n## Make sure \nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_7_ef.png\")\n```\n\n### Figure 7 (g) and (h)\n\n\n```python\n# Figure 7 (g) and (h) (click arrow to unfold)\n'''\nlast entry (100) is for the resolution in DPI\nthe value is 200 for the published version\n'''\n_args = [device_str, lang, 100]\nprint(_args)\n%run figure_7_gh.py {_args[0]} {_args[1]} {_args[2]}\n```\n\n\n```python\n# Display Figure 7 (g), (h) (click arrow to unfold + see comment below)\n## After displaying the image make sure to go to \"Kernel -> Restart & Clear Output\"\n## It looks like a bug prevents codefolding/table of contents to load properly if\n## the notebook is saved and restored with the images opened.\nfrom IPython import display\ndisplay.Image(\"./reproduced-figures/figure_7_gh.png\")\n```\n\n## Appendix\n\n### Appendix C\n\nHere we report the symbolic calculations presented in Appendix C, concerning the expressions of the weights $W(\\ell)$ as a function of the isotropy constants $e_{2n}$ and $\\varepsilon$.\n\n\n```python\n# Equations (C1), (C2), (C3) and (C4) (click arrow to unfold)\nimport sys \nsys.path.append(\"../../\")\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom sympy.solvers import solve\nfrom sympy import simplify, collect, cancel, apart, factor, ratsimp, together\n\nfrom IPython.display import display\n\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\n\ndef GetEpsilonExpr(stencil):\n '''\n GetVarepsilon: \n function for printing the value of \\varepsilon\n the 5 weights expression is assumed\n ''' \n w1, w2, w4, w5, w8, w9, w10 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8) w(9) w(10)\")\n w13, w16, w17 = sp_symbols(\"w(13) w(16) w(17)\")\n eps = sp_symbols('\\\\varepsilon')\n w_sym_list = [w1, w2, w4, w5, w8, w9, w10, w13, w16, w17]\n \n eps_expr = \\\n (48*w4 + 96*w5 + 96*w8 + 288*w9 + 576*w10 + 704*w13 + 960*w16 + 1920*w17)/\\\n (6*w1 + 12*w2 + 72*w4 + 156*w5 + 144*w8 + 342*w9 + \n 696*w10 + 812*w13 + 1056*w16 + 2124*w17)\n \n for i in range(10 - len(stencil.w_sym_list)):\n eps_expr = eps_expr.subs(w_sym_list[len(stencil.w_sym_list) + i], 0)\n \n return eps_expr\n\ndef GetIsotropyConditionsSym(stencil, order, weights_list = None):\n '''\n GetIsotropyConditions: \n function for printing the isotropy conditions\n for a given stencil and an arbitrary set of weights\n compatibly with the stencil. If no set of weights\n is provided the solution already provided by the \n stencil class is used\n '''\n if weights_list is None:\n weights_list = stencil.w_sol[0]\n \n _swap_sym = sp_symbols('I_{' + str(order) + '\\,0}')\n display(_swap_sym)\n display(stencil.B2n_expr[order][0])\n _value = stencil.B2n_expr[order][0]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n display(together(ratsimp(simplify(_value))))\n print()\n \n for i in range(len(stencil.B2q_expr[order])):\n _swap_sym = sp_symbols('I_{' + str(order) + '\\,' + str(i + 1) + '}')\n display(_swap_sym)\n display(stencil.B2q_expr[order][i])\n _value = stencil.B2q_expr[order][i]\n for w_i in range(len(stencil.w_sym_list)):\n _value = _value.subs(stencil.w_sym_list[w_i], \n weights_list[w_i])\n display(together(ratsimp(simplify(_value))))\n print()\n \ndef GetLambdaChiSym(weights_list):\n w1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\n chi_i, lambda_i = sp_symbols('\\\\chi_I \\\\Lambda_I')\n w_sym_list = [w1, w2, w4, w5, w8]\n \n chi_i_expr = 2*w4 - 8*w8 - w5\n lambda_i_expr = sp_Rational('1/2')*w1 - 2*w2 + 6*w4 - 24*w8 - 6*w5\n \n display(lambda_i)\n display(lambda_i_expr)\n _value = lambda_i_expr\n for w_i in range(len(weights_list)):\n _value = _value.subs(w_sym_list[w_i], \n weights_list[w_i])\n display(together(ratsimp(simplify(_value))))\n print() \n \n display(chi_i)\n display(chi_i_expr)\n _value = chi_i_expr\n for w_i in range(len(weights_list)):\n _value = _value.subs(w_sym_list[w_i], \n weights_list[w_i])\n display(together(ratsimp(simplify(_value))))\n print()\n\nE8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\nE8_P2F8.GetWolfEqs()\nE8_P2F8.GetTypEqs()\n\neps_expr = GetEpsilonExpr(E8_P2F8)\neps_sym = sp_symbols(\"\\\\varepsilon\")\n\nequations = []\nequations += [E8_P2F8.e_sym[2] - E8_P2F8.e_expr[2]]\nequations += [E8_P2F8.e_sym[4] - E8_P2F8.e_expr[4]]\nequations += [E8_P2F8.e_sym[6] - E8_P2F8.e_expr[6]]\nequations += [E8_P2F8.e_sym[8] - E8_P2F8.e_expr[8]]\nequations += [eps_sym - eps_expr]\n\nprint(\"The system of equations reads (=0 is understood):\")\nfor _eq in equations:\n display(_eq)\n\nprint()\nprint()\nprint(\"These are the solutions:\")\nw_sol = solve(equations, E8_P2F8.w_sym_list)\nw_sol_nice = {}\n\nfor _w_sym in E8_P2F8.w_sym_list:\n w_sol_nice[_w_sym] = together(ratsimp(w_sol[_w_sym]))\n display(_w_sym)\n display(w_sol_nice[_w_sym])\n \nprint()\nprint()\nprint(\"The forcing isotropy conditions read:\")\nw_sol_nice_list = [w_sol_nice[_w_sym] for _w_sym in w_sol_nice]\n\nGetIsotropyConditionsSym(E8_P2F8, 4, w_sol_nice_list)\nGetIsotropyConditionsSym(E8_P2F8, 6, w_sol_nice_list)\nGetIsotropyConditionsSym(E8_P2F8, 8, w_sol_nice_list)\n\nprint()\nprint()\nprint(\"The 4-th order pressure tensor isotropy conditions read:\")\nGetLambdaChiSym(w_sol_nice_list)\n```\n\n### Appendix D\nHere we provide the connection between Equation (D14) and (D15)\n\n\n```python\n# Verification of equation (D15) (click arrow to unfold)\nimport sys \nsys.path.append(\"../../\")\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom IPython.display import display\n\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\n\nS5_E12_P2F12 = SCFStencils(E = BasisVectors(x_max = 4), \n len_2s = [1, 2, 4, 5, 8, 9, 10, 13, 16, 17])\n\nS5_E12_P2F12.GetWolfEqs()\nS5_E12_P2F12.FindWeights()\n\nw1, w2, w4, w5, w8 = sp_symbols(\"w(1) w(2) w(4) w(5) w(8)\")\nw9, w10, w13, w16, w17 = sp_symbols(\"w(9) w(10) w(13) w(16) w(17)\")\n\n_sigma_c_E8 = -(w1 + 16*w4 + 18*w5)/2\n_sigma_c_E10 = _sigma_c_E8 - (81*w9 + 128*w10)/2\n_sigma_c_E12 = _sigma_c_E10 - (50*w13 + 256*w16 + 450*w17)/2\n\ndisplay(S5_E12_P2F12.e_sym[4])\ndisplay(S5_E12_P2F12.e_expr[4])\n\ndisplay(sp_symbols('I_{4\\,0}'))\ndisplay(S5_E12_P2F12.typ_eq_s[4][0])\n\ndisplay(sp_symbols('\\hat{\\sigma}'))\ndisplay(_sigma_c_E12)\nprint(\"Now we verify Eq.(D15)\")\ndisplay(-S5_E12_P2F12.e_sym[4]/2-sp_symbols('I_{4\\,0}')/4)\ndisplay(-S5_E12_P2F12.e_expr[4]/2 - S5_E12_P2F12.typ_eq_s[4][0]/4)\n```\n\n### Appendix F\n\nHere we show that starting from Eq. (F3) one can recover Eq. (F2). Since the coefficients of different vector groups are independent on each other, by checking a stencil yielding high order forcing isotropy one automatically checks the consistency of all lower orders.\n\nThe 14-th order for the forcing is imposed as a limit given the actual structure of the code which uses only the square length to label different vector groups. As discussed in the manuscript this is not sufficient as soon as $\\ell > 25$\n\n\n```python\n# Check link between (F3) and (F2) (click arrow to unfold)\nimport sys \nsys.path.append(\"../../\")\nfrom sympy import symbols as sp_symbols\nfrom sympy import Rational as sp_Rational\nfrom IPython.display import display\n\nfrom idpy.LBM.SCFStencils import SCFStencils, BasisVectors\n\nE14_P2F14 = SCFStencils(E = BasisVectors(x_max = 5), \n len_2s = [1, 2, \n 4, \n 5, 8, \n 9, 10, \n 13, 16, 17, \n 18, 20, 25])\n\nE8_P2F8 = SCFStencils(E = BasisVectors(x_max = 2), \n len_2s = [1, 2, 4, 5, 8])\n\nprint(\"Weights for the 14-th order isotropy stencil\")\nfor elem in E14_P2F14.FindWeights():\n display(elem)\nprint()\n\nprint(\"Computing Eqs. (F2) and (F3)\")\nE14_P2F14.RecoverTypEqs()\nE14_P2F14.GetTypEqs()\nprint()\n\nprint(\"Comparison\")\nfor n2 in range(4, 16, 2):\n for k in range(len(E14_P2F14.rec_typ_eq_s[n2])):\n display(sp_symbols('\\hat{I}_{' + str(n2) + '\\,' + str(k) + '}'))\n print(\"Result from (F3): \")\n display(E14_P2F14.rec_typ_eq_s[n2][k])\n print(\"Corresponding in (F2): \")\n display(E14_P2F14.typ_eq_s[n2][k])\n print(\"Subtraction: \", \n E14_P2F14.rec_typ_eq_s[n2][k] - E14_P2F14.typ_eq_s[n2][k])\n print()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "612a5f5047e6e66e0020d0d186e8370d613cc025", "size": 174200, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ShanChenPressureTensorIsotropy.ipynb", "max_stars_repo_name": "lullimat/arXiv-2009.12522", "max_stars_repo_head_hexsha": "b9c2c813983eedfc29a59a95ab441570bc7a5ba7", "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": "ShanChenPressureTensorIsotropy.ipynb", "max_issues_repo_name": "lullimat/arXiv-2009.12522", "max_issues_repo_head_hexsha": "b9c2c813983eedfc29a59a95ab441570bc7a5ba7", "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": "ShanChenPressureTensorIsotropy.ipynb", "max_forks_repo_name": "lullimat/arXiv-2009.12522", "max_forks_repo_head_hexsha": "b9c2c813983eedfc29a59a95ab441570bc7a5ba7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.343218279, "max_line_length": 808, "alphanum_fraction": 0.491423651, "converted": true, "num_tokens": 41145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.1755380649971796, "lm_q1q2_score": 0.06371491199047714}} {"text": "# MO-book Style and Hints\n\n## Preamble for Google Colab\n\nA core premise of the book and companion notebooks is that code should be immediately usable through the browser without extensive installation procedures. \n\nGoogle Colab is a target platform for every notebook. With a few exceptions, tis preamble is included at the start of every notebook.\n\n\n```python\n# install Pyomo and solvers for Google Colab\nimport sys\nif \"google.colab\" in sys.modules:\n !wget -N -q https://raw.githubusercontent.com/jckantor/MO-book/main/tools/install_on_colab.py \n %run install_on_colab.py\n```\n\nIt may be worth testing if a similar procedure could be used for Windows or MacOS platforms. Using `wget` on windows, however, apparently requires installation, while `curl` provides sufficient functionality and available on Windows, MacOS, and Google Colab (need to verify this is true for Windows).\n\n\n```python\n!curl -s https://raw.githubusercontent.com/jckantor/MO-book/main/tools/_mobook.py -o mobook.py\nimport mobook\nmobook.setup_pyomo()\nmobook.setup_solvers()\nmobook.svg()\n```\n\n## Matplotlib graphics\n\nThe `mobook.svg()` causes `matplotlib` graphics to appear as SVG files with embedded stix fonts. On JupyterLab, holding down the shift key while clicking on the image will give a `Save Image As ...` menu option that will save an SVG formatted image. This needs to be tuned up tested, but gives a path forward with the book images.\n\n* Font styles documented at https://matplotlib.org/stable/api/font_manager_api.html#matplotlib.font_manager.FontProperties\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom IPython.display import set_matplotlib_formats\n\n\nx = np.linspace(0, 200, 2001)\nplt.plot(x, np.sin(x))\nplt.title(\"$sin(x)$\")\n```\n\n\n\n\n Text(0.5, 1.0, '$sin(x)$')\n\n\n\n\n \n\n \n\n\n## Main Book Drawings\n\n\n```python\nimport matplotlib\n%matplotlib inline\n\nuse_latex_fonts_on_colab = False\n\nmatplotlib.rcParams['text.usetex'] = use_latex_fonts_on_colab\n\nimport sys\nif 'google.colab' in sys.modules:\n import shutil\n if not shutil.which('pyomo'):\n !pip install pyomo\n assert( shutil.which('pyomo') )\n\n if use_latex_fonts_on_colab and not shutil.which( '/usr/share/texmf/tex/latex/type1cm' ):\n ! sudo apt-get install texlive-latex-recommended \n ! sudo apt-get install dvipng texlive-latex-extra texlive-fonts-recommended \n ! wget http://mirrors.ctan.org/macros/latex/contrib/type1cm.zip \n ! unzip type1cm.zip -d /tmp/type1cm \n ! cd /tmp/type1cm/type1cm/ && sudo latex type1cm.ins\n ! sudo mkdir /usr/share/texmf/tex/latex/type1cm \n ! sudo cp /tmp/type1cm/type1cm/type1cm.sty /usr/share/texmf/tex/latex/type1cm \n ! sudo texhash \n !apt install cm-super\nelse: # locally, assume that LaTeX is installed and use its fonts\n matplotlib.rcParams['text.usetex'] = True \n```\n\n\n```python\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n\n# https://stackoverflow.com/questions/17687213/how-to-obtain-the-same-font-style-size-etc-in-matplotlib-output-as-in-latex\nparams = {'font.size' : 10, # the book seems to be in 10pt, change if needed\n 'font.family' : 'lmodern',\n }\n\nplt.rcParams.update(params)\ndefault_size_inches = (3.54,3.54) \nplt.rcParams['figure.figsize'] = default_size_inches\n```\n\n\n```python\n!curl -sO https://raw.githubusercontent.com/jckantor/MO-book/main/tools/install_on_colab.py\n```\n\n\n```python\n[ k for k in plt.rcParams.keys() if 'font' in k ]\n```\n\n\n\n\n ['font.cursive',\n 'font.family',\n 'font.fantasy',\n 'font.monospace',\n 'font.sans-serif',\n 'font.serif',\n 'font.size',\n 'font.stretch',\n 'font.style',\n 'font.variant',\n 'font.weight',\n 'legend.fontsize',\n 'legend.title_fontsize',\n 'mathtext.fontset',\n 'pdf.fonttype',\n 'pdf.use14corefonts',\n 'pgf.rcfonts',\n 'ps.fonttype',\n 'svg.fonttype']\n\n\n\n\n```python\nimport pyomo.environ as pyo\nimport pyomo\npyomo.__version__\n```\n\n\n\n\n '6.4.0'\n\n\n\n\n```python\n%load_ext autoreload\n%autoreload 2\n```\n\n The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n\n\n\n```python\nimport sys\nsys.path.append('./code/')\nimport draw\n```\n\n\n```python\ndraw.SetOutputPath( '/work in progress/MO book/results' )\n```\n\n# Chapter one\n\n\n```python\nimport sympy, math, numpy as np, sys\n\nx = sympy.Symbol('x')\n\n# now pi is a symbol, just like x\npi = sympy.Symbol('pi')\n\n# we redefine h using the same right-hand-side code as before, \n# but now with x and pi as symbols\nh = (pi*x**2 + 500)/(2*pi*x+50)\n\n# to have the drivative on the symbol pi we need it from the new version of h\nhprime = sympy.diff( h, x )\n\nsolution = sympy.solveset( sympy.diff( h, x ), x )\nsolution\n```\n\n\n\n\n$\\displaystyle \\left\\{\\frac{- 5 \\sqrt{5} \\sqrt{4 \\pi + 5} - 25}{\\pi}, \\frac{5 \\sqrt{5} \\sqrt{4 \\pi + 5} - 25}{\\pi}\\right\\}$\n\n\n\n\n```python\ndef Preety( formula ):\n from sympy import latex\n from IPython.display import display, Math\n display( Math( latex( formula ) ) )\n\nPreety( h )\nPreety( sympy.simplify( h ) )\nPreety( hprime )\nPreety( sympy.simplify( hprime ) )\n```\n\n\n$\\displaystyle \\frac{\\pi x^{2} + 500}{2 \\pi x + 50}$\n\n\n\n$\\displaystyle \\frac{\\pi x^{2} + 500}{2 \\left(\\pi x + 25\\right)}$\n\n\n\n$\\displaystyle \\frac{2 \\pi x}{2 \\pi x + 50} - \\frac{2 \\pi \\left(\\pi x^{2} + 500\\right)}{\\left(2 \\pi x + 50\\right)^{2}}$\n\n\n\n$\\displaystyle \\frac{\\pi \\left(- \\pi x^{2} + 2 x \\left(\\pi x + 25\\right) - 500\\right)}{2 \\left(\\pi x + 25\\right)^{2}}$\n\n\n\n```python\nPreety( solution )\n\ns = max(solution.subs( pi, math.pi ).evalf())\n\nprint(s)\n```\n\n\n$\\displaystyle \\left\\{\\frac{- 5 \\sqrt{5} \\sqrt{4 \\pi + 5} - 25}{\\pi}, \\frac{5 \\sqrt{5} \\sqrt{4 \\pi + 5} - 25}{\\pi}\\right\\}$\n\n\n 6.95803920980307\n\n\n\n```python\ndef Plot( h, s=None, start=0, stop=20, width=18, height=8, file_name=None ):\n with plt.rc_context({'figure.figsize': (width,height)}): \n plt.rcParams['figure.figsize'] = (width,height)\n\n plt.grid()\n plt.xlabel(r'$x$')\n plt.ylabel(r'$h(x)$')\n\n plt.xticks(np.arange(start, stop+1, step=1))\n\n x = sympy.Symbol('x')\n f = sympy.lambdify( x, h.subs( pi, math.pi ) )\n\n import numpy\n x = numpy.linspace(start=start,stop=stop,num=100) \n y = f(x)\n\n plt.plot(x,y,label='$h(x)='+sympy.latex(h)+'$',linewidth=3)\n if s is None:\n x = numpy.linspace(start=start,stop=stop,num=stop-start+1) \n y = f(x)\n plt.plot(x,y, 'bo', label='some points', markersize=8)\n else:\n plt.plot(s,f(s), 'ro', label='$x^*$ optimum', markersize=8)\n\n plt.legend()\n\n if file_name is not None:\n plt.savefig( draw._output_path+file_name, bbox_inches='tight', pad_inches=0 )\n\n plt.show()\n```\n\n\n```python\nPlot( h, None, 0, 20, 8, 5, 'AliceSome.pdf' )\n```\n\n\n```python\nPlot( h, s, 0, 20, 6, 3, 'AliceOptimum.pdf' )\n```\n\n# Chapter two\n\n\n```python\ndef SimpleDraw( model ):\n with plt.rc_context({'figure.figsize': (8,6)}):\n return draw.Draw( model, isolines=True, file_name=model.name+'.pdf' )\n```\n\n\n```python\ndef CreateBIM():\n m = pyo.ConcreteModel('BIM')\n \n m.x1 = pyo.Var( within=pyo.NonNegativeReals )\n m.x2 = pyo.Var( within=pyo.NonNegativeReals )\n\n @m.Objective( sense= pyo.maximize )\n def obj(m):\n return 12*m.x1 + 9*m.x2\n\n @m.Constraint() \n def silicon(m): return m.x1 <= 1000\n @m.Constraint() \n def germanium(m): return m.x2 <= 1500\n @m.Constraint()\n def plastic(m): return m.x1 + m.x2 <= 1750\n @m.Constraint()\n def copper(m): return 4*m.x1 + 2*m.x2 <= 4800\n \n return m\n```\n\n\n```python\nSimpleDraw( CreateBIM() )\n```\n\n\n```python\nbasicfeasiblesolutions = draw.Draw( CreateBIM(), 'BuildingMicrochips.pdf' )\n```\n\n\n```python\nbasicfeasiblesolutions.rename(columns={'x1': '$x_1$', 'x2': '$x_2$'}).astype(int).to_latex(draw._output_path+'chips.tex')\nif 'google.colab' in sys.modules:\n import os\n from google.colab import files\n files.download( 'chips.tex' )\n```\n\n C:\\Users\\joaquimg\\AppData\\Local\\Temp\\ipykernel_22328\\2016893662.py:1: FutureWarning: In future versions `DataFrame.to_latex` is expected to utilise the base implementation of `Styler.to_latex` for formatting and rendering. The arguments signature may therefore change. It is recommended instead to use `DataFrame.style.to_latex` which also contains additional functionality.\n basicfeasiblesolutions.rename(columns={'x1': '$x_1$', 'x2': '$x_2$'}).astype(int).to_latex(draw._output_path+'chips.tex')\n\n\n# Chapter three\n\nThe first version was a copy of [the model on this deck](http://web.tecnico.ulisboa.pt/mcasquilho/compute/_linpro/TaylorB_module_c.pdf]).\n\nBelow several versions of possible models.\n\n\n```python\ndef CreateBBaExample():\n model = pyo.ConcreteModel('BBa')\n \n model.x1 = pyo.Var( within=pyo.NonNegativeReals )\n model.x2 = pyo.Var( within=pyo.NonNegativeReals )\n\n model.obj = pyo.Objective( sense= pyo.maximize\n , expr = 2*model.x1 + 3*model.x2 )\n\n model.c1 = pyo.Constraint(expr = 2*model.x1 + 1*model.x2 <= 10)\n model.c2 = pyo.Constraint(expr = 3*model.x1 + 6*model.x2 <= 40)\n \n return model\n```\n\n\n```python\ndraw.Draw( CreateBBaExample(), integer=True, isolines=True, file_name=CreateBBaExample().name+'.pdf', title='First B\\&B example' )\n```\n\n\n```python\nsol,root = draw.BB( CreateBBaExample(), solver='gurobi_direct' )\n```\n\n\n```python\ndraw.ToTikz(root, 'BBa.tex', fig_only=True )\n```\n\n\n```python\ndraw.DrawBB(root, 'BB.pdf')\n```\n\n\n```python\ndraw.DotExporter(root).to_picture(draw._output_path+'BBplain.pdf')\n```\n\n\n```python\ndef CreateBBbExample():\n m = pyo.ConcreteModel('BBb')\n \n m.x1 = pyo.Var( within=pyo.NonNegativeReals )\n m.x2 = pyo.Var( within=pyo.NonNegativeReals )\n\n m.obj= pyo.Objective( sense= pyo.maximize\n , expr = 1*m.x1 + 2*m.x2 )\n\n m.c1 = pyo.Constraint(expr = -4*m.x1 + 5*m.x2 <= 11)\n m.c2 = pyo.Constraint(expr = 5*m.x1 - 2*m.x2 <= 9)\n \n return m\n```\n\n\n```python\ndraw.Draw( CreateBBbExample(), integer=True, isolines=False, file_name=None, title='test' )\n```\n\n\n```python\nsol,root = draw.BB( CreateBBbExample(), solver='gurobi_direct' )\n```\n\n\n```python\ndraw.ToTikz(root, 'BBb.tex', fig_only=True )\n```\n\n\n```python\ndraw.DotExporter(root).to_dotfile(draw._output_path+'test.dot')\n```\n\n\n```python\ndraw.DrawBB(root,'BBBook.pdf')\n```\n\n\n```python\ndef CreateBIMmodified():\n m = pyo.ConcreteModel('BIMmodified')\n \n m.x1 = pyo.Var( within=pyo.NonNegativeReals )\n m.x2 = pyo.Var( within=pyo.NonNegativeReals )\n\n m.obj = pyo.Objective( sense= pyo.maximize\n , expr = 12*m.x1 + 9*m.x2 )\n\n m.silicon = pyo.Constraint(expr = m.x1 <= 900 )\n m.germanium = pyo.Constraint(expr = m.x2 <= 1350)\n m.plastic = pyo.Constraint(expr = m.x1 + m.x2 <= 1801)\n m.copper = pyo.Constraint(expr = 4*m.x1 + 2*m.x2 <= 4903)\n \n return m\n```\n\n\n```python\nsol,root = draw.BB( CreateBIMmodified(), solver='gurobi_direct', draw_integer=False, xlim=(-50,1050), ylim=(-50,1550) )\n```\n\n\n```python\ndraw.ToTikz(root, 'BIMmodified.tex', fig_only=True )\n```\n\n\n```python\ndef CreateBIMperturbed():\n m = pyo.ConcreteModel('BIMperturbed')\n \n m.x1 = pyo.Var( within=pyo.NonNegativeReals )\n m.x2 = pyo.Var( within=pyo.NonNegativeReals )\n\n m.obj = pyo.Objective( sense= pyo.maximize\n , expr = 12*m.x1 + 9*m.x2 )\n\n m.silicon = pyo.Constraint(expr = m.x1 <= 1000 )\n m.germanium = pyo.Constraint(expr = m.x2 <= 1500)\n m.plastic = pyo.Constraint(expr = m.x1 + m.x2 <= 1750)\n m.copper = pyo.Constraint(expr = 4.04*m.x1 + 2.02*m.x2 <= 4800)\n \n return m\n```\n\n\n```python\nsol,root = draw.BB( CreateBIMperturbed(), solver='gurobi_direct', draw_integer=False, xlim=(-50,1050), ylim=(-50,1550) )\n```\n\n\n```python\ndraw.ToTikz(root, 'BIMperturbed.tex', fig_only=True )\n```\n\n\n```python\ndraw.Draw( CreateBIM(), integer=False, isolines=True, file_name=None, title='First B\\&B example' )\n```\n\n\n```python\nnx,ny = 6,5\nF = { (2,1), (3,1), (4,1), (2,2), (3,2), (4,2), (3,3), (4,3), (3,4) }\n\nimport itertools \npoints = list(itertools.product( range(0,nx+1), range(0,ny+1) ) )\nfeasible = [ p for p in points if p in F ]\ninfeasible = [ p for p in points if not p in F ]\nif infeasible:\n plt.plot( *zip(*infeasible), 'ro', zorder=2, markersize=9)\nif feasible:\n plt.plot( *zip(*feasible), 'bo', zorder=2, markersize=9)\n \ndef Pol( coord, style, alpha, width ):\n coord.append(coord[0]) #repeat the first point to create a 'closed loop'\n plt.plot(*zip(*coord),style, alpha=alpha, linewidth=width, zorder=1) \n\nPol( [ (1.6,.5), (2.5,5), (4.5,3.5), (4,.5) ], 'g-', 1, 2 )\nPol( [ (2,1), (2,2), (2.5, 3.5), (3.5, 4.5), (4,3), (4,1) ], 'm--', .8, 3 )\nPol( [ (2,1), (2,2), (3,4), (4,3), (4,1) ], 'c-.', 1, 3 )\n\nax = plt.gca()\n\n# Hide the right and top spines\nfor position in ['left','right','top','bottom']:\n ax.spines[position].set_visible(False)\n \nax.xaxis.set_visible(False)\nax.yaxis.set_visible(False)\n\nplt.savefig( draw._output_path+'3regions.pdf', bbox_inches='tight', pad_inches=0 )\nplt.show()\n```\n", "meta": {"hexsha": "adf0340a80001c38d5966d728056747c95c7a08e", "size": 569426, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tools/main book drawings.ipynb", "max_stars_repo_name": "jckantor/MO-book", "max_stars_repo_head_hexsha": "f6ead8dc06327ec5cbb7065ead8a6df0631c05fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-03T22:07:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T22:07:45.000Z", "max_issues_repo_path": "tools/main book drawings.ipynb", "max_issues_repo_name": "jckantor/MO-book", "max_issues_repo_head_hexsha": "f6ead8dc06327ec5cbb7065ead8a6df0631c05fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2022-02-11T09:50:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:52:48.000Z", "max_forks_repo_path": "tools/main book drawings.ipynb", "max_forks_repo_name": "jckantor/MO-book", "max_forks_repo_head_hexsha": "f6ead8dc06327ec5cbb7065ead8a6df0631c05fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2022-02-06T02:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:56:53.000Z", "avg_line_length": 171.6689779922, "max_line_length": 39718, "alphanum_fraction": 0.8489004717, "converted": true, "num_tokens": 4101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.14804719427274565, "lm_q1q2_score": 0.06368210808199473}} {"text": "```python\nimport sys\nsys.path = ['/Users/sebastian/github/mlxtend/'] + sys.path\n```\n\n\n```python\n%load_ext watermark\n%watermark -a 'Sebastian Raschka' -v\n```\n\n Sebastian Raschka \n \n CPython 3.4.3\n IPython 3.0.0\n\n\n# Artificial Neurons and Single-Layer Neural Networks\n\n## - How Machine Learning Algorithms Work Part 1\n\n
    \n
    \n\n**This article offers a brief glimpse of the history and basic concepts of machine learning. We will take a look at the first algorithmically described neural network and the gradient descent algorithm in context of adaptive linear neurons, which will not only introduce the principles of machine learning but also serve as the basis for modern multilayer neural networks in future articles.**\n\n## Sections\n\n- [Introduction](#Introduction)\n- [Artificial Neurons and the McCulloch-Pitts Model](#Artificial-Neurons-and-the-McCulloch-Pitts-Model)\n- [Frank Rosenblatt's Perceptron](#Frank-Rosenblatt's-Perceptron)\n - [The Unit Step Function](#The-Unit-Step-Function)\n - [The Perceptron Learning Rule](#The-Perceptron-Learning-Rule)\n - [Implementing the Perceptron Rule in Python](#Implementing-the-Perceptron-Rule-in-Python)\n - [Problems with Perceptrons](#Problems-with-Perceptrons)\n- [Adaptive Linear Neurons and the Delta Rule](#Adaptive-Linear-Neurons-and-the-Delta-Rule)\n - [Gradient Descent](#Gradient-Descent)\n - [The Gradient Descent Rule in Action](#The-Gradient-Descent-Rule-in-Action)\n - [Online Learning via Stochastic Gradient Descent](#Online-Learning-via-Stochastic-Gradient-Descent)\n- [What's Next?](#What's-Next?)\n- [References](#References)\n\n
    \n
    \n\n# Introduction\n\n[[back to top](#Sections)]\n\nMachine learning is one of the hottest and most exciting fields in the modern age of technology. Thanks to machine learning, we enjoy robust email spam filters, convenient text and voice recognition, reliable web search engines, challenging chess players, and, hopefully soon, safe and efficient self-driving cars. \n\nWithout any doubt, machine learning has become a big and popular field, and sometimes it may be challenging to see the (random) forest for the (decision) trees. Thus, I thought that it might be worthwhile to explore different machine learning algorithms in more detail by not only discussing the theory but also by implementing them step by step.\n\nTo briefly summarize what machine learning is all about: \"[Machine learning is the] field of study that gives computers the ability to learn without being explicitly programmed\" (Arthur Samuel, 1959). Machine learning is about the development and use of algorithms that can recognize patterns in data in order to make decisions based on statistics, probability theory, combinatorics, and optimization.\n\n\n\n\nThe first article in this series will introduce perceptrons and the adaline (ADAptive LINear NEuron), which fall into the category of single-layer neural networks. The perceptron is not only the first algorithmically described learning algorithm [[1](#References)], but it is also very intuitive, easy to implement, and a good entry point to the (re-discovered) modern state-of-the-art machine learning algorithms: Artificial neural networks (or \"deep learning\" if you like). As we will see later, the adaline is a consequent improvement of the perceptron algorithm and offers a good opportunity to learn about a popular optimization algorithm in machine learning: gradient descent.\n\n
    \n
    \n\n# Artificial Neurons and the McCulloch-Pitts Model\n\n[[back to top](#Sections)]\n\nThe initial idea of the perceptron dates back to the work of Warren McCulloch and Walter Pitts in 1943 [[2](#References)], who drew an analogy between biological neurons and simple logic gates with binary outputs. In more intuitive terms, neurons can be understood as the subunits of a neural network in a biological brain. Here, the signals of variable magnitudes arrive at the dendrites. Those input signals are then accumulated in the cell body of the neuron, and if the accumulated signal exceeds a certain threshold, a output signal is generated that which will be passed on by the axon.\n\n\n\n\n
    \n
    \n\n# Frank Rosenblatt's Perceptron\n\n[[back to top](#Sections)]\n\nTo continue with the story, a few years after McCulloch and Walter Pitt, Frank Rosenblatt published the first concept of the Perceptron learning rule [[1](#References)]. The main idea was to define an algorithm in order to learn the values of the weights $w$ that are then multiplied with the input features in order to make a decision whether a neuron fires or not. In context of pattern classification, such an algorithm could be useful to determine if a sample belongs to one class or the other. \n\n\n\n\n\nTo put the perceptron algorithm into the broader context of machine learning: The perceptron belongs to the category of supervised learning algorithms, single-layer binary linear classifiers to be more specific. In brief, the task is to predict to which of two possible categories a certain data point belongs based on a set of input variables. In this article, I don't want to discuss the concept of predictive modeling and classification in too much detail, but if you prefer more background information, please see my previous article \"[Introduction to supervised learning](http://sebastianraschka.com/Articles/2014_intro_supervised_learning.html)\".\n\n
    \n
    \n\n## The Unit Step Function\n\n[[back to top](#Sections)]\n\nBefore we dive deeper into the algorithm(s) for learning the weights of the artificial neuron, let us take a brief look at the basic notation. In the following sections, we will label the *positive* and *negative* class in our binary classification setting as \"1\" and \"-1\", respectively. Next, we define an activation function $g(\\mathbf{z})$ that takes a linear combination of the input values $\\mathbf{x}$ and weights $\\mathbf{w}$ as input ($\\mathbf{z} = w_1x_{1} + \\dots + w_mx_{m}$), and if $g(\\mathbf{z})$ is greater than a defined threshold $\\theta$ we predict 1 and -1 otherwise; in this case, this activation function $g$ is an alternative form of a simple \"unit step function,\" which is sometimes also called \"Heaviside step function.\" \n\n*(Please note that the *unit step* is classically defined as being equal to 0 if $ z < 0$ and 1 for $z \\ge 0$; nonetheless, we will refer to the following piece-wise linear function with -1 if $z < \\theta$ and 1 for $z \\ge \\theta$ as *unit step function* for simplicity).*\n\n$$\n g(\\mathbf{z}) =\\begin{cases}\n 1 & \\text{if $\\mathbf{z} \\ge \\theta$}\\\\\n -1 & \\text{otherwise}.\n \\end{cases}\n$$\n\n\nwhere\n\n$$\\mathbf{z} = w_1x_{1} + \\dots + w_mx_{m} = \\sum_{j=1}^{m} x_{j}w_{j} \\\\ = \\mathbf{w}^T\\mathbf{x}$$\n\n$\\mathbf{w}$ is the feature vector, and $\\mathbf{x}$ is an $m$-dimensional sample from the training dataset:\n\n$$ \n\\mathbf{w} = \\begin{bmatrix}\n w_{1} \\\\\n \\vdots \\\\\n w_{m}\n\\end{bmatrix}\n\\quad \\mathbf{x} = \\begin{bmatrix}\n x_{1} \\\\\n \\vdots \\\\\n x_{m}\n\\end{bmatrix}$$\n\n\n\nIn order to simplify the notation, we bring $\\theta$ to the left side of the equation and define $w_0 = -\\theta \\text{ and } x_0=1$ \n\nso that \n\n$$\\begin{equation}\n g({\\mathbf{z}}) =\\begin{cases}\n 1 & \\text{if $\\mathbf{z} \\ge 0$}\\\\\n -1 & \\text{otherwise}.\n \\end{cases}\n\\end{equation}$$\n\nand\n\n\n$$\\mathbf{z} = w_0x_{0} + w_1x_{1} + \\dots + w_mx_{m} = \\sum_{j=0}^{m} x_{j}w_{j} \\\\ = \\mathbf{w}^T\\mathbf{x}.$$\n\n\n\n\n
    \n
    \n\n## The Perceptron Learning Rule\n\n[[back to top](#Sections)]\n\nIt might sound like extreme case of a reductionist approach, but the idea behind this \"thresholded\" perceptron was to mimic how a single neuron in the brain works: It either \"fires\" or not. To summarize the main points from the previous section: A perceptron receives multiple input signals, and if the sum of the input signals exceed a certain threshold it either returns a signal or remains \"silent\" otherwise. What made this a \"machine learning\" algorithm was Frank Rosenblatt's idea of the perceptron learning rule: The perceptron algorithm is about learning the weights for the input signals in order to draw linear decision boundary that allows us to discriminate between the two linearly separable classes +1 and -1.\n\n\n\n\n\n\nRosenblatt's initial perceptron rule is fairly simple and can be summarized by the following steps: \n\n1. Initialize the weights to 0 or small random numbers.\n2. For each training sample $\\mathbf{x^{(i)}}$:\n 2. Calculate the *output* value.\n 2. Update the weights.\n\nThe output value is the class label predicted by the unit step function that we defined earlier (output $=g(\\mathbf{z})$) and the weight update can be written more formally as $w_j := w_j + \\Delta w_j$.\n\nThe value for updating the weights at each increment is calculated by the learning rule\n\n$\\Delta w_j = \\eta \\; (\\text{target}^{(i)} - \\text{output}^{(i)})\\;x^{(i)}_{j}$\n\nwhere $\\eta$ is the learning rate (a constant between 0.0 and 1.0), \"target\" is the true class label, and the \"output\" is the predicted class label.\n\nIt is important to note that all weights in the weight vector are being updated simultaneously. Concretely, for a 2-dimensional dataset, we would write the update as:\n\n$\\Delta w_0 = \\eta(\\text{target}^{(i)} - \\text{output}^{(i)})$ \n$\\Delta w_1 = \\eta(\\text{target}^{(i)} - \\text{output}^{(i)})\\;x^{(i)}_{1}$ \n$\\Delta w_2 = \\eta(\\text{target}^{(i)} - \\text{output}^{(i)})\\;x^{(i)}_{2}$ \n\nBefore we implement the perceptron rule in Python, let us make a simple thought experiment to illustrate how beautifully simple this learning rule really is. In the two scenarios where the perceptron predicts the class label correctly, the weights remain unchanged:\n\n- $\\Delta w_j = \\eta(-1^{(i)} - -1^{(i)})\\;x^{(i)}_{j} = 0$ \n- $\\Delta w_j = \\eta(1^{(i)} - 1^{(i)})\\;x^{(i)}_{j} = 0$ \n\nHowever, in case of a wrong prediction, the weights are being \"pushed\" towards the direction of the positive or negative target class, respectively:\n\n- $\\Delta w_j = \\eta(1^{(i)} - -1^{(i)})\\;x^{(i)}_{j} = \\eta(2)\\;x^{(i)}_{j}$ \n- $\\Delta w_j = \\eta(-1^{(i)} - 1^{(i)})\\;x^{(i)}_{j} = \\eta(-2)\\;x^{(i)}_{j}$ \n\n\n\nIt is important to note that the convergence of the perceptron is only guaranteed if the two classes are linearly separable. If the two classes can't be separated by a linear decision boundary, we can set a maximum number of passes over the training dataset (\"epochs\") and/or a threshold for the number of tolerated misclassifications.\n\n
    \n
    \n\n## Implementing the Perceptron Rule in Python\n\n[[back to top](#Sections)]\n\nIn this section, we will implement the simple perceptron learning rule in Python to classify flowers in the Iris dataset.\nPlease note that I omitted some \"safety checks\" for clarity, for a more \"robust\" version please see the following [code on GitHub](https://github.com/rasbt/mlxtend/blob/master/mlxtend/classifier/perceptron.py).\n\n\n```python\nimport numpy as np\n\nclass Perceptron(object):\n \n def __init__(self, eta=0.01, epochs=50):\n self.eta = eta\n self.epochs = epochs\n\n def train(self, X, y):\n\n self.w_ = np.zeros(1 + X.shape[1])\n self.errors_ = []\n\n for _ in range(self.epochs):\n errors = 0\n for xi, target in zip(X, y):\n update = self.eta * (target - self.predict(xi))\n self.w_[1:] += update * xi\n self.w_[0] += update\n errors += int(update != 0.0)\n self.errors_.append(errors)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def predict(self, X):\n return np.where(self.net_input(X) >= 0.0, 1, -1)\n```\n\nFor the following example, we will load the Iris data set from the [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml/) and only focus on the two flower species *Setosa* and *Versicolor*. Furthermore, we will only use the two features *sepal length* and *petal length* for visualization purposes.\n\n\n```python\nimport pandas as pd\ndf = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)\n\n# setosa and versicolor\ny = df.iloc[0:100, 4].values\ny = np.where(y == 'Iris-setosa', -1, 1)\n\n# sepal length and petal length\nX = df.iloc[0:100, [0,2]].values\n```\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mlxtend.plotting import plot_decision_regions\n\nppn = Perceptron(epochs=10, eta=0.1)\n\nppn.train(X, y)\nprint('Weights: %s' % ppn.w_)\nplot_decision_regions(X, y, clf=ppn)\nplt.title('Perceptron')\nplt.xlabel('sepal length [cm]')\nplt.ylabel('petal length [cm]')\nplt.show()\n\nplt.plot(range(1, len(ppn.errors_)+1), ppn.errors_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Misclassifications')\nplt.show()\n\n```\n\nAs we can see, the perceptron converges after the 6th iteration and separates the two flower classes perfectly.\n\n
    \n
    \n\n## Problems with Perceptrons\n\n[[back to top](#Sections)]\n\nAlthough the perceptron classified the two Iris flower classes perfectly, convergence is one of the biggest problems of the perceptron. Frank Rosenblatt proofed mathematically that the perceptron learning rule converges if the two classes can be separated by linear hyperplane, but problems arise if the classes cannot be separated perfectly by a linear classifier. To demonstrate this issue, we will use two different classes and features from the Iris dataset.\n\n\n```python\n# versicolor and virginica\ny2 = df.iloc[50:150, 4].values\ny2 = np.where(y2 == 'Iris-virginica', -1, 1)\n\n# sepal width and petal width\nX2 = df.iloc[50:150, [1,3]].values\n\nppn = Perceptron(epochs=25, eta=0.01)\nppn.train(X2, y2)\n\nplot_decision_regions(X2, y2, clf=ppn)\nplt.show()\n\nplt.plot(range(1, len(ppn.errors_)+1), ppn.errors_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Misclassifications')\nplt.show()\n```\n\n\n```python\nprint('Total number of misclassifications: %d of 100' % (y2 != ppn.predict(X2)).sum())\n```\n\n Total number of misclassifications: 43 of 100\n\n\nEven at a lower training rate, the perceptron failed to find a good decision boundary since one or more samples will always be misclassified in every epoch so that the learning rule never stops updating the weights.\n\nIt may seem paradoxical in this context that another shortcoming of the perceptron algorithm is that it stops updating the weights as soon as all samples are classified correctly. Our intuition tells us that a decision boundary with a large margin between the classes (as indicated by the dashed line in the figure below) likely has a better generalization error than the decision boundary of the perceptron. But large-margin classifiers such as Support Vector Machines are a topic for another time.\n\n\n\n
    \n
    \n\n# Adaptive Linear Neurons and the Delta Rule\n\n[[back to top](#Sections)]\n\nThe perceptron surely was very popular at the time of its discovery, however, it only took a few years until Bernard Widrow and his doctoral student Tedd Hoff proposed the idea of the Adaptive Linear Neuron (adaline) [[3](#References)].\n\nIn contrast to the perceptron rule, the delta rule of the adaline (also known as Widrow-Hoff\" rule or Adaline rule) updates the weights based on a linear activation function rather than a unit step function; here, this linear activation function $g(\\mathbf{z})$ is just the identity function of the net input $g(\\mathbf{w}^T\\mathbf{x}) = \\mathbf{w}^T\\mathbf{x}$. In the next section, we will see why this linear activation is an improvement over the perceptron update and where the name \"delta rule\" comes from.\n\n\n\n
    \n
    \n\n## Gradient Descent\n\n[[back to top](#Sections)]\n\nBeing a continuous function, one of the biggest advantages of the linear activation function over the unit step function is that it is differentiable. This property allows us to define a cost function $J(\\mathbf{w})$ that we can minimize in order to update our weights. In the case of the linear activation function, we can define the cost function $J(\\mathbf{w})$ as the *sum of squared errors* (SSE), which is similar to the cost function that is minimized in ordinary least squares (OLS) linear regression.\n\n$$J(\\mathbf{w}) = \\frac{1}{2} \\sum_{i} (\\text{target}^{(i)} - \\text{output}^{(i)})^2 \\quad \\quad \\text{output}^{(i)} \\in \\mathbb{R}$$\n\n(The fraction $\\frac{1}{2}$ is just used for convenience to derive the gradient as we will see in the next paragraphs.)\n\nIn order to minimize the SSE cost function, we will use gradient descent, a simple yet useful optimization algorithm that is often used in machine learning to find the local minimum of linear systems.\n\nBefore we get to the fun part (calculus), let us consider a convex cost function for one single weight. As illustrated in the figure below, we can describe the principle behind gradient descent as \"climbing down a hill\" until a local or global minimum is reached. At each step, we take a step into the opposite direction of the gradient, and the step size is determined by the value of the learning rate as well as the slope of the gradient.\n\n\n\nNow, as promised, onto the fun part -- deriving the Adaline learning rule.\nAs mentioned above, each update is updated by taking a step into the opposite direction of the gradient $\\Delta \\mathbf{w} = - \\eta \\nabla J(\\mathbf{w})$, thus, we have to compute the partial derivative of the cost function for each weight in the weight vector: $\\Delta w_j = - \\eta \\frac{\\partial J}{\\partial w_j}$. \n\n\n\n\nThe partial derivative of the SSE cost function for a particular weight can be calculated as follows:\n\n$$\\begin{equation}\n \\frac{\\partial J}{\\partial w_j} = \\frac{\\partial }{\\partial w_j} \\frac{1}{2} \\sum_i (t^{(i)} - o^{(i)})^2 \\\\\n= \\frac{1}{2} \\sum_i \\frac{\\partial}{\\partial w_j} (t^{(i)} - o^{(i)})^2 \\\\\n= \\frac{1}{2} \\sum_i 2 (t^{(i)} - o^{(i)}) \\frac{\\partial}{\\partial w_j} (t^{(i)} - o^{(i)}) \\\\\n= \\sum_i (t^{(i)} - o^{(i)}) \\frac{\\partial}{\\partial w_j} \\bigg(t^{(i)} - \\sum_j w_j x^{(i)}_{j}\\bigg) \\\\\n= \\sum_i (t^{(i)} - o^{(i)})(-x^{(i)}_{j}) \n\\end{equation}$$\n\n(t = target, o = output)\n\nAnd if we plug the results back into the learning rule, we get\n\n$\\Delta w_j = - \\eta \\frac{\\partial J}{\\partial w_j} = - \\eta \\sum_i (t^{(i)} - o^{(i)})(- x^{(i)}_{j}) = \\eta \\sum_i (t^{(i)} - o^{(i)})x^{(i)}_{j}$,\n\nEventually, we can apply a simultaneous weight update similar to the perceptron rule: \n\n$\\mathbf{w} := \\mathbf{w} + \\Delta \\mathbf{w}$.\n\n**Although, the learning rule above looks identical to the perceptron rule, we shall note the two main differences:**\n\n1. Here, the output \"o\" is a real number and not a class label as in the perceptron learning rule.\n2. The weight update is calculated based on all samples in the training set (instead of updating the weights incrementally after each sample), which is why this approach is also called \"batch\" gradient descent.\n\n
    \n
    \n\n## The Gradient Descent Rule in Action\n\n[[back to top](#Sections)]\n\nNow, it's time to implement the gradient descent rule in Python.\n\n\n```python\nimport numpy as np\n\nclass AdalineGD(object):\n \n def __init__(self, eta=0.01, epochs=50): \n self.eta = eta\n self.epochs = epochs\n\n def train(self, X, y):\n\n self.w_ = np.zeros(1 + X.shape[1])\n self.cost_ = []\n\n for i in range(self.epochs):\n output = self.net_input(X)\n errors = (y - output)\n self.w_[1:] += self.eta * X.T.dot(errors)\n self.w_[0] += self.eta * errors.sum()\n cost = (errors**2).sum() / 2.0\n self.cost_.append(cost)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def activation(self, X):\n return self.net_input(X)\n\n def predict(self, X):\n return np.where(self.activation(X) >= 0.0, 1, -1)\n```\n\nIn practice, it often requires some experimentation to find a good learning rate for optimal convergence, thus, we will start by plotting the cost for two different learning rates.\n\n\n```python\nada = AdalineGD(epochs=10, eta=0.01).train(X, y)\nplt.plot(range(1, len(ada.cost_)+1), np.log10(ada.cost_), marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('log(Sum-squared-error)')\nplt.title('Adaline - Learning rate 0.01')\nplt.show()\n\nada = AdalineGD(epochs=10, eta=0.0001).train(X, y)\nplt.plot(range(1, len(ada.cost_)+1), ada.cost_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Sum-squared-error')\nplt.title('Adaline - Learning rate 0.0001')\nplt.show()\n```\n\nThe two plots above nicely emphasize the importance of plotting learning curves by illustrating two most common problems with gradient descent:\n\n1. If the learning rate is too large, gradient descent will overshoot the minima and diverge.\n2. If the learning rate is too small, the algorithm will require too many epochs to converge and can become trapped in local minima more easily.\n\n\n\n\n\nGradient descent is also a good example why feature scaling is important for many machine learning algorithms. \nIt is not only easier to find an appropriate learning rate if the features are on the same scale, but it also often leads to faster convergence and can prevent the weights from becoming too small (numerical stability).\n\nA common way of feature scaling is standardization\n\n$$\\mathbf{x}_{j, std} = \\frac{\\mathbf{x}_j - \\mathbf{\\mu}_j}{\\mathbf{\\sigma}_j}$$\n\nwhere $\\mathbf{\\mu}_j$ is the sample mean of the feature $\\mathbf{x}_{j}$ and $\\mathbf{\\sigma}_j$ the standard deviation, respectively. After standardization, the features will have unit variance and are centered around mean zero. \n\n\n```python\n# standardize features\nX_std = np.copy(X)\nX_std[:,0] = (X[:,0] - X[:,0].mean()) / X[:,0].std()\nX_std[:,1] = (X[:,1] - X[:,1].mean()) / X[:,1].std()\n```\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mlxtend.evaluate import plot_decision_regions\n\nada = AdalineGD(epochs=15, eta=0.01)\n\nada.train(X_std, y)\nplot_decision_regions(X_std, y, clf=ada)\nplt.title('Adaline - Gradient Descent')\nplt.xlabel('sepal length [standardized]')\nplt.ylabel('petal length [standardized]')\nplt.show()\n\nplt.plot(range(1, len( ada.cost_)+1), ada.cost_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Sum-squared-error')\nplt.show()\n```\n\n\n\n
    \n
    \n\n## Online Learning via Stochastic Gradient Descent\n\n[[back to top](#Sections)]\n\nThe previous section was all about \"batch\" gradient descent learning. The \"batch\" updates refers to the fact that the cost function is minimized based on the complete training data set. If we think back to the perceptron rule, we remember that it performed the weight update incrementally after each individual training sample. This approach is also called \"online\" learning, and in fact, this is also how Adaline was first described by Bernard Widrow et al. [[3](#References)]\n\nThe process of incrementally updating the weights is also called \"stochastic\" gradient descent since it approximates the minimization of the cost function. Although the stochastic gradient descent approach might sound inferior to gradient descent due its \"stochastic\" nature and the \"approximated\" direction (gradient), it can have certain advantages in practice. Often, stochastic gradient descent converges much faster than gradient descent since the updates are applied immediately after each training sample; stochastic gradient descent is computationally more efficient, especially for very large datasets. Another advantage of online learning is that the classifier can be immediately updated as new training data arrives, e.g., in web applications, and old training data can be discarded if storage is an issue. In large-scale machine learning systems, it is also common practice to use so-called \"mini-batches\", a compromise with smoother convergence than stochastic gradient descent.\n\nIn the interests of completeness let us also implement the stochastic gradient descent Adaline and confirm that it converges on the linearly separable iris dataset.\n\n\n```python\nimport numpy as np\n\nclass AdalineSGD(object):\n \n def __init__(self, eta=0.01, epochs=50):\n self.eta = eta\n self.epochs = epochs\n\n def train(self, X, y, reinitialize_weights=True):\n\n if reinitialize_weights:\n self.w_ = np.zeros(1 + X.shape[1])\n self.cost_ = []\n\n for i in range(self.epochs):\n for xi, target in zip(X, y):\n output = self.net_input(xi)\n error = (target - output)\n self.w_[1:] += self.eta * xi.dot(error)\n self.w_[0] += self.eta * error\n \n cost = ((y - self.activation(X))**2).sum() / 2.0\n self.cost_.append(cost)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def activation(self, X):\n return self.net_input(X)\n\n def predict(self, X):\n return np.where(self.activation(X) >= 0.0, 1, -1)\n```\n\nOne more advice before we let the adaline learn via stochastic gradient descent is to shuffle the training dataset to iterate over the training samples in random order. \n\nWe shall note that the \"standard\" stochastic gradient descent algorithm uses sampling \"with replacement,\" which means that at each iteration, a training sample is chosen randomly from the entire training set. In contrast, sampling \"without replacement,\" which means that each training sample is evaluated exactly once in every epoch, is not only easier to implement but also shows a better performance in empirical comparisons. A more detailed discussion about this topic can be found in Benjamin Recht and Christopher Re's paper *Beneath the valley of the noncommutative arithmetic-geometric mean inequality: conjectures, case-studies, and consequences* [[4](#References)].\n\n\n\n```python\nada = AdalineSGD(epochs=15, eta=0.01)\n\n# shuffle data\nnp.random.seed(123)\nidx = np.random.permutation(len(y))\nX_shuffled, y_shuffled = X_std[idx], y[idx]\n\n# train and adaline and plot decision regions\nada.train(X_shuffled, y_shuffled)\nplot_decision_regions(X_shuffled, y_shuffled, clf=ada)\nplt.title('Adaline - Gradient Descent')\nplt.xlabel('sepal length [standardized]')\nplt.ylabel('petal length [standardized]')\nplt.show()\n\nplt.plot(range(1, len(ada.cost_)+1), ada.cost_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Sum-squared-error')\nplt.show()\n```\n\n
    \n
    \n\n# What's Next?\n\n[[back to top](#Sections)]\n\nAlthough we covered many different topics during this article, we just scratched the surface of artificial neurons. \n\nIn later articles, we will take a look at different approaches to dynamically adjust the learning rate, the concepts of \"One-vs-All\" and \"One-vs-One\" for multi-class classification, regularization to overcome overfitting by introducing additional information, dealing with nonlinear problems and multilayer neural networks, different activation functions for artificial neurons, and related concepts such as logistic regression and support vector machines.\n\n\n\n\n\n
    \n
    \n\n### References\n\n[[back to top](#Sections)]\n\n[1] F. Rosenblatt. The perceptron, a perceiving and recognizing automaton Project Para. Cornell Aeronautical Laboratory, 1957.\n\n[2] W. S. McCulloch and W. Pitts. A logical calculus of the ideas immanent in nervous activity. The bulletin of mathematical biophysics, 5(4):115–133, 1943.\n\n[3] B. Widrow et al. Adaptive ”Adaline” neuron using chemical ”memistors”. Number Technical Report 1553-2. Stanford Electron. Labs., Stanford, CA, October 1960.\n\n[4] B. Recht and C. R ́e. Beneath the valley of the noncommutative arithmetic-geometric mean inequality: conjectures, case-studies, and consequences. arXiv preprint arXiv:1202.4184, 2012.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "1a5d83956b85ea9aed9f98024ddb337c754ec88e", "size": 174700, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pattern-classification/machine_learning/singlelayer_neural_networks/singlelayer_neural_networks.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": "2021-12-13T15:41:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:41:48.000Z", "max_issues_repo_path": "pattern-classification/machine_learning/singlelayer_neural_networks/singlelayer_neural_networks.ipynb", "max_issues_repo_name": "gopala-kr/ds-notebooks", "max_issues_repo_head_hexsha": "bc35430ecdd851f2ceab8f2437eec4d77cb59423", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-09-12T15:06:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:02:08.000Z", "max_forks_repo_path": "pattern-classification/machine_learning/singlelayer_neural_networks/singlelayer_neural_networks.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": "2022-01-29T00:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T00:37:52.000Z", "avg_line_length": 135.742035742, "max_line_length": 15598, "alphanum_fraction": 0.8651345163, "converted": true, "num_tokens": 7083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.15203224546424315, "lm_q1q2_score": 0.06365543129828372}} {"text": "```python\n%pylab inline\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n__END_OF_DEFS__\n\n# Programming ulab\n\nEarlier we have seen, how `ulab`'s functions and methods can be accessed in `micropython`. This last section of the book explains, how these functions are implemented. By the end of this chapter, not only would you be able to extend `ulab`, and write your own `numpy`-compatible functions, but through a deeper understanding of the inner workings of the functions, you would also be able to see what the trade-offs are at the `python` level.\n\n\n## Code organisation\n\nAs mentioned earlier, the `python` functions are organised into sub-modules at the C level. The C sub-modules can be found in `./ulab/code/`.\n\n## The `ndarray` object\n\n### General comments\n\n`ndarrays` are efficient containers of numerical data of the same type (i.e., signed/unsigned chars, signed/unsigned integers or `mp_float_t`s, which, depending on the platform, are either C `float`s, or C `double`s). Beyond storing the actual data in the void pointer `*array`, the type definition has eight additional members (on top of the `base` type). Namely, the `dtype`, which tells us, how the bytes are to be interpreted. Moreover, the `itemsize`, which stores the size of a single entry in the array, `boolean`, an unsigned integer, which determines, whether the arrays is to be treated as a set of Booleans, or as numerical data, `ndim`, the number of dimensions (`uint8_t`), `len`, the length of the array (the number of entries), the shape (`*size_t`), the strides (`*int32_t`). The length is simply the product of the numbers in `shape`.\n\nThe type definition is as follows:\n\n```c\ntypedef struct _ndarray_obj_t {\n mp_obj_base_t base;\n uint8_t dtype;\n uint8_t itemsize;\n uint8_t boolean;\n uint8_t ndim;\n size_t len;\n size_t shape[ULAB_MAX_DIMS];\n int32_t strides[ULAB_MAX_DIMS];\n void *array;\n} ndarray_obj_t;\n```\n\n### Memory layout\n\nThe values of an `ndarray` are stored in a contiguous segment in the RAM. The `ndarray` can be dense, meaning that all numbers in the linear memory segment belong to a linar combination of coordinates, and it can also be sparse, i.e., some elements of the linear storage space will be skipped, when the elements of the tensor are traversed. \n\nIn the RAM, the position of the item $M(n_1, n_2, ..., n_{k-1}, n_k)$ in a dense tensor of rank $k$ is given by the linear combination \n\n\\begin{equation}\nP(n_1, n_2, ..., n_{k-1}, n_k) = n_1 s_1 + n_2 s_2 + ... + n_{k-1}s_{k-1} + n_ks_k = \\sum_{i=1}^{k}n_is_i\n\\end{equation}\nwhere $s_i$ are the strides of the tensor, defined as \n\n\\begin{equation}\ns_i = \\prod_{j=i+1}^k l_j\n\\end{equation}\n\nwhere $l_j$ is length of the tensor along the $j$th axis. When the tensor is sparse (e.g., when the tensor is sliced), the strides along a particular axis will be multiplied by a non-zero integer. If this integer is different to $\\pm 1$, the linear combination above cannot access all elements in the RAM, i.e., some numbers will be skipped. Note that $|s_1| > |s_2| > ... > |s_{k-1}| > |s_k|$, even if the tensor is sparse. The statement is trivial for dense tensors, and it follows from the definition of $s_i$. For sparse tensors, a slice cannot have a step larger than the shape along that axis. But for dense tensors, $s_i/s_{i+1} = l_i$. \n\nWhen creating a *view*, we simply re-calculate the `strides`, and re-set the `*array` pointer.\n\n## Iterating over elements of a tensor\n\nThe `shape` and `strides` members of the array tell us how we have to move our pointer, when we want to read out the numbers. For technical reasons that will become clear later, the numbers in `shape` and in `strides` are aligned to the right, and begin on the right hand side, i.e., if the number of possible dimensions is `ULAB_MAX_DIMS`, then `shape[ULAB_MAX_DIMS-1]` is the length of the last axis, `shape[ULAB_MAX_DIMS-2]` is the length of the last but one axis, and so on. If the number of actual dimensions, `ndim < ULAB_MAX_DIMS`, the first `ULAB_MAX_DIMS - ndim` entries in `shape` and `strides` will be equal to zero, but they could, in fact, be assigned any value, because these will never be accessed in an operation.\n\nWith this definition of the strides, the linear combination in $P(n_1, n_2, ..., n_{k-1}, n_k)$ is a one-to-one mapping from the space of tensor coordinates, $(n_1, n_2, ..., n_{k-1}, n_k)$, and the coordinate in the linear array, $n_1s_1 + n_2s_2 + ... + n_{k-1}s_{k-1} + n_ks_k$, i.e., no two distinct sets of coordinates will result in the same position in the linear array. \n\nSince the `strides` are given in terms of bytes, when we iterate over an array, the void data pointer is usually cast to `uint8_t`, and the values are converted using the proper data type stored in `ndarray->dtype`. However, there might be cases, when it makes perfect sense to cast `*array` to a different type, in which case the `strides` have to be re-scaled by the value of `ndarray->itemsize`.\n\n### Iterating using the unwrapped loops\n\nThe following macro definition is taken from [vector.h](https://github.com/v923z/micropython-ulab/blob/master/code/numpy/vector/vector.h), and demonstrates, how we can iterate over a single array in four dimensions. \n\n```c\n#define ITERATE_VECTOR(type, array, source, sarray) do {\n size_t i=0;\n do {\n size_t j = 0;\n do {\n size_t k = 0;\n do {\n size_t l = 0;\n do {\n *(array)++ = f(*((type *)(sarray)));\n (sarray) += (source)->strides[ULAB_MAX_DIMS - 1];\n l++;\n } while(l < (source)->shape[ULAB_MAX_DIMS-1]);\n (sarray) -= (source)->strides[ULAB_MAX_DIMS - 1] * (source)->shape[ULAB_MAX_DIMS-1];\n (sarray) += (source)->strides[ULAB_MAX_DIMS - 2];\n k++;\n } while(k < (source)->shape[ULAB_MAX_DIMS-2]);\n (sarray) -= (source)->strides[ULAB_MAX_DIMS - 2] * (source)->shape[ULAB_MAX_DIMS-2];\n (sarray) += (source)->strides[ULAB_MAX_DIMS - 3];\n j++;\n } while(j < (source)->shape[ULAB_MAX_DIMS-3]);\n (sarray) -= (source)->strides[ULAB_MAX_DIMS - 3] * (source)->shape[ULAB_MAX_DIMS-3];\n (sarray) += (source)->strides[ULAB_MAX_DIMS - 4];\n i++;\n } while(i < (source)->shape[ULAB_MAX_DIMS-4]);\n} while(0)\n```\n\nWe start with the innermost loop, the one recursing `l`. `array` is already of type `mp_float_t`, while the source array, `sarray`, has been cast to `uint8_t` in the calling function. The numbers contained in `sarray` have to be read out in the proper type dictated by `ndarray->dtype`. This is what happens in the statement `*((type *)(sarray))`, and this number is then fed into the function `f`. Vectorised mathematical functions produce *dense* arrays, and for this reason, we can simply advance the `array` pointer. \n\nThe advancing of the `sarray` pointer is a bit more involving: first, in the innermost loop, we simply move forward by the amount given by the last stride, which is `(source)->strides[ULAB_MAX_DIMS - 1]`, because the `shape` and the `strides` are aligned to the right. We move the pointer as many times as given by `(source)->shape[ULAB_MAX_DIMS-1]`, which is the length of the very last axis. Hence the the structure of the loop\n\n```c\n size_t l = 0;\n do {\n ...\n l++;\n } while(l < (source)->shape[ULAB_MAX_DIMS-1]);\n\n```\nOnce we have exhausted the last axis, we have to re-wind the pointer, and advance it by an amount given by the last but one stride. Keep in mind that in the the innermost loop we moved our pointer `(source)->shape[ULAB_MAX_DIMS-1]` times by `(source)->strides[ULAB_MAX_DIMS - 1]`, i.e., we re-wind it by moving it backwards by `(source)->strides[ULAB_MAX_DIMS - 1] * (source)->shape[ULAB_MAX_DIMS-1]`. In the next step, we move forward by `(source)->strides[ULAB_MAX_DIMS - 2]`, which is the last but one stride. \n\n\n```c\n (sarray) -= (source)->strides[ULAB_MAX_DIMS - 1] * (source)->shape[ULAB_MAX_DIMS-1];\n (sarray) += (source)->strides[ULAB_MAX_DIMS - 2];\n\n```\n\nThis pattern must be repeated for each axis of the array, and this is how we arrive at the four nested loops listed above.\n\n### Re-winding arrays by means of a function\n\n\nIn addition to un-wrapping the iteration loops by means of macros, there is another way of traversing all elements of a tensor: we note that, since $|s_1| > |s_2| > ... > |s_{k-1}| > |s_k|$, $P(n1, n2, ..., n_{k-1}, n_k)$ changes most slowly in the last coordinate. Hence, if we start from the very beginning, ($n_i = 0$ for all $i$), and walk along the linear RAM segment, we increment the value of $n_k$ as long as $n_k < l_k$. Once $n_k = l_k$, we have to reset $n_k$ to 0, and increment $n_{k-1}$ by one. After each such round, $n_{k-1}$ will be incremented by one, as long as $n_{k-1} < l_{k-1}$. Once $n_{k-1} = l_{k-1}$, we reset both $n_k$, and $n_{k-1}$ to 0, and increment $n_{k-2}$ by one. \n\nRewinding the arrays in this way is implemented in the function `ndarray_rewind_array` in [ndarray.c](https://github.com/v923z/micropython-ulab/blob/master/code/ndarray.c). \n\n```c\nvoid ndarray_rewind_array(uint8_t ndim, uint8_t *array, size_t *shape, int32_t *strides, size_t *coords) {\n // resets the data pointer of a single array, whenever an axis is full\n // since we always iterate over the very last axis, we have to keep track of\n // the last ndim-2 axes only\n array -= shape[ULAB_MAX_DIMS - 1] * strides[ULAB_MAX_DIMS - 1];\n array += strides[ULAB_MAX_DIMS - 2];\n for(uint8_t i=1; i < ndim-1; i++) {\n coords[ULAB_MAX_DIMS - 1 - i] += 1;\n if(coords[ULAB_MAX_DIMS - 1 - i] == shape[ULAB_MAX_DIMS - 1 - i]) { // we are at a dimension boundary\n array -= shape[ULAB_MAX_DIMS - 1 - i] * strides[ULAB_MAX_DIMS - 1 - i];\n array += strides[ULAB_MAX_DIMS - 2 - i];\n coords[ULAB_MAX_DIMS - 1 - i] = 0;\n coords[ULAB_MAX_DIMS - 2 - i] += 1;\n } else { // coordinates can change only, if the last coordinate changes\n return;\n }\n }\n}\n```\n\nand the function would be called as in the snippet below. Note that the innermost loop is factored out, so that we can save the `if(...)` statement for the last axis.\n\n```c\n size_t *coords = ndarray_new_coords(results->ndim);\n for(size_t i=0; i < results->len/results->shape[ULAB_MAX_DIMS -1]; i++) {\n size_t l = 0;\n do {\n ...\n l++;\n } while(l < results->shape[ULAB_MAX_DIMS - 1]);\n ndarray_rewind_array(results->ndim, array, results->shape, strides, coords);\n } while(0)\n\n```\n\nThe advantage of this method is that the implementation is independent of the number of dimensions: the iteration requires more or less the same flash space for 2 dimensions as for 22. However, the price we have to pay for this convenience is the extra function call.\n\n## Iterating over two ndarrays simultaneously: broadcasting\n\nWhenever we invoke a binary operator, call a function with two arguments of `ndarray` type, or assign something to an `ndarray`, we have to iterate over two views at the same time. The task is trivial, if the two `ndarray`s in question have the same shape (but not necessarily the same set of strides), because in this case, we can still iterate in the same loop. All that happens is that we move two data pointers in sync.\n\nThe problem becomes a bit more involving, when the shapes of the two `ndarray`s are not identical. For such cases, `numpy` defines so-called broadcasting, which boils down to two rules. \n\n1. The shapes in the tensor with lower rank has to be prepended with axes of size 1 till the two ranks become equal.\n2. Along all axes the two tensors should have the same size, or one of the sizes must be 1. \n\nIf, after applying the first rule the second is not satisfied, the two `ndarray`s cannot be broadcast together. \n\nNow, let us suppose that we have two compatible `ndarray`s, i.e., after applying the first rule, the second is satisfied. How do we iterate over the elements in the tensors? \n\nWe should recall, what exactly we do, when iterating over a single array: normally, we move the data pointer by the last stride, except, when we arrive at a dimension boundary (when the last axis is exhausted). At that point, we move the pointer by an amount dictated by the strides. And this is the key: *dictated by the strides*. Now, if we have two arrays that are originally not compatible, we define new strides for them, and use these in the iteration. With that, we are back to the case, where we had two compatible arrays. \n\nNow, let us look at the second broadcasting rule: if the two arrays have the same size, we take both `ndarray`s' strides along that axis. If, on the other hand, one of the `ndarray`s is of length 1 along one of its axes, we set the corresponding strides to 0. This will ensure that that data pointer is not moved, when we iterate over both `ndarray`s at the same time. \n\nThus, in order to implement broadcasting, we first have to check, whether the two above-mentioned rules can be satisfied, and if so, we have to find the two new sets strides. \n\nThe `ndarray_can_broadcast` function from [ndarray.c](https://github.com/v923z/micropython-ulab/blob/master/code/ndarray.c) takes two `ndarray`s, and returns `true`, if the two arrays can be broadcast together. At the same time, it also calculates new strides for the two arrays, so that they can be iterated over at the same time. \n\n```c\nbool ndarray_can_broadcast(ndarray_obj_t *lhs, ndarray_obj_t *rhs, uint8_t *ndim, size_t *shape, int32_t *lstrides, int32_t *rstrides) {\n // returns True or False, depending on, whether the two arrays can be broadcast together\n // numpy's broadcasting rules are as follows:\n //\n // 1. the two shapes are either equal\n // 2. one of the shapes is 1\n memset(lstrides, 0, sizeof(size_t)*ULAB_MAX_DIMS);\n memset(rstrides, 0, sizeof(size_t)*ULAB_MAX_DIMS);\n lstrides[ULAB_MAX_DIMS - 1] = lhs->strides[ULAB_MAX_DIMS - 1];\n rstrides[ULAB_MAX_DIMS - 1] = rhs->strides[ULAB_MAX_DIMS - 1];\n for(uint8_t i=ULAB_MAX_DIMS; i > 0; i--) {\n if((lhs->shape[i-1] == rhs->shape[i-1]) || (lhs->shape[i-1] == 0) || (lhs->shape[i-1] == 1) ||\n (rhs->shape[i-1] == 0) || (rhs->shape[i-1] == 1)) {\n shape[i-1] = MAX(lhs->shape[i-1], rhs->shape[i-1]);\n if(shape[i-1] > 0) (*ndim)++;\n if(lhs->shape[i-1] < 2) {\n lstrides[i-1] = 0;\n } else {\n lstrides[i-1] = lhs->strides[i-1];\n }\n if(rhs->shape[i-1] < 2) {\n rstrides[i-1] = 0;\n } else {\n rstrides[i-1] = rhs->strides[i-1];\n }\n } else {\n return false;\n }\n }\n return true;\n}\n```\n\nA good example of how the function would be called can be found in [vector.c](https://github.com/v923z/micropython-ulab/blob/master/code/numpy/vector/vector.c), in the `vector_arctan2` function:\n\n```c\nmp_obj_t vectorise_arctan2(mp_obj_t y, mp_obj_t x) {\n ...\n uint8_t ndim = 0;\n size_t *shape = m_new(size_t, ULAB_MAX_DIMS);\n int32_t *xstrides = m_new(int32_t, ULAB_MAX_DIMS);\n int32_t *ystrides = m_new(int32_t, ULAB_MAX_DIMS);\n if(!ndarray_can_broadcast(ndarray_x, ndarray_y, &ndim, shape, xstrides, ystrides)) {\n mp_raise_ValueError(translate(\"operands could not be broadcast together\"));\n m_del(size_t, shape, ULAB_MAX_DIMS);\n m_del(int32_t, xstrides, ULAB_MAX_DIMS);\n m_del(int32_t, ystrides, ULAB_MAX_DIMS);\n }\n\n uint8_t *xarray = (uint8_t *)ndarray_x->array;\n uint8_t *yarray = (uint8_t *)ndarray_y->array;\n \n ndarray_obj_t *results = ndarray_new_dense_ndarray(ndim, shape, NDARRAY_FLOAT);\n mp_float_t *rarray = (mp_float_t *)results->array;\n ...\n```\n\nAfter the new strides have been calculated, the iteration loop is identical to what we discussed in the previous section.\n\n## Contracting an `ndarray`\n\n\nThere are many operations that reduce the number of dimensions of an `ndarray` by 1, i.e., that remove an axis from the tensor. The drill is the same as before, with the exception that first we have to remove the `strides` and `shape` that corresponds to the axis along which we intend to contract. The `numerical_reduce_axes` function from [numerical.c](https://github.com/v923z/micropython-ulab/blob/master/code/numerical/numerical.c) does that. \n\n\n```c\nstatic void numerical_reduce_axes(ndarray_obj_t *ndarray, int8_t axis, size_t *shape, int32_t *strides) {\n // removes the values corresponding to a single axis from the shape and strides array\n uint8_t index = ULAB_MAX_DIMS - ndarray->ndim + axis;\n if((ndarray->ndim == 1) && (axis == 0)) {\n index = 0;\n shape[ULAB_MAX_DIMS - 1] = 0;\n return;\n }\n for(uint8_t i = ULAB_MAX_DIMS - 1; i > 0; i--) {\n if(i > index) {\n shape[i] = ndarray->shape[i];\n strides[i] = ndarray->strides[i];\n } else {\n shape[i] = ndarray->shape[i-1];\n strides[i] = ndarray->strides[i-1];\n }\n }\n}\n```\n\nOnce the reduced `strides` and `shape` are known, we place the axis in question in the innermost loop, and wrap it with the loops, whose coordinates are in the `strides`, and `shape` arrays. The `RUN_STD` macro from [numerical.h](https://github.com/v923z/micropython-ulab/blob/master/code/numpy/numerical/numerical.h) is a good example. The macro is expanded in the `numerical_sum_mean_std_ndarray` function. \n\n\n```c\nstatic mp_obj_t numerical_sum_mean_std_ndarray(ndarray_obj_t *ndarray, mp_obj_t axis, uint8_t optype, size_t ddof) {\n uint8_t *array = (uint8_t *)ndarray->array;\n size_t *shape = m_new(size_t, ULAB_MAX_DIMS);\n memset(shape, 0, sizeof(size_t)*ULAB_MAX_DIMS);\n int32_t *strides = m_new(int32_t, ULAB_MAX_DIMS);\n memset(strides, 0, sizeof(uint32_t)*ULAB_MAX_DIMS);\n\n int8_t ax = mp_obj_get_int(axis);\n if(ax < 0) ax += ndarray->ndim;\n if((ax < 0) || (ax > ndarray->ndim - 1)) {\n mp_raise_ValueError(translate(\"index out of range\"));\n }\n numerical_reduce_axes(ndarray, ax, shape, strides);\n uint8_t index = ULAB_MAX_DIMS - ndarray->ndim + ax;\n ndarray_obj_t *results = NULL;\n uint8_t *rarray = NULL;\n ...\n\n```\nHere is the macro for the three-dimensional case: \n\n```c\n#define RUN_STD(ndarray, type, array, results, r, shape, strides, index, div) do {\n size_t k = 0;\n do {\n size_t l = 0;\n do {\n RUN_STD1((ndarray), type, (array), (results), (r), (index), (div));\n (array) -= (ndarray)->strides[(index)] * (ndarray)->shape[(index)];\n (array) += (strides)[ULAB_MAX_DIMS - 1];\n l++;\n } while(l < (shape)[ULAB_MAX_DIMS - 1]);\n (array) -= (strides)[ULAB_MAX_DIMS - 2] * (shape)[ULAB_MAX_DIMS-2];\n (array) += (strides)[ULAB_MAX_DIMS - 3];\n k++;\n } while(k < (shape)[ULAB_MAX_DIMS - 2]);\n} while(0)\n```\nIn `RUN_STD`, we simply move our pointers; the calculation itself happens in the `RUN_STD1` macro below. (Note that this is the implementation of the numerically stable Welford algorithm.)\n\n```c\n#define RUN_STD1(ndarray, type, array, results, r, index, div)\n({\n mp_float_t M, m, S = 0.0, s = 0.0;\n M = m = *(mp_float_t *)((type *)(array));\n for(size_t i=1; i < (ndarray)->shape[(index)]; i++) {\n (array) += (ndarray)->strides[(index)];\n mp_float_t value = *(mp_float_t *)((type *)(array));\n m = M + (value - M) / (mp_float_t)i;\n s = S + (value - M) * (value - m);\n M = m;\n S = s;\n }\n (array) += (ndarray)->strides[(index)];\n *(r)++ = MICROPY_FLOAT_C_FUN(sqrt)((ndarray)->shape[(index)] * s / (div));\n})\n```\n\n## Upcasting\n\nWhen in an operation the `dtype`s of two arrays are different, the result's `dtype` will be decided by the following upcasting rules:\n\n1. Operations with two `ndarray`s of the same `dtype` preserve their `dtype`, even when the results overflow.\n\n2. if either of the operands is a float, the result automatically becomes a float\n\n3. otherwise\n\n - `uint8` + `int8` => `int16`, \n - `uint8` + `int16` => `int16`\n - `uint8` + `uint16` => `uint16`\n \n - `int8` + `int16` => `int16`\n - `int8` + `uint16` => `uint16` (in numpy, the result is a `int32`)\n\n - `uint16` + `int16` => `float` (in numpy, the result is a `int32`)\n \n4. When one operand of a binary operation is a generic scalar `micropython` variable, i.e., `mp_obj_int`, or `mp_obj_float`, it will be converted to a linear array of length 1, and with the smallest `dtype` that can accommodate the variable in question. After that the broadcasting rules apply, as described in the section [Iterating over two ndarrays simultaneously: broadcasting](#Iterating_over_two_ndarrays_simultaneously:_broadcasting)\n\nUpcasting is resolved in place, wherever it is required. Notable examples can be found in [ndarray_operators.c](https://github.com/v923z/micropython-ulab/blob/master/code/ndarray_operators.c)\n\n## Slicing and indexing\n\nAn `ndarray` can be indexed with three types of objects: integer scalars, slices, and another `ndarray`, whose elements are either integer scalars, or Booleans. Since slice and integer indices can be thought of as modifications of the `strides`, these indices return a view of the `ndarray`. This statement does not hold for `ndarray` indices, and therefore, the return a copy of the array.\n\n## Extending ulab\n\nThe `user` module is disabled by default, as can be seen from the last couple of lines of [ulab.h](https://github.com/v923z/micropython-ulab/blob/master/code/ulab.h)\n\n```c\n// user-defined module\n#ifndef ULAB_USER_MODULE\n#define ULAB_USER_MODULE (0)\n#endif\n```\n\nThe module contains a very simple function, `user_dummy`, and this function is bound to the module itself. In other words, even if the module is enabled, one has to `import`:\n\n```python\n\nimport ulab\nfrom ulab import user\n\nuser.dummy_function(2.5)\n```\nwhich should just return 5.0. Even if `numpy`-compatibility is required (i.e., if most functions are bound at the top level to `ulab` directly), having to `import` the module has a great advantage. Namely, only the [user.h](https://github.com/v923z/micropython-ulab/blob/master/code/user/user.h) and [user.c](https://github.com/v923z/micropython-ulab/blob/master/code/user/user.c) files have to be modified, thus it should be relatively straightforward to update your local copy from [github](https://github.com/v923z/micropython-ulab/blob/master/). \n\nNow, let us see, how we can add a more meaningful function. \n\n## Creating a new ndarray\n\nIn the [General comments](#General_comments) sections we have seen the type definition of an `ndarray`. This structure can be generated by means of a couple of functions listed in [ndarray.c](https://github.com/v923z/micropython-ulab/blob/master/code/ndarray.c). \n\n\n### ndarray_new_ndarray\n\nThe `ndarray_new_ndarray` functions is called by all other array-generating functions. It takes the number of dimensions, `ndim`, a `uint8_t`, the `shape`, a pointer to `size_t`, the `strides`, a pointer to `int32_t`, and `dtype`, another `uint8_t` as its arguments, and returns a new array with all entries initialised to 0. \n\nAssuming that `ULAB_MAX_DIMS > 2`, a new dense array of dimension 3, of `shape` (3, 4, 5), of `strides` (1000, 200, 10), and `dtype` `uint16_t` can be generated by the following instructions\n\n```c\nsize_t *shape = m_new(size_t, ULAB_MAX_DIMS);\nshape[ULAB_MAX_DIMS - 1] = 5;\nshape[ULAB_MAX_DIMS - 2] = 4;\nshape[ULAB_MAX_DIMS - 3] = 3;\n\nint32_t *strides = m_new(int32_t, ULAB_MAX_DIMS);\nstrides[ULAB_MAX_DIMS - 1] = 10;\nstrides[ULAB_MAX_DIMS - 2] = 200;\nstrides[ULAB_MAX_DIMS - 3] = 1000;\n\nndarray_obj_t *new_ndarray = ndarray_new_ndarray(3, shape, strides, NDARRAY_UINT16);\n```\n\n### ndarray_new_dense_ndarray\n\nThe functions simply calculates the `strides` from the `shape`, and calls `ndarray_new_ndarray`. Assuming that `ULAB_MAX_DIMS > 2`, a new dense array of dimension 3, of `shape` (3, 4, 5), and `dtype` `mp_float_t` can be generated by the following instructions\n\n```c\nsize_t *shape = m_new(size_t, ULAB_MAX_DIMS);\nshape[ULAB_MAX_DIMS - 1] = 5;\nshape[ULAB_MAX_DIMS - 2] = 4;\nshape[ULAB_MAX_DIMS - 3] = 3;\n\nndarray_obj_t *new_ndarray = ndarray_new_dense_ndarray(3, shape, NDARRAY_FLOAT);\n```\n\n### ndarray_new_linear_array\n\nSince the dimensions of a linear array are known (1), the `ndarray_new_linear_array` takes the `length`, a `size_t`, and the `dtype`, an `uint8_t`. Internally, `ndarray_new_linear_array` generates the `shape` array, and calls `ndarray_new_dense_array` with `ndim = 1`.\n\nA linear array of length 100, and `dtype` `uint8` could be created by the function call\n\n```c\nndarray_obj_t *new_ndarray = ndarray_new_linear_array(100, NDARRAY_UINT8)\n```\n\n### ndarray_new_ndarray_from_tuple\n\nThis function takes a `tuple`, which should hold the lengths of the axes (in other words, the `shape`), and the `dtype`, and calls internally `ndarray_new_dense_array`. A new `ndarray` can be generated by calling \n\n```c\nndarray_obj_t *new_ndarray = ndarray_new_ndarray_from_tuple(shape, NDARRAY_FLOAT);\n```\nwhere `shape` is a tuple.\n\n\n### ndarray_new_view\n\nThis function crates a *view*, and takes the source, an `ndarray`, the number of dimensions, an `uint8_t`, the `shape`, a pointer to `size_t`, the `strides`, a pointer to `int32_t`, and the offset, an `int32_t` as arguments. The offset is the number of bytes by which the void `array` pointer is shifted. E.g., the `python` statement\n\n```python\na = np.array([0, 1, 2, 3, 4, 5], dtype=uint8)\nb = a[1::2]\n```\n\nproduces the array\n\n```python\narray([1, 3, 5], dtype=uint8)\n```\nwhich holds its data at position `x0 + 1`, if `a`'s pointer is at `x0`. In this particular case, the offset is 1. \n\nThe array `b` from the example above could be generated as \n\n```c\nsize_t *shape = m_new(size_t, ULAB_MAX_DIMS);\nshape[ULAB_MAX_DIMS - 1] = 3;\n\nint32_t *strides = m_new(int32_t, ULAB_MAX_DIMS);\nstrides[ULAB_MAX_DIMS - 1] = 2;\n\nint32_t offset = 1;\nuint8_t ndim = 1;\n\nndarray_obj_t *new_ndarray = ndarray_new_view(ndarray_a, ndim, shape, strides, offset);\n```\n\n### ndarray_copy_array\n\nThe `ndarray_copy_array` function can be used for copying the contents of an array. Note that the target array has to be created beforehand. E.g., a one-to-one copy can be gotten by \n\n```c\nndarray_obj_t *new_ndarray = ndarray_new_ndarray(source->ndim, source->shape, source->strides, source->dtype);\nndarray_copy_array(source, new_ndarray);\n\n```\nNote that the function cannot be used for forcing type conversion, i.e., the input and output types must be identical, because the function simply calls the `memcpy` function. On the other hand, the input and output `strides` do not necessarily have to be equal.\n\n### ndarray_copy_view\n\nThe `ndarray_obj_t *new_ndarray = ...` instruction can be saved by calling the `ndarray_copy_view` function with the single `source` argument. \n\n\n## Accessing data in the ndarray\n\nHaving seen, how arrays can be generated and copied, it is time to look at how the data in an `ndarray` can be accessed and modified. \n\nFor starters, let us suppose that the object in question comes from the user (i.e., via the `micropython` interface), First, we have to acquire a pointer to the `ndarray` by calling \n\n```c\nndarray_obj_t *ndarray = MP_OBJ_TO_PTR(object_in);\n```\n\nIf it is not clear, whether the object is an `ndarray` (e.g., if we want to write a function that can take `ndarray`s, and other iterables as its argument), we find this out by evaluating \n\n```c\nMP_OBJ_IS_TYPE(object_in, &ulab_ndarray_type)\n```\nwhich should return `true`. Once the pointer is at our disposal, we can get a pointer to the underlying numerical array as discussed earlier, i.e., \n\n```c\nuint8_t *array = (uint8_t *)ndarray->array;\n```\n\nIf you need to find out the `dtype` of the array, you can get it by accessing the `dtype` member of the `ndarray`, i.e., \n\n```c\nndarray->dtype\n```\nshould be equal to `B`, `b`, `H`, `h`, or `f`. The size of a single item is stored in the `itemsize` member. This number should be equal to 1, if the `dtype` is `B`, or `b`, 2, if the `dtype` is `H`, or `h`, 4, if the `dtype` is `f`, and 8 for `d`. \n\n## Boilerplate\n\nIn the next section, we will construct a function that generates the element-wise square of a dense array, otherwise, raises a `TypeError` exception. Dense arrays can easily be iterated over, since we do not have to care about the `shape` and the `strides`. If the array is sparse, the section [Iterating over elements of a tensor](#Iterating-over-elements-of-a-tensor) should contain hints as to how the iteration can be implemented.\n\nThe function is listed under [user.c](https://github.com/v923z/micropython-ulab/tree/master/code/user/). The `user` module is bound to `ulab` in [ulab.c](https://github.com/v923z/micropython-ulab/tree/master/code/ulab.c) in the lines \n\n```c\n #if ULAB_USER_MODULE\n { MP_ROM_QSTR(MP_QSTR_user), MP_ROM_PTR(&ulab_user_module) },\n #endif\n```\nwhich assumes that at the very end of [ulab.h](https://github.com/v923z/micropython-ulab/tree/master/code/ulab.h) the \n\n```c\n// user-defined module\n#ifndef ULAB_USER_MODULE\n#define ULAB_USER_MODULE (1)\n#endif\n```\nconstant has been set to 1. After compilation, you can call a particular `user` function in `python` by importing the module first, i.e., \n\n```python\nfrom ulab import numpy as np\nfrom ulab import user\n\nuser.some_function(...)\n```\n\nThis separation of user-defined functions from the rest of the code ensures that the integrity of the main module and all its functions are always preserved. Even in case of a catastrophic failure, you can exclude the `user` module, and start over.\n\nAnd now the function:\n\n\n```c\nstatic mp_obj_t user_square(mp_obj_t arg) {\n // the function takes a single dense ndarray, and calculates the \n // element-wise square of its entries\n \n // raise a TypeError exception, if the input is not an ndarray\n if(!MP_OBJ_IS_TYPE(arg, &ulab_ndarray_type)) {\n mp_raise_TypeError(translate(\"input must be an ndarray\"));\n }\n ndarray_obj_t *ndarray = MP_OBJ_TO_PTR(arg);\n \n // make sure that the input is a dense array\n if(!ndarray_is_dense(ndarray)) {\n mp_raise_TypeError(translate(\"input must be a dense ndarray\"));\n }\n \n // if the input is a dense array, create `results` with the same number of \n // dimensions, shape, and dtype\n ndarray_obj_t *results = ndarray_new_dense_ndarray(ndarray->ndim, ndarray->shape, ndarray->dtype);\n \n // since in a dense array the iteration over the elements is trivial, we \n // can cast the data arrays ndarray->array and results->array to the actual type\n if(ndarray->dtype == NDARRAY_UINT8) {\n uint8_t *array = (uint8_t *)ndarray->array;\n uint8_t *rarray = (uint8_t *)results->array;\n for(size_t i=0; i < ndarray->len; i++, array++) {\n *rarray++ = (*array) * (*array);\n }\n } else if(ndarray->dtype == NDARRAY_INT8) {\n int8_t *array = (int8_t *)ndarray->array;\n int8_t *rarray = (int8_t *)results->array;\n for(size_t i=0; i < ndarray->len; i++, array++) {\n *rarray++ = (*array) * (*array);\n }\n } else if(ndarray->dtype == NDARRAY_UINT16) {\n uint16_t *array = (uint16_t *)ndarray->array;\n uint16_t *rarray = (uint16_t *)results->array;\n for(size_t i=0; i < ndarray->len; i++, array++) {\n *rarray++ = (*array) * (*array);\n }\n } else if(ndarray->dtype == NDARRAY_INT16) {\n int16_t *array = (int16_t *)ndarray->array;\n int16_t *rarray = (int16_t *)results->array;\n for(size_t i=0; i < ndarray->len; i++, array++) {\n *rarray++ = (*array) * (*array);\n }\n } else { // if we end up here, the dtype is NDARRAY_FLOAT\n mp_float_t *array = (mp_float_t *)ndarray->array;\n mp_float_t *rarray = (mp_float_t *)results->array;\n for(size_t i=0; i < ndarray->len; i++, array++) {\n *rarray++ = (*array) * (*array);\n } \n }\n // at the end, return a micropython object\n return MP_OBJ_FROM_PTR(results);\n}\n\n```\n\nTo summarise, the steps for *implementing* a function are\n\n1. If necessary, inspect the type of the input object, which is always a `mp_obj_t` object\n2. If the input is an `ndarray_obj_t`, acquire a pointer to it by calling `ndarray_obj_t *ndarray = MP_OBJ_TO_PTR(arg);`\n3. Create a new array, or modify the existing one; get a pointer to the data by calling `uint8_t *array = (uint8_t *)ndarray->array;`, or something equivalent\n4. Once the new data have been calculated, return a `micropython` object by calling `MP_OBJ_FROM_PTR(...)`.\n\nThe listing above contains the implementation of the function, but as such, it cannot be called from `python`: \nit still has to be bound to the name space. This we do by first defining a function object in \n\n```c\nMP_DEFINE_CONST_FUN_OBJ_1(user_square_obj, user_square);\n\n```\n\n`micropython` defines a number of `MP_DEFINE_CONST_FUN_OBJ_N` macros in [obj.h](https://github.com/micropython/micropython/blob/master/py/obj.h). `N` is always the number of arguments the function takes. We had a function definition `static mp_obj_t user_square(mp_obj_t arg)`, i.e., we dealt with a single argument. \n\nFinally, we have to bind this function object in the globals table of the `user` module: \n\n```c\nSTATIC const mp_rom_map_elem_t ulab_user_globals_table[] = {\n { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_user) },\n { MP_OBJ_NEW_QSTR(MP_QSTR_square), (mp_obj_t)&user_square_obj },\n};\n```\n\nThus, the three steps required for the definition of a user-defined function are \n\n1. The low-level implementation of the function itself\n2. The definition of a function object by calling MP_DEFINE_CONST_FUN_OBJ_N()\n3. Binding this function object to the namespace in the `ulab_user_globals_table[]`\n", "meta": {"hexsha": "0776981f0be8e744abd36d547f9e3b801217114f", "size": 42312, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/ulab-programming.ipynb", "max_stars_repo_name": "jsimonrichard/micropython-ulab", "max_stars_repo_head_hexsha": "b3b22ab63844afd0ea3e8af73612970aa8626f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-20T08:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T08:49:42.000Z", "max_issues_repo_path": "docs/ulab-programming.ipynb", "max_issues_repo_name": "jsimonrichard/micropython-ulab", "max_issues_repo_head_hexsha": "b3b22ab63844afd0ea3e8af73612970aa8626f1d", "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": "docs/ulab-programming.ipynb", "max_forks_repo_name": "jsimonrichard/micropython-ulab", "max_forks_repo_head_hexsha": "b3b22ab63844afd0ea3e8af73612970aa8626f1d", "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": 52.9561952441, "max_line_length": 860, "alphanum_fraction": 0.602311401, "converted": true, "num_tokens": 9577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.18242552602881168, "lm_q1q2_score": 0.06360177221068129}} {"text": "##### Copyright 2022 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# Parameter Sweeps\n\n\n \n \n \n \n
    \n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
    \n\n\n```\ntry:\n import cirq\nexcept ImportError:\n print(\"installing cirq...\")\n !pip install --quiet cirq\n print(\"installed cirq.\")\n import cirq\n```\n\n## Concept of Circuit Parameterization and Sweeps\n\nSuppose you have a quantum circuit and in this circuit there is a gate with some parameter. You might wish to run this circuit for different values of this parameter. An example of this type of circuit is a Rabi flop experiment. This experiment runs a set of quantum computations which 1) starts in $|0\\rangle$ state, 2) rotates the state by $\\theta$ about the $x$ axis, i.e. applies the gate $\\exp(i \\theta X)$, and 3) measures the state in the computational basis. Running this experiment for multiple values of $\\theta$, and plotting the probability of observing a $|1\\rangle$ outcome yields the quintessential $\\cos^2$ probability distribution as a function of the parameter $\\theta$. To support this type of experiment, Cirq provides the concept of parameterized circuits and parameter sweeps. \n\nThe next cell illustrates parameter sweeps with a simple example. Suppose you want to compare two quantum circuits that are identical except for a single exponentiated `cirq.Z` gate.\n\n\n```\nq0 = cirq.LineQubit(0)\n\ncircuit1 = cirq.Circuit([cirq.H(q0), cirq.Z(q0)**0.5, cirq.H(q0), cirq.measure(q0)])\nprint(f\"circuit1:\\n{circuit1}\")\n\ncircuit2 = cirq.Circuit([cirq.H(q0), cirq.Z(q0)**0.25, cirq.H(q0), cirq.measure(q0)])\nprint(f\"circuit2:\\n{circuit2}\")\n```\n\nYou could run these circuits separately (either on hardware or in simulation), and collect statistics on the results of these circuits. However parameter sweeps can do this in a cleaner and more perfomant manner. \n\nFirst define a parameter, and construct a circuit that depends on this parameter. Cirq uses [SymPy](https://www.sympy.org/en/index.html){:external}, a symbolic mathematics package, to define parameters. In this example the Sympy parameter is `theta`, which is used to construct a parameterized circuit.\n\n\n```\nimport sympy\n\ntheta = sympy.Symbol(\"theta\")\n\ncircuit = cirq.Circuit([cirq.H(q0), cirq.Z(q0)**theta, cirq.H(q0), cirq.measure(q0)])\nprint(f\"circuit:\\n{circuit}\")\n```\n\nNotice now that the circuit contains a `cirq.Z` gate that is raised to a power, but this power is the parameter `theta`. This is a \"parameterized circuit\". An equivalent way to construct this circuit, where the parameter is actually a parameter in the gate constructor's arguments, is:\n\n\n```\ncircuit = cirq.Circuit(\n cirq.H(q0), cirq.ZPowGate(exponent=theta)(q0), cirq.H(q0), cirq.measure(q0)\n)\nprint(f\"circuit:\\n{circuit}\")\n```\n\nNote: You can check whether an object in Cirq is parameterized using `cirq.is_parameterized`:\n\n\n```\ncirq.is_parameterized(circuit)\n```\n\nParameterized circuits are just like normal circuits; they just aren't defined in terms of gates that you can actually run on a quantum computer without the additional information about the values of the parameters. Following the example above, you can generate the two circuits (`circuit1` and `circuit2`) by using `cirq.resolve_parameter` and supplying the values that you want the parameter(s) to take:\n\n\n```\n# circuit1 has theta = 0.5\ncirq.resolve_parameters(circuit, {\"theta\": 0.5})\n# circuit2 has theta = 0.25\ncirq.resolve_parameters(circuit, {\"theta\": 0.25})\n```\n\nMore interestingly, you can combine parameterized circuits with a list of parameter assignments when doing things like running circuits or simulating them. These lists of parameter assignements are called \"sweeps\". For example you can use a simulator's `run_sweep` method to run simulations for the parameters corresponding to the two circuits defined above. \n\n\n```\nsim = cirq.Simulator()\nresults = sim.run_sweep(circuit, repetitions=25, params=[{\"theta\": 0.5}, {\"theta\": 0.25}])\nfor result in results:\n print(f\"param: {result.params}, result: {result}\")\n```\n\nTo recap, you can construct parameterized circuits that depend on parameters that have not yet been assigned a value. These parameterized circuits can then be resolved to circuits with actual values via a dictionary that maps the sympy variable name to the value that parameter should take. You can also construct lists of dictionaries of parameter assignments, called sweeps, and pass this to many functions in Cirq that use circuits to do an action (such as `simulate` or `run`). For each of the elements in the sweep, the function will execute using the parameters as described by the element.\n\n## Constructing Sweeps\n\nThe previous example constructed a sweep by simply constructing a list of parameter assignments, `[{\"theta\": 0.5}, {\"theta\": 0.25}]`. Cirq also provides other ways to construct sweeps. \n\nOne useful method for constructing parameter sweeps is `cirq.Linspace` which creates a sweep over a list of equally spaced elements. \n\n\n```\n# Create a sweep over 5 equally spaced values from 0 to 2.5.\nparams = cirq.Linspace(key=\"theta\", start=0, stop=2.5, length=5)\nfor param in params:\n print(param)\n```\n\nNote: The `Linspace` sweep is composed of `cirq.ParamResolver` instances instead of simple dictionaries. However, you can think of them as effectively the same for most use cases. \n\nIf you need to explicitly and individually specify each parameter resolution, you can do it by constructing a list of dictionaries as before. However, you can also use `cirq.Points` to do this more succinctly.\n\n\n```\nparams = cirq.Points(key=\"theta\", points=[0, 1, 3])\nfor param in params:\n print(param)\n```\n\nIf you're working with parameterized circuits, it is very likely you'll need to keep track of multiple parameters. Two common use cases necessitate building a sweep from two constituent sweeps, where the new sweep includes: \n- Every possible combination of the elements of each sweep: A cartesian product. \n- A element-wise pairing of the two sweeps: A zip.\n\nThe following are examples of using the `*` and `+` operators to combine sweeps by cartesian product and zipping, respectively. \n\n\n```\nsweep1 = cirq.Linspace(\"theta\", 0, 1, 5)\nsweep2 = cirq.Points(\"gamma\", [0, 3])\n# By taking the product of these two sweeps, you can sweep over all possible\n# combinations of the parameters.\nfor param in sweep1 * sweep2:\n print(param)\n```\n\n\n```\nsweep1 = cirq.Points(\"theta\", [1, 2, 3])\nsweep2 = cirq.Points(\"gamma\", [0, 3, 4])\n# By taking the sum of these two sweeps, you can combine the sweeps\n# elementwise (similar to python's zip function):\nfor param in sweep1 + sweep2:\n print(param)\n```\n\n`cirq.Linspace` and `cirq.Points` are instances of the `cirq.Sweep` class, which explicitly supports cartesian product with the `*` operation, and zipping with the `+` operation. The `*` operation produces a `cirq.Product` object, and `+` produces a `cirq.Zip` object, both of which are also `Sweep`s. Other mathematical operations will not work in general *between sweeps*.\n\n## Symbols and Expressions\n\n[SymPy](https://www.sympy.org/en/index.html){:external} is a general symbolic mathematics toolset, and you can leverage this in Cirq to define more complex parameters than have been shown so far. For example, you can define an expression in Sympy and use it to construct circuits that depend on this expression:\n\n\n```\n# Construct an expression for 0.5 * a + 0.25:\nexpr = 0.5 * sympy.Symbol(\"a\") + 0.25\nprint(expr)\n```\n\n\n```\n# Use the expression in the circuit:\ncircuit = cirq.Circuit(cirq.X(q0)**expr, cirq.measure(q0))\nprint(f\"circuit:\\n{circuit}\")\n```\n\nBoth the exponents and parameter arguments of circuit operations can in fact be any general Sympy expression: The previous examples just used single-variable expressions. When you resolve parameters for this circuit, the expressions are evaluated under the given assignments to the variables in the expression. \n\n\n```\nprint(cirq.resolve_parameters(circuit, {\"a\": 0}))\n```\n\nJust as before, you can pass a sweep over variable values to `run` or `simulate`, and Cirq will evaluate the expression for each possible value. \n\n\n```\nsim = cirq.Simulator()\nresults = sim.run_sweep(circuit, repetitions=25, params=cirq.Points('a', [0, 1]))\nfor result in results:\n print(f\"param: {result.params}, result: {result}\")\n```\n\nSympy supports a large number of numeric functions and methods, which can be used to create fairly sophisticated expressions, like cosine, exponentiation, and more:\n\n\n```\nprint(sympy.cos(sympy.Symbol(\"a\"))**sympy.Symbol(\"b\"))\n```\n\nCirq can numerically evaluate all of the expressions Sympy can evalute. However, if you are running a parameterized circuit on a service (such as on a hardware backed quantum computing service) that service may not support evaluating all expressions. See documentation for the particular service you're using for details. \n\nAs a general workaround, you can instead use Cirq's flattening ability to evaluate the parameters before sending them off to the service.\n\n### Flattening Expressions\n\nSuppose you build a circuit that includes multiple different expressions:\n\n\n```\na = sympy.Symbol('a')\ncircuit = cirq.Circuit(cirq.X(q0)**(a / 4), cirq.Y(q0)**(1 - a / 2), cirq.measure(q0))\nprint(circuit)\n```\n\nFlattening replaces every expression in the circuit with a new symbol that is representative of the value of that expression. Additionally, it keeps track of the new symbols and provices a `cirq.ExpressionMap` object to map the old sympy expression objects to the new symbols that replaced them. \n\n\n```\n# Flatten returns two objects, the circuit with new symbols, and the mapping from old to new values.\nc_flat, expr_map = cirq.flatten(circuit)\nprint(c_flat)\nprint(expr_map)\n```\n\nNotice that the new circuit has new symbols, `` and `<1-a/2>`, which are explicitly not expressions. You can see this by looking at the value of the exponent in the first gate:\n\n\n```\nfirst_gate = c_flat[0][q0].gate\nprint(first_gate.exponent)\n# Note this is a symbol, not an expression\nprint(type(first_gate.exponent))\n```\n\nThe second object returned by `cirq.flatten` is an object that can be used to map sweeps over the previous symbols to new sweeps over the new expression-symbols. The values assigned to the new expression symbols in the resulting sweep are the old expressions kept track of in the `ExpressionMap`, but resolved with the values provided by the original input sweep.\n\n\n```\nsweep = cirq.Linspace(a, start=0, stop=3, length=4)\nprint(f\"Old {sweep}\")\n\nnew_sweep = expr_map.transform_sweep(sweep)\nprint(f\"New {new_sweep}\")\n```\n\nTo reinforce: The new sweep is over two new symbols, which each represent the values of the expressions in the original circuit. The values assigned to these new expression symbols is acquired by evaluating the expressions with `a` resolved to a value in `[0, 4]`, according to the old sweep. \n\nYou can use these new sweep elements to resolve the parameters of the flattened circuit:\n\n\n```\nfor params in new_sweep:\n print(c_flat, '=>', end=' ')\n print(cirq.resolve_parameters(c_flat, params))\n```\n\nUsing `cirq.flatten`, you can always take a parameterized circuit with any complicated expressions, plus a sweep, and produce an equivalent circuit with no expressions, only symbols, and a sweep for these new symbols. Because this is a common flow, Cirq provides `cirq.flatten_sweep` to do this in one step:\n\n\n```\nc_flat, new_sweep = cirq.flatten_with_sweep(circuit, sweep)\nprint(c_flat)\nprint(new_sweep)\n```\n\nYou can then directly use these objects to run the sweeps. For example, you can use them to perform a simulation:\n\n\n```\nsim = cirq.Simulator()\nresults = sim.run_sweep(c_flat, repetitions=20, params=new_sweep)\nfor result in results:\n print(result.params, result)\n```\n\nYou can see that the different flattened parameters have corresponding different results for their simulation.\n\n# Summary\n\n- Cirq circuits can handle arbitrary Sympy expressions in place of exponents and parameter arguments in operations.\n- By providing one or a sequence of `ParamResolver`s or dictionaries that resolve the Sympy variables to values, `run`, `simulate`, and other functions can iterate efficiently over different parameter assignments for otherwise identical circuits. \n- Sweeps can be created succinctly with `cirq.Points` and `cirq.Linspace`, and composed with each other with `*` and `+`, to create `cirq.Product` and `cirq.Zip` sweeps. \n- When the service you're using does not support arbitrary expressions, you can flatten a circuit and sweep into a new circuit that doesn't have complex expressions, and a corresponding new sweep. \n", "meta": {"hexsha": "cb4c44732bc67da6f86e4760ff3b466d33d099e9", "size": 22007, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/params.ipynb", "max_stars_repo_name": "Nexuscompute/Cirq", "max_stars_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "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/params.ipynb", "max_issues_repo_name": "Nexuscompute/Cirq", "max_issues_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-16T14:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T03:58:46.000Z", "max_forks_repo_path": "docs/params.ipynb", "max_forks_repo_name": "Nexuscompute/Cirq", "max_forks_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "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": 33.3439393939, "max_line_length": 821, "alphanum_fraction": 0.6222565547, "converted": true, "num_tokens": 3328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.13846178523628042, "lm_q1q2_score": 0.0632959638609084}} {"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n \n\n \n\n\n\n[Python for Probability, Statistics, and Machine Learning](https://www.springer.com/fr/book/9783319307152)\n\n# Projection Methods\n\nThe concept of projection is key to developing an intuition about conditional\nprobability. We already have a natural intuition of projection from looking at\nthe shadows of objects on a sunny day. As we will see, this simple idea\nconsolidates many abstract ideas in optimization and mathematics. Consider\n[Figure](#fig:probability_001) where we want to find a point along the blue\nline (namely, $\\mathbf{x}$) that is closest to the black square (namely,\n$\\mathbf{y}$). In other words, we want to inflate the gray circle until it just\ntouches the black line. Recall that the circle boundary is the set of points for\nwhich\n\n$$\n\\sqrt{(\\mathbf{y}-\\mathbf{x})^T(\\mathbf{y}-\\mathbf{x})} =\\|\\mathbf{y}-\\mathbf{x} \\| = \\epsilon\n$$\n\n for some value of $\\epsilon$. So we want a point $\\mathbf{x}$ along\nthe line that satisfies this for the smallest $\\epsilon$. Then, that point\nwill be the closest point on the black line to the black square.\n It may be obvious from the diagram, but the closest point on the line\noccurs where the line segment from the black square to the black line is\nperpedicular to the line. At this point, the gray circle just touches the black\nline. This is illustrated below in [Figure](#fig:probability_002).\n\n\n\n
    \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\n

    The 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\n

    In 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

    Table of Contents

    \n
    \n\nIn this section we estimate a statistical model that leverages some of the main advantages of using panel data: **Fixed Effects**. We show some examples of how to estimate and interpret this model, and reflect on the conditions under which the model is appropriate.\n\n## Quick reminder\n\nLet's briefly recap some essential concepts regarding panel data:\n\nTwo sources of variation ([Gould, n.d.](https://www.stata.com/support/faqs/statistics/between-estimator/)): \n1. Cross-section information on differences between units\n2. Time series information on differences over time within units\n\nSo far our panel data models — Pooled OLS and Between Effects — only allow us to examine differences between units.\n\nTwo main issues with estimating statistical models:\n1. Interdependence of errors\n2. Improper model specification\n\nThe first can lead to inefficient estimates: under-estimated standard errors and false positive tests of statistical significance.\n\nThe second to biased coefficients and incorrect inferences regarding magnitude and direction of effect of explanatory variables.\n\nTherefore we need a statistical model that allows us to **examine change over time** and/or **control for omitted variable bias**.\n\n## Defining our statistical model\n\nBefore estimating Fixed Effects and Random Effects models separately, it is worth identifying the key commonality between their respective statistical models.\n\nLet's take a simplified version of our charity income statistical model, this time with only one explanatory variable (*age*) - typically it looks as follows:\n\n\\begin{equation} \\text{y}_{it} = \\beta_0 + \\beta_1x_{1it} + \\epsilon_{it} \\tag{1.2} \\end{equation}\n\nHowever it is possible to **decompose** the residual variation (error term) into two separate terms:\n\n\\begin{equation} \\text{y}_{it} = \\beta_0 + \\beta_1x_{1it} + \\mu_{i} + \\text{e}_{it} \\tag{1.3} \\end{equation}\n\nIn equation 1.3. we have introduced a **unit-specific** term to represent some of the residual variation in the outcome that is unexplained by the explanatory variables.\n\n### Decomposition implications\n\nThis term ($\\mu_{i}$) captures the effect of *residual heterogeneity* on the outcome i.e., unobserved or immeasurable characteristics of the units that are associated with the outcome (and possibly the explanatory variables), and vary across units.\n\nIn our charity data example, these charity-specific effects could be organisational culture, informal connections to government etc. In theory these characteristics could be measured but it's often wildly impractical.\n\nIt also controls for the effect of other omitted variables on the outcome (and possibly the explanatory variables).\n\nIn our charity data example, we do not include explanatory variables capturing the amount a charity spends on fundraising, how well known it is etc. \n\n### A word of caution\n\nNote the lack of a time subscript *t* in the new term $\\mu_{i}$.\n\nThe implication is that the unobserved unit-specific effect is **constant** over time (i.e., within units).\n\nTherefore Fixed Effects and Random Effects models only control for omitted variables that do not change within units (e.g., race, sex at birth, natural ability).\n\n## Fixed Effects Model\n\n### Conceptualising the Fixed Effects model\n\n1. The Fixed Effects model focuses on how changes in explanatory variables are associated with changes in the outcome **within units**.\n\n2. It assumes the observed explanatory variables and unobserved unit-specific effect are correlated (i.e., omitted variable bias is an issue).\n\nMehmetoglu and Jakobsen (2016, p. 241):\n> \"In other words, we use fixed effects whenever we are only interested in the impact of variables that vary over time. This estimator helps us explore the relationship between the dependent and the explanatory variables within a unit (person, company, country, etc.) Each unit has its own individual characteristics that may or may not influence the predictor variables.\"\n\nThe Fixed Effects model is specified as follows:\n\n\\begin{equation} \\text{y}_{it} = \\beta_0 + \\lambda_{i} + \\beta_1x_{1it} +...+ \\beta_kx_{kit} + \\text{e}_{it} \\tag{1.4} \\end{equation}\n\nWhere:\n\n$\\lambda_{i}$ represents the unit-specific effect on the outcome.\n\nThe value of $\\lambda_{i}$ captures the effect of **all** of the unobserved time-invariant explanatory variables that are missing from the model.\n\nAs a result, while the value of $\\lambda_{i}$ is calculated, it is not of much interest in and of itself.\n\nIt's main role is to allow for a more robust (i.e., unbiased) estimation of the effects of the explanatory variables in the model.\n\nIn essence the Fixed Effects model produces a unit-specific intercept, which is the sum of the overall constant and the unit-specific effect:\n\n\\begin{equation} \\text{y}_{it} = \\alpha_{i} + \\beta_1x_{1it} +...+ \\beta_kx_{kit} + \\text{e}_{it} \\tag{1.5} \\end{equation}\n\nWhere:\n\n$\\alpha_{i} = \\beta_0 + \\lambda_{i}$\n\nThe unit-specific effect shifts the overall intercept up or down the y axis by the value of $\\lambda$.\n\n**QUESTION**\n\nWhy is the unobserved unit-specific effect incorporated into the constant?\n\nTwo reasons:\n* It is not of interest in and of itself (who cares what the effect is of being you?)\n* It doesn't vary within a unit: remember we are only modelling within-unit variation and the unit-specific effect does not vary within a unit, therefore it does not make sense to interpret the unit-specific term like an explanatory variable.\n\n#### Final thoughts on conceptualisation\n\nConsider it a standard cross-sectional regression model with the addition of a dummy variable being included for every unit in the panel except for one (i.e., *n - 1* dummy variables are added to the model).\n\n### Estimation\n\n\n```stata\nuse \"../data/charity-panel-analysis-2020-09-10.dta\", clear\n```\n\n (Contains annual accounts of charities in E&W for financial years 2006-2017)\n\n\n\n```stata\nxtreg linc orgage localc west genchar nsources govern_share, fe\n```\n\n note: localc omitted because of collinearity\n note: west omitted because of collinearity\n note: genchar omitted because of collinearity\n \n Fixed-effects (within) regression Number of obs = 23,826\n Group variable: regno Number of groups = 2,166\n \n R-sq: Obs per group:\n within = 0.0140 min = 11\n between = 0.0425 avg = 11.0\n overall = 0.0403 max = 11\n \n F(3,21657) = 102.28\n corr(u_i, Xb) = -0.1002 Prob > F = 0.0000\n \n ------------------------------------------------------------------------------\n linc | Coef. Std. Err. t P>|t| [95% Conf. Interval]\n -------------+----------------------------------------------------------------\n orgage | .0069072 .0005802 11.90 0.000 .00577 .0080444\n localc | 0 (omitted)\n west | 0 (omitted)\n genchar | 0 (omitted)\n nsources | .0289886 .0027931 10.38 0.000 .0235139 .0344633\n govern_share | .0010325 .0001225 8.43 0.000 .0007923 .0012727\n _cons | 14.71504 .026082 564.18 0.000 14.66392 14.76616\n -------------+----------------------------------------------------------------\n sigma_u | .94534636\n sigma_e | .2821005\n rho | .91823289 (fraction of variance due to u_i)\n ------------------------------------------------------------------------------\n F test that all u_i=0: F(2165, 21657) = 120.80 Prob > F = 0.0000\n\n\n**QUESTION TIME**\n\n1. How much of the variation in the outcome is accounted for by the model? Is this a lot?\n2. Why were three of the observed explanatory variables excluded in the estimation of the model?\n3. What does the $\\text{rho}$ statistic tell us?\n4. Is there evidence of correlation between the unit-specific effects and observed explanatory variables?\n\n### Interpretation\n\nThe effect of the observed explanatory variables is **net of** the effect of the unit-specific term. That is, we've controlled away the correlation between *X* and $\\mu_{i}$.\n\n$\\text{_cons}$ is the intercept and represents the average value of the fixed effects + the overall constant.\n\n$\\text{orgage}$ is the predicted change in the outcome for a one-unit increase in organisational age.\n\n$\\text{rho}$ is the proportion of unexplained variance in the outcome explained by unobserved differences between charities (the unit-specific effects), rather than changes within them.\n\nIf $\\text{rho}$ > .5 then most of the residual variation in the outcome is due to differences between units, if $\\text{rho}$ < .5 then most of the residual variation is accounted for by differences within units (i.e., the effects of the explanatory variables).\n\n$\\text{corr(u_i, Xb)}$ is the correlation between the unit-specific effect and the observed explanatory variables in the model.\n\n\n* $\\text{sigma_u}$ (or $\\sigma_u$) is the standard deviation of residuals within units.\n* $\\text{sigma_e}$ (or $\\sigma_e$) is the standard deviation of residuals ei.\n* \n* $\\text{R-sq: within}$ is the proportion of variance explained by the observed explanatory variables (i.e., excluding the unit-specific effect).\n\n### Post-estimation\n\nThough it's very rarely of substantive interest, we can recover the unit-specific effects (and other parameter estimates) after estimating a Fixed Effects model:\n\n\n```stata\ncapture predict fixed, u\ncapture predict y_hat, xb\ncapture predict ei, e\ncapture predict residuals, ue\ncapture egen pickone = tag(regno)\n```\n\n\n```stata\nl regno fin_year fixed if pickone in 1/100\n```\n\n \n +-------------------------------+\n | regno fin_year fixed |\n |-------------------------------|\n 1. | 200048 2006-07 -.9911593 |\n 12. | 200051 2006-07 1.341765 |\n 23. | 200069 2006-07 -.4608771 |\n 34. | 200222 2006-07 -.1173254 |\n 45. | 200424 2006-07 -.4077182 |\n |-------------------------------|\n 56. | 200431 2006-07 -.5248324 |\n 67. | 200500 2006-07 -.0236679 |\n 78. | 201081 2006-07 .0432656 |\n 89. | 201321 2006-07 -1.400211 |\n 100. | 201911 2006-07 -.7076412 |\n +-------------------------------+\n\n\n\n```stata\nl regno fin_year linc y_hat residuals fixed ei in 1/11\n```\n\n \n +-----------------------------------------------------------------+\n 1. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2006-07 | 14.00189 | 15.17772 | -1.175828 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | -.1846687 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 2. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2007-08 | 14.17788 | 15.18462 | -1.006747 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | -.0155877 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 3. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2008-09 | 14.1851 | 15.22075 | -1.03565 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | -.0444904 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 4. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2009-10 | 14.2326 | 15.19844 | -.9658405 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | .0253188 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 5. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2010-11 | 14.1709 | 15.20695 | -1.036052 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | -.0448926 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 6. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2011-12 | 14.14801 | 15.21225 | -1.06424 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | -.0730808 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 7. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2012-13 | 14.376 | 15.25097 | -.8749701 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | .1161892 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 8. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2013-14 | 14.29996 | 15.22607 | -.9261075 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | .0650518 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 9. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2014-15 | 14.26031 | 15.2623 | -1.001989 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | -.0108296 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 10. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2015-16 | 14.30113 | 15.23988 | -.9387508 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | .0524085 |\n +-----------------------------------------------------------------+\n \n +-----------------------------------------------------------------+\n 11. | regno | fin_year | linc | y_hat | residuals | fixed |\n | 200048 | 2016-17 | 14.37021 | 15.24679 | -.8765777 | -.9911593 |\n |-----------------------------------------------------------------|\n | ei |\n | .1145816 |\n +-----------------------------------------------------------------+\n\n\n\n```stata\ndi -.9911593 + -.1846687\n```\n\n -1.175828\n\n\n\n```stata\ntabstat fixed ei, s(mean sd) format(%5.4f)\n```\n\n \n stats | fixed ei\n ---------+--------------------\n mean | -0.0000 -0.0000\n sd | 0.9451 0.2690\n ------------------------------\n\n\n### Benefits of Fixed Effects\n\nAnalyse change over time [Substantive]\n\nControl for residual heterogeneity [Methodological]\n\n(Mehmetoglu and Jakobsen, 2016)\n\nCoefficient estimates are **consistent** if the key assumption is true.\n\nThat is, because we have controlled for the effect of unobserved time-invariant explanatory variables, our coefficients are more robust, which means increasing the sample size increases the likelihood the estimates are converging on their true values.\n\n### Limitations of Fixed Effects\n\nIgnores differences between units [Substantive]\n\nCoefficient estimates are **inefficient**, especially when compared to those from a Random Effects model. As a result, standard errors tend to be larger.\n\nPut simply, the estimates of the coefficients are based on only one source of variation (within) and thus are more uncertain.\n\nCannot include observed time-invariant explanatory variables [Methodological]\n\nThis is due to a very simple reason: if a value does not vary, how can it be associated with variation in the value of another variable?\n\nIt is not well suited for variables that rarely change within units.\n\nThink carefully about variables that change little over time - how might these influence the outcome? For example, few individuals in your panel might switch from non-graduate to graduate (let's say you have a sample of older individuals). In a fixed effects model, your estimation of the effect of switching between non-graduate and graduate will be based on a small number of occurrences and care is due in interpreting the coefficient.\n\nCannot control for unobserved residual heterogeneity that varies over time [Methodological]\n\nEducational ability? Natural resilience?\n\nThe last point is worth expanding on: if units differ in an unobserved way that varies over time, this will not be controlled for in the Fixed Effects model.\n\n### Summarising the Fixed Effects model\n\nFocuses on change over time within a unit of analysis.\n\nCan control for the effect of unobserved time-invariant explanatory variables (residual heterogeneity).\n\nProvides robust estimates of observed explanatory variables when said variables are correlated with unobserved effects.\n\nHowever cannot include observed explanatory variables that do not vary within units.\n\n## Summary\n\nBoth the Pooled OLS and Between Effects models provide useful information on the association between an outcome *Y* and a set of explanatory variables *X*.\n\nFixed Effects provide potentially different information on the association between an outcome *Y* and a set of explanatory variables *X.\n\nIs there a way to combine the *within* and *between* perspectives?\n", "meta": {"hexsha": "6e4ede20371faada7819781914f114b4ca275b3e", "size": 37273, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lda-panel-data-analysis-III-2020-08-28.ipynb", "max_stars_repo_name": "DiarmuidM/longitudinal-data-analysis", "max_stars_repo_head_hexsha": "36f96443bd790a0bc761624b19795ccfbca425fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-10T18:14:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-10T18:14:20.000Z", "max_issues_repo_path": "notebooks/lda-panel-data-analysis-III-2020-08-28.ipynb", "max_issues_repo_name": "DiarmuidM/longitudinal-data-analysis", "max_issues_repo_head_hexsha": "36f96443bd790a0bc761624b19795ccfbca425fe", "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": "notebooks/lda-panel-data-analysis-III-2020-08-28.ipynb", "max_forks_repo_name": "DiarmuidM/longitudinal-data-analysis", "max_forks_repo_head_hexsha": "36f96443bd790a0bc761624b19795ccfbca425fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-10T09:48:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T09:48:56.000Z", "avg_line_length": 29.9622186495, "max_line_length": 2509, "alphanum_fraction": 0.4829232957, "converted": true, "num_tokens": 4956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1294027399852894, "lm_q1q2_score": 0.06318520924060117}} {"text": "Here are some points to remember:\n\n• Objects share operations according to their category; for instance, strings, lists, and tuples all share sequence operations such as concatenation, length, and\nindexing.\n\n• Only mutable objects (lists, dictionaries, and sets) may be changed in-place; you\ncannot change numbers, strings, or tuples in-place.\n\n• Files export only methods, so mutability doesn’t really apply to them—their state\nmay be changed when they are processed, but this isn’t quite the same as Python core type mutability constraints.\n\n• “Numbers” in Table 9-3 includes all number types: integer (and the distinct long\ninteger in 2.6), floating-point, complex, decimal, and fraction.\n\n• “Strings” in Table 9-3 includes str, as well as bytes in 3.0 and unicode in 2.6; the byte array string type in 3.0 is mutable.\n\n• Sets are something like the keys of a valueless dictionary, but they don’t map to\nvalues and are not ordered, so sets are neither a mapping nor a sequence type; frozenset is an immutable variant of set.\n\n• In addition to type category operations, as of Python 2.6 and 3.0 all the types in Table 9-3 have callable methods, which are generally specific to their type\n\n\n```python\nX = [1,2,3]\nL = ['a',X,'b'] # Embed references to X's object\nD = {'x':X,'y':2}\n```\n\n\n```python\nprint(X,L,D)\n```\n\n [1, 2, 3] ['a', [1, 2, 3], 'b'] {'x': [1, 2, 3], 'y': 2}\n\n\n\n```python\nX[1] = 'surprise' # Changes all three references!\n```\n\n\n```python\nL, D\n```\n\n\n\n\n (['a', [1, 'surprise', 3], 'b'], {'x': [1, 'surprise', 3], 'y': 2})\n\n\n\n\n```python\nfrom wordcloud import WordCloud\nimport PIL.Image as image\n\nwith open(\"output.txt\",'r',encoding='utf-8') as fp:\n text=fp.read()\n #print(text)\n #将文本放入WordCoud容器对象中并分析\n WordCloud = WordCloud(width=1000,height=800).generate(text)\n image_produce = WordCloud.to_image()\n image_produce.show()\n```\n\n\n```python\nfrom sympy import plot_implicit, sin, symbols, pi\nx, y = symbols('x y')\nmy_plot = plot_implicit(x**2 + y**2 <= 1 + 0.5 * sin((x**3 + y**3) * 2 * pi))\n```\n\n\n```python\nfrom __future__ import division\na,b,c = symbols('a b c')\nplot2 = plot_implicit( a**2 + b**2 <= 0)\n```\n\n\n```python\n(a**2+b**2)/(2*c) + (b**2+c**2)/(2*a) + (c**2+a**2)/(2*b)\n```\n\n\n\n\n$\\displaystyle \\frac{a^{2} + b^{2}}{2 c} + \\frac{a^{2} + c^{2}}{2 b} + \\frac{b^{2} + c^{2}}{2 a}$\n\n\n\n\n```python\na + b + c\n```\n\n\n\n\n$\\displaystyle a + b + c$\n\n\n\n\n```python\nL = [1,2,3]\nD = {'a': 1, 'b': 2}\n```\n\n\n```python\nA = L[:] # Instead of A = L (or list(L))\nB = D.copy() # Instead of B = D (ditto for sets)\n```\n\n\n```python\nA[1] = \"Ni\"\nB['c'] = 'spam'\nL, D\n```\n\n\n\n\n ([1, 2, 3], {'a': 1, 'b': 2})\n\n\n\n\n```python\nA, B\n```\n\n\n\n\n ([1, 'Ni', 3], {'a': 1, 'b': 2, 'c': 'spam'})\n\n\n\n\n```python\nL = [1,2,3]\nD = {'a': 1, 'b': 2}\nA = L \nB = D\nA[1] = \"Ni\"\nB['c'] = 'spam'\nprint(L,D)\nprint(A,B)\n```\n\n [1, 'Ni', 3] {'a': 1, 'b': 2, 'c': 'spam'}\n [1, 'Ni', 3] {'a': 1, 'b': 2, 'c': 'spam'}\n\n\n\n```python\n# Case 1\nX = [1,2,3]\nL = ['a',X[:],'b'] # Embed copies of X's object\nD = {'x': X[:],'y':2}\nX[1] = 'surprise' # It doesn't change all three references!\n```\n\n\n```python\nprint(X,L,D)\n```\n\n [1, 'surprise', 3] ['a', [1, 2, 3], 'b'] {'x': [1, 2, 3], 'y': 2}\n\n\n\n```python\n# case 2\nX = [1,2,3]\nL = ['a',X,'b']\nD = {'x': X, 'y': 2}\nX[1] = 'surprise'\n```\n\n\n```python\nprint(X,L,D)\n```\n\n [1, 2, 3] ['a', [1, 2, 3], 'b'] {'x': [1, 2, 3], 'y': 2}\n\n\n• Slice expressions with empty limits (L[:]) copy sequences.\n\n• The dictionary and set copy method (X.copy()) copies a dictionary or set.\n\n• Some built-in functions, such as list, make copies (list(L)).\n\n• The copy standard library module makes full copies.\n\nEmpty-limit slices and the dictionary copy method only make top-level copies; that is, they do not copy nested data structures, if any are present. If you need a complete, fully independent copy of a deeply nested data structure, use the standard copy module: include an import copy statement and say X = copy.deepcopy(Y) to fully copy an arbitrarily nested object Y. This call recursively traverses objects\nto copy all their parts. \n\n\n```python\nE = {'x': X, 'y': {str(X): X}}\n```\n\n\n```python\nE\n```\n\n\n\n\n {'x': [1, 2, 3], 'y': {'[1, 2, 3]': [1, 2, 3]}}\n\n\n\n\n```python\nF = E.copy()\n```\n\n\n```python\nF\n```\n\n\n\n\n {'x': [1, 2, 3], 'y': {'[1, 2, 3]': [1, 2, 3]}}\n\n\n\n\n```python\nfrom sympy import symbols\nimport sympy\nn = symbols('n')\n```\n\n\n```python\nfrom itertools import product\nT = product(k,(k,1,1000))\n```\n\n\n```python\nfrom sympy import plot_implicit, sin, symbols, pi\nimport numpy\n\nx, y = symbols('x y')\nmy_plot1 = plot_implicit(3*x**2 <= 6-2*y**2)\nmy_plot2 = plot_implicit(abs(2*x+y)<=numpy.sqrt(11))\n```\n\n\n```python\nfrom chempy import Substance\nferricyanide = Substance.from_formula('Fe(CN)6-3')\nferricyanide.composition == {0: -3, 26: 1, 6: 6, 7: 6} # 0 for charge\n```\n\n\n\n\n True\n\n\n\n\n```python\nprint(ferricyanide.unicode_name)\nprint(ferricyanide.latex_name + \", \" + ferricyanide.html_name)\nprint('%.3f' % ferricyanide.mass)\n```\n\n Fe(CN)₆³⁻\n Fe(CN)_{6}^{3-}, Fe(CN)63-\n 211.955\n\n\n\n```python\nfrom chempy import balance_stoichiometry # Main reaction in NASA's booster rockets:\nreac, prod = balance_stoichiometry({'NH4ClO4', 'Al'}, {'Al2O3', 'HCl', 'H2O', 'N2'})\nfrom pprint import pprint\npprint(dict(reac))\npprint(dict(prod))\nfrom chempy import mass_fractions\nfor fractions in map(mass_fractions, [reac, prod]):\n pprint({k: '{0:.3g} wt%'.format(v*100) for k, v in fractions.items()})\n```\n\n {'Al': 10, 'NH4ClO4': 6}\n {'Al2O3': 5, 'H2O': 9, 'HCl': 6, 'N2': 3}\n {'Al': '27.7 wt%', 'NH4ClO4': '72.3 wt%'}\n {'Al2O3': '52.3 wt%', 'H2O': '16.6 wt%', 'HCl': '22.4 wt%', 'N2': '8.62 wt%'}\n\n\n\n```python\nsubstances = {s.name: s for s in [\n Substance('pancake', composition=dict(eggs=1, spoons_of_flour=2, cups_of_milk=1)),\n Substance('eggs_6pack', composition=dict(eggs=6)),\n Substance('milk_carton', composition=dict(cups_of_milk=4)),\n Substance('flour_bag', composition=dict(spoons_of_flour=60))\n]}\npprint([dict(_) for _ in balance_stoichiometry({'eggs_6pack', 'milk_carton', 'flour_bag'},\n {'pancake'}, substances=substances)])\n```\n\n [{'eggs_6pack': 10, 'flour_bag': 2, 'milk_carton': 15}, {'pancake': 60}]\n\n\n\n```python\npprint([dict(_) for _ in balance_stoichiometry({'C', 'O2'}, {'CO2', 'CO'})]) # doctest: +SKIP\n```\n\n [{'C': x1 + 1, 'O2': x1 + 1/2}, {'CO': 1, 'CO2': x1}]\n\n\n\n```python\npprint([dict(_) for _ in balance_stoichiometry({'C', 'O2'}, {'CO2', 'CO'}, underdetermined=None)])\n```\n\n [{'C': 3, 'O2': 2}, {'CO': 2, 'CO2': 1}]\n\n\n\n```python\nfrom chempy import Equilibrium\nfrom sympy import symbols\nK1, K2, Kw = symbols('K1 K2 Kw')\ne1 = Equilibrium({'MnO4-': 1, 'H+': 8, 'e-': 5}, {'Mn+2': 1, 'H2O': 4}, K1)\ne2 = Equilibrium({'O2': 1, 'H2O': 2, 'e-': 4}, {'OH-': 4}, K2)\ncoeff = Equilibrium.eliminate([e1, e2], 'e-')\nprint(coeff)\nredox = e1*coeff[0] + e2*coeff[1]\nprint(redox)\nautoprot = Equilibrium({'H2O': 1}, {'H+': 1, 'OH-': 1}, Kw)\nn = redox.cancel(autoprot)\nprint(n)\nredox2 = redox + n*autoprot\nprint(redox2)\n```\n\n [4, -5]\n 32 H+ + 4 MnO4- + 20 OH- = 26 H2O + 4 Mn+2 + 5 O2; K1**4/K2**5\n 20\n 12 H+ + 4 MnO4- = 6 H2O + 4 Mn+2 + 5 O2; K1**4*Kw**20/K2**5\n\n\n\n```python\nfrom collections import defaultdict\n>>> from chempy.equilibria import EqSystem\n>>> eqsys = EqSystem.from_string(\"\"\"HCO3- = H+ + CO3-2; 10**-10.3\n... H2CO3 = H+ + HCO3-; 10**-6.3\n... H2O = H+ + OH-; 10**-14/55.4\n... \"\"\") # pKa1(H2CO3) = 6.3 (implicitly incl. CO2(aq)), pKa2=10.3 & pKw=14\n>>> arr, info, sane = eqsys.root(defaultdict(float, {'H2O': 55.4, 'HCO3-': 1e-2}))\n>>> conc = dict(zip(eqsys.substances, arr))\n>>> from math import log10\n>>> print(\"pH: %.2f\" % -log10(conc['H+']))\n```\n\n pH: 8.30\n\n\n\n```python\n>>> from chempy import Equilibrium\n>>> from chempy.chemistry import Species\n>>> water_autop = Equilibrium({'H2O'}, {'H+', 'OH-'}, 10**-14) # unit \"molar\" assumed\n>>> ammonia_prot = Equilibrium({'NH4+'}, {'NH3', 'H+'}, 10**-9.24) # same here\n>>> substances = [Species.from_formula(f) for f in 'H2O OH- H+ NH3 NH4+'.split()]\n>>> eqsys = EqSystem([water_autop, ammonia_prot], substances)\n>>> print('\\n'.join(map(str, eqsys.rxns))) # \"rxns\" short for \"reactions\"\n\n>>> init_conc = defaultdict(float, {'H2O': 1, 'NH3': 0.1})\n>>> x, sol, sane = eqsys.root(init_conc)\n>>> assert sol['success'] and sane\n>>> print(', '.join('%.2g' % v for v in x))\n```\n\n H2O = H+ + OH-; 1e-14\n NH4+ = H+ + NH3; 5.75e-10\n 1, 0.0013, 7.6e-12, 0.099, 0.0013\n\n\n\n```python\n>>> from chempy.electrolytes import ionic_strength\n>>> ionic_strength({'Fe+3': 0.050, 'ClO4-': 0.150}) == .3\n```\n\n\n\n\n True\n\n\n\n\n```python\n>>> from chempy.henry import Henry\n>>> kH_O2 = Henry(1.2e-3, 1800, ref='carpenter_1966')\n>>> print('%.1e' % kH_O2(298.15))\n```\n\n 1.2e-03\n\n\n\n```python\n>>> from chempy import ReactionSystem # The rate constants below are arbitrary\n>>> rsys = ReactionSystem.from_string(\"\"\"2 Fe+2 + H2O2 -> 2 Fe+3 + 2 OH-; 42\n... 2 Fe+3 + H2O2 -> 2 Fe+2 + O2 + 2 H+; 17\n... H+ + OH- -> H2O; 1e10\n... H2O -> H+ + OH-; 1e-4\"\"\") # \"[H2O]\" = 1.0 (actually 55.4 at RT)\n>>> from chempy.kinetics.ode import get_odesys\n>>> odesys, extra = get_odesys(rsys)\n>>> from collections import defaultdict\n>>> import numpy as np\n>>> tout = sorted(np.concatenate((np.linspace(0, 23), np.logspace(-8, 1))))\n>>> c0 = defaultdict(float, {'Fe+2': 0.05, 'H2O2': 0.1, 'H2O': 1.0, 'H+': 1e-2, 'OH-': 1e-12})\n>>> result = odesys.integrate(tout, c0, atol=1e-12, rtol=1e-14)\n>>> import matplotlib.pyplot as plt\n>>> fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n>>> for ax in axes:\n... _ = result.plot(names=[k for k in rsys.substances if k != 'H2O'], ax=ax)\n... _ = ax.legend(loc='best', prop={'size': 9})\n... _ = ax.set_xlabel('Time')\n... _ = ax.set_ylabel('Concentration')\n>>> _ = axes[1].set_ylim([1e-13, 1e-1])\n>>> _ = axes[1].set_xscale('log')\n>>> _ = axes[1].set_yscale('log')\n>>> _ = fig.tight_layout()\n>>> _ = fig.savefig('kinetics.png', dpi=500)\n```\n\n\n```python\n>>> from chempy import Substance\n>>> from chempy.properties.water_density_tanaka_2001 import water_density as rho\n>>> from chempy.units import to_unitless, default_units as u\n>>> water = Substance.from_formula('H2O')\n>>> for T_C in (15, 25, 35):\n... concentration_H2O = rho(T=(273.15 + T_C)*u.kelvin, units=u)/water.molar_mass(units=u)\n... print('[H2O] = %.2f M (at %d °C)' % (to_unitless(concentration_H2O, u.molar), T_C))\n...\n```\n\n [H2O] = 55.46 M (at 15 °C)\n [H2O] = 55.35 M (at 25 °C)\n [H2O] = 55.18 M (at 35 °C)\n\n\n\n```python\nimport pandas as pd\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plot\ntarget_url = (\"https://archive.ics.uci.edu/ml/machine-learning-\"\n\"databases/undocumented/connectionist-bench/sonar/sonar.all-data\")\n#read rocks versus mines data into pandas data frame\nrocksVMines = pd.read_csv(target_url,header=None, prefix=\"V\")\n#print head and tail of data frame\nprint(rocksVMines.head())\nprint(rocksVMines.tail())\n#print summary of data frame\nsummary = rocksVMines.describe()\nprint(summary)\n```\n\n V0 V1 V2 V3 V4 V5 V6 V7 V8 \\\n 0 0.0200 0.0371 0.0428 0.0207 0.0954 0.0986 0.1539 0.1601 0.3109 \n 1 0.0453 0.0523 0.0843 0.0689 0.1183 0.2583 0.2156 0.3481 0.3337 \n 2 0.0262 0.0582 0.1099 0.1083 0.0974 0.2280 0.2431 0.3771 0.5598 \n 3 0.0100 0.0171 0.0623 0.0205 0.0205 0.0368 0.1098 0.1276 0.0598 \n 4 0.0762 0.0666 0.0481 0.0394 0.0590 0.0649 0.1209 0.2467 0.3564 \n \n V9 ... V51 V52 V53 V54 V55 V56 V57 \\\n 0 0.2111 ... 0.0027 0.0065 0.0159 0.0072 0.0167 0.0180 0.0084 \n 1 0.2872 ... 0.0084 0.0089 0.0048 0.0094 0.0191 0.0140 0.0049 \n 2 0.6194 ... 0.0232 0.0166 0.0095 0.0180 0.0244 0.0316 0.0164 \n 3 0.1264 ... 0.0121 0.0036 0.0150 0.0085 0.0073 0.0050 0.0044 \n 4 0.4459 ... 0.0031 0.0054 0.0105 0.0110 0.0015 0.0072 0.0048 \n \n V58 V59 V60 \n 0 0.0090 0.0032 R \n 1 0.0052 0.0044 R \n 2 0.0095 0.0078 R \n 3 0.0040 0.0117 R \n 4 0.0107 0.0094 R \n \n [5 rows x 61 columns]\n V0 V1 V2 V3 V4 V5 V6 V7 V8 \\\n 203 0.0187 0.0346 0.0168 0.0177 0.0393 0.1630 0.2028 0.1694 0.2328 \n 204 0.0323 0.0101 0.0298 0.0564 0.0760 0.0958 0.0990 0.1018 0.1030 \n 205 0.0522 0.0437 0.0180 0.0292 0.0351 0.1171 0.1257 0.1178 0.1258 \n 206 0.0303 0.0353 0.0490 0.0608 0.0167 0.1354 0.1465 0.1123 0.1945 \n 207 0.0260 0.0363 0.0136 0.0272 0.0214 0.0338 0.0655 0.1400 0.1843 \n \n V9 ... V51 V52 V53 V54 V55 V56 V57 \\\n 203 0.2684 ... 0.0116 0.0098 0.0199 0.0033 0.0101 0.0065 0.0115 \n 204 0.2154 ... 0.0061 0.0093 0.0135 0.0063 0.0063 0.0034 0.0032 \n 205 0.2529 ... 0.0160 0.0029 0.0051 0.0062 0.0089 0.0140 0.0138 \n 206 0.2354 ... 0.0086 0.0046 0.0126 0.0036 0.0035 0.0034 0.0079 \n 207 0.2354 ... 0.0146 0.0129 0.0047 0.0039 0.0061 0.0040 0.0036 \n \n V58 V59 V60 \n 203 0.0193 0.0157 M \n 204 0.0062 0.0067 M \n 205 0.0077 0.0031 M \n 206 0.0036 0.0048 M \n 207 0.0061 0.0115 M \n \n [5 rows x 61 columns]\n V0 V1 V2 V3 V4 V5 \\\n count 208.000000 208.000000 208.000000 208.000000 208.000000 208.000000 \n mean 0.029164 0.038437 0.043832 0.053892 0.075202 0.104570 \n std 0.022991 0.032960 0.038428 0.046528 0.055552 0.059105 \n min 0.001500 0.000600 0.001500 0.005800 0.006700 0.010200 \n 25% 0.013350 0.016450 0.018950 0.024375 0.038050 0.067025 \n 50% 0.022800 0.030800 0.034300 0.044050 0.062500 0.092150 \n 75% 0.035550 0.047950 0.057950 0.064500 0.100275 0.134125 \n max 0.137100 0.233900 0.305900 0.426400 0.401000 0.382300 \n \n V6 V7 V8 V9 ... V50 \\\n count 208.000000 208.000000 208.000000 208.000000 ... 208.000000 \n mean 0.121747 0.134799 0.178003 0.208259 ... 0.016069 \n std 0.061788 0.085152 0.118387 0.134416 ... 0.012008 \n min 0.003300 0.005500 0.007500 0.011300 ... 0.000000 \n 25% 0.080900 0.080425 0.097025 0.111275 ... 0.008425 \n 50% 0.106950 0.112100 0.152250 0.182400 ... 0.013900 \n 75% 0.154000 0.169600 0.233425 0.268700 ... 0.020825 \n max 0.372900 0.459000 0.682800 0.710600 ... 0.100400 \n \n V51 V52 V53 V54 V55 V56 \\\n count 208.000000 208.000000 208.000000 208.000000 208.000000 208.000000 \n mean 0.013420 0.010709 0.010941 0.009290 0.008222 0.007820 \n std 0.009634 0.007060 0.007301 0.007088 0.005736 0.005785 \n min 0.000800 0.000500 0.001000 0.000600 0.000400 0.000300 \n 25% 0.007275 0.005075 0.005375 0.004150 0.004400 0.003700 \n 50% 0.011400 0.009550 0.009300 0.007500 0.006850 0.005950 \n 75% 0.016725 0.014900 0.014500 0.012100 0.010575 0.010425 \n max 0.070900 0.039000 0.035200 0.044700 0.039400 0.035500 \n \n V57 V58 V59 \n count 208.000000 208.000000 208.000000 \n mean 0.007949 0.007941 0.006507 \n std 0.006470 0.006181 0.005031 \n min 0.000300 0.000100 0.000600 \n 25% 0.003600 0.003675 0.003100 \n 50% 0.005800 0.006400 0.005300 \n 75% 0.010350 0.010325 0.008525 \n max 0.044000 0.036400 0.043900 \n \n [8 rows x 60 columns]\n\n\n\n```python\nimport requests\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-\"\n\"databases/undocumented/connectionist-bench/sonar/sonar.all-data\"\nr = requests.get(url)\nwith open('2.csv','wb') as f:\n f.write(r.content)\n f.close()\n```\n\n\n```python\nimport pandas as pd\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plot\ntarget_url = (\"https://archive.ics.uci.edu/ml/machine-learning-\"\n\"databases/undocumented/connectionist-bench/sonar/sonar.all-data\")\n#read rocks versus mines data into pandas data frame\nrocksVMines = pd.read_csv(target_url,header=None, prefix=\"V\")\nfor i in range(208):\n #assign color based on \"M\" or \"R\" labels\n if rocksVMines.iat[i,60] == \"M\":\n pcolor = \"red\"\n else:\n pcolor = \"blue\"\n #plot rows of data as if they were series data\n dataRow = rocksVMines.iloc[i,0:60]\n dataRow.plot(color=pcolor)\nplot.xlabel(\"Attribute Index\")\nplot.ylabel((\"Attribute Values\"))\nplot.show()\n```\n\n\n```python\nurl1 = 'https://haier.ceping.com/Login/Elink?elink=RopfZpaoU63RmcBFDcPl1iIJ4jIYxZou39p1886LYXPfE0rnyFCU/2lWmTWBv5Zidl8EGSLHQjU=&v=1'\nurl2 = 'https://haier.ceping.com/Login/Elink?elink=RopfZpaoU63RmcBFDcPl1iIJ4jIYxZou39p1886LYXPfE0rnyFCU/2lWmTWBv5Zidl8EGSLHQjU=&v=1'\n```\n\n\n```python\nurl1 == url2\n```\n\n\n\n\n True\n\n\n\n\n```python\n# 导入扩展库\nimport re # 正则表达式库\nimport collections # 词频统计库\nimport numpy as np # numpy数据处理库\nimport jieba # 结巴分词\nimport wordcloud # 词云展示库\nfrom PIL import Image # 图像处理库\nimport matplotlib.pyplot as plt # 图像展示库\n\n# 读取文件\nfn = open('1.txt',encoding='utf-8') # 打开文件\nstring_data = fn.read() # 读出整个文件\nfn.close() # 关闭文件\n\n# 文本预处理\npattern = re.compile(u'\\t|\\n|\\.|-|:|;|\\)|\\(|\\?|\"') # 定义正则表达式匹配模式\nstring_data = re.sub(pattern, '', string_data) # 将符合模式的字符去除\n\n# 文本分词\nseg_list_exact = jieba.cut(string_data, cut_all = False) # 精确模式分词\nobject_list = []\nremove_words = [u'的', u',',u'和', u'是', u'随着', u'对于', u'对',u'等',u'能',u'都',u'。',u' ',u'、',u'中',u'在',u'了',\n u'通常',u'如果',u'我们',u'需要'] # 自定义去除词库\n\nfor word in seg_list_exact: # 循环读出每个分词\n if word not in remove_words: # 如果不在去除词库中\n object_list.append(word) # 分词追加到列表\n\n# 词频统计\nword_counts = collections.Counter(object_list) # 对分词做词频统计\nword_counts_top10 = word_counts.most_common(10) # 获取前10最高频的词\nprint (word_counts_top10) # 输出检查\nbackgroud_Image = plt.imread('2.jpg')\n\n\n# 词频展示\nmask = np.array(Image.open('2.jpg')) # 定义词频背景\nwc = wordcloud.WordCloud(\n font_path='C:/Windows/Fonts/simhei.ttf', # 设置字体格式\n background_color='white',# 设置背景颜色\n mask=backgroud_Image,# 设置背景图片\n max_words=1000, # 最多显示词数\n max_font_size=100, # 字体最大值\n width = 10000,\n height = 10000\n)\n\nwc.generate_from_frequencies(word_counts) # 从字典生成词云\nimage_colors = wordcloud.ImageColorGenerator(mask) # 从背景图建立颜色方案\nwc.recolor(color_func=image_colors) # 将词云颜色设置为背景图方案\nplt.imshow(wc) # 显示词云\nplt.axis('off') # 关闭坐标轴\nplt.show() # 显示图像\n```\n\n\n```python\nimport pickle\nfrom os import path\nimport jieba\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\ntext = ''\nwith open('1.txt', 'r', encoding='utf-8') as fin:\n for line in fin.readlines():\n line = line.strip('\\n')\n # sep’.join(seq)以sep作为分隔符,将seq所有的元素合并成一个新的字符串\n text += ' '.join(jieba.cut(line))\nbackgroud_Image = plt.imread('2.jpg')\nprint('加载图片成功!')\n'''设置词云样式'''\nwc = WordCloud(\n background_color='white',# 设置背景颜色\n mask=backgroud_Image,# 设置背景图片\n font_path='C:\\Windows\\Fonts\\STZHONGS.TTF', # 若是有中文的话,这句代码必须添加,不然会出现方框,不出现汉字\n max_words=2000, # 设置最大现实的字数\n stopwords=STOPWORDS,# 设置停用词\n max_font_size=75,# 设置字体最大值\n random_state=30,# 设置有多少种随机生成状态,即有多少种配色方案\n width = 10000,\n height = 10000\n)\nwc.generate_from_text(text)\nprint('开始加载文本')\n#改变字体颜色\nimg_colors = ImageColorGenerator(backgroud_Image)\n#字体颜色为背景图片的颜色\nwc.recolor(color_func=img_colors)\n# 显示词云图\nplt.imshow(wc)\n# 是否显示x轴、y轴下标\nplt.axis('off')\nplt.show()\n# 获得模块所在的路径的\nprint('生成词云成功!')\n```\n\n Building prefix dict from the default dictionary ...\n Dumping model to file cache C:\\Users\\NickC\\AppData\\Local\\Temp\\jieba.cache\n Loading model cost 0.898 seconds.\n Prefix dict has been built successfully.\n\n\n 加载图片成功!\n 开始加载文本\n\n\n\n
    \n\n\n 生成词云成功!\n\n\n# Comparisons, Equality and Truth\n\n\n```python\nL1 = [1,('a',3)] # Same value, unique objects\nL2 = [1,('a',3)]\nL1 == L2, L1 is L2 # Equivalent? Same object ?\n```\n\n\n\n\n (True, False)\n\n\n\n\n```python\nL = ['grail']\nL.append(L)\nprint(L)\n```\n\n ['grail', [...]]\n\n\n#### The == operator tests value equivalence. Python performs an equivalence test, comparing all nested objects recursively.\n\n#### The is operator tests object identity. Python tests whether the two are really the same object (i.e., live at the same address in memory).\n\n\n\n```python\nS1 = 'spam'\nS2 = 'spam'\n```\n\n\n```python\nS1 == S2, S1 is S2\n```\n\n\n\n\n (True, True)\n\n\n\nHere, we should again have two distinct objects that happen to have the same value:\n== should be true, and is should be false. But because Python internally caches and\nreuses some strings as an optimization, there really is just a single string 'spam' in\nmemory, shared by S1 and S2; hence, the is identity test reports a true result. To trigger\nthe normal behavior, we need to use longer strings:\n\n\n```python\nS1 = 'a longer string'\nS2 = 'a longer string'\nS1 == S2, S1 is S2\n```\n\n\n\n\n (True, False)\n\n\n\n\n```python\nL1 = [1, ('a', 3)]\nL2 = [1,('a', 2)]\nL1 < L2, L1 == L2, L1 > L2\n```\n\n\n\n\n (False, False, True)\n\n\n\nIn general, Python compares types as follows:\n\n• Numbers are compared by relative magnitude.\n\n• Strings are compared lexicographically, character by character (\"abc\" < \"ac\").\n\n• Lists and tuples are compared by comparing each component from left to right.\n\n• Dictionaries compare as equal if their sorted (key, value) lists are equal. Relative magnitude comparisons are not supported for dictionaries in Python 3.0, but they work in 2.6 and earlier as though comparing sorted (key, value) lists.\n\n• Nonnumeric mixed-type comparisons (e.g., 1 < 'spam') are errors in Python 3.0.\n\nThey are allowed in Python 2.6, but use a fixed but arbitrary ordering rule. By proxy, this also applies to sorts, which use comparisons internally: nonnumeric mixed-type collections cannot be sorted in 3.0.\n\n# Python 3.0 Dictionary Comparisons\n\n\n```python\nD1 = {'a': 1, 'b': 2}\nD2 = {'a': 1, 'b': 3}\nprint(D1 == D2)\n# print( D1 < D2 )\n```\n\n False\n\n\n\n```python\n# D1 < D2 # In Python 3.0, magnitude comparisons for dictionaries are removed because they incur too much overhead when equality is desired (equality uses an optimized scheme in 3.0 that doesn’t literally compare sorted key/value lists). The alternative in 3.0 is to either write loops to compare values by key or compare the sorted key/value lists manually— the items dictionary methods and sorted built-in suffice\n# '<' not supported between instances of 'dict' and 'dict'\n```\n\n\n```python\nlist(D1.items())\nsorted(D1.items())\nprint(sorted(D1.items()) < sorted(D2.items()))\nprint(sorted(D1.items()) < sorted(D2.items()))\n```\n\n True\n True\n\n\n# The None object\n\n\n```python\nL = [None]*100\n```\n\n\n```python\nprint(L,end='')\n```\n\n [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]\n\nKeep in mind that None does not mean “undefined.” That is, None is something, not\nnothing (despite its name!)—it is a real object and piece of memory, given a built-in\nname by Python. Watch for other uses of this special object later in the book; it is also\nthe default return value of functions, as we’ll see in Part IV\n\n# The bool type\n\n\n```python\nbool(1)\nbool('spam')\nbool({})\n```\n\n\n\n\n False\n\n\n\nPython also provides a bool builtin function that can be used to test the Boolean value of an object (i.e., whether it is\nTrue—that is, nonzero or nonempty)\n\n# Type Objects\n\n\n```python\ntype([1]) == type([]) # Type of another list\n```\n\n\n\n\n True\n\n\n\n\n```python\ntype([1]) == list # list type name\n```\n\n\n\n\n True\n\n\n\n\n```python\nisinstance([1],list) # List or customization thereof\n```\n\n\n\n\n True\n\n\n\n\n```python\nimport types\ndef f(): pass\ntype(f) == types.FunctionType\n```\n\n\n\n\n True\n\n\n\n# Other Types in Python\n\n\n```python\nL = [1,2,3]\nM = ['X',L,'Y']\nM\nL[1] = 0 # Changes M too\nM\n```\n\n\n\n\n ['X', [1, 0, 3], 'Y']\n\n\n\n\n```python\nL = [1,2,3]\nM = ['X',L[:],'Y'] # Embed a copy of L\nL[1] = 0 # Changes only L, not M\nprint(L)\nprint(M)\n```\n\n [1, 0, 3]\n ['X', [1, 2, 3], 'Y']\n\n\n# Repetition Adds One Level Deep\n\n\n```python\nL = [4,5,6]\nX = L * 4 # Like [4,5,6] + [4,5,6] + ...\n```\n\n\n```python\nY = [L] * 4\n```\n\n\n```python\n(X,Y)\n```\n\n\n\n\n ([4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6],\n [[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]])\n\n\n\n\n```python\nL[1] = 0 # Impacts Y but not X\nprint(X, Y)\n```\n\n [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6] [[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]\n\n\n# Beware of Cyclic Data Structures\n\n\n```python\nL = ['grail'] # Append references to same object\nL.append(L) # Generates cycle in object: [...]\nprint(L)\n```\n\n ['grail', [...]]\n\n\n# Immutable Types Can’t Be Changed In-Place\n\n\n```python\nT = (1,2,3)\n# T[2] = 4 # Error!\nT = T[:2] + (4,) # Ok: (1,2,4)\n```\n\n\n```python\nT\n```\n\n\n\n\n (1, 2, 4)\n\n\n\n# Chapter Summary\n\nThis chapter explored the last two major core object types—the tuple and the file. We\nlearned that tuples support all the usual sequence operations, have just a few methods,\nand do not allow any in-place changes because they are immutable. We also learned\nthat files are returned by the built-in open function and provide methods for reading\nand writing data. We explored how to translate Python objects to and from strings for\nstoring in files, and we looked at the pickle and struct modules for advanced roles\n(object serialization and binary data). Finally, we wrapped up by reviewing some properties common to all object types (e.g., shared references) and went through a list of\ncommon mistakes (“gotchas”) in the object type domain.\nIn the next part, we’ll shift gears, turning to the topic of statement syntax in Python—\nwe’ll explore all of Python’s basic procedural statements in the chapters that follow.\nThe next chapter kicks off that part of the book with an introduction to Python’s general\nsyntax model, which is applicable to all statement types. Before moving on, though,\ntake the chapter quiz, and then work through the end-of-part lab exercises to review\ntype concepts. Statements largely just create and process objects, so make sure you’ve\nmastered this domain by working through all the exercises before reading on.\n\n# Test Your Knowledge: Quiz\n\n\n```python\nT = (4,5,6)\n```\n\n\n```python\nlen(T)\n```\n\n\n\n\n 3\n\n\n\n\n```python\nL = list(T)\n```\n\n\n```python\nL[0]=1\n```\n\n\n```python\nT = tuple()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "3e50e1902e2d39e59fae2640cd72482847846694", "size": 293482, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ch9 Additional information.ipynb", "max_stars_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_stars_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-08T07:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-08T07:56:09.000Z", "max_issues_repo_path": "Ch9 Additional information.ipynb", "max_issues_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_issues_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "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": "Ch9 Additional information.ipynb", "max_forks_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_forks_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "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": 157.5319377348, "max_line_length": 94364, "alphanum_fraction": 0.8864564096, "converted": true, "num_tokens": 10448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.13117323225300487, "lm_q1q2_score": 0.06302594122819487}} {"text": "
    \n# [cknowledge.org](http://cknowledge.org): Community-driven benchmarking and optimization of computing systems - from classical to quantum\n
    \n\n[Quantum Computing](https://github.com/ctuning/ck-quantum/wiki)\n* [CK-QISKit](https://github.com/ctuning/ck-qiskit) (IBM)\n* [CK-Rigetti](https://github.com/ctuning/ck-rigetti) ([Rigetti Computing](https://rigetti.com/))\n* [CK-ProjectQ](https://github.com/ctuning/ck-projectq) ([ProjectQ](https://projectq.ch/))\n\n[Artificial Intelligence and Machine Learning](http://cknowledge.org/ai)\n* [Reproducible Quality-Efficient Systems Tournaments](http://cknowledge.org/request) ([ReQuEST initiative](http://cknowledge.org/request.html#organizers))\n* [AI artifacts](http://cknowledge.org/ai-artifacts) (cTuning foundation)\n* [Android app](https://play.google.com/store/apps/details?id=openscience.crowdsource.video.experiments) (dividiti)\n* [Desktop app](https://github.com/dividiti/ck-crowdsource-dnn-optimization) (dividiti)\n* [CK-Caffe](https://github.com/dividiti/ck-caffe) (Berkeley)\n* [CK-Caffe2](https://github.com/ctuning/ck-caffe2) (Facebook)\n* [CK-CNTK](https://github.com/ctuning/ck-cntk) (Microsoft)\n* [CK-KaNN](https://github.com/ctuning/ck-kann) (Kalray)\n* [CK-MVNC](https://github.com/ctuning/ck-mvnc) (Movidius / Intel)\n* [CK-MXNet](https://github.com/ctuning/ck-mxnet) (Apache)\n* [CK-NNTest](https://github.com/ctuning/ck-nntest) (cTuning foundation)\n* [CK-TensorFlow](https://github.com/ctuning/ck-tensorflow) (Google)\n* [CK-TensorRT](https://github.com/ctuning/ck-tensorrt) (NVIDIA)\n* etc.\n\n
    \n# Variational Quantum Eigensolver (VQE) on Rigetti machines\n[Quantum Collective Knowledge Hackaton](https://www.eventbrite.co.uk/e/quantum-computing-hackathon-tickets-46441126660#), [Centre for Mathematical Science - University of Cambridge](http://www.cms.cam.ac.uk/), 15 June 2018\n\n## Table of Contents\n\n1. [Organisers](#organisers)\n1. [References](#references)\n1. [Time-to-solution metric](#metric)\n1. [Setting up](#settingup)\n1. [Running experiments](#running)\n1. [Experimental data](#data)\n1. [Data wrangling code](#code) (for developers)\n1. [Analysis](#analysis)\n\n\n## Organisers\n\n- [Rigetti Computing](https://rigetti.com): access to [Quantum Virtual Machine](http://pyquil.readthedocs.io/en/latest/qvm.html) (QVM) and [Quantum Processing Unit](http://pyquil.readthedocs.io/en/latest/qpu.html) (QPU).\n- [River Lane Research](https://riverlane.io/): Steve Brierley, Oscar Higgott, Daochen Wang, Amy Flower\n- [dividiti](http://dividiti.com/): Anton Lokhmotov, Leo Gordon, Flavio Vella, Grigori Fursin\n\n\n## References\n\n- [Rigetti's docs](http://grove-docs.readthedocs.io/en/latest/vqe.html)\n- [\"A variational eigenvalue solver on a quantum processor\"](https://arxiv.org/abs/1304.3061) (2013)\n- [\"The theory of variational hybrid quantum-classical algorithms\"](https://arxiv.org/abs/1509.04279) (2015)\n- [\"Quantum optimization using variational algorithms\non near-term quantum devices\"](https://arxiv.org/abs/1710.01022) [2017]\n\n\n## Time-to-solution metric\n\nTo compare solutions of participants we use a **time-to-solution** $T$ metric defined as follows.\n\n### Definition\n\nLet's assume that to find the ground state of a given molecule (e.g. [Helium](https://en.wikipedia.org/wiki/Helium)) a participant makes $N$ runs of their implementation (e.g. $N=3$). A run is considered _successful_ if the ground state found in this run is equal to the ground state known for the molecule to given precision $\\delta$ (e.g. $\\delta=0.1$). Assume that a single run takes $t$ samples (calls to the quantum computer) on average.\n\nLet $s$ be the probability of success of the participant's VQE implementation (i.e. the number of successful runs divided by the total number of runs $N$).\n\nLet $R$ be the number of runs required to find the ground state with given probability $p$ (e.g. $p=0.6$):\n\\begin{equation}\nR = {\\frac{\\log(1-p)}{\\log(1-s)}}.\n\\end{equation}\n\nThe **time-to-solution** $T$, defined as the total number of samples used throughout the whole optimisation procedure of VQE, is then calculated as:\n\\begin{equation}\nT = R \\times t.\n\\end{equation}\n\n### Derivation\n\nIf the probability of success is $s$, then the probability of _failing to find_ the ground state after $R$ runs is $(1-s)^R$. Therefore, the probability of finding the ground state at least once after $R$ runs is $p =1 - (1-s)^R$. Therefore, the number of runs $R$ required to find the ground state at least once with probability $p$ can be found by solving $p=1-(1-s)^R$.\n\n### Uncertainties\n\nWe can also calculate the standard error associated with the calculated time-to-solution $T$. \n\nFrom the [binomial distribution](Binomial_distribution), the uncertainty $\\sigma_s$ in the success probability $s$ is:\n\\begin{equation}\n \\sigma_s=\\sqrt{\\frac{s(1-s)}{N}}\n\\end{equation}\nwhere $N$ is the number of runs used to determine $s$.\n\nThe uncertainty in the time taken per run $t$ is:\n\\begin{equation}\n \\sigma_t=\\frac{\\mathrm{std}}{\\sqrt{N}}\n\\end{equation}\nwhere $\\mathrm{std}$ is the standard deviation of the times taken by all $N$ runs.\n\nThe uncertainty in total time taken is:\n\\begin{equation}\n\\sigma_T=\\sqrt{0.25 \\cdot (T(t+\\sigma_t, s) - T(t-\\sigma_t,s))^2 + (T(t, s + \\sigma_s) - T(t,s))^2}\n\\end{equation}\n\n\n## Setting up\n\nPlease follow instructions [here](https://github.com/ctuning/ck-quantum/blob/master/README.md).\n\n\n## Running experiments\n\n```\n$ ck benchmark program:rigetti-vqe \\\n --env.RIGETTI_QUANTUM_DEVICE= \\\n --env.VQE_MINIMIZER_METHOD= \\\n --env.VQE_SAMPLE_SIZE= \\\n --env.VQE_MAX_ITERATIONS= \\\n --record --record_repo=local --record_uoa=- \\\n --tags=qck,hackathon-2018_06_15,,, \\\n --repetitions=\n```\nwhere:\n- `platform`: `8Q-Agave` or `QVM`;\n- `minimizer_method`: `my_melder_nead` or `my_cobyla` or `my_minimizer` (as defined in [optimizers.py](https://github.com/ctuning/ck-quantum/blob/master/package/tool-hackathon/hackathon-src/hackathon/optimizers.py) installed under e.g. `$CK_TOOLS/hackathon-1.0-linux-64/lib/hackathon`);\n- `sample_size`: e.g. `100` (or another resolution);\n- `max_iterations`: e.g. `80` (or another cut-off point);\n- `email`: a valid email address (later to be replaced with a team id e.g. `team-01`);\n- `repetitions`: how many times to run the experiment with the given parameters: e.g. `3`.\n\n\n## Get sample experimental data\n\nThe sample experimental data can be downloaded and registered with CK as follows:\n\n```\n$ wget https://www.dropbox.com/s/a1odux4asze9zpd/ck-quantum-hackathon-20180615.zip\n$ ck add repo --zip=ck-quantum-hackathon-20180615.zip\n```\n\n\n```python\nrepo_uoa = 'ck-quantum-hackathon-20180615'\n!ck list $repo_uoa:experiment:* --print_full | sort\n```\n\n\n## Data wrangling code\n\n**NB:** Please ignore this section if you are not interested in re-running or modifying this notebook.\n\n### Includes\n\n#### Standard\n\n\n```python\nimport os\nimport sys\nimport json\nimport re\n```\n\n#### Scientific\n\nIf some of the scientific packages are missing, please install them using:\n```\n# pip install jupyter pandas numpy matplotlib\n```\n\n\n```python\nimport IPython as ip\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mp\n```\n\n\n```python\nprint ('IPython version: %s' % ip.__version__)\nprint ('Pandas version: %s' % pd.__version__)\nprint ('NumPy version: %s' % np.__version__)\nprint ('Matplotlib version: %s' % mp.__version__)\n```\n\n\n```python\nfrom IPython.display import Image, display\ndef display_in_full(df):\n pd.options.display.max_columns = len(df.columns)\n pd.options.display.max_rows = len(df.index)\n display(df)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n%matplotlib inline\n```\n\n\n```python\ndefault_colormap = cm.autumn\ndefault_fontsize = 16\ndefault_barwidth = 0.8\ndefault_figwidth = 16\ndefault_figheight = 8\ndefault_figdpi = 200\ndefault_figsize = [default_figwidth, default_figheight]\n```\n\n\n```python\nif mp.__version__[0]=='2': mp.style.use('classic')\nmp.rcParams['figure.max_open_warning'] = 200\nmp.rcParams['figure.dpi'] = default_figdpi\nmp.rcParams['font.size'] = default_fontsize\nmp.rcParams['legend.fontsize'] = 'medium'\n```\n\n#### Collective Knowledge\n\nIf CK is not installed, please install it using:\n```\n# pip install ck\n```\n\n\n```python\nimport ck.kernel as ck\nprint ('CK version: %s' % ck.__version__)\n```\n\n\n```python\n# NB: Make sure the quantum hackathon tool is installed. (It should be if you have run any experiments.)\n# $ ck install package --tags=ck-quantum,tool,hackathon,v1\nr=ck.access({'action':'show', 'module_uoa':'env', 'tags':'tool,hackathon'})\nif r['return']>0:\n print (\"Error: %s\" % r['error'])\n exit(1)\n \n# Get the path to the first returned environment entry.\ntool_hackathon_dir=r['lst'][0]['meta']['env']['CK_ENV_LIB_HACKATHON_LIB']\nsys.path.append(tool_hackathon_dir)\nfrom hackathon.utils import *\n```\n\n### Access experimental data\n\n\n```python\ndef get_experimental_results(repo_uoa, tags='qck', module_uoa='experiment'):\n r = ck.access({'action':'search', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'tags':tags})\n if r['return']>0:\n print('Error: %s' % r['error'])\n exit(1)\n experiments = r['lst']\n \n dfs = []\n for experiment in experiments:\n data_uoa = experiment['data_uoa']\n r = ck.access({'action':'list_points', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'data_uoa':data_uoa})\n if r['return']>0:\n print('Error: %s' % r['error'])\n exit(1)\n tags = r['dict']['tags']\n\n skip = False\n # Get team name (final data) or email (submission data).\n team_tags = [ tag for tag in tags if tag.startswith('team-') ]\n email_tags = [ tag for tag in tags if tag.find('@')!=-1 ]\n if len(team_tags) > 0:\n team = team_tags[0][0:7]\n elif len(email_tags) > 0:\n team = email_tags[0]\n else:\n print('[Warning] Cannot determine team name for experiment in: \\'%s\\'' % r['path'])\n team = 'team-default'\n\n if skip:\n print('[Warning] Skipping experiment with bad tags:')\n print(tags)\n continue\n \n # For each point. \n for point in r['points']:\n point_file_path = os.path.join(r['path'], 'ckp-%s.0001.json' % point)\n with open(point_file_path) as point_file:\n point_data_raw = json.load(point_file)\n characteristics_list = point_data_raw['characteristics_list']\n num_repetitions = len(characteristics_list)\n data = [\n {\n # features\n 'platform': characteristics['run'].get('vqe_input', {}).get('q_device_name', 'unknown').lower(),\n # choices\n 'minimizer_method': characteristics['run'].get('vqe_input', {}).get('minimizer_method', 'n/a'),\n 'minimizer_options': characteristics['run'].get('vqe_input', {}).get('minimizer_options', {'maxfev':-1}),\n 'minimizer_src': characteristics['run'].get('vqe_input', {}).get('minimizer_src', ''),\n 'sample_number': characteristics['run'].get('vqe_input', {}).get('sample_number','n/a'),\n # statistical repetition\n 'repetition_id': repetition_id,\n # runtime characteristics\n 'run': characteristics['run'],\n 'report': characteristics['run'].get('report', {}),\n 'vqe_output': characteristics['run'].get('vqe_output', {}),\n }\n for (repetition_id, characteristics) in zip(range(num_repetitions), characteristics_list)\n if len(characteristics['run']) > 0\n ]\n \n for datum in data:\n datum['team'] = team\n datum['point'] = point\n datum['success'] = datum.get('vqe_output',{}).get('success',False)\n datum['nfev'] = np.int64(datum.get('vqe_output',{}).get('nfev',-1))\n datum['nit'] = np.int64(datum.get('vqe_output',{}).get('nit',-1))\n datum['fun'] = np.float64(datum.get('vqe_output',{}).get('fun',0))\n datum['fun_validated'] = np.float64(datum.get('vqe_output',{}).get('fun_validated',0))\n datum['fun_exact'] = np.float64(datum.get('vqe_output',{}).get('fun_exact',0))\n datum['total_seconds'] = np.float64(datum.get('report',{}).get('total_seconds',0))\n datum['total_q_seconds'] = np.float64(datum.get('report',{}).get('total_q_seconds',0))\n datum['total_q_shots'] = np.int64(datum.get('report',{}).get('total_q_shots',0))\n tmp_max_iterations = list(datum.get('minimizer_options',{'maxfev':-1}).values())\n datum['max_iterations'] = tmp_max_iterations[0] if len(tmp_max_iterations)>0 else -1\n index = [\n 'platform', 'team', 'minimizer_method', 'sample_number', 'max_iterations', 'point', 'repetition_id'\n ]\n # Construct a DataFrame.\n df = pd.DataFrame(data)\n df = df.set_index(index)\n # Append to the list of similarly constructed DataFrames.\n dfs.append(df)\n if dfs:\n # Concatenate all thus constructed DataFrames (i.e. stack on top of each other).\n result = pd.concat(dfs)\n result.sort_index(ascending=True, inplace=True)\n else:\n # Construct a dummy DataFrame the success status of which can be safely checked.\n result = pd.DataFrame(columns=['success'])\n return result\n```\n\n\n```python\n# Merge experimental results from the same team with the same parameters\n# (minimizer_method, sample_number, max_iterations) and minimizer source.\ndef merge_experimental_results(df):\n dfs = []\n df_prev = None\n for index, row in df.iterrows():\n # Construct a DataFrame.\n df_curr = pd.DataFrame(row).T\n # Check if this row is similar to the previous row.\n if df_prev is not None: # if not the very first row\n if df_prev.index.levels[:-2]==df_curr.index.levels[:-2]: # if the indices match for all but the last two levels\n if df_prev.index.levels[-2]!=df_curr.index.levels[-2]: # if the experiments are different\n if df_prev['minimizer_src'].values==df_curr['minimizer_src'].values: # if the minimizer source is the same\n print('[Info] Merging experiment:')\n print(df_curr.index.levels)\n print('[Info] into:')\n print(df_prev.index.levels)\n print('[Info] as:')\n # df_curr.index = df_prev.index.copy() # TODO: increment repetition_id\n df_curr.index = pd.MultiIndex.from_tuples([(x[0],x[1],x[2],x[3],x[4],x[5],x[6]+1) for x in df_prev.index])\n print(df_curr.index.levels)\n print\n else:\n print('[Warning] Cannot merge experiments as the minimizer source is different:')\n # print('------------------------------------------------------------------------')\n print(df_prev.index.levels)\n # print(df_prev['minimizer_src'].values[0])\n # print\n # print('------------------------------------------------------------------------')\n print(df_curr.index.levels)\n # print(df_curr['minimizer_src'].values[0])\n print\n # else:\n # print('[Info] Keeping experiments separate:')\n # print(df_prev.index.levels)\n # print(df_curr.index.levels)\n # print\n # Append to the list of similarly constructed DataFrames.\n dfs.append(df_curr)\n # Prepare for next iteration.\n df_prev = df_curr\n\n # Concatenate all thus constructed DataFrames (i.e. stack on top of each other).\n result = pd.concat(dfs)\n result.index.names = df.index.names\n result.sort_index(ascending=True, inplace=True)\n \n return result\n```\n\n\n```python\ndef get_metrics(df, delta=0.1, prob=0.5, which_fun_key='fun_exact', which_time_key='total_q_shots'):\n dfs = []\n names_no_repetitions = df.index.names[:-1]\n for index, group in df.groupby(level=names_no_repetitions):\n # Compute metrics.\n classical_energy, minimizer_method, minimizer_src, n_succ, T_ave, T_err, t_ave, t_err, s, s_err = \\\n benchmark_list_of_runs(group['run'], verbose=False, delta=delta, prob=prob,\n which_fun_key=which_fun_key, which_time_key=which_time_key)\n # Construct a DataFrame from the metrics.\n data = {\n # Time to solution.\n 'T_ave' : T_ave,\n 'T_err' : T_err,\n # Time metric (seconds or shots).\n 't_ave' : t_ave,\n 't_err' : t_err,\n # Tries metric.\n 's' : s,\n 's_err' : s_err\n }\n data.update({ k : v for (k, v) in zip(names_no_repetitions, index) })\n data['num_repetitions'] = len(group)\n # NB: index must be something.\n df_ = pd.DataFrame(data=data, index=[0])\n df_ = df_.set_index(names_no_repetitions)\n # Append to the list of similarly constructed DataFrames.\n dfs.append(df_)\n if dfs:\n # Concatenate all thus constructed DataFrames (i.e. stack on top of each other).\n result = pd.concat(dfs).dropna()\n result.sort_index(ascending=True, inplace=True)\n return result\n```\n\n### Plot experimental data\n\n\n```python\ndef plot(df, platform_set=None, minimizer_method_set=None, sample_number_set=None, max_iterations_set=None,\n markersize_divisor=20,\n xmin=0.0, xmax=85.01, xstep=5.00,\n ymin=-3.0, ymax=-0.49, ystep=0.25,\n figsize=(18,9), dpi=200, legend_loc='lower right'):\n \n platform_set = platform_set or df.index.get_level_values(level='platform').unique()\n minimizer_method_set = minimizer_method_set or df.index.get_level_values(level='minimizer_method').unique()\n sample_number_set = sample_number_set or df.index.get_level_values(level='sample_number').unique()\n max_iterations_set = max_iterations_set or df.index.get_level_values(level='max_iterations').unique()\n\n # Options.\n minimizer_method_to_color = {\n 'my_cobyla' : 'orange',\n 'my_nelder_mead' : 'green',\n 'my_minimizer' : 'blue'\n }\n platform_to_marker = {\n '8q-agave' : '8', # octagon\n 'qvm' : 's', # square\n 'local_qasm_simulator' : 'p' # pentagon\n }\n \n last_marker_size = 10\n last_marker_color = 'black'\n last_marker_success_true = '^'\n last_marker_success_false = 'v'\n\n fig = plt.figure(figsize=figsize, dpi=dpi)\n ax = fig.gca()\n for index, row in df.iterrows():\n (platform, team, minimizer_method, sample_number, max_iterations, point, repetition_id) = index\n if platform not in platform_set: continue\n if sample_number not in sample_number_set: continue\n if minimizer_method not in minimizer_method_set: continue\n # NB: This uses 'fun', not 'fun_exact' or 'fun_validated'.\n energies = [ iteration['energy'] for iteration in row['report']['iterations'] ]\n marker=platform_to_marker[platform]\n markersize=sample_number/markersize_divisor\n color=minimizer_method_to_color.get(minimizer_method, 'red')\n markerfacecolor=color\n linestyle='-'\n ax.plot(range(len(energies)), energies, marker=marker, color=color, linestyle=linestyle,\n markerfacecolor=markerfacecolor, markersize=markersize)\n # Mark last function evaluation.\n last_energy = energies[-1]\n last_fev = row['nfev']-1 if minimizer_method=='my_cobyla' or 'my_nelder_mead' else row['nfev']\n last_marker = last_marker_success_true if row['success'] else last_marker_success_false\n ax.plot(last_fev, last_energy, color=last_marker_color, marker=last_marker, markersize=last_marker_size)\n\n # Horizontal line for the known ground state.\n plt.axhline(y=-2.80778395754, color='red', linestyle='--')\n # Vertical lines for max_iterations.\n for max_iterations in max_iterations_set:\n plt.axvline(x=max_iterations, color='black')\n # Grid.\n plt.grid()\n # Title.\n title = 'Variational Quantum Eigensolver (VQE)'\n ax.set_title(title)\n # X axis.\n xlabel='Function evaluation'\n ax.set_xlabel(xlabel)\n ax.set_xlim(xmin, xmax)\n ax.set_xticks(np.arange(xmin, xmax, xstep))\n # Y axis.\n ylabel='Energy'\n ax.set_ylabel(ylabel)\n ax.set_ylim(ymin, ymax)\n ax.set_yticks(np.arange(ymin, ymax, ystep))\n # Legend. https://matplotlib.org/users/legend_guide.html\n handles = [\n mp.lines.Line2D([], [], label='platform=\"%s\",minimizer_method=\"%s\"' % (p,m), color=minimizer_method_to_color.get(m, 'red'),\n marker=platform_to_marker[p], markersize=last_marker_size)\n for p in sorted(platform_set)\n for m in sorted(minimizer_method_set)\n ]\n handles.append(mp.lines.Line2D([],[], label='ground state', color='red', linestyle='--'))\n plt.legend(handles=handles, title='platform,minimizer_method', loc=legend_loc)\n # Save figure.\n# plt.savefig('vqe.energy.png')\n```\n\n\n```python\ndef plot_metric(df, metric='total_q_seconds'):\n df.columns.name='metric'\n # \"df.index.names[:-1]\" means reduce along 'repetition_id' (statistical variation).\n df_mean = df[[metric]].groupby(level=df.index.names[:-1]).mean().unstack('platform')\n df_std = df[[metric]].groupby(level=df.index.names[:-1]).std().unstack('platform')\n ax = df_mean.plot(kind='bar', yerr=df_std, grid=True, legend=True, rot=45,\n fontsize=default_fontsize, figsize=default_figsize, colormap=default_colormap)\n```\n\n\n## Analysis\n\n### All experimental data\n\n\n```python\ndf = get_experimental_results(repo_uoa=repo_uoa)\ndisplay_in_full(df)\n```\n\n### Merge experimental results from different runs with the same parameters\n\n\n```python\ndf = merge_experimental_results(df)\ndisplay_in_full(df)\n```\n\n### Compute the time-to-solution metric etc.\n\n\n```python\ndf_metrics = get_metrics(df, delta=0.1, prob=0.5, which_fun_key='fun_exact', which_time_key='total_q_shots')\ndf_metrics\n```\n\n### The (unexpected) winner\n\nSomewhat unexpectedly, the winner obtained the exact answer (!) with `sample_number=1` (!!) on real hardware (!!!). Please see below an explanation why this was the case.\n\n\n```python\nidxmin1 = df_metrics['T_ave'].idxmin()\nidxmin1\n```\n\n\n```python\ndf_metrics.loc[[idxmin1]]\n```\n\n\n```python\ndf.loc[idxmin1]\n```\n\n\n```python\n# Platform, Team, minimizer Function, number of Samples, number of function eValuations, Experiment, Repetition\n(p,t,f,s,v,e) = idxmin1\n# Plot the winner.\nplot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[idxmin1]))]],\n xmax=7, xstep=1, ymin=-3.00, ymax=0.00+0.01, legend_loc='upper center')\n```\n\n\n```python\n# Exclude the winner.\ndf_metrics = df_metrics.drop(idxmin1)\n```\n\n#### Explanation\n\nThe [Hamiltonian](https://en.wikipedia.org/wiki/Hamiltonian_(quantum_mechanics)) of [Helium](https://en.wikipedia.org/wiki/Helium) in the [STO-3G](https://en.wikipedia.org/wiki/STO-nG_basis_sets) basis is given by:\n\n\\begin{equation}\n H = -1.6678202144537553 + 0.7019459893849936 \\cdot Z_0 + 0.7019459893849936 \\cdot Z_1 + 0.263928235683768058 \\cdot Z_0 \\cdot Z_1\n\\end{equation}\n\nSince the Hamiltonian consists of a sum of commuting operators ($Z_0$, $Z_1$, $Z_0\\cdot Z1$), there exists a simultaneous eigenbasis (including the ground state) on which the value of each of the operators is $+1$ or $-1$. \n\nWhen `sample_number=1`, measuring an operator once in any state also results in $+1$ or $-1$. This implies that one get \"lucky\" with _any_ mininizer method even on noisy hardware. (Indeed, we have been able to reproduce this result with `my_nelder_mead`.)\n\nFor more complex molecules, the Hamiltonian is unlikely to consist of a sum of commuting operators, hence picking up a good optimizer and its parameters will be crucial for success.\n\n### The (conditional) runner-up\n\nThe runner-up also used `sample_number=1` but only a single run (hence, it's a \"conditional\" runner-up, as we can determine the error only from multiple runs).\n\n\n```python\nidxmin2 = df_metrics['T_ave'].idxmin()\nidxmin2\n```\n\n\n```python\ndf_metrics.loc[[idxmin2]]\n```\n\n\n```python\ndf.loc[idxmin2]\n```\n\n\n```python\n# Platform, Team, minimizer Function, number of Samples, number of function eValuations, Experiment, Repetition\n(p,t,f,s,v,e) = idxmin2\n# Plot the winner.\nplot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[idxmin2]))]],\n xmax=7, xstep=1, ymin=-3.00, ymax=0.00+0.01, legend_loc='upper center')\n```\n\n\n```python\n# Print the minimizer source.\nprint(df.loc[(p,t,f,s,v,e,0)]['minimizer_src'])\n```\n\n\n```python\n# Exclude the conditional runner-up.\ndf_metrics = df_metrics.drop(idxmin2)\n```\n\n### The QVM runner-up\n\n\n```python\nplatform_qvm = 'qvm'\ndf_metrics_qvm = df_metrics.loc[platform_qvm]\nidxmin_qvm = df_metrics_qvm['T_ave'].idxmin()\nidxmin_qvm\n```\n\n\n```python\ndf_metrics.loc[platform_qvm].loc[[idxmin_qvm]]\n```\n\n\n```python\ndf.loc[platform_qvm].loc[idxmin_qvm]\n```\n\n\n```python\n# Platform, Team, minimizer Function, number of Samples, number of function eValuations, Experiment, Repetition\np = platform_qvm\n(t,f,s,v,e) = idxmin_qvm\n# Plot the runner up.\nplot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]],\n xmax=9, xstep=1, ymin=-3.00, ymax=0.00+0.01, legend_loc='upper right')\n```\n\n\n```python\n# Print the minimizer source.\nprint(df.loc[(p,t,f,s,v,e,0)]['minimizer_src'])\n```\n\n\n```python\n# Exclude the QVM runner-up.\ndf_metrics = df_metrics.drop((p,t,f,s,v,e))\n```\n\n### The QPU runner-up\n\n\n```python\nplatform_qpu = '8q-agave'\ndf_metrics_qpu = df_metrics.loc[platform_qpu]\nidxmin_qpu = df_metrics_qpu['T_ave'].idxmin()\nidxmin_qpu\n```\n\n\n```python\ndf_metrics_qpu.loc[[idxmin_qpu]]\n```\n\n\n```python\ndf.loc[platform_qpu].loc[idxmin_qpu]\n```\n\n\n```python\n# Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition\np = platform_qpu\n(t,f,s,v,e) = idxmin_qpu\n# Plot the QPU runner-up.\nplot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]],\n xmax=7, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right')\n```\n\n\n```python\n# Print the minimizer source.\nprint(df.loc[(p,t,f,s,v,e,0)]['minimizer_src'])\n```\n\n\n```python\n# Exclude the QPU runner-up.\ndf_metrics = df_metrics.drop((p,t,f,s,v,e))\n```\n\n### The best entry with 100% convergence (prob=0.999)\n\n\n```python\ndf_metrics_prob100 = get_metrics(df, delta=0.1, prob=0.999, which_fun_key='fun_exact', which_time_key='total_q_shots')\ndf_metrics_prob100 = df_metrics_prob100[(df_metrics_prob100['s']==1) & (df_metrics_prob100['num_repetitions']>1)]\n```\n\n\n```python\nidxmin_prob100 = df_metrics_prob100['T_ave'].idxmin()\nidxmin_prob100\n```\n\n\n```python\ndf_metrics_prob100.loc[[idxmin_prob100]]\n```\n\n\n```python\ndf.loc[idxmin_prob100]\n```\n\n\n```python\n# Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition\n(p,t,f,s,v,e) = idxmin_prob100\n# Plot.\nplot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]],\n xmax=30, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right')\n```\n\n### The worst entry with 100% convergence (prob=0.999)\n\n\n```python\nidxmax_prob100 = df_metrics_prob100['T_ave'].idxmax()\nidxmax_prob100\n```\n\n\n```python\ndf_metrics_prob100.loc[[idxmax_prob100]]\n```\n\n\n```python\ndf.loc[idxmax_prob100]\n```\n\n\n```python\n# Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition\n(p,t,f,s,v,e) = idxmax_prob100\n# Plot.\nplot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]],\n xmax=31, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right')\n```\n\n\n```python\n# The ratio of the worst of the best with 100% convergence.\ndf_metrics_prob100.loc[idxmax_prob100]['T_ave'] / df_metrics_prob100.loc[idxmin_prob100]['T_ave']\n```\n\n\n```python\n# Exclude the best entry with 100% convergence.\ndf_metrics_prob100 = df_metrics_prob100.drop(idxmin_prob100)\n```\n\n### The most accurate entry (also the runner-up with 100% convergence!)\n\n\n```python\ndf_metrics_delta0 = get_metrics(df, delta=0.01, prob=0.999, which_fun_key='fun_exact', which_time_key='total_q_shots')\ndf_metrics_delta0 = df_metrics_delta0[(df_metrics_delta0['num_repetitions']>1)]\n```\n\n\n```python\nidxmin_delta0 = df_metrics_delta0['T_ave'].idxmin()\nidxmin_delta0\n```\n\n\n```python\n# Also, the runner-up entry with 100% convergence!\nidxmin_prob100 = df_metrics_prob100['T_ave'].idxmin()\nidxmin_prob100\n```\n\n\n```python\ndf_metrics_delta0.loc[[idxmin_delta0]]\n```\n\n\n```python\ndf.loc[idxmin_delta0]\n```\n\n\n```python\n# Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition\n(p,t,f,s,v,e) = idxmin_delta0\n# Plot.\nplot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]],\n xmax=9, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right')\n```\n\n\n```python\n# Print the minimizer source.\nprint(df.loc[(p,t,f,s,v,e,0)]['minimizer_src'])\n```\n\n### Plot convergence\n\n\n```python\n# # Plot all.\n# plot(df, legend_loc='center')\n```\n\n\n```python\n# Plot QPU only.\nplot(df, platform_set=[platform_qpu], markersize_divisor=10,\n xmin=0, xmax=34+0.01, xstep=1, ymin=-2.80, ymax=-1.80-0.01, ystep=0.05, legend_loc='lower left')\n```\n\n\n```python\n# Plot COBYLA only.\nplot(df, minimizer_method_set=['my_cobyla'], sample_number_set=[50], markersize_divisor=5,\n xmin=5, xmax=32+0.01, xstep=1, ymin=-2.89, ymax=-1.79+0.01, ystep=0.05, legend_loc='upper right')\n```\n\n### Plot execution metrics\n\n\n```python\n# plot_metric(df)\n```\n\n\n```python\n# plot_metric(df, metric='total_q_shots')\n```\n", "meta": {"hexsha": "a13c39671240aa8d0beaaa3be3ff49b207a21bf3", "size": 45983, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jnotebook/hackathon.20181006/analysis.ipynb", "max_stars_repo_name": "ctuning/ck-quantum", "max_stars_repo_head_hexsha": "c5283893b9767cfb032286e68f29525761e1ec82", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:19:17.000Z", "max_issues_repo_path": "jnotebook/hackathon.20180615/analysis.ipynb", "max_issues_repo_name": "ctuning/ck-quantum", "max_issues_repo_head_hexsha": "c5283893b9767cfb032286e68f29525761e1ec82", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-10-06T10:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T15:51:17.000Z", "max_forks_repo_path": "jnotebook/hackathon.20181006/analysis.ipynb", "max_forks_repo_name": "ctuning/ck-quantum", "max_forks_repo_head_hexsha": "c5283893b9767cfb032286e68f29525761e1ec82", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-10-01T17:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-09T19:24:29.000Z", "avg_line_length": 32.2687719298, "max_line_length": 453, "alphanum_fraction": 0.5484853098, "converted": true, "num_tokens": 8187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.13660839881392145, "lm_q1q2_score": 0.06297876404820647}} {"text": "```python\n%load_ext watermark\n%watermark -a 'cs224' -u -d -v -p numpy,pandas,matplotlib,sklearn,h5py,pytest\n```\n\n Author: cs224\n \n Last updated: 2021-09-10\n \n Python implementation: CPython\n Python version : 3.8.10\n IPython version : 7.22.0\n \n numpy : 1.20.2\n pandas : 1.2.5\n matplotlib: 3.3.4\n sklearn : 0.24.2\n h5py : 2.10.0\n pytest : 6.2.4\n \n\n\n\n```python\n%matplotlib inline\nimport numpy as np, scipy, scipy.stats as stats, pandas as pd, matplotlib.pyplot as plt, seaborn as sns\nimport sklearn, sklearn.pipeline, sklearn.model_selection, sklearn.preprocessing, sklearn.linear_model\n\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\n# pd.set_option('display.float_format', lambda x: '%.2f' % x)\nnp.set_printoptions(edgeitems=10)\nnp.set_printoptions(linewidth=1000)\nnp.set_printoptions(suppress=True)\nnp.core.arrayprint._line_width = 180\n\nSEED = 42\nnp.random.seed(SEED)\n\nsns.set()\n```\n\n\n```python\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"\"))\n```\n\n\n\n\n\n\n```python\n# import os,sys\n# sys.path.append(os.path.realpath(os.path.abspath('') + '/../../lib'))\n```\n\n\n```python\n# %load_ext autoreload\n# %autoreload 1\n# %aimport somemodule\n```\n\n\n```python\nfrom IPython.display import display, HTML\n\nfrom IPython.display import display_html\ndef display_side_by_side(*args):\n html_str=''\n for df in args:\n if type(df) == np.ndarray:\n df = pd.DataFrame(df)\n html_str+=df.to_html()\n html_str = html_str.replace('table','table style=\"display:inline\"')\n # print(html_str)\n display_html(html_str,raw=True)\n\nCSS = \"\"\"\n.output {\n flex-direction: row;\n}\n\"\"\"\n\ndef display_graphs_side_by_side(*args):\n html_str=''\n for g in args:\n html_str += ''\n html_str += '
    '\n html_str += g._repr_svg_()\n html_str += '
    '\n display_html(html_str,raw=True)\n \n\ndisplay(HTML(\"\"))\n```\n\n\n\n\n\n\n```python\n# import importlib, logging\n# importlib.reload(logging)\n# logging.basicConfig(level=logging.DEBUG)\n# logging.info('test')\n```\n\n\n```python\n# import warnings\n# with warnings.catch_warnings():\n# warnings.simplefilter(\"ignore\")\n# warnings.filterwarnings(\"ignore\", module='xxx_module_xxx')\n# warnings.filterwarnings('error', category=RuntimeWarning, module='empyrical.stats')\n\n\n# with warnings.catch_warnings(record=True) as w:\n# # Cause all warnings to always be triggered.\n# warnings.simplefilter(\"always\")\n\n# warnings.filterwarnings('error, message='', category=Warning, module='', lineno=0, append=False)\n# warnings.filterwarnings('error', module='pandas')\n# warnings.filterwarnings('ignore', module='numba_scipy')\n# warnings.filterwarnings('ignore', module='zipline.assets')\n```\n\n\n```python\nN_subjects = 1000\n\nX = stats.norm(loc=0, scale=10).rvs(size=(N_subjects,1), random_state=np.random.RandomState(43))\nX[:5,:]\n```\n\n\n\n\n array([[ 2.57399925],\n [-9.08481433],\n [-3.78503106],\n [-5.34915599],\n [ 8.58073346]])\n\n\n\n\n```python\na = 0.5\nb = 1\ny = a * X + b\ny = y + stats.norm(loc=0, scale=0.5).rvs(size=(N_subjects,1), random_state=np.random.RandomState(44))\ny[:5,:]\n```\n\n\n\n\n array([[ 1.91169227],\n [-2.8842285 ],\n [-0.26944552],\n [-2.47703586],\n [ 4.55629489]])\n\n\n\n\n```python\nx_min = np.min(X)\nx_max = np.max(X)\nx_lin = np.linspace(x_min, x_max, 100)\ny_lin = a * x_lin + b\n```\n\n\n```python\nlr_poly = sklearn.linear_model.LinearRegression()\nlr_poly.fit(X, y)\nlr_poly.intercept_, lr_poly.coef_\n```\n\n\n\n\n (array([0.99580863]), array([[0.49856981]]))\n\n\n\n\n```python\nplt.figure(figsize=(15, 8), dpi=80, facecolor='w', edgecolor='k')\nax = plt.subplot(1, 1, 1)\nax.scatter(X,y)\nax.plot(x_lin,y_lin)\n```\n\n# LaTeX\n\nHere is a `newcommand` (see in the source):\n$$\\newcommand{gpvec}[1]{{\\bf #1}}$$\n$$\\newcommand{bfvec}[1]{{\\pmb{#1}}}$$\n$$p(f_*|x_*, X, y) = \\mathcal{N}\\left(\\frac{1}{\\sigma_n^2}\\gpvec{x_*}^TA^{-1}X\\gpvec{y},\\; \\gpvec{x_*}^TA^{-1}\\bfvec{x_*}\\right)$$\n$$A=\\frac{1}{\\sigma_n^2}XX^T+\\Sigma_p^{-1}$$\n\n$\\displaystyle\n\\begin{array}{rcl}\n\\text{μ} & \\sim & a\\\\\n\\text{σ} & \\sim & b\\\\\n\\end{array}\n$\n\n$$\n\\begin{align}\ns_{t+1}=\\begin{pmatrix}\\beta_{t+1}\\\\\\alpha_{t+1}\\end{pmatrix}&=&\\begin{pmatrix}\\beta_t\\\\\\alpha_t\\end{pmatrix}+\\eta_t&,\\qquad& \\eta_t \\sim N(0, I_2\\sigma_\\eta^2)\\\\\ny_t &=& Z_t\\cdot s_t + \\varepsilon_t = \\begin{pmatrix}x_t&1\\end{pmatrix}\\cdot\\begin{pmatrix}\\beta_t\\\\\\alpha_t\\end{pmatrix} + \\varepsilon_t =\\beta_tx_t+\\alpha_t \\\n&,\\qquad&\\varepsilon_t \\sim N(0, \\sigma_\\varepsilon^2)\n\\end{align}\n$$\n\nGiven a joint distribution:\n$$\\left[\\begin{matrix}x\\\\ y\\end{matrix}\\right]\\sim\\mathcal{N}\\left(\n\\left[\\begin{matrix}\\mu_x\\\\\\mu_y\\end{matrix}\\right],\n\\left[\\begin{matrix}A&C\\\\ C^T&B\\end{matrix}\\right]\n\\right)$$\n\nWe get the conditional distribution analytically as follows:\n\n$$p(x\\,|\\, y)\\sim\\mathcal{N}(\\mu_x+CB^{-1}(y-\\mu_y), A-CB^{-1}C^T)$$\n\nAnd as we set the mean to $0$ this reduces to:\n\n$$p(x\\,|\\, y)\\sim\\mathcal{N}(CB^{-1}y, A-CB^{-1}C^T)$$\n\n# SymPy\n\n\n```python\nimport sympy\nsympy.init_printing()\n```\n\n\n```python\ndef myfn(x):\n return (x+1)*(x-2)*(x-2.5)*(x-4)\n\nsymx = sympy.symbols('x')\nsympy.expand(myfn(symx))\n```\n\n\n```python\nsx = sympy.symbols('x')\nsfx = \\\n -0.0000009957371 * sx**16 + \\\n 0.000056100257831 * sx**15 + \\\n -0.0014371151322 * sx**14 + \\\n 0.022152182049259 * sx**13 + \\\n -0.229167949577895 * sx**12 + \\\n 1.680307250977133 * sx**11 + \\\n -8.98984498449258 * sx**10 + \\\n 35.59846747504916 * sx** 9 + \\\n -104.74198119349185 * sx**8 + \\\n 227.94559624952703 * sx**7 + \\\n -362.2994941897943 * sx**6 + \\\n 411.6650485438511 * sx**5 + \\\n -323.9001750849299 * sx**4 + \\\n 168.63970442305256 * sx**3 + \\\n -54.90472890518606 * sx**2 + \\\n 11.515498193577798 * sx\nsfx2 = sfx**2\nisfx2 = sympy.Integral(sfx2, sx)\nisfx2\n```\n\n\n```python\nisfx2 = sympy.integrate(sfx2, (sx,0,6.56))\nisfx2*sympy.pi\n```\n\n\n```python\nprecision=50\nsympy.N(isfx2*sympy.pi, precision)\n```\n\n\n```python\nsympy.plotting.plot(sfx, (sx, 0, 6.56))\n```\n\n\n```python\nsa, sb, sc, sd = sympy.symbols(['a', 'b', 'c', 'd'])\nse, sf, sg, sh = sympy.symbols('e f g h')\n```\n\n\n```python\nsm = sympy.Matrix([[sa, sb], [sc, sd]])\nsm, sm.inv()\n```\n\n\n```python\nsympy.S(\"{:6.2f}\".format(1.23))\n```\n\n\n```python\nsolution = sympy.solveset(sympy.Eq(sx**2 - 1, 0), sx)\nsolution\n```\n\n\n```python\nlist(solution)[0]\n```\n", "meta": {"hexsha": "e9f8f4c854cb38506305797ed3a7640f0ec5a0f9", "size": 127819, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0000-template-standard.ipynb", "max_stars_repo_name": "cs224/blog-series-monte-carlo-methods", "max_stars_repo_head_hexsha": "5300dc80077a64433b02954f648b9cf43f4573c9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-12T04:06:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T04:06:34.000Z", "max_issues_repo_path": "0000-template-standard.ipynb", "max_issues_repo_name": "cs224/blog-series-monte-carlo-methods", "max_issues_repo_head_hexsha": "5300dc80077a64433b02954f648b9cf43f4573c9", "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": "0000-template-standard.ipynb", "max_forks_repo_name": "cs224/blog-series-monte-carlo-methods", "max_forks_repo_head_hexsha": "5300dc80077a64433b02954f648b9cf43f4573c9", "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": 175.8170563961, "max_line_length": 44916, "alphanum_fraction": 0.8846885048, "converted": true, "num_tokens": 2291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.16667539640920673, "lm_q1q2_score": 0.06292674063252791}} {"text": "\n\n## This Jupyter notebook is available at https://github.com/dkp-quantum/Tutorials\n\n## Further Information\n\n#### * Qiskit: https://qiskit.org\n\n#### * Qiskit GitHub: https://github.com/Qiskit\n\n\n\n\n\n\n\n\n\n## What is Qiskit?\n\n* Quantum Information Science Kit\n\n* Open-source SDK for working with quantum computers at the level of pulses, circuits and algorithms\n\n* Founded by IBM Research in 2017 to allow software development for their cloud quantum computing service known as IBM Q Experience.\n\n* The primary version of Qiskit uses the Python programming language. It is used to create quantum programs based on the OpenQASM (Open Quantum Assembly Language) representation of quantum instructions.\n\n\n## What can we do with Qiskit?\n\n* Access to circuits\n* Access to a library of quantum algorithms\n* Access to quantum hardware\n* Access to optimization against noise\n\n## IBM Quantum Experience Backend\n\n* 9 real quantum devices with number of qubits 1, 5, and 16.\n* 32-qubit simulator\n\n\n\n## Main simulator backends\n\n1. __QASM Simulator__: It emulates execution of a quantum circuits on a real device and returns __measurement counts__. It includes highly configurable noise models and can even be loaded with automatically generated approximate noise models based on the calibration parameters of actual hardware devices.\n\n * What is __QASM__? QASM = Quantum Assembly Language (see https://arxiv.org/abs/1707.03429 for more detail)\n \n\n2. __Statevector Simulator__: It simulates the ideal execution of a quantum circuit and returns __the final quantum state vector__ of the device at the end of simulation.\n\n3. __Unitary Simulator__: It allows simulation of the final unitary matrix implemented by an ideal quantum circuit. This only works if all the elements in the circuit are unitary operations.\n\n\n\n## How to start\n\n1. Start Online: https://quantum-computing.ibm.com\n\n## How to start\n\n2. Start Locally \n\n
    \n\n* Qiskit is tested and supported on the following 64-bit systems:\n\n\n * Ubuntu 16.04 or later\n * macOS 10.12.6 or later\n * Windows 7 or later\n \n\n* To install Qiskit locally, you will need Python 3.5+.\n\n* IBM recommends using a virtual environment with Anaconda, a cross-platform Python distribution for scientific computing: https://www.anaconda.com/products/individual\n\n## Let's start on Mac\n\n\n\n## Let's start on Windows\n\n\n\n## Let's start on Windows\n\n\n\n## Let's start on Windows\n\n\n\n\n```python\n%matplotlib inline\n# Importing standard Qiskit libraries and configuring account\nfrom qiskit import *\nfrom qiskit.visualization import *\nimport numpy as np\n```\n\n\n```python\n# Create a quantum register with 2 qubits\nq = QuantumRegister(2,'q')\n# Form a quantum circuit\n# Note that the circuit name is optional\nqc = QuantumCircuit(q,name=\"first_qc\")\n# Display the quantum circuit\nqc.draw()\n```\n\n\n\n\n
            \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\n\n\n\n```python\n# Grab the results from the job.\nresult_sim1 = job_sim1.result()\nresult_sim1\n```\n\n\n\n\n namespace(backend_name='qasm_simulator',\n backend_version='0.3.2',\n qobj_id='944ac6fa-832c-4ecd-a579-f14eb1b1be04',\n job_id='7d81d747-8230-4474-b9d5-f73191109997',\n success=True,\n results=[namespace(shots=4096,\n success=True,\n data=namespace(counts=namespace(0x0=1995,\n 0x3=2101)),\n meas_level=2,\n header=namespace(memory_slots=2,\n clbit_labels=[['c', 0],\n ['c', 1]],\n name='circuit2',\n qubit_labels=[['q', 0],\n ['q', 1]],\n n_qubits=2,\n qreg_sizes=[['q', 2]],\n creg_sizes=[['c', 2]]),\n status='DONE',\n time_taken=0.010838524,\n seed_simulator=4177817008,\n metadata={'measure_sampling': True,\n 'method': 'stabilizer',\n 'parallel_shots': 1,\n 'parallel_state_update': 8})],\n date=datetime.datetime(2020, 8, 5, 11, 22, 8, 660150),\n header=namespace(backend_name='qasm_simulator',\n backend_version='0.3.2'),\n status='COMPLETED',\n time_taken=0.028506040573120117,\n metadata={'max_memory_mb': 4096,\n 'omp_enabled': True,\n 'parallel_experiments': 1,\n 'time_taken': 0.011715323000000001})\n\n\n\n\n```python\nresult_sim1.get_counts(qc_all)\n```\n\n\n\n\n {'00': 1995, '11': 2101}\n\n\n\n\n```python\nplot_histogram(result_sim1.get_counts(qc_all))\n```\n\n\n```python\n# Use Aer's statevector_simulator\nbackend_sv = Aer.get_backend('statevector_simulator')\n\n# Execute the circuit on the statevector simulator.\n# It is important to note that the measurement has been excluded\njob_sim2 = execute(qc, backend_sv)\n```\n\n\n```python\n# Grab the results from the job.\nresult_sim2 = job_sim2.result()\n# Output the entire result\nresult_sim2\n```\n\n\n\n\n namespace(backend_name='statevector_simulator',\n backend_version='0.3.2',\n qobj_id='1861012f-18e1-4186-80eb-848ae00b8cad',\n job_id='2e6f72fa-2de1-4166-8414-d03ce5c6ec02',\n success=True,\n results=[namespace(shots=1,\n success=True,\n data=namespace(statevector=[(0.7071067811865476+0j),\n 0j,\n 0j,\n (0.7071067811865475+0j)]),\n meas_level=2,\n header=namespace(memory_slots=0,\n clbit_labels=[],\n name='first_qc',\n qubit_labels=[['q', 0],\n ['q', 1]],\n n_qubits=2,\n qreg_sizes=[['q', 2]],\n creg_sizes=[]),\n status='DONE',\n time_taken=0.000285063,\n seed_simulator=1215084373,\n metadata={'parallel_shots': 1,\n 'parallel_state_update': 8})],\n date=datetime.datetime(2020, 8, 5, 11, 28, 16, 708104),\n header=namespace(backend_name='statevector_simulator',\n backend_version='0.3.2'),\n status='COMPLETED',\n time_taken=0.006955862045288086,\n metadata={'max_memory_mb': 4096,\n 'omp_enabled': True,\n 'parallel_experiments': 1,\n 'time_taken': 0.002053295})\n\n\n\n\n```python\n# See output state as a vector\noutputstate = result_sim2.get_statevector(qc, decimals=5)\nprint(outputstate)\n\n# Visualize density matrix\nplot_state_city(outputstate)\n```\n\n\n```python\n# Create the quantum circuit with the measurement in one go.\nqc_3 = QuantumCircuit(3,3,name=\"qc_bloch\")\nqc_3.x(1)\nqc_3.h(2)\nqc_3.barrier()\nqc_3.draw(output='mpl')\n```\n\n\n```python\n# Execute the circuit on the statevector simulator.\n# It is important to note that the measurement has been excluded\njob_sim_bloch = execute(qc_3, backend_sv)\n\n# Grab the results from the job.\nresult_sim_bloch = job_sim_bloch.result()\n\n# See output state as a vector\noutput_bloch = result_sim_bloch.get_statevector(qc_3, decimals=5)\n\n# Draw on the Bloch sphere\nplot_bloch_multivector(output_bloch)\n```\n\n\n```python\n# Use Aer's unitary_simulator\nbackend_u = Aer.get_backend('unitary_simulator')\n\n# Execute the circuit on the unitary simulator.\njob_usim = execute(qc, backend_u)\n\n# Grab the results from the job.\nresult_usim = job_usim.result()\nresult_usim\n```\n\n\n\n\n namespace(backend_name='unitary_simulator',\n backend_version='0.3.2',\n qobj_id='5518d9ba-fed3-4b4c-a9aa-a92c72010b39',\n job_id='e3d1367f-6943-4fa0-a8ef-25156827f137',\n success=True,\n results=[namespace(shots=1,\n success=True,\n data=namespace(unitary=[[(0.7071067811865476+0j),\n (0.7071067811865475+0j),\n 0j,\n 0j],\n [0j,\n 0j,\n (0.7071067811865475+0j),\n (-0.7071067811865476+0j)],\n [0j,\n 0j,\n (0.7071067811865476+0j),\n (0.7071067811865475+0j)],\n [(0.7071067811865475+0j),\n (-0.7071067811865476+0j),\n 0j,\n 0j]]),\n meas_level=2,\n status='DONE',\n header=namespace(qreg_sizes=[['q', 2]],\n creg_sizes=[],\n n_qubits=2,\n name='first_qc',\n qubit_labels=[['q', 0],\n ['q', 1]],\n memory_slots=0,\n clbit_labels=[]),\n seed_simulator=2335392040,\n time_taken=9.462500000000001e-05,\n metadata={'parallel_shots': 1,\n 'parallel_state_update': 8})],\n status='COMPLETED',\n header=namespace(backend_version='0.3.2',\n backend_name='unitary_simulator'),\n date=datetime.datetime(2020, 8, 3, 15, 36, 22, 517107),\n time_taken=0.002722024917602539,\n metadata={'max_memory_mb': 4096,\n 'omp_enabled': True,\n 'parallel_experiments': 1,\n 'time_taken': 0.00021459200000000002})\n\n\n\n\n```python\n# Output the unitary matrix\nunitary = result_usim.get_unitary(qc)\nprint('%s\\n' % unitary)\n```\n\n [[ 0.70710678+0.j 0.70710678+0.j 0. +0.j 0. +0.j]\n [ 0. +0.j 0. +0.j 0.70710678+0.j -0.70710678+0.j]\n [ 0. +0.j 0. +0.j 0.70710678+0.j 0.70710678+0.j]\n [ 0.70710678+0.j -0.70710678+0.j 0. +0.j 0. +0.j]]\n \n\n\n## Exercise 1: \n## Design a quantum circuit to create the following 2-qubit entangled state: $\\frac{|01\\rangle+|10\\rangle}{\\sqrt{2}}$. \n## Check the answer with the QASM simulation and by plotting the histogram of the measurement statistics.\n\n\n```python\n# Create the quantum circuit with the measurement in one go.\nqc_ex1 = QuantumCircuit(q,c,name=\"ex1\")\n```\n\n\n```python\n# Put the first qubit in equal superposition\nqc_ex1.h(0)\n```\n\n\n\n\n \n\n\n\n\n```python\n# Rest of the circuit\nqc_ex1.x(1)\nqc_ex1.cx(0,1)\nqc_ex1.barrier()\nqc_ex1.measure(0,0)\nqc_ex1.measure(1,1)\nqc_ex1.draw(output='mpl')\n```\n\n\n```python\n# Execute the circuit on the qasm simulator.\njob_ex1 = execute(qc_ex1, backend_q, shots=4096)\n```\n\n\n```python\njob_ex1.status()\n```\n\n\n\n\n \n\n\n\n\n```python\n# Grab the results from the job.\nresult_ex1 = job_ex1.result()\nresult_ex1.get_counts(qc_ex1)\n```\n\n\n\n\n {'10': 2117, '01': 1979}\n\n\n\n\n```python\nplot_histogram(result_ex1.get_counts(qc_ex1))\n```\n\n\n```python\n# Or get the histogram in one go\nplot_histogram(job_ex1.result().get_counts(qc_ex1))\n```\n\n## Exercise 2: \n## Design a quantum circuit that creates a 3-qubit entangled state: $\\alpha|000\\rangle+\\beta|111\\rangle$,\n## such that $|\\alpha|^2 = 0.25$, and $|\\beta|^2 = 0.75$. \n## Check the answer with the QASM simulation and by plotting the histogram of the measurement statistics.\n\n### Hint:\n$R_y(\\theta) = \\begin{bmatrix} \\cos(\\theta/2) & -\\sin(\\theta/2)\\\\ \\sin(\\theta/2) & \\cos(\\theta/2)\\end{bmatrix}$ can be implemented by the qiskit code: `qc.ry(theta,q)`\n\n\n```python\n# Create a quantum register with 3 qubits\nq3 = QuantumRegister(3,'q')\n# Create a classical register with 3 qubits\nc3 = ClassicalRegister(3,'c')\n\n# Create the quantum circuit with the measurement in one go.\nqc_ex2 = QuantumCircuit(q3,c3,name=\"ex1\")\n\nqc_ex2.ry(2*np.pi/3,0)\nqc_ex2.cx(0,1)\nqc_ex2.cx(1,2)\nqc_ex2.barrier()\nqc_ex2.measure(q3,c3)\nqc_ex2.draw(output='mpl')\n```\n\n\n```python\n# Execute the circuit on the qasm simulator.\njob_ex2 = execute(qc_ex2, backend_q, shots=4096)\n\n# Grab the results from the job.\nresult_ex2 = job_ex2.result()\nplot_histogram(result_ex2.get_counts(qc_ex2))\n```\n\n## 3-qubit gate example: Toffoli gate\n\n\n```python\n# Create a quantum register with 3 qubits\nq3 = QuantumRegister(3,'q')\n# Create a classical register with 3 qubits\nc3 = ClassicalRegister(3,'c')\n\n# Create the quantum circuit without a Toffoli gate\nqc_toff = QuantumCircuit(q3,c3,name=\"ex1\")\n\nqc_toff.ry(2*np.pi/3,0)\nqc_toff.h(1)\nqc_toff.h(2)\nqc_toff.barrier()\nqc_toff.measure(q3,c3)\nqc_toff.draw(output='mpl')\n```\n\n\n```python\n# Execute the circuit on the qasm simulator.\njob_toff = execute(qc_toff, backend_q, shots=4096)\n\n# Grab the results from the job.\nresult_toff = job_toff.result()\nplot_histogram(result_toff.get_counts(qc_toff))\n```\n\n\n```python\n# Now, add a Toffoli gate\nqc_toff = QuantumCircuit(q3,c3,name=\"ex1\")\n\nqc_toff.ry(2*np.pi/3,0)\nqc_toff.h(1)\nqc_toff.h(2)\nqc_toff.ccx(1,2,0)\nqc_toff.barrier()\nqc_toff.measure(q3,c3)\nqc_toff.draw(output='mpl')\n```\n\n\n```python\n# Execute the circuit on the qasm simulator.\njob_toff = execute(qc_toff, backend_q, shots=4096)\n\n# Grab the results from the job.\nresult_toff = job_toff.result()\nplot_histogram(result_toff.get_counts(qc_toff))\n```\n\n## Native single-qubit gates of IBM Q devices\n\nOne way to write a general form of a single qubit unitary:\n
    \n
    \n$$\nU(\\theta,\\phi,\\lambda)=\\begin{bmatrix} \n \\cos(\\theta/2) & -e^{i\\lambda}\\sin(\\theta/2) \\\\\ne^{i\\phi}\\sin(\\theta/2) & e^{i(\\lambda+\\phi)}\\cos(\\theta/2) \n\\end{bmatrix}\n$$\n***\nNative single qubit gates:\n* `u3`=$U(\\theta,\\phi,\\lambda)$\n* `u2`=$U(\\pi/2,\\phi,\\lambda)$\n* `u1`=$U(0,0,\\lambda)$\n\nNative two qubit gate:\n* controlled-NOT\n\n### But why such form? $\\rightarrow$ This is related to gate implementations on real devices\n\n### Note that $$\nU(\\theta,\\phi,\\lambda)=\\begin{bmatrix} \n \\cos(\\theta/2) & -e^{i\\lambda}\\sin(\\theta/2) \\\\\ne^{i\\phi}\\sin(\\theta/2) & e^{i(\\lambda+\\phi)}\\cos(\\theta/2) \n\\end{bmatrix}\n$$ \n### can be written as:\n### \\begin{align}\nU(\\theta,\\phi,\\lambda)&=R_z(\\phi)R_y(\\theta)R_z(\\lambda)\\\\\n&=R_z(\\phi)R_x(-\\pi/2)R_z(\\theta)R_x(\\pi/2)R_z(\\lambda)\n\\end{align}\n\n### In RF/MW based quantum control, $R_z$ is given for free, and $R_x(\\pm\\pi/2)$ can be calibrated with high precision.\n\n## Running Quantum Circuits on IBM Q\n\n\n### Need IBM Token for running an experiment on a IBM cloud quantum computer: https://quantum-computing.ibm.com\n\n\n```python\nIBMQ.disable_account()\nprovider = IBMQ.enable_account('IBM_TOKEN')\n```\n\n\n```python\n# provider = IBMQ.get_provider(hub='ibm-q-research')\n```\n\n\n```python\nprovider.backends()\n```\n\n\n\n\n [,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ]\n\n\n\n\n```python\nfrom qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor\nfrom qiskit.tools.visualization import plot_gate_map, plot_error_map\n```\n\n\n```python\n# Retrieve IBM Quantum device information\nbackend_overview()\n```\n\n ibmq_rome ibmq_armonk ibmq_essex\n --------- ----------- ----------\n Num. Qubits: 5 Num. Qubits: 1 Num. Qubits: 5\n Pending Jobs: 6 Pending Jobs: 2 Pending Jobs: 70\n Least busy: False Least busy: False Least busy: False\n Operational: True Operational: True Operational: True\n Avg. T1: 77.2 Avg. T1: 149.4 Avg. T1: 104.2\n Avg. T2: 109.1 Avg. T2: 225.6 Avg. T2: 143.5\n \n \n \n ibmq_burlington ibmq_london ibmq_valencia\n --------------- ----------- -------------\n Num. Qubits: 5 Num. Qubits: 5 Num. Qubits: 5\n Pending Jobs: 7 Pending Jobs: 7 Pending Jobs: 6\n Least busy: False Least busy: False Least busy: False\n Operational: True Operational: True Operational: True\n Avg. T1: 80.5 Avg. T1: 60.5 Avg. T1: 98.0\n Avg. T2: 75.7 Avg. T2: 68.1 Avg. T2: 65.1\n \n \n \n ibmq_ourense ibmq_vigo ibmq_16_melbourne\n ------------ --------- -----------------\n Num. Qubits: 5 Num. Qubits: 5 Num. Qubits: 15\n Pending Jobs: 1 Pending Jobs: 7 Pending Jobs: 8\n Least busy: True Least busy: False Least busy: False\n Operational: True Operational: True Operational: True\n Avg. T1: 106.2 Avg. T1: 95.5 Avg. T1: 53.2\n Avg. T2: 64.7 Avg. T2: 63.0 Avg. T2: 56.6\n \n \n \n ibmqx2\n ------\n Num. Qubits: 5\n Pending Jobs: 13\n Least busy: False\n Operational: True\n Avg. T1: 64.1\n Avg. T2: 40.6\n \n \n \n\n\n\n```python\n# Let's get two quantum devices as an example\nbackend_qx2 = provider.get_backend('ibmqx2')\nbackend_vigo = provider.get_backend('ibmq_vigo')\n```\n\n\n```python\nbackend_monitor(backend_qx2)\n```\n\n ibmqx2\n ======\n Configuration\n -------------\n n_qubits: 5\n operational: True\n status_msg: active\n pending_jobs: 13\n backend_version: 2.1.0\n basis_gates: ['id', 'u1', 'u2', 'u3', 'cx']\n local: False\n simulator: False\n sample_name: sparrow\n memory: True\n credits_required: True\n meas_map: [[0, 1, 2, 3, 4]]\n max_shots: 8192\n n_registers: 1\n coupling_map: [[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1], [2, 3], [2, 4], [3, 2], [3, 4], [4, 2], [4, 3]]\n description: 5 qubit device\n backend_name: ibmqx2\n quantum_volume: 8\n conditional: False\n open_pulse: False\n allow_q_object: True\n url: None\n max_experiments: 75\n allow_object_storage: True\n online_date: 2017-01-24T05:00:00+00:00\n \n Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]\n -----------------------------------------------------------------------\n Q0 / 5.2829 GHz / 73.79798 µs / 27.86901 µs / 0.0 / 0.00133 / 0.00266 / 0.0495\n Q1 / 5.24766 GHz / 61.62679 µs / 27.59343 µs / 0.0 / 0.00122 / 0.00243 / 0.023\n Q2 / 5.03384 GHz / 54.81727 µs / 62.96767 µs / 0.0 / 0.0009 / 0.0018 / 0.02\n Q3 / 5.29225 GHz / 59.02961 µs / 41.38983 µs / 0.0 / 0.00053 / 0.00107 / 0.014\n Q4 / 5.07847 GHz / 71.2559 µs / 43.16323 µs / 0.0 / 0.00051 / 0.00102 / 0.026\n \n Multi-Qubit Gates [Name / Type / Gate Error]\n --------------------------------------------\n cx0_1 / cx / 0.0194\n cx0_2 / cx / 0.01643\n cx1_0 / cx / 0.0194\n cx1_2 / cx / 0.02873\n cx2_0 / cx / 0.01643\n cx2_1 / cx / 0.02873\n cx2_3 / cx / 0.01804\n cx2_4 / cx / 0.01461\n cx3_2 / cx / 0.01804\n cx3_4 / cx / 0.01251\n cx4_2 / cx / 0.01461\n cx4_3 / cx / 0.01251\n\n\n\n```python\nplot_error_map(backend_qx2)\n```\n\n\n```python\nbackend_monitor(backend_vigo)\n```\n\n ibmq_vigo\n =========\n Configuration\n -------------\n n_qubits: 5\n operational: True\n status_msg: active\n pending_jobs: 7\n backend_version: 1.0.3\n basis_gates: ['id', 'u1', 'u2', 'u3', 'cx']\n local: False\n simulator: False\n sample_name: Giraffe\n memory: True\n credits_required: True\n meas_map: [[0, 1, 2, 3, 4]]\n max_shots: 8192\n n_registers: 1\n coupling_map: [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]]\n description: 5 qubit device Vigo\n backend_name: ibmq_vigo\n quantum_volume: 16\n conditional: False\n open_pulse: False\n allow_q_object: True\n url: None\n max_experiments: 75\n allow_object_storage: True\n online_date: 2019-07-03T04:00:00+00:00\n \n Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]\n -----------------------------------------------------------------------\n Q0 / 4.79649 GHz / 122.04295 µs / 13.28137 µs / 0.0 / 0.00035 / 0.0007 / 0.008\n Q1 / 4.94014 GHz / 64.04633 µs / 78.91768 µs / 0.0 / 0.0005 / 0.001 / 0.013\n Q2 / 4.83352 GHz / 85.55076 µs / 103.29922 µs / 0.0 / 0.00038 / 0.00076 / 0.011\n Q3 / 4.80797 GHz / 64.45464 µs / 65.45159 µs / 0.0 / 0.00061 / 0.00123 / 0.026\n Q4 / 4.74967 GHz / 141.21974 µs / 54.21269 µs / 0.0 / 0.00054 / 0.00107 / 0.022\n \n Multi-Qubit Gates [Name / Type / Gate Error]\n --------------------------------------------\n cx0_1 / cx / 0.00953\n cx1_0 / cx / 0.00953\n cx1_2 / cx / 0.00934\n cx1_3 / cx / 0.01271\n cx2_1 / cx / 0.00934\n cx3_1 / cx / 0.01271\n cx3_4 / cx / 0.00726\n cx4_3 / cx / 0.00726\n\n\n\n```python\nplot_error_map(backend_vigo)\n```\n\n## Let's create a 5-qubit GHZ state, i.e. $ \\frac{|00000\\rangle + |11111\\rangle}{\\sqrt{2}}$.\n\n\n```python\n# Create a 5-qubit GHZ state (i.e. (|00000> + |11111>)/sqrt(2))\nq5 = QuantumRegister(5,'q')\nc5 = ClassicalRegister(5,'c')\nghz5= QuantumCircuit(q5,c5)\n\nghz5.h(0)\nfor i in range(1,5):\n ghz5.cx(0,i)\n\nghz5.barrier()\nghz5.measure(q5,c5)\nghz5.draw(output='mpl')\n```\n\n## Now, let's run it on a real IBMQ device.\n\n\n```python\n# Run the 5-qubit GHZ experiment on a 5-qubit device (try vigo)\njob_exp1 = execute(ghz5, backend=backend_vigo, shots=4096)\njob_monitor(job_exp1)\n```\n\n Job Status: job has successfully run\n\n\n\n```python\n# Grab experimental results\nresult_vigo = job_exp1.result()\ncounts_vigo = result_vigo.get_counts(ghz5)\n```\n\n\n```python\n# Let's also try the same experiment on the 14-qubit device.\njob_exp2 = execute(ghz5, backend=provider.get_backend('ibmq_16_melbourne'), shots=4096)\njob_monitor(job_exp2)\n```\n\n Job Status: job has successfully run\n\n\n\n```python\n# Grab experimental results\nresult_mel = job_exp2.result()\ncounts_mel = result_mel.get_counts(ghz5)\n```\n\n\n```python\n# Now, compare to theory by running it on qasm_simulator\njob_qasm = execute(ghz5,backend=backend_q)\nresult_qasm = job_qasm.result()\ncounts_qasm = result_qasm.get_counts(ghz5)\n\n# Plot both experimental and ideal results\nplot_histogram([counts_qasm,counts_vigo,counts_mel],\n color=['black','green','blue'],\n legend=['QASM','Vigo','Melbourne'],figsize = [20,8])\n```\n\n## Elementary Quantum Protocols\n\n* Superdense coding\n* Quantum teleportation\n\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "120dff5692e35470a83e755af10ce8ae01d79e2a", "size": 529851, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "2020 Yonsei-IBM/Yonsei_qiskit_lecture1.ipynb", "max_stars_repo_name": "dkp-quantum/tutorial", "max_stars_repo_head_hexsha": "cfb68dedc2762a39b0760057882f5cfd1f5089a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-05T01:08:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T15:45:50.000Z", "max_issues_repo_path": "2020 Yonsei-IBM/Yonsei_qiskit_lecture1.ipynb", "max_issues_repo_name": "dkp-quantum/tutorial", "max_issues_repo_head_hexsha": "cfb68dedc2762a39b0760057882f5cfd1f5089a0", "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": "2020 Yonsei-IBM/Yonsei_qiskit_lecture1.ipynb", "max_forks_repo_name": "dkp-quantum/tutorial", "max_forks_repo_head_hexsha": "cfb68dedc2762a39b0760057882f5cfd1f5089a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-05T01:05:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T04:01:28.000Z", "avg_line_length": 256.4622458858, "max_line_length": 121116, "alphanum_fraction": 0.9156687446, "converted": true, "num_tokens": 7987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.1540575704593912, "lm_q1q2_score": 0.06275279397803928}} {"text": "#
    BÁO CÁO ĐỒ ÁN 01: REGRESSION
    \n
    \n \n__TÊN MÔN HỌC:__ NHẬP MÔN HỌC MÁY\n\n__ĐỀ TÀI:__ CHI PHÍ SỬ DỤNG DỊCH VỤ Y TẾ\n\n__GIẢNG VIÊN:__ NGUYỄN TIẾN HUY\n \n__THỨ TỰ NHÓM:__ 07\n \n__THÀNH VIÊN:__\n\n- 18120184 Nguyễn Nguyên Khang \n- 18120189 Trần Đăng Khoa\n- 18120264 Nguyễn Duy Vũ\n- 18120283 Nguyễn Chiêu Bản\n- 18120286 Nguyễn Quốc Bảo\n\n__PHÂN CÔNG:__\n\nCông việc | Thực hiện | Mức độ hoàn thành\n------------ | ------------- | ------------\nKhám phá dữ liệu cơ bản | Vũ | 100%\nTiền xử lý dữ liệu | Vũ | 100%\nMô hình hóa dữ liệu | Bản, Bảo | 100%\nPhân tích dữ liệu tìm Insight| Khang, Khoa | 100%\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## Mục Lục\n\n- [I. Phân tích dữ liệu](#I.-Phân-tích-dữ-liệu)\n - [1. Vẽ biểu đồ một biến và nhận xét](#1.-Vẽ-biểu-đồ-một-biến-và-nhận-xét)\n - [2. Vẽ biểu đồ các biến tương quan và nhận xét](#2.-Vẽ-biểu-đồ-các-biến-tương-quan-và-nhận-xét)\n - [3. VIF](#3.-VIF)\n - [4. Insight: Sex có ảnh hưởng đến Smoker?](#4.-Insight:-Sex-có-ảnh-hưởng-đến-Smoker?)\n - [5. Insight: Trung bình của 'age', 'bmi', 'children' giữa người có hút thuốc và người không hút thuốc có bằng nhau](#5.-Insight:-Trung-bình-của-'age',-'bmi',-'children'-giữa-người-có-hút-thuốc-và-người-không-hút-thuốc-có-bằng-nhau)\n - [6. Insight: Sự phụ thuộc của 'charges' vào 'sex', 'smoker', 'age', 'bmi', 'children'](#6.-Insight:-Sự-phụ-thuộc-của-'charges'-vào-'sex',-'smoker',-'age',-'bmi',-'children')\n- [II. Thuật toán sử dụng](#II.-Thuật-toán-sử-dụng)\n - [1. Cách thức đánh giá mô hình](#1.-Cách-thức-đánh-giá-mô-hình)\n - [ 2. Thuật toán SVR](#2.-Thuật-toán-SVR)\n - [a. Giới thiệu SVR](#a.-Giới-thiệu-SVR)\n - [b. Sử dụng SVR từ thư viện Scikit-learn](#b.-Sử-dụng-SVR-từ-thư-viện-Scikit-learn)\n - [c. Thử nghiệm tương tự với các kernel khác](#c.-Thử-nghiệm-tương-tự-với-các-kernel-khác)\n - [d. Thử xóa các outlier](#d.-Thử-xóa-các-outlier)\n - [3. Dùng Simple Linear Regression từ thư viện Scikit-learn](#3.-Dùng-Simple-Linear-Regression-từ-thư-viện-Scikit-learn)\n - [Trực quan hóa mô hình](#Trực-quan-hóa-mô-hình)\n- [III. Tham khảo](#III.-Tham-khảo)\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## I. Phân tích dữ liệu\n\n
    Thông tin về dataset:
    \n
    \n\nTên cột | Ý nghĩa\n------------ | -------------\nAge| Tuổi\nSex| Giới tính\nBMI| Chỉ số khối cơ thể\nChildren| Số lượng trẻ con/người phụ thuộc\nSmoker| Tình trạng hút thuốc\nRegion| Khu vực sinh sống\nCharges| Chi phí y tế cá nhân\n\n### 1. Vẽ biểu đồ một biến và nhận xét\n\n\n```python\nBiến charges:\n```\n\nNhận xét: Biến charges có phân bố bị lệch trái, nhiều outlier\n\n\n```python\nBiến age:\n```\n\nNhận xét: Biến age có phân bố chuẩn\n\n\n```python\nBiến bmi:\n```\n\nNhận xét: Biến bmi có phân bố chuẩn, tồn tại outlier\n\n\n```python\nBiến sex:\n```\n\nNhận xét: Tỉ lệ nam nữ bằng nhau\n\n\n```python\nBiến smoker:\n```\n\nNhận xét: Tỉ lệ người không hút thuốc gấp 4 lần người hút thuốc\n\n\n```python\nBiến children:\n```\n\nNhận xét: Tỉ lệ người có càng nhiều con giảm dần\n\n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n\n### 2. Vẽ biểu đồ các biến tương quan và nhận xét\n\nTrước tiên, ta tính ma trận tương quan\n\n\n```python\n\n```\n\nCó thể thấy những thuộc tính như age (yếu), bmi (yếu), smoker (mạnh) có tương quan với thuộc tính charges\n\n\n```python\nBiểu đồ thể hiện sự mất tiền vào chi phí y tế của người có hút thuốc\n```\n\nBiểu đồ trên cho ta thấy người hút thuốc thì có chi phí y tế cao hơn, cụ thể :\n- hơn 75% người hút thuốc trả chi phí cao hơn hầu hết tất cả người không hút thuốc\n- chi phí thấp nhất của người hút thuốc chỉ nhỉnh hơn một chút so với chi phí của 75% người không hút thuốc.\n- nếu chi phí dưới 10k, xác suất cao là người đó không hút thuốc\n- nếu chi phí trên 20k, xác suất cao là người đó hút thuốc\n\n\n```python\nPhân bố của chi phí y tế theo độ tuổi\n```\n\nNhìn vào biểu đồ trên, ta thấy\n- người càng cao tuổi thì số tiền chi cho y tế càng nhiều\n- Nếu dưới 35 tuổi và không hút thuốc thì khả năng cao chi phí dưới 6k\n\n\n```python\nPhân bố của chi phí y tế theo bmi\n```\n\n- Người hút thuốc và có chỉ số BMI lớn hơn 30 thì chi phí tổi thiểu là khoảng 30k\n\n### 3. VIF\n\n\n```python\nBảng VIF\n```\n\n feature VIF\n 0 sex 1.966855\n 1 smoker 1.254563\n 2 age 7.658193\n 3 bmi 8.638958\n 4 children 1.816248\n\n\n
    \n\n1 = Không tương quan [1]\n\nGiữa 1 và 5 = Tương quan vừa [1]\n\nLớn hơn 5 = Tương quan mạnh [1]\n\n\nTa thấy các biến `sex`, `smoker`, `children` tương quan vừa với các biến còn lại. \n\n`age` và `bmi` có sự tương quan mạnh với các biến còn lại\n\nNên thu thập thêm data để giảm sự phụ thuộc giữa các biến\n\n### 4. Insight: Sex có ảnh hưởng đến Smoker?\n\n\n
    \n${H_0}$: sex và smoker độc lập nhau\n\n${H_A}$: sex và smoker phụ thuộc nhau\n\n
    \n\nĐặt:\n\n${A =}$ sex, ${A_1 =}$ `male`, ${A_2}$ = `female`\n\n${B =}$ smoker, ${B_1 =}$ `yes`, ${B_2 =}$ `no`\n\n
    \n\nTa có:\n\n${H_0}$: ${P(A_i\\cap B_j) = P(A_i)P(B_j)}$\n\n${H_A}$: ${P(A_i\\cap B_j) \\neq P(A_i)P(B_j)}$\n\n
    \nPhần dưới sẽ trình bày về mặt toán học lẫn sử dụng thư viện scipy.stats để tính toán \n\n
    \n\n\n```python\ncontigency\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
    noyesPr(Ai)
    sex
    female406910.495513
    male3911150.504487
    \n
    \n\n\n\nTa đã tính được ${Pr(A_i)}$ như bảng trên và \n\n${Pr(B_1)}$ = 0.2053838484546361\n\n${Pr(B_2)}$ = 0.7946161515453639\n\n---\n\nĐến đây ta có thể tính: \n\nGiá trị mong đợi ${E}$:\n\n\\begin{equation}\n\\text{Do kỳ vọng A và B độc lập:}\\\\\nE_{ij} = Pr(A_i) \\times Pr(B_j) \\times N [2]\\\\\n\\text{hay}\\\\\nE_{ij} = \\frac{\\text{(Tổng dòng} \\times \\text{Tổng cột)}}{\\text{Tổng bảng}} [3] \\\\ \n\\text{với bảng là bảng contingency}\n\\end{equation}\n\nGiá trị ${\\chi^2}$:\n\n\\begin{equation}\n\\chi^2=\\Sigma\\frac{(O-E)^2}{E} [2][3]\\\\\n\\text{với O là giá trị thực sự và E là giá trị mong đợi}\n\\end{equation}\n\nGiá trị dof: Degree of freedom\n\ndof cho ${\\chi^2}$ độc lập:\n\n\\begin{equation}\ndof = v = rc - 1 - (r-1) - (c-1) = (r-1)(c-1) [2]\\\\ = 1\n\\end{equation}\n\nChọn mức ý nghĩa:\n\n\\begin{equation}\n\\alpha = 0.05\n\\end{equation}\n\nTra bảng Chi Squared với ${\\alpha = 0.05, dof = 1}$ ta được critical value ${ = 3.841459}$\t\n\nChấp nhận ${H_0}$ nếu \n\\begin{equation}\n\\chi^2_v <= 3.841459\n\\end{equation}\n\n \n
    \n\nTa có thể sử dụng `chi2_contingency` của thư viện spicy để tính toán, các giá trị tính được từ thư viện và kết luận là: \n
    \n\np-value là: 0.09827321674727184\n\nchi = 2.733346, critical value = 3.841459\n\nVới mức ý nghĩa 0.05, ta bác bỏ HA và chấp nhận H0. \n\nKết luận: sex và smoker độc lập.\n\n\n
    \n
    \n
    \n
    \n
    \n
    \n\nTa kiểm tra, không dùng thư viện, được kết quả như sau:\n \n
    \n\n\n```python\n\n```\n\n chi_square = 2.997908815661011\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
    smokersexcountExpected value(O_ij - E_ij)^2/E_ij
    0nomale391402.0757730.305099
    1yesmale115103.9242271.180406
    2nofemale406394.9242270.310623
    3yesfemale91102.0757731.201781
    \n
    \n\n\n\nTa thấy:\n\n\\begin{equation}\n\\chi^2_v = 2.997908815661011 < 3.841459\n\\end{equation}\n\n
    \n\nVậy bác bỏ ${H_A}$ với mức ý nghĩa 0.05, chấp nhận ${H_0}$ \n\n
    \n\n
    Kết luận: sex và smoker độc lập
    \n \n
    \n\n### 5. Insight: Trung bình của 'age', 'bmi', 'children' giữa người có hút thuốc và người không hút thuốc có bằng nhau\n\n \n
    \nSử dụng z-test ta tính được như sau: \n\n\n
    \n\n$H_0$: trung bình `age` của người có hút thuốc $=$ trung bình `age` của người không hút thuốc\n\n\n$H_A$: trung bình `age` của người có hút thuốc $\\neq$ trung bình `age` của người không hút thuốc\n\nstat=-1.200, p=0.230\n\nKẾT LUẬN: \nVới mức ý nghĩa 0.05, ta chấp nhận Ho, bác bỏ Ha\n\nTrung bình `age` của người có hút thuốc $=$ trung bình `age` của người không hút thuốc\n\n---\n\n$H_0$: trung bình `bmi` của người có hút thuốc $=$ trung bình `bmi` của người không hút thuốc\n\n\n$H_A$: trung bình `bmi` của người có hút thuốc $\\neq$ trung bình `bmi` của người không hút thuốc\n\nstat=-0.047, p=0.962\n\nKẾT LUẬN: \nVới mức ý nghĩa 0.05, ta chấp nhận Ho, bác bỏ Ha\n\nTrung bình `bmi` của người có hút thuốc $=$ trung bình `bmi` của người không hút thuốc\n\n---\n\n$H_0$: trung bình `children` của người có hút thuốc $=$ trung bình `children` của người không hút thuốc\n\n\n$H_A$: trung bình `children` của người có hút thuốc $\\neq$ trung bình `children` của người không hút thuốc\n\nstat=0.807, p=0.420\n\nKẾT LUẬN: \nVới mức ý nghĩa 0.05, ta chấp nhận Ho, bác bỏ Ha\n\nTrung bình `children` của người có hút thuốc $=$ trung bình `children` của người không hút thuốc \n
    \n\n### 6. Insight: Sự phụ thuộc của 'charges' vào 'sex', 'smoker', 'age', 'bmi', 'children'\n\n
    \nTa huấn luyện bằng mô hình OLS Regression:\n\n\n```python\n\n```\n\n OLS Regression Results \n ==============================================================================\n Dep. Variable: charges R-squared: 0.744\n Model: OLS Adj. R-squared: 0.743\n Method: Least Squares F-statistic: 580.0\n Date: Fri, 14 May 2021 Prob (F-statistic): 3.98e-292\n Time: 20:59:36 Log-Likelihood: -10164.\n No. Observations: 1003 AIC: 2.034e+04\n Df Residuals: 997 BIC: 2.037e+04\n Df Model: 5 \n Covariance Type: nonrobust \n ==============================================================================\n coef std err t P>|t| [0.025 0.975]\n ------------------------------------------------------------------------------\n const -1.23e+04 1121.474 -10.968 0.000 -1.45e+04 -1.01e+04\n sex 66.0697 386.570 0.171 0.864 -692.515 824.655\n smoker 2.363e+04 478.849 49.344 0.000 2.27e+04 2.46e+04\n age 260.0358 13.870 18.748 0.000 232.818 287.254\n bmi 327.5600 32.307 10.139 0.000 264.162 390.958\n children 434.8043 160.590 2.708 0.007 119.671 749.938\n ==============================================================================\n Omnibus: 241.068 Durbin-Watson: 2.068\n Prob(Omnibus): 0.000 Jarque-Bera (JB): 592.918\n Skew: 1.268 Prob(JB): 1.78e-129\n Kurtosis: 5.785 Cond. No. 299.\n ==============================================================================\n \n Notes:\n [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n \n
    \n\nKết luận:\n\n- Biến `sex` không có ý nghĩa (có thể loại bỏ)\n- Biến `smoker` có ý nghĩa đối với mô hình về mặt thống kê (với mức ý nghĩa (***) hay p-value = 0.000)\n- Biến `age` có ý nghĩa đối với mô hình về mặt thống kê (với mức ý nghĩa (***) hay p-value = 0.000)\n- Biến `bmi` có ý nghĩa đối với mô hình về mặt thống kê (với mức ý nghĩa (***) hay p-value = 0.000)\n- Biến `children` không có ý nghĩa (có thể loại bỏ)\n- Mô hình có thể giải thích được 74.3% sự thay đổi của biến `charges`\n- Mô hình tương đối tốt (p-value = 1.78e-129)\n\nTa huấn luyện lại mô hình dựa theo kết luận trên\n\n\n```python\n\n```\n\n OLS Regression Results \n ==============================================================================\n Dep. Variable: charges R-squared: 0.742\n Model: OLS Adj. R-squared: 0.741\n Method: Least Squares F-statistic: 959.1\n Date: Fri, 14 May 2021 Prob (F-statistic): 1.63e-293\n Time: 21:00:36 Log-Likelihood: -10168.\n No. Observations: 1003 AIC: 2.034e+04\n Df Residuals: 999 BIC: 2.036e+04\n Df Model: 3 \n Covariance Type: nonrobust \n ==============================================================================\n coef std err t P>|t| [0.025 0.975]\n ------------------------------------------------------------------------------\n const -1.185e+04 1097.537 -10.799 0.000 -1.4e+04 -9698.979\n smoker 2.367e+04 479.257 49.386 0.000 2.27e+04 2.46e+04\n age 262.1450 13.884 18.881 0.000 234.900 289.390\n bmi 326.7252 32.392 10.086 0.000 263.160 390.290\n ==============================================================================\n Omnibus: 238.957 Durbin-Watson: 2.060\n Prob(Omnibus): 0.000 Jarque-Bera (JB): 580.364\n Skew: 1.263 Prob(JB): 9.45e-127\n Kurtosis: 5.741 Cond. No. 291.\n ==============================================================================\n \n Notes:\n [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n```python\n\n```\n\n Parameters: const -11852.720452\n smoker 23668.497446\n age 262.144961\n bmi 326.725200\n dtype: float64\n\n\nTa thấy:\n\n- Cứ tăng 1 tuổi thì chi phí y tế cá nhân tăng 262.144961, tăng 1 chỉ số bmi thì tăng 326.725200 chi phí y tế cá nhân\n- Riêng với smoker, người có hút thuốc thì có chi phí y tế cá nhân cao hơn người không hút thuốc đến 23668.497446\n\n\n
    \n
    \n
    \n
    \n
    \n
    \n
    \n\n## II. Thuật toán sử dụng\n\nTrong lab này, nhóm em sử dụng 2 thuật toán chính là Simple linear regression và Support Vector Regression (SVR) (là một dạng mở rộng của Support Vector MachineMachine). \n\n### 1. Cách thức đánh giá mô hình\n\n\n- Nhóm em sử dụng độ do R-squared để đánh giá mô hình\n- Phương pháp lấy mẫu để đánh giá mô hình là K-Fold Cross-Validation với k = 10\n\n### 2. Thuật toán SVR\n\n#### a. Giới thiệu SVR\n\n**Support Vector Machine (SVM)**\n\nSVM là bài toán phân lớp, và đi tìm mặt phân cách sao cho margin tìm được là lớn nhất, đồng nghĩa với việc các điểm dữ liệu an toàn nhất so với mặt phân cách.\n\n**Support Vector Regression (SVR)**\n\nSVR là một biến thể của SVM để dùng cho bài toán hồi quy. SVR tìm cách cực tiểu margin sao cho có thể chứa nhiều điểm dữ liệu nhất có thể. \n\n\n\n#### b. Sử dụng SVR từ thư viện Scikit-learn\n\nTrước khi trình bày quy trình, nhóm em thống như quy tắt đặt biến như sau: \n- X là một Dataframe đọc từ file train và không bao gồm cột `charges`\n- y là Series chứa dữ liệu của cột `charges`\n- preds là output sau khi chạy mô hình\n- X_test, y_test tương tự như X, y nhưng được đọc từ file test\n\nĐể chọn ra mô hình tốt nhất, nhóm tiến hành các bước như sau\n\n#### Bước 1: Tiền xử lí:\n- Tiền xử lí X: dùng OrdinalEncoder cho cột `sex` và `smoker`, OnehotEncoder cho `region`, StandardScaler cho các cột có kiểu số\n- Tiền xử lý y bằng StandardScaler\n\nTheo các bước tiền xử lí như trên ta được Pipeline như sau:\n\n\n\n#### Bước 2:\n\nChọn tham số cho mô hình SVR với kernel mặc đinh\n\nVới phương pháp lấy mẫu là K-Fold, xem xét độ lỗi trên tập train ta được độ lỗi trung bình đối với từng siêu tham số C và gamma như sau:\n\n\n\nQua đó ta thấy mô hình đạt kết quả tốt nhất trên tập train là 0.828 với C = 10 và gamma = 0.05 \n\n#### Bước 3: Huấn luyện mô hình với các siêu tham số vừa tìm được ở trên\n\nVới các siêu tham số trên thì độ chính xác trên tập test khoảng 0.857\n\n#### c. Thử nghiệm tương tự với các kernel khác\n\nThử nghiệm tương tự với các kernel khác. Kết quả được trình bày cụ thể trong bài làm\n\n#### d. Thử xóa các outlier\n\n\n\nTa thấy nhóm bệnh nhân không hút thuốc có nhiều outlier về chi phí phải trả. Ta thử các outlier này và huấn luyện lại mô hình với các siêu tham số tốt nhất trong các thử nghiệm ở trên. Ta được kết quả như sau:\n\n\n\n\nTa thấy R-squared trên tập train đã tăng lên khá nhiều, đạt 0.899\n\nTuy nhiên khi dùng mô hình này để chạy trên tập test thì kết quả chỉ đạt 0.853. Có thể thấy các bệnh nhân này không phải là các trường hợp bất thường. Mà trong thực tế (tập test) vẫn có khá nhiều bệnh nhân giống như vậy - không hút thuốc nhưng chi phí y tế lại cao. Có thể ta cần thêm các thuộc tính khác như thu nhập, môi trường sống có ô nhiễm hay không... mới có thể dự đoán chi phí cho y tế được chính xác hơn\n\n### 3. Dùng Simple Linear Regression từ thư viện Scikit-learn\n\nTương tự như trên, Pipeline của mô hình là:\n\n\n\nĐối với mô hình này ta chỉ đặt độ chính xác R-squared là 0.766\n\n#### Trực quan hóa mô hình\n\n\n\n### III. Tham khảo\n\n[1]. [Stephanie - Variance Inflation Factor - Statisticshowto.com](https://www.statisticshowto.com/variance-inflation-factor/)\n\n[2]. https://www3.nd.edu/~rwilliam/stats1/x51.pdf\n\n[3]. https://towardsdatascience.com/gentle-introduction-to-chi-square-test-for-independence-7182a7414a95\n\n[4]. https://scikit-learn.org/0.21/documentation.html\n\n[5]. https://machinelearningmastery.com/how-to-transform-target-variables-for-regression-with-scikit-learn/\n", "meta": {"hexsha": "be877942c54c08a109d01cb5ecb1d6d59c7a2a87", "size": 429334, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "report.ipynb", "max_stars_repo_name": "Al3927/charges_regression_analysis", "max_stars_repo_head_hexsha": "e347b8669a2d83b1c8cfb9bd07e6e9f5072f459c", "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": "report.ipynb", "max_issues_repo_name": "Al3927/charges_regression_analysis", "max_issues_repo_head_hexsha": "e347b8669a2d83b1c8cfb9bd07e6e9f5072f459c", "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": "report.ipynb", "max_forks_repo_name": "Al3927/charges_regression_analysis", "max_forks_repo_head_hexsha": "e347b8669a2d83b1c8cfb9bd07e6e9f5072f459c", "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": 296.9114799447, "max_line_length": 71256, "alphanum_fraction": 0.9204908067, "converted": true, "num_tokens": 7526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12940274166401952, "lm_q1q2_score": 0.06268011091289061}} {"text": "# Please download the new class notes.\n### Step 1 : Navigate to the directory where your files are stored. \nOpen a terminal. \n\nUsing `cd`, navigate to *inside* the ILAS_Python_for_engineers folder on your computer. \n\n### Step 3 : Update the course notes by downloading the changes\nIn the terminal type:\n\n>`git add -A`\n\n>`git commit -m \"commit\"`\n\n>`git fetch upstream`\n\n>`git merge -X theirs upstream/master`\n\n\n# Introduction to Data Structures and Imported Libraries (Numpy)\n\n
    Data Structures\n
    Lists \n\t
       __Indexing__ \n\t
       Manipulating Lists \n\t
          FindingLengthList \n
          SortingLists \n
          Removing an Item from a List \n
          Adding an Item to a List \n
          Changing a List Entry \n\t
       __Nested Data Structures__ \n\t
       __Iterating over Lists__ \n
       __Indexing when Iterating over Lists__ \n\t
       `enumerate` \n
       __`zip`__ \n\t
       __Example: The Dot Product__ \n
    Libraries \n
       __The Standard Library__ \n\t
       __Packages__ \n
          __Importing a Package__ \n
          __Using Package Functions__ \n
          __Reading Function Documentation__ \n
          __Example: `numpy.cos`__ \n
          Namespaces \n
          __Importing a Function__ \n
       __Using Package Functions to Optimise your Code__ \n
       __Data Structures as Function Arguments__ \n
    The Numpy Array \n
       __Multi-Dimensional Arrays__ \n
       __Creating a Numpy Array__ \n
       __Indexing into Multi-Dimensional Arrays__- \n
       Boolean Array Indexing \n
       __Iterating over Multi-Dimensional Arrays__ \n
       Manipulating Arrays \n
          Appending Arrays\n
          Adding Elements to an Array \n
          Deleting Items from an Array \n
          Changing Items in an Array \n
    Magic Functions\n
    __Stacking Functions__\n
    __Importing Data from a .csv File to a Numpy Array__\n
    Summary \n
    Test-Yourself Exercises \n
    Review Exercises \n\n\n\n### Lesson Goal\n\nImporting data from a .csv file and perfoming calculations on it using library functions. \n\n### Fundamental programming concepts\n - Working with external files to import:\n - Code\n - Data\n - Storing and representing data e.g. arrays and graphs\n\n\n## Data Structures\n\nIn the last seminar we learnt to generate a range of numbers for use in control flow of a program, using the function `range()`:\n\n\n for j in range(20):\n ...\n \n \nOften we want to manipulate data that is more meaningful than ranges of numbers.\n\nThese collections of variables might include:\n - the results of an experiment\n - a list of names\n - the components of a vector\n - a telephone directory with names and associated numbers.\n \n\nPython has different __data structures__ that can be used to store and manipulate these values.\n\nLike variable types (`string`, `int`,`float`...) different data structures behave in different ways.\n\nToday we will learn to use `list`s and `array`'s. \n\nExample\n\nIf we want to store the names of students in a laboratory group, \nrather than representing each students using an individual string variable, we could use a list of names. \n\n\n\n\n```python\nlab_group0 = [\"Yukari\", \"Sajid\", \"Hemma\", \"Ayako\"]\nlab_group1 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nprint(lab_group0)\nprint(lab_group1)\n```\n\n ['Yukari', 'Sajid', 'Hemma', 'Ayako']\n ['Sara', 'Mari', 'Quang', 'Sam', 'Ryo', 'Nao', 'Takashi']\n\n\nThis is useful because we can perform operations on lists such as:\n - checking its length (number of students in a lab group)\n - sorting the names in the list into alphabetical order\n - making a list of lists (we call this a *nested list*):\n\n\n\n```python\nlab_groups = [lab_group0, lab_group1]\n```\n\n\n## Lists\n\nA list is a sequence of data. \n\nWe call each item in the sequence an *element*. \n\nA list is constructed using square brackets:\n\n\n\n\n```python\na = [1, 2, 3]\n```\n\nA `range` can be converted to a list with the `list` function (casting).\n\n\n```python\nprint(list(range(10)))\n```\n\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\nA list can hold a mixture of types (`int`, `string`....).\n\n\n```python\na = [1, 2.0, \"three\"]\n```\n\nAn empty list is created by\n\n\n```python\nmy_list = []\n```\n\nA list of length 5 with repeated values can be created by\n\n\n```python\nmy_list = [\"Hello\"]*5\nprint(my_list)\n```\n\n ['Hello', 'Hello', 'Hello', 'Hello', 'Hello']\n\n\nWe can check if an item is in a list using the function `in`:\n\n\n\n```python\nprint(\"Hello\" in my_list)\nprint(\"Goodbye\" in my_list)\n```\n\n True\n False\n\n\n\n### Indexing\n\nLists store data in order.\n\nWe can select a single element or multiple elements of a list using the __index__ of the element(s).\n\nYou are familiar with this process; it is the same as selecting individual characters of a string:\n\n\n```python\nword = \"string\"\n\nletter = word[1]\n\nprint(letter)\n```\n\n t\n\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nfirst_member = lab_group0[0]\n\nprint(first_member)\n```\n\n Sara\n\n\nIf we select multiple elements they are returned as a list:\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nfirst_members = lab_group0[0:2]\n\nprint(first_members)\n```\n\n ['Sara', 'Mari']\n\n\nWe can select the individual characters of a string using a second index.\n\nFor example to select the first letter of the second group member's name:\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nletter = lab_group0[1][0]\n\nprint(letter)\n```\n\n M\n\n\n\n### Manipulating Lists \n\nThere are many functions for manipulating lists.\n\nMany of these functions apply to other data structures.\n\n\n\n\n\n\n\n\n\n\n\n\n### Finding the Length of a List\n\nWe can find the length (number of items) of a list using the function `len()`, by including the name of the list in the brackets. \n\nIn the example below, we find the length of the list `lab_group0`. \n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\"]\n\nsize = len(lab_group0)\n\nprint(\"Lab group members:\", lab_group0)\n\nprint(\"Size of lab group:\", size)\n\nprint(\"Check the Python object type:\", type(lab_group0))\n```\n\n Lab group members: ['Sara', 'Mari', 'Quang']\n Size of lab group: 3\n Check the Python object type: \n\n\n\n### Sorting Lists\n\nTo sort the list we use the function `sorted()`.\n\n#### Sorting Numerically\n\nIf the list contains numerical variables, the numbers is sorted in ascending order.\n\n\n```python\nnumbers = [7, 1, 3.0]\n\nprint(numbers)\n\nnumbers = sorted(numbers)\n\nprint(numbers)\n```\n\n [7, 1, 3.0]\n [1, 3.0, 7]\n\n\n__Note:__ We can sort a list with mixed numeric types (e.g. `float` and `int`). \n\nHowever, we cannot sort a list with types that cannot be sorted by the same ordering rule. \n\n(e.g. `numbers = sorted([\"7\", 1, 3.0])` causes an error.)\n\n\n```python\n\n\n\n```\n\n#### Sorting Alphabetically\n\nIf the list contains strings of alphabet characters, the list is sorted by alphabetical order. \n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\"]\n\nprint(lab_group0)\n\nlab_group0 = sorted(lab_group0)\n\nprint(lab_group0)\n```\n\n ['Sara', 'Mari', 'Quang']\n ['Mari', 'Quang', 'Sara']\n\n\nAs with `len()` we include the name of the list we want to sort in the brackets. \n\n`sort` is known as a 'method' of a `list`. \n\nIf we suffix a list with `.sort()`, it performs an *in-place* sort.\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\"]\n\nprint(lab_group0)\n\n#lab_group0 = sorted(lab_group0)\nlab_group0.sort()\n\nprint(lab_group0)\n```\n\n ['Sara', 'Mari', 'Quang']\n ['Mari', 'Quang', 'Sara']\n\n\n__Try it yourself__\n\nIn the cell provided in your textbook create a list of __numeric__ or __string__ values.\n\nSort the list using `sorted()` __or__ `.sort()`.\n\nPrint the sorted list.\n\nPrint the length of the list using `len()`.\n\n\n```python\n# Sorting a list\n```\n\n\n### Removing an Item from a List\n\nWe can remove items from a list using the method `pop`.\n\nWe place the index of the element we wish to remove in brackets. \n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\"]\nprint(lab_group0)\n\n# Remove the second student from the list: lab_group (remember indexing starts from 0 so 1 is the second element)\n\nlab_group0.pop(1)\nprint(lab_group0)\n```\n\n ['Sara', 'Mari', 'Quang', 'Sam', 'Ryo']\n ['Sara', 'Quang', 'Sam', 'Ryo']\n\n\n\n```python\n# By default, pop removes the last element\n\nlab_group0.pop()\nprint(lab_group0)\n```\n\n ['Sara', 'Quang', 'Sam']\n\n\n\n```python\n# Pop can by used to assign the removed value to a variable name\n\ngroup_member = lab_group0.pop(1)\nprint(lab_group0)\nprint(group_member)\n```\n\n ['Sara', 'Sam']\n Quang\n\n\n\n### Adding an Item to a List\n\nWe can add items to a list using the method `insert`.\n\nWe place the desired index of new element in brackets. \n\n\n```python\n# Add new student \"Mark\" to the list\nlab_group0.insert(2, \"Mark\")\nprint(lab_group0)\n```\n\n ['Sara', 'Sam', 'Mark']\n\n\nWe can add items at the end of a list using the method `append`.\n\nWe place the element we want to add to the end of the list in brackets. \n\n\n```python\n# Add new student \"Lia\" at the end of the list\nlab_group0.append(\"Lia\")\nprint(lab_group0)\n```\n\n ['Sara', 'Sam', 'Mark', 'Lia']\n\n\n\n### Changing a List Entry.\nWe can change the entry of a list using indexing.\n\n\n```python\nlab_group0[3] = \"Am\"\nprint(lab_group0)\n\n# Adding and removing items from a list.\n```\n\n ['Sara', 'Sam', 'Mark', 'Am']\n\n\n__Try it yourself__\n\nIn the cell provided in your textbook.\n\nRemove \"Sara\" from the list.\n\nPrint the new list.\n\nAdd a new lab group member, Tom, to the list.\n\nPrint the new list.\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\"]\nprint(lab_group0)\n\n# Adding and removing items from a list.\n```\n\n ['Sara', 'Mari', 'Quang', 'Sam', 'Ryo']\n\n\n\n### Nested Data Structures: Lists of Lists\n\nA *nested list* is a list within a list. \n\n(Recall *nested loops* from the last seminar 1; Control Flow). \n\n\n\nTo access a __single element__ we need as many indices as there are levels of nested list. \n\nThis is more easily explained with an example:\n\n`lab_groups` is a nested list containing the lists:\n - `lab_group0`\n - `lab_group1`\n - `lab_group2`\n\n\n```python\nlab_group0 = [\"Sara\", \"Mika\", \"Ryo\", \"Am\"]\nlab_group1 = [\"Hemma\", \"Miri\", \"Quy\", \"Sajid\"]\nlab_group2 = [\"Adam\", \"Yukari\", \"Farad\", \"Fumitoshi\"]\n\nlab_groups = [lab_group0, lab_group1, lab_group2]\n```\n\nTo select and element from `lab_group1` we:\n- first give the index of `lab_group1` in th list `lab_groups`\n- second give the index of the element within `lab_group1`\n\n\n```python\ngroup = lab_groups[1]\nprint(group)\n\nname = lab_groups[1][2]\nprint(name)\n```\n\n ['Hemma', 'Miri', 'Quy', 'Sajid']\n Quy\n\n\n\n### Iterating over Lists\n\nLooping over each item in a list is called *iterating*. \n\nTo iterate over a list of the lab group we can use a `for` loop.\n\n\n\nIn the following example, each iteration, variable `d` takes the value of the next item in the list:\n\n\n```python\nfor d in [1, 2.0, \"three\"]: \n print(\"the value of d is:\", d)\n```\n\n the value of d is: 1\n the value of d is: 2.0\n the value of d is: three\n\n\nWe could also express this as:\n\n\n```python\ndata = [1, 2.0, \"three\"]\n\nfor d in data: \n print(\"the value of d is:\", d)\n```\n\n the value of d is: 1\n the value of d is: 2.0\n the value of d is: three\n\n\nIterating backwards over a list can be acheived using the built in `reversed` function.\n\n\n```python\ndata = [1, 2.0, \"three\"]\n\nfor d in reversed(data): \n print(\"the value of d is:\", d)\n```\n\n the value of d is: three\n the value of d is: 2.0\n the value of d is: 1\n\n\n__Try it yourself__\n\n\nIn the cell provided in your textbook *iterate* over the list `data = [1, 2.0, \"three\"]`.\n\nEach time the code loops:\n1. print the value of data __cast as a string__ (Seminar 1 Data Types and Operators)\n1. print the variable type
    (to demonstrate that the variable has been cast. Note that otherwise the variable appears to remain unchanged).\n\n\n```python\n# Iterate over a list and cast each item as a string\ndata = [1, 2.0, \"three\"]\n```\n\n\n### Indexing when Iterating over Lists\nIndexing can be useful when iterating over a list.\n\n\n\nFor example, we can select a range of elements to iterate over:\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nfor member in lab_group0[2:5]: \n print(\"name:\", member)\n```\n\n name: Quang\n name: Sam\n name: Ryo\n\n\nA third value can used to choose a step size (similar to `range()`).\n\nFor example, if we want to choose every other lab member we use step size, 2:\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nfor member in lab_group0[::2]: \n print(\"name:\", member)\n```\n\n name: Sara\n name: Quang\n name: Ryo\n name: Takashi\n\n\n__Note:__
    \nSome data structures that support *iterating* but do not support *indexing*.\n\ne.g. dictionaries, which we will learn about later. \n\nWhen possible, it is better to iterate over a list rather than use indexing.\n\n\n### `enumerate()`\nThe function `enumerate` can be used to return the index of each element.\n
    This information is cast as a list to allow us to read it.\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\na = enumerate(lab_group0)\nb = list(enumerate(lab_group0))\nprint(a)\nprint(b)\n\n\n```\n\n \n [(0, 'Sara'), (1, 'Mari'), (2, 'Quang'), (3, 'Sam'), (4, 'Ryo'), (5, 'Nao'), (6, 'Takashi')]\n\n\n\n```python\nstring = \"string\"\na = list(enumerate(string))\nprint(a)\n```\n\n [(0, 's'), (1, 't'), (2, 'r'), (3, 'i'), (4, 'n'), (5, 'g')]\n\n\n\n### Iterating Over Multiple Lists Using `zip()`\nIt can be very useful to iterate through multiple lists within the same loop. than one list.\n\nFor example if we have a list of group members and a list of their scores for an assignemt, we can print the score that corresponds to each lab member:\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nassignment1 = [72, 56, 65, 52, 71, 60]\n\nfor member, score in zip(lab_group0, assignment1): \n \n print(member, \": score =\", score)\n```\n\n Sara : score = 72\n Mari : score = 56\n Quang : score = 65\n Sam : score = 52\n Ryo : score = 71\n Nao : score = 60\n\n\nIn this example \n\n`member` is the name given to the *current* value from the list `lab_group0`\n\n`score` is the names given to the *current* value from the list `assignment1`. \n\n\nWe can include any number of lists in `zip`.\n\nFor example it may be useful to print the combined score a lab member has achieved for all assigments this semester:\n\n\n```python\nlab_group0 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nassignment1 = [72, 56, 65, 52, 71, 60]\nassignment2 = [52, 61, 73, 55, 62, 55]\nassignment3 = [71, 71, 70, 66, 61, 71]\n\nfor member, score1, score2, score3 in zip(lab_group0, \n assignment1, \n assignment2, \n assignment3): \n print(member, \": score =\", (score1 + score2 + score3))\n```\n\n Sara : score = 195\n Mari : score = 188\n Quang : score = 208\n Sam : score = 173\n Ryo : score = 194\n Nao : score = 186\n\n\n\n### Example: The Dot Product (Representing Vectors using Lists)\n\n__Vector:__ A quantity with magnitude and direction.\n\nThe position vector $\\mathbf{r}$ indicates the position of a point in 3D space.\n$\\mathbf{r}$ can be expressed in terms of x,y, and z-directions.\n\n$$\n\\mathbf{r} = x\\mathbf{i} + y\\mathbf{j} + z\\mathbf{k}\n$$\n\n$\\mathbf{i}$ is the displacement one unit in the x-direction
    \n$\\mathbf{j}$ is the displacement one unit in the y-direction
    \n$\\mathbf{k}$ is the displacement one unit in the z-direction\n\n\n\n\n\nWe can conveniently express $\\mathbf{r}$ in matrix (or basis vector) form using the coefficients $x, y$ and $z$: \n$$\n\\mathbf{r} = [x, y, z]\n$$\n\n__...which looks a lot like a Python list!__\n\n\nYou will encounter 3D vectors a lot in your engineering studies.\n\nThey are used to describe many physical quantities, e.g. force.\n\nThe __dot product__ is a really useful algebraic operation.\n\nIt takes two equal-length *sequences of numbers* (often coordinate vectors) and returns a single number. \n \n\n__ALGEBRAIC REPRESENTATION OF THE DOT PRODUCT__\n\nThe dot product of two $n$-length-vectors:\n
    $ \\mathbf{A} = [A_1, A_2, ... A_n]$\n
    $ \\mathbf{B} = [B_1, B_2, ... B_n]$\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} = \\sum_{i=1}^n A_i B_i\n\\end{align}\n\n\n\nSo the dot product of two 3D vectors:\n
    $ \\mathbf{A} = [A_x, A_y, A_z]$\n
    $ \\mathbf{B} = [B_x, B_y, B_z]$\n\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} &= \\sum_{i=1}^n A_i B_i \\\\\n&= A_x B_x + A_y B_y + A_z B_z\n\\end{align}\n\n\n\n__Example : Dot Product__\n\nLet's write a program to solve this using a Python `for` loop.\n\n1. We initailise a variable, `dot_product` with a value = 0.0.\n\n1. With each iteration of the loop:\n
    `dot_product +=` the product of `a` and `b`. \n\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
    $ \\mathbf{A} = [1, 3, −5]$\n
    $ \\mathbf{B} = [4, −2, −1]$\n\n\n\n\\begin{align}\n {\\displaystyle {\\begin{aligned}\\ [1,3,-5]\\cdot [4,-2,-1]&=(1)(4)+(3)(-2)+(-5)(-1)\\\\& = 4 \\qquad - 6 \\qquad + 5 \\\\&=3\\end{aligned}}} \n\\end{align}\n\n\n## Libraries\n\nOne of the most important concepts in good programming is to reuse code and avoid repetitions.\n\nPython, like other modern programming languages, has an extensive *library* of built-in functions. \n\nThese functions are designed, tested and optimised by the developers of the Python langauge. \n\nWe can use these functions to make our code shorter, faster and more reliable.\n\n \n\n\n## The Standard Library\n\nPython has a large standard library. \n\ne.g. `print()` takes the __input__ in the parentheses and __outputs__ a visible representation.\n\nThey are listed on the Python website:\nhttps://docs.python.org/3/library/functions.html\n\nWe could write our own code to find the minimum of a group of numbers\n\n\n\n\n\n```python\nx0 = 1\nx1 = 2\nx2 = 4\n\nx_min = x0\nif x1 < x_min:\n x_min = x1\nif x2 < x_min:\n x_min = x2\n \nprint(x_min)\n```\n\n 1\n\n\nHowever, it is much faster to use the build-in function:\n\n\n```python\nprint(min(1,2,4))\n```\n\n 1\n\n\nPython built-in functions are simply a collection of Python (.py) files called 'modules'.\n\nThese files are stored on the computer you are using.\n\n__Function:__\n
    A function is a piece of code that is called by name. \n
    It can be *passed* data to operate on (i.e., the parameters) and can optionally *return* data (the return value). \n\n__Example__\n\n\n```python\na = [5, 2, 3, 1, 4]\nprint(sorted(a))\n```\n\n [1, 2, 3, 4, 5]\n\n\n__Method:__\nA method is a piece of code that is called by name.\n
    It is already associated with an object type (e.g. a list) so it is expressed after a . dot at the end of the object name. \n
    It mostly behaves the same as a function except: \n- It is automatically passed for the object which it is attached to.\n- (It can only operate on objects that contain the method. It can operate on data insde of that class.) \n\n__Example__\n\n\n```python\na = [1, 5, 2, 7, 5]\na.sort()\nprint(a)\n```\n\n [1, 2, 5, 5, 7]\n\n\nA quick google search for \"python function to sum all the numbers in a list\"...\n\nhttps://www.google.co.jp/search?q=python+function+to+sum+all+the+numbers+in+a+list&rlz=1C5CHFA_enJP751JP751&oq=python+function+to+sum+&aqs=chrome.0.0j69i57j0l4.7962j0j7&sourceid=chrome&ie=UTF-8\n\n...returns the function `sum()`.\n\n`sum()` finds the sum of the values in a data structure.\n\n\n\n\n\n\n```python\nprint(sum([1,2,3,4,5]))\n\na = [1,2,3,4,5]\nprint(sum(a))\n```\n\n 15\n 15\n 15\n\n\nThe function `max()` finds the maximum value in data structure.\n\n\n## Packages\n\nThe standard library tools are available in any Python environment.\n\nMore specialised libraries, called packages, are available for more specific tasks \n
    e.g. solving trigonometric functions.\n\nPackages contain functions and constants. \n\nWe install the packages to use them. \n\n\n\nTwo widely used packages for mathematics, science and engineeirng are `NumPy` and `SciPy`.\n\nThese are already installed as part of Anaconda.\n\nA package is a collection of Python modules: \n- a __module__ is a single Python file\n- a __package__ is a directory of Python modules.
    (It contains an __init__.py file, to distinguish it from folders that are not libraries).\n\nThe files that are stored on your computer when Numpy is installed:\n
    https://github.com/numpy/numpy\n\n\n### Importing a Package\n\nTo use an installed package, we simply `import` it. \n\n\n```python\nimport numpy \n\nx = 1\n\ny = numpy.cos(x)\n\nprint(y)\n\nprint(numpy.pi)\n```\n\n 0.540302305868\n 3.141592653589793\n\n\nThe `import` statement must appear before the use of the package in the code. \n\n import numpy \n\nAfter this, any function in `numpy` can be called as:\n\n `numpy.function()`\n \nand, any constant in `numpy` can be called as:\n\n `numpy.constant`.\n\nThere are a many mathematical functions available.
    \nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n\nWe can change the name of a package e.g. to keep our code short and neat.\n\nUsing the __`as`__ keyword:\n\n\n```python\nimport numpy as np\nprint(np.pi)\n```\n\n 3.141592653589793\n\n\nWe only need to import a package once, at the start of the program or notebook.\n\n\n## Using Package Functions. \n\nLet's learn to use `numpy` functions in our programs. \n\n\n\n\n\n\n```python\n# Some examples Numpy functions with their definitions (as given in the documentation)\n\nx = 1\n\n# Trigonometric sine\nprint(np.sin(x))\n\n# Compute tangent \nprint(np.tan(x))\n\n# Trigonometric inverse tangent\nprint(np.arctan(x))\n\n\n```\n\n 0.841470984808\n 1.55740772465\n 0.785398163397\n\n\n\n```python\nx = 1\n\n# Convert angles from radians to degrees\ndegrees = np.degrees(x)\nprint(degrees)\n\n# Convert angles from degrees to radians\nradians = np.radians(degrees)\nprint(radians) \n```\n\n 57.2957795131\n 1.0\n\n\n\n## Reading Function Documentation\n\nOnline documentation can be used to find out: \n- what to include in the () parentheses\n- allowable data types to use as arguments\n- the order in which arguments should be given \n\n\nA google search for 'numpy functions' returns:\n\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n\n(this list is not exhaustive). \n\n__Try it yourself:__\n
    Find a function in the Python Numpy documentation that matches the function definition and use it to solve the following problem: \n\nGiven the “legs” of a right angle triangle, return its hypotenuse.
    If the lengths of the two shorter sides of a right angle triangle are 6 units and 3 units, what is the length of the hypotenuse?\n\n\n```python\n# The “legs” of a right angle triangle are 6 units and 3 units, \n# Return its hypotenuse in units.\n```\n\n\n### Example : numpy.cos\nDocumentation : https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html \n\nThe documentation tells us the following information...\n\n##### What the function does.\n\"Cosine element-wise.\"\n\n\n\n##### All possible function arguments (parameters)\n\n \n\n>numpy.cos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True [, signature, extobj ]) \n\nIn the () parentheses following the function name are:\n- *positional* arguments (required)\n- *keyword* arguments (with a default value, optionally set). Listed after the `/` slash.\n- arguments that must be explicitly named. Listed after the `*` star. \n
    (including arguments without a default value. Listed in `[]` brackets.)\n\n\n\n##### Function argument definitions and acceptable forms. \n\n \n\nx : array_like *(it can be an `int`, `float`, `list` or `tuple`)*\n\nout : ndarray, None, or tuple of ndarray and None, optional\n\nwhere : array_like, optional \n\n\n\n##### What the function returns\n__y__ : ndarray
    \n        The corresponding cosine values.\n\nLet's look at the function numpy.degrees:\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.degrees.html\n\nWhat does the function do?\n\nWhat __arguments__ does it take (and are there any default arguments)? \n\nHow would we __write__ the function when __calling__ it (accept defaults)?\n\nWhat __data type__ should our input be? \n\n\n## Namespaces\n
    By prefixing `cos` with `np`, we are using a *namespace* (which in this case is `np`).\n\n\n\nThe namespace shows we want to use the `cos` function from the Numpy package.\n\nIf `cos` appears in more than one package we import, then there will be more than one `cos` function available.\n\nWe must make it clear which `cos` we want to use. \n\n\n\n\nOften, functions with the same name, from different packages, will use a different algorithms for performing the same or similar operation. \n\nThey may vary in speed and accuracy. \n\nIn some applications we might need an accurate method for computing the square root, for example, and the speed of the program may not be important. For other applications we might need speed with an allowable compromise on accuracy.\n\n\nBelow are two functions, both named `sqrt`. \n\nBoth functions compute the square root of the input.\n\n - `math.sqrt`, from the package, `math`, gives an error if the input is a negative number. It does not support complex numbers.\n - `cmath.sqrt`, from the package, `cmath`, supports complex numbers.\n\n\n\n```python\nimport math\nimport cmath\nprint(math.sqrt(4))\n#print(math.sqrt-5)\n#print(cmath.sqrt(-5))\n```\n\n 2.0\n\n\nTwo developers collaborating on the same program might choose the same name for two functions that perform similar tasks. \n\nIf these functions are in different modules, there will be no name clash since the module name provides a 'namespace'. \n\n\n## Importing a Function\nSingle functions can be imported without importing the entire package e.g. use:\n\n from numpy import cos\n\ninstead of:\n\n import numpy \n\nAfter this you call the function without the numpy prefix: \n\n\n```python\nfrom numpy import cos\n\ncos(x)\n```\n\n\n\n\n 0.54030230586813977\n\n\n\nBe careful when doing this as there can be only one definition of each function.\nIn the case that a function name is already defined, it will be overwritten by a more recent definition. \n\n\n```python\nfrom cmath import sqrt\nprint(sqrt(-1))\nfrom math import sqrt\n#print(sqrt(-1))\n```\n\n 1j\n\n\nA potential solution to this is to rename individual functions or constants when we import them:\n\n\n```python\nfrom numpy import cos as cosine\n\ncosine(x)\n```\n\n\n\n\n 0.54030230586813977\n\n\n\n\n```python\nfrom numpy import pi as pi\npi\n```\n\n\n\n\n 3.141592653589793\n\n\n\nThis can be useful when importing functions from different modules:\n\n\n```python\nfrom math import sqrt as square_root\nfrom cmath import sqrt as complex_square_root\n\nprint(square_root(4))\nprint(complex_square_root(-1))\n```\n\n 2.0\n 1j\n\n\nFunction names should be chosen wisely.\n - relevant\n - concise\n\n##### Try it yourself\nIn the cell below, copy and paste the `bisection` function you wrote for __Seminar 4: Review Excercise: Using Functions as Function Arguments.__\n\nDemonstrate that your `bisection` function works correctly by finding the zero of the Numpy $\\cos(x)$ function that lies in the interval $x_1=0$ to $x_2=3$. \n\n\n```python\n# Bisection\n```\n\n\n## Using Package Functions to Optimise your Code\n\nLet's look at some examples of where Numpy functions can make your code shorter and neater.\n\nThe mean of a group of numbers\n\n\n```python\nx_mean = (1 + 2 + 3)/3 \n```\n\nUsing Numpy:\n\n\n```python\nx_mean = np.mean([1, 2, 3])\n```\n\n\n## Data Structures as Function Arguments. \n\nNotice that the Numpy function `mean` take a lists as its argument.\n\nThe list data structure is required for the function to work. \n\n\n```python\nls = [1, 2, 3]\nx_mean = np.mean(ls)\n```\n\n\n### Elementwise Functions\nNumpy functions often operate *elementwise*. \n
    This means if the argument is a list, they will perform the same function on each element of the list.\n\nFor example, to find the square root of each number in a list, we can use:\n\n\n```python\na = [9, 25, 36]\nprint(np.sqrt(a))\n```\n\n [ 3. 5. 6.]\n\n\nElementwise operation can be particularly important when performing basic mathematical operations:\n\n\n```python\na = [1, 2, 3]\nb = [4, 5, 6]\nimport numpy as np\n\nprint(a + b)\nprint(np.add(a,b))\n```\n\n [1, 2, 3, 4, 5, 6]\n [5 7 9]\n\n\nNumpy has its own data structure that is more suitable for handling numerical data.\n\n\n## The Numpy `Array`\n\nA numpy array is a grid of values, *all of the same type*.\n\n\n\n### Why do we need another data structure?\n\nPython lists hold 'arrays' of data. \n\nLists are very flexible. e.g. holding mixed data type.\n\nThere is a trade off between flexibility and performance e.g. speed.\n\nScience engineering and mathematics problems often involve large amounts of data and numerous operations. \n\nWe therefore use specialised functions and data structures for numerical computation.\n\nTo create an array we use the Numpy `np.array()` function.\n\nWe can create an array in a number of ways.\n\nFor example we can convert a list to an array. \n\n\n```python\nc = [4.0, 5, 6.0]\n\nd = np.array(c) \n\nprint(type(c))\nprint(type(d))\nprint(d.dtype)\n\nprint(c + c)\nprint(d + d)\n```\n\n \n \n float64\n [4.0, 5, 6.0, 4.0, 5, 6.0]\n [ 8. 10. 12.]\n\n\nThe method `dtype` tells us the type of the data contained in the array.\n\n\n\n\n## Multi-Dimensional Arrays.\n\nUnlike the data types we have studied so far, arrays can have multiple dimensions.\n\n__`shape`:__ a *tuple* of *integers* giving the *size* of the array along each *dimension*.\n\n__`tuple`:__ A data structure from which you cannot add or remove elements without creating a new tuple (e.g. connecting two tuples).
    You cannot change the value of a single tuple element e.g. by indexing.
    A tuple is created by enclosing a set of numbers in () parentheses. \n\nWe define the dimensions of an array using square brackets\n\n\n```python\n# 1-dimensional array\na = np.array([1, 2, 3])\n\n# 2-dimensional array\nb = np.array([[1, 2, 3], [4, 5, 6]])\n\nb = np.array([[1, 2, 3], \n [4, 5, 6]])\n\nprint(a.shape)\nprint(b.shape)\n\n```\n\n (3,)\n (2, 3)\n\n\n\n```python\n# 2-dimensional array\nc = np.array([[1, 2, 3]])\n\n# 2-dimensional array\nd = np.array([[1], \n [4]])\n\nprint(c.shape)\nprint(d.shape)\n```\n\n (1, 3)\n (2, 1)\n\n\n\n```python\n# 3-dimensional array\n\nc = np.array(\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]])\n\nprint(c.shape)\n\nc = np.array(\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]])\n\nprint(c.shape)\n```\n\n (2, 2, 2)\n (3, 2, 2)\n\n\n\n```python\n# 3-dimensional array\n\nc = np.array(\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]])\n\n# 4-dimensional array\nd = np.array(\n [[[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]],\n\n\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]]])\n\nprint(c.shape)\nprint(d.shape)\n```\n\n (2, 2, 2)\n (2, 2, 2, 2)\n\n\n\n## Creating a Numpy Array.\n\nWe don't always have to manually create the individual elements of an array.\n\nThere are several other ways to do this.\n\nFor example, if you don’t know what data you want to put in your array you can initialise it with placeholders and load the data you want to use later. \n\n\n\n```python\n# Create an array of all zeros\n# The zeros() function argument is the shape.\n# Shape: tuple of integers giving the size along each dimension.\n\na = np.zeros(5)\nprint(a)\n\nprint()\n\na = np.zeros((2,2)) \nprint(a) \n```\n\n [ 0. 0. 0. 0. 0.]\n \n [[ 0. 0.]\n [ 0. 0.]]\n\n\n\n```python\n# Create an array of all ones\n\nb = np.ones(5)\nprint(b)\n\nprint()\n\nb = np.ones((1, 4)) \nprint(b) \n\n```\n\n [ 1. 1. 1. 1. 1.]\n \n [[ 1. 1. 1. 1.]]\n\n\n\n```python\n# Create an array of elements with the same value \n# The full() function arguments are\n# 1) Shape: tuple of integers giving the size along each dimension.\n# 2) The constant value\n\ny = np.full((1,1), 3)\nprint(y)\nprint(y.shape)\n\nprint()\n\ny = np.full((2,2), 4) \nprint(y) \n```\n\n [[3]]\n (1, 1)\n \n [[4 4]\n [4 4]]\n\n\n\n```python\n# Create a 1D array of evenly spaced values\n# The arange() function arguments are the same as the range() function. \n# Shape: tuple of integers giving the size along each dimension.\n\nz = np.arange(5,10)\nprint(z)\n\nprint()\n\nz = np.arange(5, 10, 2) \nprint(z) \n```\n\n [5 6 7 8 9]\n \n [5 7 9]\n\n\n\n```python\n# Create a 1D array of evenly spaced values\n# The linspace() function arguments are\n# The lower limit of the range of values\n# The upper limit of the range of values (inclusive)\n# The desired number of equally spaced values\n\nz = np.linspace(-4, 4, 5)\nprint(z) \n```\n\n [-4. -2. 0. 2. 4.]\n\n\n\n```python\n# Create an empty matrix\n# The empty() function argument is the shape.\n# Shape: tuple of integers giving the size along each dimension.\nimport numpy as np\nx = np.empty((4))\nprint(x)\n\nprint()\n\nx = np.empty((4,4))\nprint(x)\n```\n\n [ 4. 2. 2. 4.]\n \n [[ 4.94065646e-324 4.94065646e-324 4.94065646e-324 4.94065646e-324]\n [ 4.94065646e-324 4.94065646e-324 4.94065646e-324 4.94065646e-324]\n [ 4.94065646e-324 4.94065646e-324 4.94065646e-324 4.94065646e-324]\n [ 4.94065646e-324 4.94065646e-324 4.94065646e-324 4.94065646e-324]]\n\n\n\n```python\n# Create a constant array\n# The second function argument is the constant value\n\nc = np.full(6, 8)\nprint(c)\n\nprint()\n\nc = np.full((2,2,2), 7) \nprint(c) \n\n```\n\n [8 8 8 8 8 8]\n \n [[[7 7]\n [7 7]]\n \n [[7 7]\n [7 7]]]\n\n\n\n## Indexing into Multi-Dimensional Arrays.\n\nWe can index into an array exactly the same way as the other data structures we have studied.\n\n\n```python\nx = np.array([1, 2, 3, 4, 5])\n\n# Select a single element\nprint(x[4])\n\n# Select elements from 2 to the end\nprint(x[2:])\n```\n\n 5\n [3 4 5]\n\n\nFor an n-dimensional (nD) matrix we need n index values to address an element or range of elements.\n\nExample: The index of a 2D array is specified with two values:\n- first the row index\n- then the column index.\n\nNote the order in which dimensions are addressed.\n\n\n```python\n# 2 dimensional array\n\ny = np.array([[1, 2, 3], \n [4, 5, 6]])\n\n\n# Select a single element\nprint(y[1,2])\n\n# Select elements that are both in rows 1 to the end AND columns 0 to 2 \nprint(y[1:, 0:2])\n```\n\n 6\n [[4 5]]\n\n\nWe can address elements by selecting a range with a step: \n\nFor example the index:\n\n`z[0, 0:]`\n\nselects every element of row 0 in array, `z`\n\nThe index:\n\n`z[0, 0::2]`\n\nselects every *other* element of row 0 in array, `z`\n\n\n```python\n# 2 dimensional array\n\nz = np.zeros((4,8))\n\n# Change every element of row 0\nz[0, 0:] = 10\n\n# Change every other element of row 1\nz[1, 0::2] = 10\n\nprint(z)\n```\n\n [[ 10. 10. 10. 10. 10. 10. 10. 10.]\n [ 10. 0. 10. 0. 10. 0. 10. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0.]]\n\n\n\n```python\nz = np.zeros((4,8))\n\n# Change the last 4 elements of row 2, in negative direction\n# You MUST include a step to count in the negative direction\nz[2, -1:-5:-1] = 10\n\n# Change every other element of the last 6 elements of row 3\n# in negative direction\nz[3, -2:-7:-2] = 10\n\nprint(z)\n```\n\n [[ 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 10. 10. 10. 10.]\n [ 0. 0. 10. 0. 10. 0. 10. 0.]]\n\n\n\n```python\n# 3-dimensional array\n\nc = np.array(\n [[[2, 1, 4],\n [2, 6, 8]],\n \n [[0, 1, 5],\n [7, 8, 9]]])\n\nprint(c[0, 1, 2])\n\n\n```\n\n 8\n\n\nWhere we want to select all elements in one dimension we can use :\n\n__Exception__: If it is the last element , we can omit it. \n\n\n```python\nprint(c[0, 1])\n\nprint(c[0, :, 1])\n```\n\n [2 6 8]\n [1 6]\n\n\n\n### BooleanArrayIndexing\n\nRecall that we can use *conditional operators* to check the value of a single variable against a condition.\n\nThe value returned is a Boolean True or False value.\n\n\n\n```python\na = 4\nprint('a < 2:', a < 2)\nprint('a > 2:', a > 2)\n```\n\n a < 2: False\n a > 2: True\n\n\nIf we instead use *conditional operators* to check the value of an array against a condition.\n\nThe value returned is an *array* of Boolean True or False values.\n\n\n```python\na = np.array([[1,2], \n [3, 4], \n [5, 6]])\n\nidx = a > 2\n\nprint(idx)\n\n```\n\n [[False False]\n [ True True]\n [ True True]]\n\n\nA particular elements of an array can be are specified by using a boolean array as an index. \n\nOnly the values of the array where the boolean array is `True` are selected. \n\nThe varaible `idx` can therefore now be used as the index to select all elements greater than 2.\n\n\n```python\nprint(a[idx]) \n```\n\n [3 4 5 6]\n\n\nTo do the whole process in a single step\n\n\n```python\nprint(a[a > 2]) \n```\n\n [3 4 5 6]\n\n\nTo apply multiple conditions, use () parentheses to sperate different conditions.\n\nUse `&` for elementwise `and`.\n\nUse `|` for elementwise `or`.\n\n\n```python\nx = np.array([[4, 2, 3, 1],\n [2, 4, 2, 8],\n [2, 3, 3, 27],\n [4, 1, 4, 64]])\n\n# elements of x that are greater then 2 AND less than 10\nprint(x[(2 < x) & (x < 10)])\n\n# elements of x that are less then 2 OR greater than 10\nprint(x[(2 < x) & (x < 10)])\n```\n\n [4 3 4 8 3 3 4 4]\n [4 3 4 8 3 3 4 4]\n\n\nMultiple conditions can also be applied to a subsection of an array.\n
    For example to select elements $>2$ and $<4$ in the first row of `x` only (`x[0]`):\n\n\n```python\nx = np.array([[4, 2, 3, 1],\n [2, 4, 2, 8],\n [2, 3, 3, 27],\n [4, 1, 4, 64]])\n\n\nprint(x[0][(2 < x[0]) & (x[0] < 4)])\n\n```\n\n [3]\n\n\n\n## Iterating over Multi-Dimensional Arrays. \nWe can iterate over a 1D array in the same way as the data structures we have previously studied.\n\n\n```python\nA = np.array([1, 2, 3, 4, 5])\n```\n\n\n```python\nfor a in A:\n print(a)\n```\n\n 1\n 2\n 3\n 4\n 5\n\n\nTo loop through individual elements of a multi-dimensional array, we use a nested loop for each dimension of the array.\n\n\n```python\nB = np.array([[1, 2, 3], \n [4, 5, 6]])\n\nfor row in B:\n print(\"-----\")\n for col in row:\n print(col)\n```\n\n -----\n 1\n 2\n 3\n -----\n 4\n 5\n 6\n\n\n\n## Manipulating Arrays\nWe can use many of the same operations to manipulate arrays as we use for lists.\n\nHowever, it is important to note a few subtle differences in how array manipulations behave. \n\n\n```python\n# Length of an array\n\na = np.array([1, 3, 4, 17, 3, 21, 2, 12])\n\nb = np.array([[1, 3, 4, 17],\n [3, 21, 2, 12]])\n\n\nprint(len(a))\nprint(len(b))\n\n\n```\n\n 8\n 2\n\n\nNote the length is the length of the first dimension (e.g. indexing). \n\n\n```python\n# Sort an array\n\na = np.array([1, 3, 4, 17, 3, 21, 2, 12])\n\nb = np.array([[1, 3, 4, 17],\n [3, 21, 2, 12]])\n\n# The function sorted applies to 1D data structures only\nprint(sorted(a))\nprint(sorted(b[1]))\n\n# The method sort() applies to arrays of any size\na.sort()\nb.sort()\n\nprint(a)\nprint(b)\n```\n\n [1, 2, 3, 3, 4, 12, 17, 21]\n [2, 3, 12, 21]\n [ 1 2 3 3 4 12 17 21]\n [[ 1 3 4 17]\n [ 2 3 12 21]]\n\n\nArrays are *immutable* (unchangeable).\n\nTechnically you cannot add or delete items of an array. \n\nHowever, you can make a *new* array (which may have the same name as the original array), with the values ammended as required: \n\n\n#### Appending Arrays \nAppending connects array-like (integer, list....) value to the *end* of the original array. \n\nBy default, 2D arrays are appended as if joining lists.\nThe new array is a 1D array\n\n\n```python\n# 2D array\na = np.array([[0], [1], [2]])\nprint(a)\nprint()\n\n# 2D array\nb = np.array([[3], [4]])\nprint(b)\nprint()\n\n# 1D array\nc = np.array([3, 4])\nprint(b)\nprint()\n\n# integer\nd = 1\n\nprint(f\"original 2D array shapes: a = {a.shape}, b = {b.shape}\")\nprint()\n\nX = np.append(a, b)\nprint(X)\nprint(f\"new array shape: {a.shape}\")\nprint()\n\nX = np.append(b, d)\nprint(X)\nprint(f\"new array shape: {a.shape}\")\nprint()\n\nX = np.append(c, d)\nprint(X)\nprint(f\"new array shape: {a.shape}\")\nprint()\n```\n\n [[0]\n [1]\n [2]]\n \n [[3]\n [4]]\n \n [[3]\n [4]]\n \n original 2D array shapes: a = (3, 1), b = (2, 1)\n \n [0 1 2 3 4]\n new array shape: (3, 1)\n \n [3 4 1]\n new array shape: (3, 1)\n \n [3 4 1]\n new array shape: (3, 1)\n \n\n\nThe axis on which to append an array can be optionally specified.\n\ne.g. 2D array:\n - 0: columns\n - 1: rows\n\nThe arrays must have the same shape, except in the dimension corresponding to the specified axis \n\n\n```python\n# 2D array\na = np.array([[0], [1], [2]])\nprint(a)\nprint()\n\n# 2D array\nb = np.array([[3], [4]])\nprint(b)\nprint()\n\nnew2d = np.append(a, b, axis=0)\nprint(new2d)\nprint(f\"new array shape: {new2d.shape}\")\n```\n\n [[0]\n [1]\n [2]]\n \n [[3]\n [4]]\n \n [[0]\n [1]\n [2]\n [3]\n [4]]\n new array shape: (5, 1)\n\n\nFor example, in the cell above, if you change `axis=0` to `axis=1`, \n
    you are trying to connect the side of `a` with length=3 to the side of `b` with length=2.\n\nThere are dedicated functions to simplify joining or merging arrays.\n
    If you are interested to expeirment further with joiing arrays you can try out the following functions:\n - `np.concatenate()` : Joins a sequence of arrays along an existing axis.\n - `np.vstack()` or `np.r_[]`: Stacks arrays row-wise\n - `np.hstack()` : Stacks arrays horizontally\n - `np.column_stack()` or `np.c_[]` : Stacks arrays column-wise\nRefer to last week's seminar for how to inpterpret the function documentation. \n\nIt can also be useful to remove individual (single or multiple) elements.\n\nFor example, the following expand the locations within the array that you can change beyond the location at the *end* of the array.\n\n\n#### Adding Elements to an Array\n\n\n```python\n# Add items to an array\n# The insert() function arguments are\n# 1) The array to insert to\n# 2) The index of the inserted element\n# 3) The value of the inserted element\n\na = ([1, 2, 3])\na = np.insert(a, 1, 4)\nprint(a)\n```\n\n [1 4 2 3]\n\n\nNotice that, again, the output is a 1D aray by default\n\n\n```python\n# Add items to an array\n\nb = np.array([[1, 1], \n [2, 2], \n [3, 3]])\n\nprint(f\"original array shape: {b.shape}\")\n\nb = np.insert(b, 1, [4, 4])\n\nprint(b)\n\nprint(f\"new array shape: {b.shape}\")\n```\n\n original array shape: (3, 2)\n [1 4 4 1 2 2 3 3]\n new array shape: (8,)\n\n\nTo preserve the multi-dimensional structure of an array, we can specify the axis on which to insert an element or range of elements. \n
    In the example below, a column is inserted at element 1 of axis 1. \n\n\n```python\n# Add items to an array\n\nb = np.array([[1, 1], \n [2, 2], \n [3, 3]])\n\nb = np.insert(b, 1, [3, 2, 1], axis=1)\nprint(b)\n```\n\n [[1 3 1]\n [2 2 2]\n [3 1 3]]\n\n\nNotice what happens when we insert a *single* value on a specified axis\n\n\n```python\nb = np.insert(b, 1, 4, axis=1)\nprint(b)\n```\n\n [[1 4 3 1]\n [2 4 2 2]\n [3 4 1 3]]\n\n\nThis behaviour is due to a very useful property called *broadcasting*. \n
    We will study the rules governing broadcasting later in this seminar. \n\n\n#### Deleting Items from an Array\n\n\n```python\n# Items are deleted from their position in a 1D array by default\n\nz = np.array([1, 3, 4, 5, 6, 7, 8, 9])\n\n\nz = np.delete(z, 3)\nprint(z)\n\nz = np.delete(z, [0, 1, 2])\nprint(z)\n\n```\n\n [1 3 4 6 7 8 9]\n [6 7 8 9]\n\n\n\n```python\n# Again, axes to delete can be optionally specified:\n\nz = np.array([[1, 3, 4, 5], [6, 7, 8, 9]])\nprint(z)\nprint()\n\nz = np.delete(z, 3, axis=1)\nprint(z)\nprint()\n\nz = np.delete(z, [0, 1, 2], axis=1)\nprint(z)\nprint()\n```\n\n [[1 3 4 5]\n [6 7 8 9]]\n \n [[1 3 4]\n [6 7 8]]\n \n []\n \n\n\n\n#### Changing Items in an Array\n\n\n\n```python\nc = np.array([1, 2, 3])\nc[1] = 4\nprint(c)\n```\n\n [1 4 3]\n\n\n\n### Magic Functions\nWe can use *magic function* (http://ipython.readthedocs.io/en/stable/interactive/magics.html), `%timeit`, to compare the time the user-defined function takes to execute compared to the Numpy function. \n\nIt is important to optimise code for the most desirable parameter. In this example, the user defined code is significantly faster, but the function using numpy applies to a far wider range of input cases.\n\n\n```python\n%timeit max_min_mean(0.5, 0.1, -20)\nprint()\n%timeit np_max_min_mean([0.5, 0.1, -20])\n```\n\n##### Try it yourself \nIn the cell below, find a Numpy function that provides the same solution as the function you wrote as your answer to __Seminar 3, Review Exercise: Indexing, part (A)__: \n
    Add two vectors, $\\mathbf{A}$ and $\\mathbf{B}$ such that:\n$ \\mathbf{A} + \\mathbf{B} = [(A_1 + B_1), \n (A_2 + B_2),\n ...\n (A_n + B_n)]$\n\n__(A)__ Use the Numpy function to add vectors:\n\n$\\mathbf{A} = [-2, 1, 3]$\n\n$\\mathbf{B} = [6, 2, 2]$\n\nCheck that your answer is the same as your answer to __Seminar 3, Review Exercise: Indexing__.\n\n__(B)__ Using your answer to __Seminar 3, Review Exercise: Indexing__ write a function `vector_add` that takes vectors A and B as inputs and returns the sum of the two vectors by calling:\n\n```python\nvector_add(A, B)\n```\n\n__(C)__ Use *magic function* `%timeit`, to compare the speed of the Numpy function to the user defined function `vector_add`. \n
    Which is fastest?\n\n\n```python\n# Vector Addition\n```\n\n\n## Stacking Functions\nIf performing multiple functions on a variable or data structure, operations can be stacked to produce shorter code.\n\n\n\n```python\na = range(10)\na = list(a)\na = np.cos(a)\na = np.sum(a)\nprint(a)\n\na = np.sum(np.cos(list(range(10))))\nprint(a)\n```\n\n\n## Importing Data from a .csv File to a Numpy Array\nReal data is often stored in .csv files (typically viewed in Excel).\n\ncsv files are simply comma separated values (although the values can be separated or *delimited* by other things than commas).\n\nA Numpy array can be a very useful way to store and manipulate data e.g. the raw data from an experiment.\n\nNumerical data can be loaded from a .txt or .data. or .csv file using the function; `numpy.loadtxt`.\n\nThe file to be loaded must be in the same directory as your python program.\n
    Otherwise you must specify the the full path to the data file using / to seperate directory names. \n
    The filename (or path plus filename) needs to be between \"\" quotation marks. \n\nFor example the file data.dat in the folder sample_data contains:\n>0.000 1.053 2.105 3.158 4.211
    \n74.452 48.348 68.733 59.796 54.123\n\nThe default delimiter is a space.\n
    The default data type to output is an array of floating point values. \n\n\n```python\nA = np.loadtxt('sample_data/sample_data.dat')\nprint(A)\nprint(type(A))\nprint(A[0][1])\n```\n\n [[ 1.053 2.105 3.158 4.211 6.065]\n [ 48.348 68.733 59.796 54.123 74.452]]\n \n 2.105\n\n\nThe __delimiter__ should (sometimes) be specified.\n
    This tells Python how to separate the data into the individual elements of an array. \n
    The default delimiter is a space.\n
    (Data separated by spaces will be automatically be assigned different indices).\n\nThe __data type__ should (sometimes) be specified.\n
    This tells Python how to separate the data into the individual elements of an array. \n
    The default data type is `float`.\n
    If your data contains items that cannot be expressed as a float, importing it will cause an error unless the data-type is specified.\n
    Mixed data types can be imported as `string` values. \n\nFor example, the data in sample_student_data.txt:\n- is seperated by tabs (`/t`) \n- cannot all be converted to float data (in some columns)\n\n```Python\nSubject\tSex\tDOB\tHeight\tWeight\tBP\n(ID)\tM/F\tdd/mm/yy\tm\tkg\tmmHg\nJW-1\tM\t19/12/1995\t1.82\t92.4\t119/76\nJW-2\tM\t11/01/1996\t1.77\t80.9\t114/73\nJW-3\tF\t02/10/1995\t1.68\t69.7\t124/79\nJW-6\tM\t06/07/1995\t1.72\t75.5\t110/60\nJW-7\tF\t28/03/1996\t1.66\t72.4\t-\nJW-9\tF\t11/12/1995\t1.78\t82.1\t115/75\nJW-10\tF\t07/04/1996\t1.6\t45\t-/-\nJW-11\tM\t22/08/1995\t1.72\t77.2\t97/63\nJW-12\tM\t23/05/1996\t1.83\t88.9\t105/70\nJW-14\tF\t12/01/1996\t1.56\t56.3\t108/72\nJW-15\tF\t01/06/1996\t1.64\t65\t99/67\nJW-16\tM\t10/09/1995\t1.63\t73\t131/84\nJW-17\tM\t17/02/1996\t1.67\t89.8\t101/76\nJW-18\tM\t31/07/1996\t1.66\t75.1\t-/-\nJW-19\tF\t30/10/1995\t1.59\t67.3\t103/69\nJW-22\tF\t09/03/1996\t1.7\t45\t119/80\nJW-23\tM\t15/05/1995\t1.97\t89.2\t124/82\nJW-24\tF\t01/12/1995\t1.66\t63.8\t100/78\nJW-25\tF\t25/10/1995\t1.63\t64.4\t-/-\nJW-26\tM\t17/04/1996\t1.69\t55\t121/82\n```\n\n\n```python\nnp.loadtxt('sample_data/sample_student_data.txt', delimiter=\"\\t\", dtype=str)\n```\n\n\n\n\n array([['Student', 'Sex', 'DOB', 'Height', 'Weight', 'BP'],\n ['(ID)', 'M/F', 'dd/mm/yy', 'm', 'kg', 'mmHg'],\n ['JW-1', 'M', '19/12/1995', '1.82', '92.4', '119/76'],\n ['JW-2', 'M', '11/01/1996', '1.77', '80.9', '114/73'],\n ['JW-3', 'F', '02/10/1995', '1.68', '69.7', '124/79'],\n ['JW-4', 'M', '11/01/1996', '1.77', '80.9', '114/73'],\n ['JW-5', 'F', '02/10/1995', '1.68', '69.7', '124/79'],\n ['JW-6', 'M', '06/07/1995', '1.72', '75.5', '110/60'],\n ['JW-7', 'F', '28/03/1996', '1.66', '72.4', '-'],\n ['JW-9', 'F', '11/12/1995', '1.78', '82.1', '115/75'],\n ['JW-10', 'F', '07/04/1996', '1.6', '45', '-/-'],\n ['JW-11', 'M', '22/08/1995', '1.72', '77.2', '97/63'],\n ['JW-12', 'M', '23/05/1996', '1.83', '88.9', '105/70'],\n ['JW-14', 'F', '12/01/1996', '1.56', '56.3', '108/72'],\n ['JW-15', 'F', '01/06/1996', '1.64', '65', '99/67'],\n ['JW-16', 'M', '10/09/1995', '1.63', '73', '131/84'],\n ['JW-17', 'M', '17/02/1996', '1.67', '89.8', '101/76'],\n ['JW-18', 'M', '31/07/1996', '1.66', '75.1', '-/-'],\n ['JW-19', 'F', '30/10/1995', '1.59', '67.3', '103/69'],\n ['JW-22', 'F', '09/03/1996', '1.7', '45', '119/80'],\n ['JW-23', 'M', '15/05/1995', '1.97', '89.2', '124/82'],\n ['JW-24', 'F', '01/12/1995', '1.66', '63.8', '100/78'],\n ['JW-25', 'F', '25/10/1995', '1.63', '64.4', '-/-'],\n ['JW-26', 'M', '17/04/1996', '1.69', '55', '121/82']],\n dtype='For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns.\n\n\n```python\nimport numpy as np\nnp.loadtxt('sample_data/sample_student_data.txt', dtype=float, skiprows=9, usecols=(3,4))\n```\n\n\n\n\n array([[ 1.78, 82.1 ],\n [ 1.6 , 45. ],\n [ 1.72, 77.2 ],\n [ 1.83, 88.9 ],\n [ 1.56, 56.3 ],\n [ 1.64, 65. ],\n [ 1.63, 73. ],\n [ 1.67, 89.8 ],\n [ 1.66, 75.1 ],\n [ 1.59, 67.3 ],\n [ 1.7 , 45. ],\n [ 1.97, 89.2 ],\n [ 1.66, 63.8 ],\n [ 1.63, 64.4 ],\n [ 1.69, 55. ]])\n\n\n\nYou can now use the imported data as a regular Numpy array.\n\n\n\n\n# Summary\n\n- Python has an extensive __standard library__ of built-in functions. \n- More specialised libraries of functions and constants are available. We call these __packages__. \n- Packages are imported using the keyword `import`\n- The function documentation tells is what it does and how to use it.\n- When calling a library function it must be prefixed with a __namespace__ is used to show from which package it should be called. \n- The magic function `%timeit` can be used to time the execution of a function. \n\n\n\n\n - A data structure is used to assign a collection of values to a single collection name.\n - A Python list can store multiple items of data in sequentially numbered elements (numbering starts at zero)\n - Data stored in a list element can be referenced using the list name can be referenced using the list name followed by an index number in [] square brackets.\n - The `len()` function returns the length of a specified list.\n\n\n\n# Test-Yourself Exercises\n\nCompete the Test-Youself exercises below.\n\nSave your answers as .py files and email them to:\n
    philamore.hemma.5s@kyoto-u.ac.jp\n\n## Test-Yourself Exercise : The Dot Product\n__(A)__\n
    Earlier, we used the geometric representation of the dot product: \n\n$\\mathbf{A} \\cdot \\mathbf{B} \\sum_{i=1}^n A_i B_i = A_x B_x + A_y B_y + A_z B_z$\n\nto find the sum of two vectors:\n
    $ \\mathbf{A} = [A_x, A_y, A_z]$\n
    $ \\mathbf{B} = [B_x, B_y, B_z]$\n\nNumpy has a dedicated function to compute the dot product.\n
    Search for the function online and use it to compute the dot product of two 3D position vectors, expressed as lists `C` and `D`.\n\n\n```python\n# Find the dot product of C and D\nC = [-1, 2, 6]\nD = [4, 3, 3]\n\n\n```\n\n\n```python\n# Find the dot product of C and D\n# Example Solution\n\nimport numpy as np\nC = [-1, 2, 6]\nD = [4, 3, 3]\n\nnp.dot(C, D)\n```\n\nThe dot product has an alternative representation: \n
    __GEOMETRIC REPRESENTATION OF THE DOT PRODUCT__\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} = |\\mathbf{A}| |\\mathbf{B}| cos(\\theta)\n\\end{align}\n\nWhere:\n
    $\\theta$ is the angle between the two vectors.\n
    $|\\mathbf{A}|$ and $|\\mathbf{B}|$ are the *magnitudes* of $\\mathbf{A}$ and $\\mathbf{B}$\n\n\n\nThe magnitude of an $n$-length vector $ \\mathbf{A} = [A_1, ..., A_n]$ is:\n\n$|\\mathbf{A}| = \\sqrt{A_1^2 + ... + A_n^2}$\n\n\ne.g. \n
    The magnitude of __2D position__ vector, $\\mathbf{r} = [x, y]$:\n
    $|\\mathbf{r}| = \\sqrt{x^2 + y^2}$\n\n
    The magnitude of __3D position__ vector, $\\mathbf{r} = [x, y, z]$:\n
    $|\\mathbf{r}| = \\sqrt{x^2 + y^2 + z^2}$\n\n\n\n\n\n\n__(B)__\n
    If the dot product is known, the angle between two vectors can be found (from its cosine).\n\nSearch online to find a numpy function that computes *magnitude*.\n\nSearch online to find a numpy function for the *inverse cosine*.\n\nFind the angle between the vectors expressed as lists `C` and `D` in part __(A)__.\n\n\n\n\n\n\n```python\n# Find the angle between C and D\nC = [-1, 2, 6]\nD = [4, 3, 3]\n\n\n\n```\n\n\n```python\n# Find the angle between C and D\n# Example Solution\n\nC = [-1, 2, 6]\nD = [4, 3, 3]\n\ndotCD = np.dot(C, D)\nmagC = np.linalg.norm(C)\nmagD = np.linalg.norm(D)\n\ntheta = np.arccos(dotCD / (magC * magD))\n\nprint(theta)\n```\n\n__(C)__\n\nThe dot product also indicates if the angle between two vectors is:\n - acute ($\\mathbf{C} \\cdot \\mathbf{D}>0$)\n - obtuse ($\\mathbf{C} \\cdot \\mathbf{D}<0$)\n - right angle ($\\mathbf{C} \\cdot \\mathbf{D}==0$)\n\nUsing `if`, `elif` and `else`, classify the angle between `C` and `D` as acute, obtuse or right angle.\n\n\n```python\n# Angle between C and D is obtuse, acute or right angle? \n\nC = [-1, 2, 6]\nD = [4, 3, 3]\n\n\n```\n\n\n```python\n# Angle between C and D is obtuse, acute or right angle? \n# Example Solution\n\nC = [-1, 2, 6]\nD = [4, 3, 3]\n\ndotCD = np.dot(C, D)\n\nif dotCD > 0:\n print(\"theta is acute\")\nelif dotCD < 0:\n print(\"theta is obtuse\")\nelse:\n print(\"theta is right angle\")\n```\n\n## Test-Yourself Exercise : Importing .csv Data and Working with Arrays\n__(A) Importing Data__\n
    We can work with data stored in .csv files by importing it to a numpy array.\n
    The file `douglas_data.csv` contains a data set of recorded parameters for a sample of wooden beams. \n\n
    \nImport `douglas_data.csv` from the `sample_data` folder in the `ILAS_python_for_engineers` directory. \n\n
    \nTo import the data without errors, first try setting:\n - delimiter = `\"\\t\"` (tab)\n - data type = `str` (string)\n \n
    \n__*What are the delimiters used in the data?*__\n\n__*Which rows and columns contain non-numerical data?*__\n\n
    \nNow import the data as a Numpy array of floating point values.\n
    Exclude the rows and columns containing non-numeric data.\n\n\n
    \n*Remember : The use of scientific notation can be surpressed by:*\n\n np.set_printoptions(suppress=True)\n\n\n```python\n# Importing Data\n```\n\n\n```python\n# Importing Data\n# Example Solution\n\nimport numpy as np\n\nA = np.loadtxt('sample_data/douglas_data.csv', delimiter=\"\\t\", dtype=str)\n\nprint(A)\n\nA = np.loadtxt('sample_data/douglas_data.csv', delimiter=\",\", dtype=float, skiprows=2, usecols=(1,2,3,4,5,6,7,8))\n\nprint(A)\n```\n\n__(B) Manipulating Data__\n
    Select the first 10 rows of the array to create a new array.\n\nThe column furthest to the right is the bending strength (`bstrength`), measured in units of $\\mathrm{N/mm}^2$.\n
    Convert the data in this column to units $\\mathrm{N/m}^2$.\n\nEach beam has the same cross sectional area = $100\\mathrm{cm}^2$.\n
    Add a new column to the array that contains mass of the beam (kg) using the columns `density` and `beamheight`.\n\n\n\n\n\n\n\n```python\n# Manipulating Data\n```\n\n\n```python\n# Manipulating Data\n# Example Solution\n\nB = A[:10, :]\n\nB[:,7] *= 1000000\nB[:,-1] *= 1000000\n\narea = 0.01 # m2\n\nheight = B[:,5] /100 # m\n\ndensity = B[:,4] #kg/m3\n\nmass = area * density * height\n\n# Insert column, mass, at horizontal position -1\nB = np.insert(B, 0, mass, axis=1)\n\nprint(B)\n```\n\n [[6.8175e+00 1.3300e+01 4.0000e-02 3.0000e+00 1.4053e+04 6.7500e+02\n 1.0100e+02 1.5452e+04 5.8400e+25]\n [4.7400e+00 1.2000e+01 1.6000e-01 2.5000e+00 2.0611e+04 4.7400e+02\n 1.0000e+02 1.7272e+04 7.4350e+25]\n [5.9004e+00 1.2800e+01 1.4000e-01 3.8800e+00 1.8846e+04 5.9600e+02\n 9.9000e+01 1.8456e+04 4.9820e+25]\n [5.8200e+00 1.1700e+01 1.3000e-01 2.0200e+00 1.8587e+04 5.8200e+02\n 1.0000e+02 1.8940e+04 7.8520e+25]\n [6.7800e+00 1.2000e+01 1.6000e-01 2.1300e+00 1.9299e+04 6.7800e+02\n 1.0000e+02 1.6864e+04 7.9310e+25]\n [5.9500e+00 1.2400e+01 4.0000e-02 2.9800e+00 2.1695e+04 5.9500e+02\n 1.0000e+02 1.9440e+04 6.4340e+25]\n [5.9200e+00 1.2500e+01 3.2000e-01 3.6700e+00 1.6523e+04 5.9200e+02\n 1.0000e+02 1.6152e+04 5.8190e+25]\n [6.4034e+00 1.1500e+01 7.0000e-02 3.6700e+00 1.8333e+04 6.3400e+02\n 1.0100e+02 1.8480e+04 8.8390e+25]\n [5.9792e+00 1.3100e+01 1.9000e-01 2.4400e+00 1.8628e+04 5.9200e+02\n 1.0100e+02 1.4604e+04 3.3020e+25]\n [5.4540e+00 1.1700e+01 2.5000e-01 3.0000e+00 1.5683e+04 5.4000e+02\n 1.0100e+02 1.6628e+04 6.0280e+25]]\n\n\n__(C) Displaying Data__\n
    Print the mass of the 1st beam in the array.\n
    Print a string to indicate what this value means e.g.\n \n The mass of beam 1 is ...\n \n
    Print the data in odd numbered columns of row 5. \n\n\n\n```python\n# Displaying Data\n```\n\n The mass of beam 1 is {B[0,0]} kg\n\n\n\n```python\n# Displaying Data\n# Example Solution\n\nprint(\"The mass of beam 1 is {B[0,0]} kg\")\nprint(B[5,1::2])\n```\n\n The mass of beam 1 is {B[0,0]} kg\n [1.240e+01 2.980e+00 5.950e+02 1.944e+04]\n\n\n\n# Review Exercises\nHere are a series of short problems for you to practise each of the new Python skills that you have learnt today. \n\n### Review Exercise: Numpy Package Functions. \nFind a function in the Python Numpy documentation that matches the function definition and use it to solve the problems below:\n\n__(A)__ Definition: *Calculates the exponential function, $y= e^x$ for all elements in the input array.*\n\nPrint a list where each element is the exponential function of the corresponding element in list `a = [0.1, 0, 10]`\n\n\n```python\n# Print a list where each element is the exponential of the corresponding element in list a\n```\n\n__(B)__ Definition: *Converts angles from degrees to radians.*\n\nConvert angle `theta`, expressed in degrees, to radians:\n
    `theta` = 47\n\n\n```python\n# convert angle `theta`, expressed in degrees, to radians\n```\n\n__(C)__ Definition: *Return the positive square-root of an array, element-wise.*\n\nPrint a list where each element is the square root of the corresponding element in list `a = [4, 16, 81]`\n\n\n```python\n# Print a list where each element is the square root of the corresponding element in list a\n```\n\n### Review Exercise: Data structures.\n\n__(A)__ In the cell below, use Python to identify the type of data structure, C?\n\n__(B)__ Write a line of code that checks whether 3 exists within the data structure.\n\n__(C)__ Write a line of code that checks whether 3.0 exists within the data structure.\n\n__(D)__ Write a line of code that checks whether \"3\" exists within the data structure.\n\n\n\n```python\nC = [2, 3, 5, 6, 1, \"hello\"]\n```\n\n### Review Exercise: Using a single list with a `for` loop.\nIn the cell below, use a `for` loop to print the first letter of each month in the list.\n\nJump to Indexing for how to pick out individual letters of a string.\n\nJump to Iterating over lists for how to loop through each element of a list.\n\n\n\n\n```python\n# Print the first letter of each month in the list\n\nmonths = [\"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"]\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "65f06afa86538b6b61925f9ab95808d3e6875517", "size": 136865, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "02_DataStructures_LibraryFunctions.ipynb", "max_stars_repo_name": "Lari-chan/Python_test", "max_stars_repo_head_hexsha": "b569b4ac37486b7b0b1159a4547ea199b0f02e37", "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": "02_DataStructures_LibraryFunctions.ipynb", "max_issues_repo_name": "Lari-chan/Python_test", "max_issues_repo_head_hexsha": "b569b4ac37486b7b0b1159a4547ea199b0f02e37", "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": "02_DataStructures_LibraryFunctions.ipynb", "max_forks_repo_name": "Lari-chan/Python_test", "max_forks_repo_head_hexsha": "b569b4ac37486b7b0b1159a4547ea199b0f02e37", "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": 24.284066714, "max_line_length": 1380, "alphanum_fraction": 0.5048770686, "converted": true, "num_tokens": 20393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968261942204597, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.062477803801235104}} {"text": "# OpenMC introduction\n\nPlease indicate your name below, since you will need to submit this notebook completed latest the day after the datalab.\n\nDon't forget to save your progress during the datalab to avoid any loss due to crashes.\n\n\n```python\nname=''\n```\n\nIn our previous endeavours we experienced that performing an accurate simulation of particle transport is not trivial. There are several softwares developed to solve this task, and for someone who is more interested in performing the analysis of a reactor core, it is often better to use an already verified and validated code instead of developing a new one from scratch. There are several such codes solving neutron transport either relying on deterministic or stochastic methods. During this datalab we will use a rather young code called OpenMC, which was originally developed at MIT. \n\nOpenMC is a Monte Carlo neutron and photon transport simulation code. It can be used both for fixed source and for criticality calculations. The user can define complicated geometries with constructive solid geometries. OpenMC is written in C++, however it has a rich Python API, which will allow us to comminicate with the code through jupyter notebooks.\n\nOpenMC is not yet an industrial standard code, however our motivation to use it for this course was that it is \n\n1. freely available\n2. the important physics we could not tackle within this course ourselves (eg. thermal scattering and several reactions) are implemented in it\n3. since we can interact with the code through Python, we can deepen our programming skills\n4. for small problems it runs relatively fast on a single PC\n\nThat said, today we are going to walk through a simple openMC input file. During this course we will only work with pincell models (ie. a single fuel pin infinite in the axial length with reflective boundaries, so neutrons are reflected back from the boundary in this way approximating an infinite core). This is of course a simplification of a complete reactor core, but it will still allow us to see a lot of cool physics. One could of course perform simulations at the assembly level or for a full-core, however such simulations would be more time consuming. There are several further examples at https://docs.openmc.org/.\n\n**Note that this notebook should be opened from an environment where openmc is available!**\n\n## The input file\n\nDuring the datalab we will define the following problem which roughly matches a typical western-type pressurized water reactor's conditions:\n\n- PWR pincell with reflective boundaries\n- Fuel radius: 0.41 cm\n- Fuel material: enriched UO2 with density 10.5 g/cm3\n- Cladding inner/outer radius: 0.42/0.45 cm\n- Cladding material: zirconium with density 6.6 g/cm3\n- Coolant/moderator: pressurized water with density 0.75 g/cm3\n- Cell pitch: 1.26 cm\n\nNote that in practice, PWR fuel cladding is made of an alloy called Zircaloy, nevertheless it has little influence on the neutron economy, therefore we will approximate it as pure zirconium with its natural abundance of isotopes.\n\nSo what do we need in order to define an openMC input?\n\n1. Materials: which materials are included in our geometry (nuclide content, temperature, density)?\n2. Geometry: how does the geometry look like? \n3. Tally: what are the quantities of interest? For example flux, or fission rate?\n4. Settings: how many neutrons we would like to include in the calculation?\n\nFor each of these steps we will use the python API to export an xml file, which the code will use once we execute it. Note however that one could directly write xml files without using python, and run the code outside of Jupyter. For larger problems this is sometimes better. However we will want to analyse the output results in python, and sometimes we will script the input, so for us it is handy to use the python API.\n\nLet's get started!\n\n### Import\n\nWe will need first to import openmc, and of course anything else we might need.\n\n\n```python\nimport openmc\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n```\n\n### Materials\n\nDo you remember the example `Material()` class we developed before? That is pretty similar to the `Material()` class of openMC. We create an instance of `Material()`, with a numeric id of the material, and then we can add nuclides, and set the density. We can also set the temperature (which can be 294 K, 600 K, 900 K, 1200 K, 1500 K, the temperatures at which the cross sections are evaluated). There are other options as well (for example one can directly set the enrichment), what you can find in the documentation.\n\nIf the nuclide inventory is not relevant for a material, we can add elements, in which case openMC will assume the natural abundance of isotopes.\n\nNotice that for water we will need to link to the $S(\\alpha,\\beta)$ laws, since we need to take into account the molecular bounds for scattering on hydrogen. \n\nFinally, we create an instance of `Materials()` (note, it is plural now!), and link the materials of the problem to this object. Then with the `export_to_xml()` method we export the information into an xml file. \n\n\n```python\nuo2 = openmc.Material(1, \"uo2\",temperature=1200)\n# Add nuclides to uo2\nuo2.add_nuclide('U235', 0.04)\nuo2.add_nuclide('U238', 0.96)\nuo2.add_nuclide('O16', 2.0)\nuo2.set_density('g/cm3', 10.5)\n\n\n#cladding\nzirconium = openmc.Material(2, \"zirconium\",temperature=900)\nzirconium.add_element('Zr', 1.0)\nzirconium.set_density('g/cm3', 6.6)\n\n#coolant\nwater = openmc.Material(3, \"h2o\")\nwater.add_nuclide('H1', 2.0)\nwater.add_nuclide('O16', 1.0)\nwater.set_density('g/cm3', 0.75)\n\nwater.add_s_alpha_beta('c_H_in_H2O')\n\n#creating Materials() and exporting to xml\nmats = openmc.Materials([uo2, zirconium, water])\nmats.export_to_xml()\n```\n\nWe can print the content of the created xml file, with the linux command `cat`. (The `!` sign let's the python interpreter know that this is a command of the operating system.\n\nYou can see how all the information was structured in an xml (which is probably familiar from the previous datalab). \n\n\n```python\n!cat materials.xml\n```\n\n### Geometry\n\nDefining the geometry is only marginally more complicated. We will need to define surfaces (eg. `ZCylinder()`, `XPlane()`, and `YPlane()`), and regions bounded by the surfaces. Then we link the regions and the filling material to `Cell()` objects, which all have a numeric ID. \n\nOur geometry is infinite in the axial dimension. First we define three cylinders (the bounding surfaces of the fuel, and the cladding). Then we use constuctive solid geometry rules to define the regions between the surfaces, and create the fuel pin. Finally we will define the water region around the fuel.\n\nWe will then need to define a `Universe()` (the usefulness of this is not apparent in our simple exercise, but when defining reactor cores with repetitive patterns of various types of fuel assemblies, then \"universes\" are the way to handle this in most neutron transport code. You do not need to worry about this in this course). And finally we create a `Geometry()`, and link the universe. We will then export the information into an xml file. \n\nWe further commented the lines to explain them\n\n\n```python\nfuel_or = openmc.ZCylinder(r=0.41) #fuel cylinder with outer radius\nclad_ir = openmc.ZCylinder(r=0.42) #clad inner cylinder with inner radius\nclad_or = openmc.ZCylinder(r=0.45) #clad outer cylinder with outer radius\n\n\nfuel_region = -fuel_or #inside the fuel cylinder\ngap_region = +fuel_or & -clad_ir #outside of fuel cylinder and inside of clad inner cylinder\nclad_region = +clad_ir & -clad_or #outside of clad inner cylinder and inside of clad outer cylinder\n\nfuel = openmc.Cell(1, 'fuel')\nfuel.fill = uo2\nfuel.region = fuel_region\n\n#notice that for the gap between the fuel and the clad we do not need to link a material\n# we consider that there is void there (considering the low density of the filling gas this is a fair approximation)\ngap = openmc.Cell(2, 'air gap')\ngap.region = gap_region\n\nclad = openmc.Cell(3, 'clad')\nclad.fill = zirconium\nclad.region = clad_region\n\n\n\npitch = 1.26\n#we define the x and y planes with boundary condition\nleft = openmc.XPlane(x0=-pitch/2, boundary_type='reflective')\nright = openmc.XPlane(x0=pitch/2, boundary_type='reflective')\nbottom = openmc.YPlane(y0=-pitch/2, boundary_type='reflective')\ntop = openmc.YPlane(y0=pitch/2, boundary_type='reflective')\n\n#outside of left and inside of right, outside of bottom, and inside of top and outside of clad outer cylinder\nwater_region = +left & -right & +bottom & -top & +clad_or\n\nmoderator = openmc.Cell(4, 'moderator')\nmoderator.fill = water\nmoderator.region = water_region\n\nroot = openmc.Universe(cells=[fuel, gap, clad, moderator])\n\ngeom = openmc.Geometry()\ngeom.root_universe = root\ngeom.export_to_xml()\n```\n\nWe can again inspect the xml file.\n\n\n```python\n!cat geometry.xml\n```\n\n### Tally\n\nWe can describe the physical quantities of interest with tallies. If no tally is defined the code will only calculate the k-effective.\n\nAs we can see in the openMC documentation (in the user's guide) a tally is a quantity defined as\n\n\\begin{equation}\nX = \\underbrace{\\int d\\mathbf{r} \\int d\\mathbf{\\Omega} \\int\ndE}_{\\text{filters}} \\underbrace{f(\\mathbf{r}, \\mathbf{\\Omega},\nE)}_{\\text{scores}} \\psi (\\mathbf{r}, \\mathbf{\\Omega}, E)\n\\end{equation}\n\nFor example if function $f()$ would be unity, we would score the flux in a certain part of the phase space. If function $f()$ is a macroscopic cross section, we would score reaction rates.\n\nTherefore we have to specify two things for a tally, which is created with a `Tally()` object:\n\n1. *filters*: which part of the phase space we would like score at (for example only a certain part of the geometry is of interest, or certain energy bins)?\n2. *scores*: what is the physical quantity of interest (for example flux, fission rate etc)\n\nYou can find a detailed description of the available scores and filters in the documentation.\n\nOnce the tallies are defined, we will need to link them into a `Tallies()` object, and export an xml file.\n\nIn the following code block we define three tallies.\n\n1. tally for the neutron spectrum and the fission rate vs energy in the fuel\n2. tally for the neutron spectrum in the moderator\n3. a Mesh tally along the x-axis to tally the spatial dependence of the flux with three energy groups (thermal: 0-1eV, epithermal: 1eV-100keV, fast: 100keV-20MeV)\n\nThe reason why we tally the fission rate as well in the 1st tally is to see how openMC will store the results. \n\n\n```python\n# Tally 1: energy spectrum in fuel\ncell_filter1 = openmc.CellFilter(fuel)\nenergybins=np.logspace(-2,7,1001) #1000 bins between 1e-2 eV and 1e7 eV\nenergy_filter = openmc.EnergyFilter(energybins)\n\nt1 = openmc.Tally(1)\nt1.filters = [cell_filter1,energy_filter]\nt1.scores = ['flux','fission']\n\n# Tally 2: energy spectrum in moderator\n# we can use the same energy_filter as before\ncell_filter2 = openmc.CellFilter(moderator)\n\nt2 = openmc.Tally(2)\nt2.filters = [cell_filter2,energy_filter]\nt2.scores = ['flux']\n\n# Tally 3: mesh tally in dimension x in three energy groups\nenergy_filter2 = openmc.EnergyFilter([0., 1, 100e3, 20.0e6])\nmyMesh=openmc.Mesh(name='xmesh')\nmyMesh.dimension=[100] #number of spatial bins along x axis\nmyMesh.lower_left=[-pitch/2]\nmyMesh.upper_right=[pitch/2]\nmesh_filter = openmc.MeshFilter(myMesh)\n\nt3 = openmc.Tally(3)\nt3.filters = [mesh_filter,energy_filter2]\nt3.scores = ['flux']\n\n\n\ntallies = openmc.Tallies([t1,t2,t3])\ntallies.export_to_xml()\n```\n\nWe can inspect the xml file.\n\n\n```python\n!cat tallies.xml\n```\n\n### Settings\n\nThere are some parameters we will need to set: we have to include the original source location and specify the number of batches and particles per batches for the criticality mode calculation. We also have to specify the number of \"inactive\" batches (these cycles are used to spread the fission source over the geometry, but the scores are still biased due to the original source not sampling all the possible fission sites properly). \n\nSince we have no better guess for the moment, we will place the source first in the center of the geometry. The number of batches and particles are set so that the results are reasonably accurate. If you wanted to have more accurate results you could increase these numbers, if you wanted to have shorter calculations, you could decrease these numbers.\n\nAgain, the instance of the `Setting()` object is exported to xml.\n\n\n```python\npoint = openmc.stats.Point((0, 0, 0))\nsrc = openmc.Source(space=point)\n\nsettings = openmc.Settings()\nsettings.source = src\nsettings.batches = 100\nsettings.inactive = 10\nsettings.particles = 5000\nsettings.export_to_xml()\n```\n\n\n```python\n!cat settings.xml\n```\n\n## Plotting the geometry\n\nThere are several ways of plotting the geometry. The simplest inline plotting option is to call the `plot()` method of the `Universe()` object (in our case this was called `root`). This is a wrapper of matplotlib. However, there is a more advanced options by setting up an instance of the `Plot()` class, and running openMC directly to generate a plot. Since in this course we work with a rather simple geometry, we will not look at the advanced plotting option, but you are welcome to check the user's guide.\n\n\n```python\nroot.plot()\n```\n\n## Calculation\n\nFinally, we are done, and nothing left just to run openMC and wait for the results. For this we have to specify where the cross section files are (this we could do in the system as well). Then call the `openmc.run()` method. And you immediately see how the k-effective is being estimated.\n\n**Note 1**: The results are being stored in a file named 'statepoint.100.h5' (100 refers to the number of batches), also a 'summary.h5' and some other files are created. Sometimes openMC is complaining if there are already existing h5 files, so in this case we can remove (`rm`) these files. For this we make a system call with `os.system` to remove any file for which the name starts with 's' and ands with 'h5'. Nevertheless, be careful with removing files, not to loose data. \n\n**Note 2**: Sometimes the python API breaks for no apparent reason, you can just restart the kernel, if that happens. \n\n\n```python\nimport os\nos.system('rm s*h5')\n\nopenmc.run()\n```\n\n## Post-processing\n\nAlright, we did our calculation, we even saw that some k-effective values were printed, but we still haven't seen any more results. For this we will need to read in the statepoint file. We will read this file into an object called `sp`. If we hit TAB while typing `sp.` we can review the available methods and attributes. For example we can get the final k-effective as below.\n\n\n```python\nsp = openmc.StatePoint('statepoint.100.h5')\nsp.k_combined\n```\n\nAnd the values we can access for further processing or plotting:\n\n\n```python\nkeff=sp.k_combined.nominal_value\nkeff_error=sp.k_combined.std_dev\nprint(keff,keff_error)\n```\n\nThe tallies are stored in a dictionary where the keys are the numeric IDs we defined previously:\n\n\n```python\nsp.tallies\n```\n\nWe can convert the tally results into pandas dataframes. So at the end we have a nice table, for each energy bin there is a row for the flux and a row for the fission rate. If we prefer we can split the dataframe based on conditions to store separately the flux and the fission rate. For this we can apply conditions as we have seen during the previous datalabs.\n\nThe results are stored in the 'mean' column.\n\n\n```python\ntallydf1=sp.tallies[1].get_pandas_dataframe()\ntallydf1.head() #prints the first 5 rows\n```\n\n\n```python\ntallydf1flux=tallydf1[tallydf1['score']=='flux']\ntallydf1fiss=tallydf1[tallydf1['score']=='fission']\ntallydf1flux.head()\n```\n\nLet's plot these results.\n\n\n```python\nenergy=(tallydf1flux['energy low [eV]']+tallydf1flux['energy high [eV]'])/2\nplt.figure()\nplt.loglog(energy,tallydf1flux['mean'])\nplt.xlabel('energy (eV)')\nplt.ylabel('Group flux per source particle')\nplt.show()\n\n```\n\nThese of course does not look like the spectrum we saw during the lecture. But here actually each value is not the flux at a certain energy, but the integral of the flux between energies. If we divide the integral flux with the width of the bins (`deltaE`) we get the more familiar shape for the spectrum.\n\nWe can clearly see the Maxwellien thermal component, the 1/E part with the self-shielding effect of the resonances, and the Watt-spectrum at high energies.\n\nThe very first \"negative\" peak is due to the 6.67 eV resonance of U-238.\n\n\n```python\ndeltaE=(tallydf1flux['energy high [eV]']-tallydf1flux['energy low [eV]'])\nplt.figure()\nplt.loglog(energy,tallydf1flux['mean']/deltaE,lw=2)\n\nplt.ylabel('Spectrum per source particle (1/eV)')\nplt.xlabel('Energy (eV)')\nplt.show()\n```\n\nNow it is your turn to plot the spectrum in the moderator (preferably include both the fuel and the moderator spectrum in the same figure). You will need to `get_pandas_dataframe` from tally 2, and then plot the results. Compare with the spectrum in the fuel, what is the most noticable difference?\n\n\n```python\n# your code comes here\n```\n\nYour conclusion comes here.\n\nFinally, we can look at the spatial dependence of the flux. We read in the 3rd tally. Try to split the dataset according to the energy groups and plot the flux vs x-coordinate for the three energy groups separately. Normalize each curve by their maximum, so they are comparable.\n\nConclude your findings!\n\n\n```python\ntallydf3=sp.tallies[3].get_pandas_dataframe()\ntallydf3.head()\n```\n\n\n```python\n# your code comes here\n```\n\nYour conclusion comes here!\n\n## Experiment time!\n\nIf time permits, modify your input, and see how the results change. Points of interest:\n\n- Change the void content (ie. decrease the moderator density), and observe how the k-eff changes. What happens with the spectrum?\n- What is the impact on the k-eff if you change the UO2 temperature?\n- What is the impact of increasing the pitch of the pincell?\n\nYou can also take a look at the third set of home assignments, where you will need to implement various geometries in openMC, and already give it a try.\n\n\n```python\n\n```\n", "meta": {"hexsha": "53452ab3647ab0f215d36014a9f0e21a01bb2668", "size": 25080, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Datalabs/Datalab06/6-openMCIntro.ipynb", "max_stars_repo_name": "ezsolti/RFP", "max_stars_repo_head_hexsha": "5a410dd30ad61686b5d54d7778462e5e217be159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2021-06-18T15:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:34:42.000Z", "max_issues_repo_path": "Datalabs/Datalab06/6-openMCIntro.ipynb", "max_issues_repo_name": "ezsolti/RFP", "max_issues_repo_head_hexsha": "5a410dd30ad61686b5d54d7778462e5e217be159", "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": "Datalabs/Datalab06/6-openMCIntro.ipynb", "max_forks_repo_name": "ezsolti/RFP", "max_forks_repo_head_hexsha": "5a410dd30ad61686b5d54d7778462e5e217be159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-06-19T00:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T18:58:27.000Z", "avg_line_length": 39.2488262911, "max_line_length": 634, "alphanum_fraction": 0.6403110048, "converted": true, "num_tokens": 4474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.156104893519414, "lm_q1q2_score": 0.06241255360550791}} {"text": "```python\nimport sys\nsys.path = ['/Users/sebastian/github/mlxtend/'] + sys.path\n```\n\n\n```python\n#load watermark\n%load_ext watermark\n%watermark -a 'Gopala KR' -u -d -v -p watermark,numpy,pandas,matplotlib,nltk,sklearn,tensorflow,theano,mxnet,chainer,seaborn,keras,tflearn,bokeh,gensim\n```\n\n The watermark extension is already loaded. To reload it, use:\n %reload_ext watermark\n Gopala KR \n last updated: 2018-02-13 \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 seaborn 0.8.1\n keras 2.1.3\n tflearn n\u0007\n bokeh 0.12.14\n gensim 3.3.0\n\n\n# Artificial Neurons and Single-Layer Neural Networks\n\n## - How Machine Learning Algorithms Work Part 1\n\n
    \n
    \n\n**This article offers a brief glimpse of the history and basic concepts of machine learning. We will take a look at the first algorithmically described neural network and the gradient descent algorithm in context of adaptive linear neurons, which will not only introduce the principles of machine learning but also serve as the basis for modern multilayer neural networks in future articles.**\n\n## Sections\n\n- [Introduction](#Introduction)\n- [Artificial Neurons and the McCulloch-Pitts Model](#Artificial-Neurons-and-the-McCulloch-Pitts-Model)\n- [Frank Rosenblatt's Perceptron](#Frank-Rosenblatt's-Perceptron)\n - [The Unit Step Function](#The-Unit-Step-Function)\n - [The Perceptron Learning Rule](#The-Perceptron-Learning-Rule)\n - [Implementing the Perceptron Rule in Python](#Implementing-the-Perceptron-Rule-in-Python)\n - [Problems with Perceptrons](#Problems-with-Perceptrons)\n- [Adaptive Linear Neurons and the Delta Rule](#Adaptive-Linear-Neurons-and-the-Delta-Rule)\n - [Gradient Descent](#Gradient-Descent)\n - [The Gradient Descent Rule in Action](#The-Gradient-Descent-Rule-in-Action)\n - [Online Learning via Stochastic Gradient Descent](#Online-Learning-via-Stochastic-Gradient-Descent)\n- [What's Next?](#What's-Next?)\n- [References](#References)\n\n
    \n
    \n\n# Introduction\n\n[[back to top](#Sections)]\n\nMachine learning is one of the hottest and most exciting fields in the modern age of technology. Thanks to machine learning, we enjoy robust email spam filters, convenient text and voice recognition, reliable web search engines, challenging chess players, and, hopefully soon, safe and efficient self-driving cars. \n\nWithout any doubt, machine learning has become a big and popular field, and sometimes it may be challenging to see the (random) forest for the (decision) trees. Thus, I thought that it might be worthwhile to explore different machine learning algorithms in more detail by not only discussing the theory but also by implementing them step by step.\n\nTo briefly summarize what machine learning is all about: \"[Machine learning is the] field of study that gives computers the ability to learn without being explicitly programmed\" (Arthur Samuel, 1959). Machine learning is about the development and use of algorithms that can recognize patterns in data in order to make decisions based on statistics, probability theory, combinatorics, and optimization.\n\n\n\n\nThe first article in this series will introduce perceptrons and the adaline (ADAptive LINear NEuron), which fall into the category of single-layer neural networks. The perceptron is not only the first algorithmically described learning algorithm [[1](#References)], but it is also very intuitive, easy to implement, and a good entry point to the (re-discovered) modern state-of-the-art machine learning algorithms: Artificial neural networks (or \"deep learning\" if you like). As we will see later, the adaline is a consequent improvement of the perceptron algorithm and offers a good opportunity to learn about a popular optimization algorithm in machine learning: gradient descent.\n\n
    \n
    \n\n# Artificial Neurons and the McCulloch-Pitts Model\n\n[[back to top](#Sections)]\n\nThe initial idea of the perceptron dates back to the work of Warren McCulloch and Walter Pitts in 1943 [[2](#References)], who drew an analogy between biological neurons and simple logic gates with binary outputs. In more intuitive terms, neurons can be understood as the subunits of a neural network in a biological brain. Here, the signals of variable magnitudes arrive at the dendrites. Those input signals are then accumulated in the cell body of the neuron, and if the accumulated signal exceeds a certain threshold, a output signal is generated that which will be passed on by the axon.\n\n\n\n\n
    \n
    \n\n# Frank Rosenblatt's Perceptron\n\n[[back to top](#Sections)]\n\nTo continue with the story, a few years after McCulloch and Walter Pitt, Frank Rosenblatt published the first concept of the Perceptron learning rule [[1](#References)]. The main idea was to define an algorithm in order to learn the values of the weights $w$ that are then multiplied with the input features in order to make a decision whether a neuron fires or not. In context of pattern classification, such an algorithm could be useful to determine if a sample belongs to one class or the other. \n\n\n\n\n\nTo put the perceptron algorithm into the broader context of machine learning: The perceptron belongs to the category of supervised learning algorithms, single-layer binary linear classifiers to be more specific. In brief, the task is to predict to which of two possible categories a certain data point belongs based on a set of input variables. In this article, I don't want to discuss the concept of predictive modeling and classification in too much detail, but if you prefer more background information, please see my previous article \"[Introduction to supervised learning](http://sebastianraschka.com/Articles/2014_intro_supervised_learning.html)\".\n\n
    \n
    \n\n## The Unit Step Function\n\n[[back to top](#Sections)]\n\nBefore we dive deeper into the algorithm(s) for learning the weights of the artificial neuron, let us take a brief look at the basic notation. In the following sections, we will label the *positive* and *negative* class in our binary classification setting as \"1\" and \"-1\", respectively. Next, we define an activation function $g(\\mathbf{z})$ that takes a linear combination of the input values $\\mathbf{x}$ and weights $\\mathbf{w}$ as input ($\\mathbf{z} = w_1x_{1} + \\dots + w_mx_{m}$), and if $g(\\mathbf{z})$ is greater than a defined threshold $\\theta$ we predict 1 and -1 otherwise; in this case, this activation function $g$ is an alternative form of a simple \"unit step function,\" which is sometimes also called \"Heaviside step function.\" \n\n*(Please note that the *unit step* is classically defined as being equal to 0 if $ z < 0$ and 1 for $z \\ge 0$; nonetheless, we will refer to the following piece-wise linear function with -1 if $z < \\theta$ and 1 for $z \\ge \\theta$ as *unit step function* for simplicity).*\n\n$$\n g(\\mathbf{z}) =\\begin{cases}\n 1 & \\text{if $\\mathbf{z} \\ge \\theta$}\\\\\n -1 & \\text{otherwise}.\n \\end{cases}\n$$\n\n\nwhere\n\n$$\\mathbf{z} = w_1x_{1} + \\dots + w_mx_{m} = \\sum_{j=1}^{m} x_{j}w_{j} \\\\ = \\mathbf{w}^T\\mathbf{x}$$\n\n$\\mathbf{w}$ is the feature vector, and $\\mathbf{x}$ is an $m$-dimensional sample from the training dataset:\n\n$$ \n\\mathbf{w} = \\begin{bmatrix}\n w_{1} \\\\\n \\vdots \\\\\n w_{m}\n\\end{bmatrix}\n\\quad \\mathbf{x} = \\begin{bmatrix}\n x_{1} \\\\\n \\vdots \\\\\n x_{m}\n\\end{bmatrix}$$\n\n\n\nIn order to simplify the notation, we bring $\\theta$ to the left side of the equation and define $w_0 = -\\theta \\text{ and } x_0=1$ \n\nso that \n\n$$\\begin{equation}\n g({\\mathbf{z}}) =\\begin{cases}\n 1 & \\text{if $\\mathbf{z} \\ge 0$}\\\\\n -1 & \\text{otherwise}.\n \\end{cases}\n\\end{equation}$$\n\nand\n\n\n$$\\mathbf{z} = w_0x_{0} + w_1x_{1} + \\dots + w_mx_{m} = \\sum_{j=0}^{m} x_{j}w_{j} \\\\ = \\mathbf{w}^T\\mathbf{x}.$$\n\n\n\n\n
    \n
    \n\n## The Perceptron Learning Rule\n\n[[back to top](#Sections)]\n\nIt might sound like extreme case of a reductionist approach, but the idea behind this \"thresholded\" perceptron was to mimic how a single neuron in the brain works: It either \"fires\" or not. To summarize the main points from the previous section: A perceptron receives multiple input signals, and if the sum of the input signals exceed a certain threshold it either returns a signal or remains \"silent\" otherwise. What made this a \"machine learning\" algorithm was Frank Rosenblatt's idea of the perceptron learning rule: The perceptron algorithm is about learning the weights for the input signals in order to draw linear decision boundary that allows us to discriminate between the two linearly separable classes +1 and -1.\n\n\n\n\n\n\nRosenblatt's initial perceptron rule is fairly simple and can be summarized by the following steps: \n\n1. Initialize the weights to 0 or small random numbers.\n2. For each training sample $\\mathbf{x^{(i)}}$:\n 2. Calculate the *output* value.\n 2. Update the weights.\n\nThe output value is the class label predicted by the unit step function that we defined earlier (output $=g(\\mathbf{z})$) and the weight update can be written more formally as $w_j := w_j + \\Delta w_j$.\n\nThe value for updating the weights at each increment is calculated by the learning rule\n\n$\\Delta w_j = \\eta \\; (\\text{target}^{(i)} - \\text{output}^{(i)})\\;x^{(i)}_{j}$\n\nwhere $\\eta$ is the learning rate (a constant between 0.0 and 1.0), \"target\" is the true class label, and the \"output\" is the predicted class label.\n\nIt is important to note that all weights in the weight vector are being updated simultaneously. Concretely, for a 2-dimensional dataset, we would write the update as:\n\n$\\Delta w_0 = \\eta(\\text{target}^{(i)} - \\text{output}^{(i)})$ \n$\\Delta w_1 = \\eta(\\text{target}^{(i)} - \\text{output}^{(i)})\\;x^{(i)}_{1}$ \n$\\Delta w_2 = \\eta(\\text{target}^{(i)} - \\text{output}^{(i)})\\;x^{(i)}_{2}$ \n\nBefore we implement the perceptron rule in Python, let us make a simple thought experiment to illustrate how beautifully simple this learning rule really is. In the two scenarios where the perceptron predicts the class label correctly, the weights remain unchanged:\n\n- $\\Delta w_j = \\eta(-1^{(i)} - -1^{(i)})\\;x^{(i)}_{j} = 0$ \n- $\\Delta w_j = \\eta(1^{(i)} - 1^{(i)})\\;x^{(i)}_{j} = 0$ \n\nHowever, in case of a wrong prediction, the weights are being \"pushed\" towards the direction of the positive or negative target class, respectively:\n\n- $\\Delta w_j = \\eta(1^{(i)} - -1^{(i)})\\;x^{(i)}_{j} = \\eta(2)\\;x^{(i)}_{j}$ \n- $\\Delta w_j = \\eta(-1^{(i)} - 1^{(i)})\\;x^{(i)}_{j} = \\eta(-2)\\;x^{(i)}_{j}$ \n\n\n\nIt is important to note that the convergence of the perceptron is only guaranteed if the two classes are linearly separable. If the two classes can't be separated by a linear decision boundary, we can set a maximum number of passes over the training dataset (\"epochs\") and/or a threshold for the number of tolerated misclassifications.\n\n
    \n
    \n\n## Implementing the Perceptron Rule in Python\n\n[[back to top](#Sections)]\n\nIn this section, we will implement the simple perceptron learning rule in Python to classify flowers in the Iris dataset.\nPlease note that I omitted some \"safety checks\" for clarity, for a more \"robust\" version please see the following [code on GitHub](https://github.com/rasbt/mlxtend/blob/master/mlxtend/classifier/perceptron.py).\n\n\n```python\nimport numpy as np\n\nclass Perceptron(object):\n \n def __init__(self, eta=0.01, epochs=50):\n self.eta = eta\n self.epochs = epochs\n\n def train(self, X, y):\n\n self.w_ = np.zeros(1 + X.shape[1])\n self.errors_ = []\n\n for _ in range(self.epochs):\n errors = 0\n for xi, target in zip(X, y):\n update = self.eta * (target - self.predict(xi))\n self.w_[1:] += update * xi\n self.w_[0] += update\n errors += int(update != 0.0)\n self.errors_.append(errors)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def predict(self, X):\n return np.where(self.net_input(X) >= 0.0, 1, -1)\n```\n\nFor the following example, we will load the Iris data set from the [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml/) and only focus on the two flower species *Setosa* and *Versicolor*. Furthermore, we will only use the two features *sepal length* and *petal length* for visualization purposes.\n\n\n```python\nimport pandas as pd\ndf = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)\n\n# setosa and versicolor\ny = df.iloc[0:100, 4].values\ny = np.where(y == 'Iris-setosa', -1, 1)\n\n# sepal length and petal length\nX = df.iloc[0:100, [0,2]].values\n```\n\n\n```python\n!pip install mlxtend\n```\n\n Collecting mlxtend\n Downloading mlxtend-0.10.0-py2.py3-none-any.whl (1.3MB)\n \u001b[K 100% |████████████████████████████████| 1.3MB 927kB/s ta 0:00:01\n \u001b[?25hRequirement already satisfied: scikit-learn>=0.18 in /srv/venv/lib/python3.6/site-packages (from mlxtend)\n Requirement already satisfied: setuptools in /srv/venv/lib/python3.6/site-packages (from mlxtend)\n Requirement already satisfied: matplotlib>=1.5.1 in /srv/venv/lib/python3.6/site-packages (from mlxtend)\n Requirement already satisfied: numpy>=1.10.4 in /srv/venv/lib/python3.6/site-packages (from mlxtend)\n Requirement already satisfied: pandas>=0.17.1 in /srv/venv/lib/python3.6/site-packages (from mlxtend)\n Requirement already satisfied: scipy>=0.17 in /srv/venv/lib/python3.6/site-packages (from mlxtend)\n Requirement already satisfied: pyparsing!=2.0.0,!=2.0.4,!=2.1.2,!=2.1.6,>=1.5.6 in /srv/venv/lib/python3.6/site-packages (from matplotlib>=1.5.1->mlxtend)\n Requirement already satisfied: pytz in /srv/venv/lib/python3.6/site-packages (from matplotlib>=1.5.1->mlxtend)\n Requirement already satisfied: python-dateutil in /srv/venv/lib/python3.6/site-packages (from matplotlib>=1.5.1->mlxtend)\n Requirement already satisfied: cycler>=0.10 in /srv/venv/lib/python3.6/site-packages (from matplotlib>=1.5.1->mlxtend)\n Requirement already satisfied: six>=1.10 in /srv/venv/lib/python3.6/site-packages (from matplotlib>=1.5.1->mlxtend)\n Installing collected packages: mlxtend\n Successfully installed mlxtend-0.10.0\n\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mlxtend.plotting import plot_decision_regions\n\nppn = Perceptron(epochs=10, eta=0.1)\n\nppn.train(X, y)\nprint('Weights: %s' % ppn.w_)\nplot_decision_regions(X, y, clf=ppn)\nplt.title('Perceptron')\nplt.xlabel('sepal length [cm]')\nplt.ylabel('petal length [cm]')\nplt.show()\n\nplt.plot(range(1, len(ppn.errors_)+1), ppn.errors_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Misclassifications')\nplt.show()\n\n```\n\nAs we can see, the perceptron converges after the 6th iteration and separates the two flower classes perfectly.\n\n
    \n
    \n\n## Problems with Perceptrons\n\n[[back to top](#Sections)]\n\nAlthough the perceptron classified the two Iris flower classes perfectly, convergence is one of the biggest problems of the perceptron. Frank Rosenblatt proofed mathematically that the perceptron learning rule converges if the two classes can be separated by linear hyperplane, but problems arise if the classes cannot be separated perfectly by a linear classifier. To demonstrate this issue, we will use two different classes and features from the Iris dataset.\n\n\n```python\n# versicolor and virginica\ny2 = df.iloc[50:150, 4].values\ny2 = np.where(y2 == 'Iris-virginica', -1, 1)\n\n# sepal width and petal width\nX2 = df.iloc[50:150, [1,3]].values\n\nppn = Perceptron(epochs=25, eta=0.01)\nppn.train(X2, y2)\n\nplot_decision_regions(X2, y2, clf=ppn)\nplt.show()\n\nplt.plot(range(1, len(ppn.errors_)+1), ppn.errors_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Misclassifications')\nplt.show()\n```\n\n\n```python\nprint('Total number of misclassifications: %d of 100' % (y2 != ppn.predict(X2)).sum())\n```\n\n Total number of misclassifications: 43 of 100\n\n\nEven at a lower training rate, the perceptron failed to find a good decision boundary since one or more samples will always be misclassified in every epoch so that the learning rule never stops updating the weights.\n\nIt may seem paradoxical in this context that another shortcoming of the perceptron algorithm is that it stops updating the weights as soon as all samples are classified correctly. Our intuition tells us that a decision boundary with a large margin between the classes (as indicated by the dashed line in the figure below) likely has a better generalization error than the decision boundary of the perceptron. But large-margin classifiers such as Support Vector Machines are a topic for another time.\n\n\n\n
    \n
    \n\n# Adaptive Linear Neurons and the Delta Rule\n\n[[back to top](#Sections)]\n\nThe perceptron surely was very popular at the time of its discovery, however, it only took a few years until Bernard Widrow and his doctoral student Tedd Hoff proposed the idea of the Adaptive Linear Neuron (adaline) [[3](#References)].\n\nIn contrast to the perceptron rule, the delta rule of the adaline (also known as Widrow-Hoff\" rule or Adaline rule) updates the weights based on a linear activation function rather than a unit step function; here, this linear activation function $g(\\mathbf{z})$ is just the identity function of the net input $g(\\mathbf{w}^T\\mathbf{x}) = \\mathbf{w}^T\\mathbf{x}$. In the next section, we will see why this linear activation is an improvement over the perceptron update and where the name \"delta rule\" comes from.\n\n\n\n
    \n
    \n\n## Gradient Descent\n\n[[back to top](#Sections)]\n\nBeing a continuous function, one of the biggest advantages of the linear activation function over the unit step function is that it is differentiable. This property allows us to define a cost function $J(\\mathbf{w})$ that we can minimize in order to update our weights. In the case of the linear activation function, we can define the cost function $J(\\mathbf{w})$ as the *sum of squared errors* (SSE), which is similar to the cost function that is minimized in ordinary least squares (OLS) linear regression.\n\n$$J(\\mathbf{w}) = \\frac{1}{2} \\sum_{i} (\\text{target}^{(i)} - \\text{output}^{(i)})^2 \\quad \\quad \\text{output}^{(i)} \\in \\mathbb{R}$$\n\n(The fraction $\\frac{1}{2}$ is just used for convenience to derive the gradient as we will see in the next paragraphs.)\n\nIn order to minimize the SSE cost function, we will use gradient descent, a simple yet useful optimization algorithm that is often used in machine learning to find the local minimum of linear systems.\n\nBefore we get to the fun part (calculus), let us consider a convex cost function for one single weight. As illustrated in the figure below, we can describe the principle behind gradient descent as \"climbing down a hill\" until a local or global minimum is reached. At each step, we take a step into the opposite direction of the gradient, and the step size is determined by the value of the learning rate as well as the slope of the gradient.\n\n\n\nNow, as promised, onto the fun part -- deriving the Adaline learning rule.\nAs mentioned above, each update is updated by taking a step into the opposite direction of the gradient $\\Delta \\mathbf{w} = - \\eta \\nabla J(\\mathbf{w})$, thus, we have to compute the partial derivative of the cost function for each weight in the weight vector: $\\Delta w_j = - \\eta \\frac{\\partial J}{\\partial w_j}$. \n\n\n\n\nThe partial derivative of the SSE cost function for a particular weight can be calculated as follows:\n\n$$\\begin{equation}\n \\frac{\\partial J}{\\partial w_j} = \\frac{\\partial }{\\partial w_j} \\frac{1}{2} \\sum_i (t^{(i)} - o^{(i)})^2 \\\\\n= \\frac{1}{2} \\sum_i \\frac{\\partial}{\\partial w_j} (t^{(i)} - o^{(i)})^2 \\\\\n= \\frac{1}{2} \\sum_i 2 (t^{(i)} - o^{(i)}) \\frac{\\partial}{\\partial w_j} (t^{(i)} - o^{(i)}) \\\\\n= \\sum_i (t^{(i)} - o^{(i)}) \\frac{\\partial}{\\partial w_j} \\bigg(t^{(i)} - \\sum_j w_j x^{(i)}_{j}\\bigg) \\\\\n= \\sum_i (t^{(i)} - o^{(i)})(-x^{(i)}_{j}) \n\\end{equation}$$\n\n(t = target, o = output)\n\nAnd if we plug the results back into the learning rule, we get\n\n$\\Delta w_j = - \\eta \\frac{\\partial J}{\\partial w_j} = - \\eta \\sum_i (t^{(i)} - o^{(i)})(- x^{(i)}_{j}) = \\eta \\sum_i (t^{(i)} - o^{(i)})x^{(i)}_{j}$,\n\nEventually, we can apply a simultaneous weight update similar to the perceptron rule: \n\n$\\mathbf{w} := \\mathbf{w} + \\Delta \\mathbf{w}$.\n\n**Although, the learning rule above looks identical to the perceptron rule, we shall note the two main differences:**\n\n1. Here, the output \"o\" is a real number and not a class label as in the perceptron learning rule.\n2. The weight update is calculated based on all samples in the training set (instead of updating the weights incrementally after each sample), which is why this approach is also called \"batch\" gradient descent.\n\n
    \n
    \n\n## The Gradient Descent Rule in Action\n\n[[back to top](#Sections)]\n\nNow, it's time to implement the gradient descent rule in Python.\n\n\n```python\nimport numpy as np\n\nclass AdalineGD(object):\n \n def __init__(self, eta=0.01, epochs=50): \n self.eta = eta\n self.epochs = epochs\n\n def train(self, X, y):\n\n self.w_ = np.zeros(1 + X.shape[1])\n self.cost_ = []\n\n for i in range(self.epochs):\n output = self.net_input(X)\n errors = (y - output)\n self.w_[1:] += self.eta * X.T.dot(errors)\n self.w_[0] += self.eta * errors.sum()\n cost = (errors**2).sum() / 2.0\n self.cost_.append(cost)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def activation(self, X):\n return self.net_input(X)\n\n def predict(self, X):\n return np.where(self.activation(X) >= 0.0, 1, -1)\n```\n\nIn practice, it often requires some experimentation to find a good learning rate for optimal convergence, thus, we will start by plotting the cost for two different learning rates.\n\n\n```python\nada = AdalineGD(epochs=10, eta=0.01).train(X, y)\nplt.plot(range(1, len(ada.cost_)+1), np.log10(ada.cost_), marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('log(Sum-squared-error)')\nplt.title('Adaline - Learning rate 0.01')\nplt.show()\n\nada = AdalineGD(epochs=10, eta=0.0001).train(X, y)\nplt.plot(range(1, len(ada.cost_)+1), ada.cost_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Sum-squared-error')\nplt.title('Adaline - Learning rate 0.0001')\nplt.show()\n```\n\nThe two plots above nicely emphasize the importance of plotting learning curves by illustrating two most common problems with gradient descent:\n\n1. If the learning rate is too large, gradient descent will overshoot the minima and diverge.\n2. If the learning rate is too small, the algorithm will require too many epochs to converge and can become trapped in local minima more easily.\n\n\n\n\n\nGradient descent is also a good example why feature scaling is important for many machine learning algorithms. \nIt is not only easier to find an appropriate learning rate if the features are on the same scale, but it also often leads to faster convergence and can prevent the weights from becoming too small (numerical stability).\n\nA common way of feature scaling is standardization\n\n$$\\mathbf{x}_{j, std} = \\frac{\\mathbf{x}_j - \\mathbf{\\mu}_j}{\\mathbf{\\sigma}_j}$$\n\nwhere $\\mathbf{\\mu}_j$ is the sample mean of the feature $\\mathbf{x}_{j}$ and $\\mathbf{\\sigma}_j$ the standard deviation, respectively. After standardization, the features will have unit variance and are centered around mean zero. \n\n\n```python\n# standardize features\nX_std = np.copy(X)\nX_std[:,0] = (X[:,0] - X[:,0].mean()) / X[:,0].std()\nX_std[:,1] = (X[:,1] - X[:,1].mean()) / X[:,1].std()\n```\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mlxtend.evaluate import plot_decision_regions\n\nada = AdalineGD(epochs=15, eta=0.01)\n\nada.train(X_std, y)\nplot_decision_regions(X_std, y, clf=ada)\nplt.title('Adaline - Gradient Descent')\nplt.xlabel('sepal length [standardized]')\nplt.ylabel('petal length [standardized]')\nplt.show()\n\nplt.plot(range(1, len( ada.cost_)+1), ada.cost_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Sum-squared-error')\nplt.show()\n```\n\n\n\n
    \n
    \n\n## Online Learning via Stochastic Gradient Descent\n\n[[back to top](#Sections)]\n\nThe previous section was all about \"batch\" gradient descent learning. The \"batch\" updates refers to the fact that the cost function is minimized based on the complete training data set. If we think back to the perceptron rule, we remember that it performed the weight update incrementally after each individual training sample. This approach is also called \"online\" learning, and in fact, this is also how Adaline was first described by Bernard Widrow et al. [[3](#References)]\n\nThe process of incrementally updating the weights is also called \"stochastic\" gradient descent since it approximates the minimization of the cost function. Although the stochastic gradient descent approach might sound inferior to gradient descent due its \"stochastic\" nature and the \"approximated\" direction (gradient), it can have certain advantages in practice. Often, stochastic gradient descent converges much faster than gradient descent since the updates are applied immediately after each training sample; stochastic gradient descent is computationally more efficient, especially for very large datasets. Another advantage of online learning is that the classifier can be immediately updated as new training data arrives, e.g., in web applications, and old training data can be discarded if storage is an issue. In large-scale machine learning systems, it is also common practice to use so-called \"mini-batches\", a compromise with smoother convergence than stochastic gradient descent.\n\nIn the interests of completeness let us also implement the stochastic gradient descent Adaline and confirm that it converges on the linearly separable iris dataset.\n\n\n```python\nimport numpy as np\n\nclass AdalineSGD(object):\n \n def __init__(self, eta=0.01, epochs=50):\n self.eta = eta\n self.epochs = epochs\n\n def train(self, X, y, reinitialize_weights=True):\n\n if reinitialize_weights:\n self.w_ = np.zeros(1 + X.shape[1])\n self.cost_ = []\n\n for i in range(self.epochs):\n for xi, target in zip(X, y):\n output = self.net_input(xi)\n error = (target - output)\n self.w_[1:] += self.eta * xi.dot(error)\n self.w_[0] += self.eta * error\n \n cost = ((y - self.activation(X))**2).sum() / 2.0\n self.cost_.append(cost)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def activation(self, X):\n return self.net_input(X)\n\n def predict(self, X):\n return np.where(self.activation(X) >= 0.0, 1, -1)\n```\n\nOne more advice before we let the adaline learn via stochastic gradient descent is to shuffle the training dataset to iterate over the training samples in random order. \n\nWe shall note that the \"standard\" stochastic gradient descent algorithm uses sampling \"with replacement,\" which means that at each iteration, a training sample is chosen randomly from the entire training set. In contrast, sampling \"without replacement,\" which means that each training sample is evaluated exactly once in every epoch, is not only easier to implement but also shows a better performance in empirical comparisons. A more detailed discussion about this topic can be found in Benjamin Recht and Christopher Re's paper *Beneath the valley of the noncommutative arithmetic-geometric mean inequality: conjectures, case-studies, and consequences* [[4](#References)].\n\n\n\n```python\nada = AdalineSGD(epochs=15, eta=0.01)\n\n# shuffle data\nnp.random.seed(123)\nidx = np.random.permutation(len(y))\nX_shuffled, y_shuffled = X_std[idx], y[idx]\n\n# train and adaline and plot decision regions\nada.train(X_shuffled, y_shuffled)\nplot_decision_regions(X_shuffled, y_shuffled, clf=ada)\nplt.title('Adaline - Gradient Descent')\nplt.xlabel('sepal length [standardized]')\nplt.ylabel('petal length [standardized]')\nplt.show()\n\nplt.plot(range(1, len(ada.cost_)+1), ada.cost_, marker='o')\nplt.xlabel('Iterations')\nplt.ylabel('Sum-squared-error')\nplt.show()\n```\n\n
    \n
    \n\n# What's Next?\n\n[[back to top](#Sections)]\n\nAlthough we covered many different topics during this article, we just scratched the surface of artificial neurons. \n\nIn later articles, we will take a look at different approaches to dynamically adjust the learning rate, the concepts of \"One-vs-All\" and \"One-vs-One\" for multi-class classification, regularization to overcome overfitting by introducing additional information, dealing with nonlinear problems and multilayer neural networks, different activation functions for artificial neurons, and related concepts such as logistic regression and support vector machines.\n\n\n\n\n\n
    \n
    \n\n### References\n\n[[back to top](#Sections)]\n\n[1] F. Rosenblatt. The perceptron, a perceiving and recognizing automaton Project Para. Cornell Aeronautical Laboratory, 1957.\n\n[2] W. S. McCulloch and W. Pitts. A logical calculus of the ideas immanent in nervous activity. The bulletin of mathematical biophysics, 5(4):115–133, 1943.\n\n[3] B. Widrow et al. Adaptive ”Adaline” neuron using chemical ”memistors”. Number Technical Report 1553-2. Stanford Electron. Labs., Stanford, CA, October 1960.\n\n[4] B. Recht and C. R ́e. Beneath the valley of the noncommutative arithmetic-geometric mean inequality: conjectures, case-studies, and consequences. arXiv preprint arXiv:1202.4184, 2012.\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\ntested; gopal\n```\n", "meta": {"hexsha": "cae92dfa9a2387bc1dd478a52e9c829bb366f5da", "size": 157507, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tests/ml-books/singlelayer_nn(perceptron).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/ml-books/singlelayer_nn(perceptron).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/ml-books/singlelayer_nn(perceptron).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": 118.8732075472, "max_line_length": 16468, "alphanum_fraction": 0.8561651228, "converted": true, "num_tokens": 7818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.15002881674163046, "lm_q1q2_score": 0.06224678290235742}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\n!ls \\content\n```\n\n ls: cannot access 'content': No such file or directory\n\n\n\nAdversarial Example Generation\n==============================\n\n**Author:** `Nathan Inkawhich `__\n\nIf you are reading this, hopefully you can appreciate how effective some\nmachine learning models are. Research is constantly pushing ML models to\nbe faster, more accurate, and more efficient. However, an often\noverlooked aspect of designing and training models is security and\nrobustness, especially in the face of an adversary who wishes to fool\nthe model.\n\nThis tutorial will raise your awareness to the security vulnerabilities\nof ML models, and will give insight into the hot topic of adversarial\nmachine learning. You may be surprised to find that adding imperceptible\nperturbations to an image *can* cause drastically different model\nperformance. Given that this is a tutorial, we will explore the topic\nvia example on an image classifier. Specifically we will use one of the\nfirst and most popular attack methods, the Fast Gradient Sign Attack\n(FGSM), to fool an MNIST classifier.\n\n\n\n\nThreat Model\n------------\n\nFor context, there are many categories of adversarial attacks, each with\na different goal and assumption of the attacker’s knowledge. However, in\ngeneral the overarching goal is to add the least amount of perturbation\nto the input data to cause the desired misclassification. There are\nseveral kinds of assumptions of the attacker’s knowledge, two of which\nare: **white-box** and **black-box**. A *white-box* attack assumes the\nattacker has full knowledge and access to the model, including\narchitecture, inputs, outputs, and weights. A *black-box* attack assumes\nthe attacker only has access to the inputs and outputs of the model, and\nknows nothing about the underlying architecture or weights. There are\nalso several types of goals, including **misclassification** and\n**source/target misclassification**. A goal of *misclassification* means\nthe adversary only wants the output classification to be wrong but does\nnot care what the new classification is. A *source/target\nmisclassification* means the adversary wants to alter an image that is\noriginally of a specific source class so that it is classified as a\nspecific target class.\n\nIn this case, the FGSM attack is a *white-box* attack with the goal of\n*misclassification*. With this background information, we can now\ndiscuss the attack in detail.\n\nFast Gradient Sign Attack\n-------------------------\n\nOne of the first and most popular adversarial attacks to date is\nreferred to as the *Fast Gradient Sign Attack (FGSM)* and is described\nby Goodfellow et. al. in `Explaining and Harnessing Adversarial\nExamples `__. The attack is remarkably\npowerful, and yet intuitive. It is designed to attack neural networks by\nleveraging the way they learn, *gradients*. The idea is simple, rather\nthan working to minimize the loss by adjusting the weights based on the\nbackpropagated gradients, the attack *adjusts the input data to maximize\nthe loss* based on the same backpropagated gradients. In other words,\nthe attack uses the gradient of the loss w.r.t the input data, then\nadjusts the input data to maximize the loss.\n\nBefore we jump into the code, let’s look at the famous\n`FGSM `__ panda example and extract\nsome notation.\n\n.. figure:: /_static/img/fgsm_panda_image.png\n :alt: fgsm_panda_image\n\nFrom the figure, $\\mathbf{x}$ is the original input image\ncorrectly classified as a “panda”, $y$ is the ground truth label\nfor $\\mathbf{x}$, $\\mathbf{\\theta}$ represents the model\nparameters, and $J(\\mathbf{\\theta}, \\mathbf{x}, y)$ is the loss\nthat is used to train the network. The attack backpropagates the\ngradient back to the input data to calculate\n$\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y)$. Then, it adjusts\nthe input data by a small step ($\\epsilon$ or $0.007$ in the\npicture) in the direction (i.e.\n$sign(\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y))$) that will\nmaximize the loss. The resulting perturbed image, $x'$, is then\n*misclassified* by the target network as a “gibbon” when it is still\nclearly a “panda”.\n\nHopefully now the motivation for this tutorial is clear, so lets jump\ninto the implementation.\n\n\n\n\n\n```python\nfrom __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import DataLoader, TensorDataset\n\nimport torchvision.utils\nfrom torchvision import models\nimport torchvision.datasets as dsets\nimport torchvision.transforms as transforms\n\n```\n\nImplementation\n--------------\n\nIn this section, we will discuss the input parameters for the tutorial,\ndefine the model under attack, then code the attack and run some tests.\n\nInputs\n~~~~~~\n\nThere are only three inputs for this tutorial, and are defined as\nfollows:\n\n- **epsilons** - List of epsilon values to use for the run. It is\n important to keep 0 in the list because it represents the model\n performance on the original test set. Also, intuitively we would\n expect the larger the epsilon, the more noticeable the perturbations\n but the more effective the attack in terms of degrading model\n accuracy. Since the data range here is $[0,1]$, no epsilon\n value should exceed 1.\n\n- **pretrained_model** - path to the pretrained MNIST model which was\n trained with\n `pytorch/examples/mnist `__.\n For simplicity, download the pretrained model `here `__.\n\n- **use_cuda** - boolean flag to use CUDA if desired and available.\n Note, a GPU with CUDA is not critical for this tutorial as a CPU will\n not take much time.\n\n\n\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/gdrive')\n\n```\n\n Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n \n Enter your authorization code:\n ··········\n Mounted at /gdrive\n\n\n\n```python\npretrained_model = '/gdrive/My Drive/Tmp/cifar_net.pth' #pretrained_model = \"lenet_mnist_model.pth\"\nuse_cuda=True\n```\n\nModel Under Attack\n~~~~~~~~~~~~~~~~~~\n\nAs mentioned, the model under attack is the same MNIST model from\n`pytorch/examples/mnist `__.\nYou may train and save your own MNIST model or you can download and use\nthe provided model. The *Net* definition and test dataloader here have\nbeen copied from the MNIST example. The purpose of this section is to\ndefine the model and dataloader, then initialize the model and load the\npretrained weights.\n\n\n\n\n\n```python\n# transform = transforms.Compose(\n# [transforms.ToTensor(),\n# transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])\n\n\n# normalize to range [0 1]; also the model has been trained on this range. Later I found this is not very imortant and [-1 1] also works fine,\ntransform = transforms.Compose( \n [transforms.ToTensor()]) \n\n\n# cifar10_train = dsets.CIFAR10(root='./data', train=True,\n# download=True, transform=transform)\ncifar10_test = dsets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n\n\ntest_loader = torch.utils.data.DataLoader(cifar10_test, batch_size=1,\n shuffle=False, num_workers=1)\n\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n\n```\n\n Files already downloaded and verified\n\n\n\n```python\n# simply define a silu function\ndef srelu(input, slope):\n return slope * F.relu(input)\n\nclass SReLU(nn.Module):\n def __init__(self, slope):\n super().__init__() # init the base class\n self.slope = slope\n\n def forward(self, input):\n return srelu(input, self.slope) # simply apply already implemented SiLU\n```\n\n\n```python\nclass Net(nn.Module):\n def __init__(self, slope):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n self.slope = slope\n\n def forward(self, x):\n x = self.pool(srelu(self.conv1(x), self.slope))\n x = self.pool(srelu(self.conv2(x), self.slope))\n x = x.view(-1, 16 * 5 * 5)\n x = srelu(self.fc1(x), self.slope)\n x = srelu(self.fc2(x), self.slope)\n x = self.fc3(x)\n return F.log_softmax(x, dim=1)\n\n\n# Define what device we are using\nprint(\"CUDA Available: \",torch.cuda.is_available())\ndevice = torch.device(\"cuda\" if (use_cuda and torch.cuda.is_available()) else \"cpu\")\n\n# # Initialize the network\nmodel = Net(1).to(device)\n\n# # Load the pretrained model\nmodel.load_state_dict(torch.load(pretrained_model, map_location='cpu'))\n\n# # Set the model in evaluation mode. In this case this is for the Dropout layers\nmodel.eval()\n```\n\n CUDA Available: True\n\n\n\n\n\n Net(\n (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))\n (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n (fc1): Linear(in_features=400, out_features=120, bias=True)\n (fc2): Linear(in_features=120, out_features=84, bias=True)\n (fc3): Linear(in_features=84, out_features=10, bias=True)\n )\n\n\n\nFGSM Attack\n~~~~~~~~~~~\n\nNow, we can define the function that creates the adversarial examples by\nperturbing the original inputs. The ``fgsm_attack`` function takes three\ninputs, *image* is the original clean image ($x$), *epsilon* is\nthe pixel-wise perturbation amount ($\\epsilon$), and *data_grad*\nis gradient of the loss w.r.t the input image\n($\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y)$). The function\nthen creates perturbed image as\n\n\\begin{align}perturbed\\_image = image + epsilon*sign(data\\_grad) = x + \\epsilon * sign(\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y))\\end{align}\n\nFinally, in order to maintain the original range of the data, the\nperturbed image is clipped to range $[0,1]$.\n\n\n\n\n\n```python\n# FGSM attack code\ndef fgsm_attack(image, epsilon, data_grad):\n # Collect the element-wise sign of the data gradient\n sign_data_grad = data_grad.sign()\n # Create the perturbed image by adjusting each pixel of the input image\n perturbed_image = image + epsilon*sign_data_grad\n # Adding clipping to maintain [0,1] range\n perturbed_image = torch.clamp(perturbed_image, 0, 1)\n # Return the perturbed image\n return perturbed_image\n```\n\nTesting Function\n~~~~~~~~~~~~~~~~\n\nFinally, the central result of this tutorial comes from the ``test``\nfunction. Each call to this test function performs a full test step on\nthe MNIST test set and reports a final accuracy. However, notice that\nthis function also takes an *epsilon* input. This is because the\n``test`` function reports the accuracy of a model that is under attack\nfrom an adversary with strength $\\epsilon$. More specifically, for\neach sample in the test set, the function computes the gradient of the\nloss w.r.t the input data ($data\\_grad$), creates a perturbed\nimage with ``fgsm_attack`` ($perturbed\\_data$), then checks to see\nif the perturbed example is adversarial. In addition to testing the\naccuracy of the model, the function also saves and returns some\nsuccessful adversarial examples to be visualized later.\n\n\n\n\n\n```python\ndef test_scale( model, device, test_loader, epsilon, scale=1 ):\n\n # Accuracy counter\n correct = 0\n adv_examples = []\n\n # Loop over all examples in test set\n for data, target in test_loader:\n\n # scaling the inout\n data = scale * data\n data = torch.clamp(data, 0, 1)\n \n # Send the data and label to the device\n data, target = data.to(device), target.to(device)\n\n # Set requires_grad attribute of tensor. Important for Attack\n data.requires_grad = True\n\n # Forward pass the data through the model\n output = model(data)\n init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n\n # If the initial prediction is wrong, dont bother attacking, just move on\n # import pdb; pdb.set_trace()\n if init_pred.item() != target.item():\n continue\n\n # Calculate the loss\n loss = F.nll_loss(output, target)\n\n # Zero all existing gradients\n model.zero_grad()\n\n # Calculate gradients of model in backward pass\n loss.backward()\n\n # Collect datagrad\n data_grad = data.grad.data\n\n # Call FGSM Attack\n perturbed_data = fgsm_attack(data, epsilon, data_grad)\n\n # Re-classify the perturbed image\n output = model(perturbed_data)\n\n # Check for success\n final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n if final_pred.item() == target.item():\n correct += 1\n # Special case for saving 0 epsilon examples\n if (epsilon == 0) and (len(adv_examples) < 5):\n adv_ex = perturbed_data.squeeze().detach().cpu().numpy()\n adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )\n else:\n # Save some adv examples for visualization later\n if len(adv_examples) < 5:\n adv_ex = perturbed_data.squeeze().detach().cpu().numpy()\n adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )\n\n # Calculate final accuracy for this epsilon\n final_acc = correct/float(len(test_loader))\n print(\"Epsilon: {}\\tTest Accuracy = {} / {} = {}\".format(epsilon, correct, len(test_loader), final_acc))\n\n # Return the accuracy and an adversarial example\n return final_acc, adv_examples\n```\n\nRun Attack\n~~~~~~~~~~\n\nThe last part of the implementation is to actually run the attack. Here,\nwe run a full test step for each epsilon value in the *epsilons* input.\nFor each epsilon we also save the final accuracy and some successful\nadversarial examples to be plotted in the coming sections. Notice how\nthe printed accuracies decrease as the epsilon value increases. Also,\nnote the $\\epsilon=0$ case represents the original test accuracy,\nwith no attack.\n\n\n\n\n\n```python\nepsilons = [0, 0.003, 0.007, 0.01, 0.05, 0.1 ]\n\nscales = [.5, 1, 2, 5, 10, 100]\nexamples = []\n\nall_res = []\n# Run test for each epsilon\nfor s in scales:\n print(f'sclae={s}')\n accuracies = []\n for eps in epsilons:\n acc, ex = test_scale(model, device, test_loader, eps, s)\n accuracies.append(acc)\n# examples.append(ex)\n all_res.append(accuracies)\n```\n\n sclae=0.5\n Epsilon: 0\tTest Accuracy = 3753 / 10000 = 0.3753\n Epsilon: 0.003\tTest Accuracy = 1871 / 10000 = 0.1871\n Epsilon: 0.007\tTest Accuracy = 814 / 10000 = 0.0814\n Epsilon: 0.01\tTest Accuracy = 444 / 10000 = 0.0444\n Epsilon: 0.05\tTest Accuracy = 60 / 10000 = 0.006\n Epsilon: 0.1\tTest Accuracy = 148 / 10000 = 0.0148\n sclae=1\n Epsilon: 0\tTest Accuracy = 5739 / 10000 = 0.5739\n Epsilon: 0.003\tTest Accuracy = 4155 / 10000 = 0.4155\n Epsilon: 0.007\tTest Accuracy = 2650 / 10000 = 0.265\n Epsilon: 0.01\tTest Accuracy = 1936 / 10000 = 0.1936\n Epsilon: 0.05\tTest Accuracy = 124 / 10000 = 0.0124\n Epsilon: 0.1\tTest Accuracy = 91 / 10000 = 0.0091\n sclae=2\n Epsilon: 0\tTest Accuracy = 4726 / 10000 = 0.4726\n Epsilon: 0.003\tTest Accuracy = 3775 / 10000 = 0.3775\n Epsilon: 0.007\tTest Accuracy = 2811 / 10000 = 0.2811\n Epsilon: 0.01\tTest Accuracy = 2271 / 10000 = 0.2271\n Epsilon: 0.05\tTest Accuracy = 249 / 10000 = 0.0249\n Epsilon: 0.1\tTest Accuracy = 90 / 10000 = 0.009\n sclae=5\n Epsilon: 0\tTest Accuracy = 2223 / 10000 = 0.2223\n Epsilon: 0.003\tTest Accuracy = 1782 / 10000 = 0.1782\n Epsilon: 0.007\tTest Accuracy = 1245 / 10000 = 0.1245\n Epsilon: 0.01\tTest Accuracy = 1009 / 10000 = 0.1009\n Epsilon: 0.05\tTest Accuracy = 153 / 10000 = 0.0153\n Epsilon: 0.1\tTest Accuracy = 52 / 10000 = 0.0052\n sclae=10\n Epsilon: 0\tTest Accuracy = 1465 / 10000 = 0.1465\n Epsilon: 0.003\tTest Accuracy = 1187 / 10000 = 0.1187\n Epsilon: 0.007\tTest Accuracy = 624 / 10000 = 0.0624\n Epsilon: 0.01\tTest Accuracy = 494 / 10000 = 0.0494\n Epsilon: 0.05\tTest Accuracy = 86 / 10000 = 0.0086\n Epsilon: 0.1\tTest Accuracy = 43 / 10000 = 0.0043\n sclae=100\n Epsilon: 0\tTest Accuracy = 1018 / 10000 = 0.1018\n Epsilon: 0.003\tTest Accuracy = 938 / 10000 = 0.0938\n Epsilon: 0.007\tTest Accuracy = 118 / 10000 = 0.0118\n Epsilon: 0.01\tTest Accuracy = 95 / 10000 = 0.0095\n Epsilon: 0.05\tTest Accuracy = 14 / 10000 = 0.0014\n Epsilon: 0.1\tTest Accuracy = 9 / 10000 = 0.0009\n\n\nResults\n-------\n\nAccuracy vs Epsilon\n~~~~~~~~~~~~~~~~~~~\n\nThe first result is the accuracy versus epsilon plot. As alluded to\nearlier, as epsilon increases we expect the test accuracy to decrease.\nThis is because larger epsilons mean we take a larger step in the\ndirection that will maximize the loss. Notice the trend in the curve is\nnot linear even though the epsilon values are linearly spaced. For\nexample, the accuracy at $\\epsilon=0.05$ is only about 4% lower\nthan $\\epsilon=0$, but the accuracy at $\\epsilon=0.2$ is 25%\nlower than $\\epsilon=0.15$. Also, notice the accuracy of the model\nhits random accuracy for a 10-class classifier between\n$\\epsilon=0.25$ and $\\epsilon=0.3$.\n\n\n\n\n\n```python\nsymbs = ['*-', 'o-', 's-', 'd-', '+-', 'x-', '^-', '<-']\nplt.figure(figsize=(5,5))\n\nfor idx, accuracies in enumerate(all_res):\n plt.plot( accuracies, symbs[idx])\nplt.yticks(np.arange(0, 1, step=0.1))\nplt.xticks(np.arange(0, len(epsilons), step=1), epsilons)\nplt.title(\"Accuracy vs Epsilon\")\nplt.xlabel(\"Epsilon\")\nplt.ylabel(\"Accuracy\")\nplt.legend(scales)\nplt.show()\n```\n\n\n```python\nfor name, param in model.named_parameters():\n print(name, '\\t\\t', param)\n```\n\n conv1.weight \t\t Parameter containing:\n tensor([[[[ 0.0716, -0.2105, -0.3368, -0.3054, -0.4158],\n [ 0.2207, 0.0393, -0.0686, -0.1781, -0.2624],\n [ 0.2308, 0.3688, 0.3894, 0.1577, -0.0135],\n [ 0.0110, 0.2730, 0.3224, 0.4715, 0.2458],\n [-0.2249, -0.2656, -0.1713, -0.1037, 0.0250]]],\n \n \n [[[ 0.1627, 0.3068, 0.0103, -0.4056, -0.1544],\n [ 0.2326, 0.3716, -0.0010, -0.4189, -0.3831],\n [ 0.1694, 0.4279, -0.1721, -0.2089, -0.3222],\n [ 0.3818, 0.0690, 0.0631, -0.2041, -0.2434],\n [ 0.2582, 0.1175, 0.1383, -0.1191, -0.0858]]],\n \n \n [[[-0.4009, -0.2780, 0.0117, 0.0297, 0.2906],\n [-0.1245, -0.1157, 0.0199, 0.3325, 0.1503],\n [-0.2538, 0.1658, 0.3959, 0.4191, -0.1492],\n [ 0.0242, 0.1532, 0.2859, -0.0572, -0.2331],\n [ 0.1785, 0.0378, 0.0625, -0.1391, -0.1094]]],\n \n \n [[[ 0.2123, 0.3867, 0.3543, 0.0238, 0.1834],\n [-0.1520, -0.0358, 0.1342, 0.1333, 0.2333],\n [-0.1841, -0.2525, 0.0497, -0.0087, 0.1459],\n [ 0.0662, -0.2662, -0.1838, -0.0887, -0.2658],\n [-0.0270, 0.0353, -0.1582, -0.2547, -0.2047]]],\n \n \n [[[ 0.3354, 0.0766, 0.1723, 0.0181, -0.2436],\n [-0.1808, 0.3147, 0.0959, 0.0672, -0.0186],\n [-0.0161, 0.3644, 0.3018, -0.1804, 0.0325],\n [ 0.1156, 0.3093, 0.2729, -0.0490, -0.0082],\n [-0.1838, 0.0518, 0.3013, 0.0050, 0.2397]]],\n \n \n [[[-0.2074, -0.3270, -0.1741, 0.2165, 0.3955],\n [-0.1506, 0.0792, 0.2740, 0.3807, 0.2204],\n [ 0.2410, 0.1996, 0.0631, -0.0692, -0.2378],\n [-0.0067, -0.0351, -0.2246, 0.0627, 0.1113],\n [-0.0117, 0.0261, 0.0133, 0.1745, 0.2427]]],\n \n \n [[[-0.1348, 0.1092, -0.0244, 0.0292, -0.2357],\n [-0.2222, -0.1731, -0.0452, 0.2187, -0.1051],\n [-0.2438, 0.0446, 0.1167, 0.1665, -0.1699],\n [-0.0126, -0.0873, -0.0293, -0.1430, -0.0684],\n [-0.0143, 0.0911, 0.0647, 0.1692, 0.3910]]],\n \n \n [[[ 0.1434, 0.2022, 0.1325, -0.1210, 0.2094],\n [-0.2349, -0.2177, -0.4011, -0.3501, -0.3614],\n [ 0.0977, -0.2784, -0.3112, -0.1948, -0.2123],\n [ 0.2357, 0.1336, 0.1090, 0.1476, 0.2865],\n [-0.0037, 0.3885, 0.4732, 0.4028, 0.0174]]],\n \n \n [[[ 0.0279, -0.1312, 0.2581, 0.0561, 0.1460],\n [-0.0524, -0.0660, 0.0468, 0.2466, 0.2751],\n [-0.0179, -0.0107, -0.2264, 0.2436, 0.4001],\n [ 0.0906, 0.0360, -0.2536, -0.1249, 0.3145],\n [-0.3844, -0.0830, -0.4069, -0.4139, -0.0060]]],\n \n \n [[[-0.1255, -0.0125, 0.3053, 0.3956, 0.3941],\n [-0.0981, -0.2020, 0.3015, 0.1462, 0.1056],\n [-0.0702, -0.2145, 0.1430, 0.2274, -0.0538],\n [-0.2880, -0.1260, -0.0125, -0.0389, -0.1249],\n [-0.1637, -0.4058, -0.3674, -0.2811, 0.0233]]]], device='cuda:0',\n requires_grad=True)\n conv1.bias \t\t Parameter containing:\n tensor([ 0.0208, -0.1223, -0.0758, 0.0572, 0.1769, 0.0333, 0.1023, 0.0913,\n -0.0270, 0.0105], device='cuda:0', requires_grad=True)\n conv2.weight \t\t Parameter containing:\n tensor([[[[ 3.2406e-03, 2.3492e-02, -1.5451e-01, -3.8980e-02, 3.2560e-02],\n [-5.6062e-02, -3.6786e-02, -1.1818e-01, 3.1350e-02, -1.2680e-02],\n [ 7.0198e-02, -1.4161e-03, -3.1375e-02, 5.6263e-02, 3.1962e-02],\n [-8.3054e-02, -4.4973e-02, 1.6788e-02, 1.2552e-02, 2.7096e-02],\n [ 1.5355e-02, 5.4694e-02, 7.2467e-02, 2.3650e-02, -6.8467e-02]],\n \n [[-2.3582e-02, -9.7704e-02, -8.8937e-03, 1.9265e-02, -4.0476e-03],\n [-3.5773e-02, -8.9463e-02, 5.7462e-02, 7.4515e-02, -1.1988e-02],\n [-8.7023e-02, 1.1307e-02, 1.9738e-02, 1.1747e-02, -1.2718e-02],\n [-7.1679e-02, -3.8960e-03, 2.0039e-02, -1.7698e-02, -3.4618e-02],\n [-8.4022e-03, 2.1286e-03, 5.1770e-03, -7.5517e-02, -9.0349e-02]],\n \n [[ 6.1617e-02, -1.9899e-02, 3.5535e-02, 4.7708e-02, 1.3664e-01],\n [-7.5929e-02, 3.7885e-02, 8.0744e-02, 1.0877e-01, 2.2666e-02],\n [-5.3058e-02, 1.3982e-02, -1.2811e-03, 6.6976e-03, -3.6921e-02],\n [-1.0464e-01, -1.0586e-01, -4.8237e-02, -1.0337e-01, -6.8164e-02],\n [ 2.5132e-02, -7.9188e-02, -7.0288e-02, -7.7731e-02, -7.8140e-02]],\n \n ...,\n \n [[-7.1625e-02, 3.4197e-02, -4.0996e-02, -9.0841e-03, 6.6187e-02],\n [ 1.5555e-03, 1.0294e-01, -1.1165e-01, 5.5047e-03, 4.1969e-02],\n [-7.7031e-03, -4.6209e-02, -2.1860e-02, -5.0044e-02, 3.7437e-03],\n [ 5.0873e-02, 2.0071e-02, 7.9846e-02, 7.3587e-02, 1.1663e-01],\n [ 1.3951e-01, 3.4201e-02, 1.3915e-02, 3.2151e-02, -8.7847e-02]],\n \n [[ 3.3142e-02, -7.6181e-02, -2.5871e-04, 4.8773e-03, -1.9490e-02],\n [ 6.1528e-03, -4.4825e-02, -4.8179e-02, 1.4189e-02, -1.6885e-02],\n [ 4.7568e-02, 5.9331e-03, 9.6932e-02, 6.5544e-02, 2.1964e-02],\n [ 6.6608e-02, -2.2974e-02, 6.3493e-02, 9.8286e-03, -1.1296e-01],\n [-7.3091e-02, -9.7398e-02, -2.2807e-02, -5.1994e-02, -6.6852e-02]],\n \n [[ 9.1175e-02, -7.4183e-02, 5.7258e-02, -9.9369e-03, -2.3709e-02],\n [ 5.3960e-02, -1.5873e-02, 8.4859e-03, -1.0613e-01, 2.8231e-02],\n [ 5.7768e-02, 7.6650e-02, -4.3169e-02, -3.7843e-02, 2.8252e-02],\n [ 2.9920e-02, 2.0983e-02, -1.2960e-02, 1.3957e-02, -3.1601e-02],\n [-1.0488e-01, -7.4026e-02, -5.8408e-02, 3.8878e-02, -7.5910e-02]]],\n \n \n [[[-2.9365e-02, 3.2399e-02, -2.5986e-02, 8.8294e-02, 1.2441e-01],\n [-7.2747e-02, -5.8488e-02, -1.8048e-02, -5.8308e-03, 4.5541e-02],\n [-9.5670e-02, -5.6461e-02, 4.9058e-02, 1.3813e-02, 4.0005e-02],\n [-5.8488e-03, 1.2354e-01, 7.9167e-02, 2.5777e-02, 6.3247e-04],\n [ 1.1749e-01, 7.6435e-02, 4.1616e-02, -5.3279e-02, -9.6389e-02]],\n \n [[-1.2692e-02, 4.4093e-03, -1.4037e-01, -1.5158e-01, 5.0030e-02],\n [ 2.1660e-02, -1.0190e-01, -6.0065e-02, -2.4457e-02, 1.5927e-02],\n [-5.7182e-03, -5.3580e-02, 6.5555e-02, -1.5922e-02, 6.8660e-02],\n [-4.0793e-02, -4.0750e-02, 1.8933e-02, -1.2689e-01, -7.8944e-02],\n [-3.2061e-02, 1.7704e-02, -1.1314e-01, -1.7181e-01, -1.2024e-01]],\n \n [[ 1.1056e-02, -3.2912e-02, -4.7793e-02, -3.5121e-02, 6.6325e-02],\n [ 1.9364e-03, 3.4033e-02, 5.5499e-02, 1.3518e-01, 3.8330e-02],\n [ 7.0822e-02, 8.0836e-02, -1.2617e-03, -6.7602e-04, -5.9030e-02],\n [-5.4586e-02, -3.5652e-02, -6.5056e-02, -9.0833e-03, -7.8283e-02],\n [-6.3437e-02, -7.5626e-02, -1.2237e-01, 1.6368e-02, -2.7867e-02]],\n \n ...,\n \n [[-2.1205e-02, 6.3997e-02, 7.4062e-02, 5.0037e-02, -1.7404e-02],\n [ 2.7888e-02, -1.2465e-02, -5.5007e-02, -4.0537e-02, -1.0537e-02],\n [-1.0281e-01, 1.7290e-02, 1.0763e-02, 7.4117e-02, 1.1354e-01],\n [-2.8639e-02, 1.6626e-02, 4.7252e-02, 7.3116e-02, 9.9302e-04],\n [ 7.7133e-02, 8.5157e-02, 1.0495e-01, 4.5579e-02, -1.2862e-01]],\n \n [[-3.9319e-02, -8.3736e-02, -1.1566e-02, -4.8101e-02, -7.5922e-02],\n [-6.6929e-02, -2.9602e-02, 2.6696e-02, 1.0357e-02, -2.7448e-02],\n [ 2.9584e-02, 4.6510e-02, 5.8329e-02, -7.3835e-02, 3.4107e-04],\n [ 7.0233e-02, 1.8823e-02, -3.9542e-03, 9.3295e-03, -6.7738e-02],\n [ 5.6451e-02, 3.3854e-02, -3.1170e-02, -9.0905e-02, -6.8238e-02]],\n \n [[ 6.0264e-02, 1.3489e-02, -1.1083e-01, -6.4834e-02, -1.0347e-01],\n [-1.3426e-01, -4.9525e-02, 2.7510e-02, 4.3950e-02, -3.8565e-02],\n [-3.4958e-02, 7.6161e-02, 1.0131e-01, 4.6756e-02, -5.1791e-02],\n [-1.1140e-02, 5.0631e-02, 7.2451e-02, -3.4299e-02, -5.4583e-02],\n [-3.6768e-02, 6.0417e-02, 4.5989e-02, -6.2761e-02, -9.5459e-02]]],\n \n \n [[[ 4.4563e-02, 5.9872e-02, 1.2271e-01, 4.8217e-02, 6.7621e-02],\n [ 9.6950e-02, 5.0030e-02, 4.5794e-02, 5.4723e-03, 4.7155e-02],\n [ 7.9957e-03, 3.5117e-02, -6.6099e-02, 2.8642e-02, 1.3039e-01],\n [ 2.8450e-02, 2.1658e-02, -6.6176e-02, -7.6192e-02, -4.8325e-02],\n [-7.5177e-02, 9.1468e-03, -3.2752e-03, 1.7911e-02, -2.2739e-02]],\n \n [[-4.5614e-02, 2.9085e-02, -4.1997e-02, 1.0645e-03, -1.8657e-04],\n [-7.9652e-02, -2.5191e-02, -2.6619e-02, -9.5521e-03, 1.1337e-01],\n [-7.2420e-02, -7.8455e-03, -6.8409e-02, -4.2262e-02, -4.7118e-02],\n [-6.1591e-02, 7.5016e-02, -1.6441e-02, 3.4968e-02, -9.9923e-02],\n [ 2.9125e-03, 6.4524e-02, 2.0775e-02, -9.1303e-02, -1.1663e-01]],\n \n [[ 1.1815e-02, -1.1561e-01, -3.5057e-02, -4.1431e-02, 4.5217e-02],\n [-2.7642e-02, 4.6790e-02, 4.1553e-02, -1.6990e-02, 1.0332e-02],\n [ 2.7691e-02, 5.1338e-02, -8.6081e-02, -1.6986e-02, -2.7818e-02],\n [-4.1001e-02, -7.5508e-02, -3.6931e-02, -4.6065e-02, -3.2646e-02],\n [ 5.5465e-02, 6.4031e-02, 4.5948e-02, -5.4590e-02, -5.0784e-02]],\n \n ...,\n \n [[ 5.1806e-03, 8.6599e-02, 4.4183e-02, -7.3262e-03, 3.2709e-02],\n [ 5.8628e-04, 9.2975e-02, 5.4805e-02, 9.3968e-03, 8.1422e-02],\n [ 3.2659e-02, -4.6189e-02, 1.0316e-03, -3.3372e-02, 1.4532e-02],\n [ 5.0147e-02, -2.1381e-02, 2.5049e-02, 6.1027e-02, -7.7898e-02],\n [-3.0626e-03, 1.0922e-01, 4.9009e-02, 2.9281e-02, -3.3414e-02]],\n \n [[ 5.1430e-02, -1.7307e-02, -4.0158e-02, -4.6593e-02, -2.2410e-02],\n [ 9.3532e-02, 6.0234e-02, 5.3747e-02, 1.4397e-01, -9.7555e-02],\n [ 1.2916e-02, -3.4177e-02, -3.1555e-02, 3.9536e-02, -4.0185e-02],\n [-9.2673e-02, -4.6246e-02, -7.6708e-02, 2.9954e-02, 1.6910e-02],\n [-3.2925e-02, 5.3984e-03, -3.1208e-02, 1.1060e-02, -5.3339e-02]],\n \n [[-1.4054e-02, -8.2115e-02, -1.6085e-02, -1.2302e-01, -1.0704e-01],\n [ 6.8058e-02, 1.1936e-01, 7.1887e-02, 1.8280e-03, -4.4231e-02],\n [ 1.4987e-01, 7.1005e-02, -5.6956e-02, 2.1013e-03, 3.7827e-02],\n [ 5.2238e-02, -6.3953e-02, -4.9763e-02, -2.6169e-02, -2.4818e-03],\n [ 2.9697e-02, 5.0945e-03, -7.9696e-02, -5.5902e-02, -1.0575e-01]]],\n \n \n ...,\n \n \n [[[ 1.1673e-01, 6.8688e-02, 3.8541e-02, -1.8145e-02, -4.0311e-02],\n [-5.5185e-02, -5.1283e-02, -7.8085e-02, -8.6606e-02, -2.3905e-02],\n [-6.5268e-02, -8.4449e-02, -2.9057e-02, 1.3444e-01, 4.2075e-02],\n [-9.2482e-02, -1.0340e-01, -2.3502e-02, 1.0009e-01, 8.2379e-02],\n [-4.2585e-02, 6.7819e-03, 6.3555e-02, -8.0110e-03, -5.1712e-02]],\n \n [[-1.8320e-02, -9.5806e-02, -3.2208e-02, -7.5349e-02, -9.4703e-02],\n [-2.2735e-02, 4.3093e-02, 1.5593e-01, 5.1182e-02, 2.6505e-03],\n [-6.5782e-02, -3.2418e-02, 2.0098e-01, 1.3105e-01, -1.8755e-04],\n [-7.5738e-02, -1.9528e-02, 2.0169e-01, 7.8797e-02, 3.4014e-02],\n [-3.0056e-02, 1.2195e-03, -4.8983e-03, -2.6672e-02, 2.2467e-02]],\n \n [[-1.4346e-02, -4.9363e-03, 2.4653e-03, 1.0575e-01, 5.2716e-03],\n [-1.7676e-02, -8.9843e-02, -6.4424e-02, 5.6984e-02, -3.8588e-02],\n [-9.4159e-02, -1.4147e-01, -3.4852e-02, -5.4545e-02, 9.6373e-03],\n [ 4.6069e-03, -9.2915e-02, -1.2575e-01, -1.1252e-01, -4.9302e-03],\n [ 6.5314e-02, -4.6186e-03, 3.7907e-03, 5.0026e-03, -5.2141e-02]],\n \n ...,\n \n [[-5.1717e-02, -1.1548e-02, -3.5722e-02, -4.8252e-02, -2.3624e-03],\n [-1.0316e-02, -1.0061e-01, -9.6746e-02, -2.2608e-02, 4.8633e-02],\n [-1.5764e-02, -1.1463e-01, -1.1854e-01, 2.3761e-02, 1.0033e-01],\n [-2.1364e-02, -3.6315e-02, 1.1347e-02, 1.2085e-03, 4.8508e-03],\n [ 1.5899e-02, -7.0534e-04, 1.5393e-02, 2.7154e-02, -4.5235e-02]],\n \n [[-5.3407e-03, 3.5194e-02, -5.4456e-02, -1.3259e-03, -2.5566e-02],\n [ 5.5321e-02, 9.6244e-02, 2.3939e-02, -4.4724e-02, -7.4791e-02],\n [ 3.4828e-02, 7.5973e-02, 1.6468e-01, 3.1776e-02, -1.5392e-02],\n [-1.2091e-01, 7.3690e-02, 7.7322e-02, 1.0333e-01, -5.8316e-02],\n [-8.3618e-02, 2.2486e-02, -3.8987e-02, 1.1463e-02, -5.3135e-02]],\n \n [[-4.7398e-02, -1.7160e-02, -1.1741e-01, -1.0121e-01, -2.3814e-02],\n [ 4.2046e-02, -5.2907e-02, -1.1056e-01, 4.4180e-03, -1.2532e-01],\n [ 3.8826e-02, -1.4651e-01, 3.9591e-02, 5.9154e-03, -3.1876e-02],\n [ 2.9826e-02, 1.7856e-02, -3.9436e-03, 4.9777e-02, -6.0402e-03],\n [-1.0284e-01, -4.6473e-02, 1.2968e-02, -2.0338e-02, 1.5976e-04]]],\n \n \n [[[ 1.5193e-02, 5.7096e-02, -3.5322e-02, -5.5820e-02, -1.3253e-01],\n [ 8.0359e-02, 1.7342e-02, 1.0950e-02, -4.6353e-02, -9.9457e-02],\n [ 8.3726e-02, -5.7086e-04, -5.4463e-02, -7.2609e-02, -8.2260e-02],\n [ 3.1282e-02, -8.8818e-02, -9.3672e-02, -1.1095e-01, -1.2400e-01],\n [-6.8372e-02, -1.7500e-01, -1.0916e-01, -2.1871e-02, -3.1304e-02]],\n \n [[ 5.6444e-02, 4.9185e-02, 7.5450e-02, 8.8123e-02, 2.6439e-02],\n [ 1.2896e-02, 1.1045e-01, 1.2714e-01, 2.6480e-02, 1.2326e-01],\n [-4.1653e-02, 5.0474e-02, 1.3976e-01, 5.9167e-02, 1.1080e-01],\n [ 4.3210e-02, 9.1162e-02, 6.3861e-02, -1.8224e-02, -4.6584e-02],\n [ 9.1414e-02, -7.1644e-03, 4.7173e-02, 2.0085e-02, 5.5844e-02]],\n \n [[ 3.4813e-02, -9.3072e-02, -7.1623e-02, -3.7221e-02, 6.3834e-04],\n [-8.5928e-02, 3.6634e-05, -1.9533e-02, 2.4342e-02, -3.0719e-02],\n [-9.2936e-03, 4.5266e-02, 9.5609e-02, 7.5996e-02, -1.0007e-01],\n [ 8.0353e-02, 3.1478e-02, 1.3575e-01, 1.4468e-02, 1.2206e-02],\n [ 5.4383e-02, 6.1522e-02, 3.8471e-02, -1.2687e-02, 9.7042e-02]],\n \n ...,\n \n [[ 7.9088e-03, -2.5339e-02, -5.0461e-02, -8.1445e-02, -1.8118e-01],\n [ 3.3992e-02, 1.9507e-02, -2.1310e-02, -1.1999e-01, -1.5138e-01],\n [ 7.4818e-02, -8.3039e-02, -1.6725e-02, -1.1600e-01, -3.6865e-02],\n [ 6.0182e-02, -5.8928e-02, -1.3846e-01, 3.6211e-03, -3.7769e-02],\n [-2.1468e-02, -5.6421e-02, -6.0800e-03, 9.5311e-02, 1.2233e-01]],\n \n [[ 7.8180e-02, 2.7584e-02, 6.7619e-02, -6.1883e-02, -2.2267e-02],\n [ 5.2021e-02, 5.8063e-02, 2.0244e-02, -5.2788e-02, -9.3708e-02],\n [-5.8100e-02, 9.6376e-03, -6.5814e-02, -8.8950e-02, -1.0554e-01],\n [ 4.5192e-02, -5.5434e-02, -1.1351e-01, -1.4918e-01, -7.2342e-02],\n [-1.0280e-02, -8.3596e-02, -9.5348e-02, -8.1241e-02, -4.6028e-02]],\n \n [[ 1.4847e-02, -7.2905e-03, -4.3224e-02, -3.9776e-02, 1.6482e-02],\n [-6.5112e-02, -2.9044e-02, 2.5568e-02, 2.0679e-02, -2.8948e-02],\n [-7.6850e-02, 3.2196e-02, 7.3615e-02, 6.7641e-02, -4.7219e-02],\n [-3.0013e-02, -1.7610e-02, 1.9233e-02, -2.1600e-02, -1.2320e-01],\n [-1.5888e-02, -3.2151e-02, -3.0425e-02, -7.2162e-02, 3.2722e-02]]],\n \n \n [[[ 3.8342e-02, -7.1643e-02, -3.8899e-02, -3.1054e-02, -9.2070e-02],\n [ 5.8230e-02, 3.8005e-03, -3.3761e-02, -1.0233e-01, -1.3204e-01],\n [ 3.8958e-03, -4.6927e-02, -7.7617e-02, -1.2274e-01, -5.3947e-02],\n [-1.0023e-01, -7.0598e-02, 1.4389e-02, -1.2138e-01, -2.7234e-02],\n [-1.4343e-01, -1.5076e-01, -1.1692e-01, -6.0956e-02, 5.2540e-03]],\n \n [[ 1.5956e-02, 9.3919e-03, 6.4916e-02, -1.0452e-02, -4.2572e-02],\n [ 7.6396e-02, 7.9740e-02, 3.8097e-03, -1.1123e-03, -8.2374e-02],\n [ 8.1111e-02, 4.3804e-02, 9.6647e-02, 4.2713e-02, 7.0432e-02],\n [ 9.5397e-02, 3.5690e-02, 8.9411e-02, 2.9462e-02, 5.3192e-02],\n [ 1.2352e-01, 6.9035e-02, 1.3839e-01, -2.0425e-02, 1.3936e-01]],\n \n [[-5.0452e-02, -7.5217e-02, -3.7385e-02, 5.8201e-02, 4.0725e-02],\n [-8.7560e-02, -5.4459e-02, 6.3860e-02, -2.8118e-02, 4.0431e-02],\n [ 4.1790e-02, 6.6813e-02, 4.0199e-02, -9.2723e-02, 1.8208e-01],\n [ 2.0361e-01, 3.3444e-02, -8.7835e-02, -1.3059e-02, 8.6943e-02],\n [ 1.2563e-01, 8.6099e-02, -6.7836e-03, -2.1245e-02, -1.3146e-03]],\n \n ...,\n \n [[ 2.7495e-02, -8.7357e-02, -1.0211e-01, -4.8019e-02, -7.6701e-02],\n [ 2.2642e-02, -6.4198e-02, -4.1811e-02, -6.7755e-02, -3.4063e-02],\n [ 1.4155e-02, -9.0433e-02, -9.1400e-02, -5.8746e-02, -4.8009e-02],\n [-1.1856e-02, -8.3386e-02, -1.5353e-01, -7.6114e-02, -7.6436e-02],\n [-3.4464e-02, -6.2143e-02, 2.7012e-02, 7.0886e-04, -4.4748e-03]],\n \n [[ 9.4607e-02, 1.8445e-02, -4.7002e-02, -2.2003e-02, -1.3177e-02],\n [ 2.0734e-02, -2.2912e-02, -8.0467e-02, -2.7710e-02, -2.8224e-03],\n [-6.8572e-03, 1.0440e-02, -3.5518e-02, 4.1372e-03, -2.0476e-02],\n [ 2.9808e-02, -9.7879e-02, -4.7983e-03, 9.0547e-02, 1.2234e-01],\n [-3.5634e-02, -1.3524e-01, -1.4973e-01, -7.2582e-02, -4.4997e-03]],\n \n [[ 3.9441e-02, -3.8255e-02, 1.9479e-02, 1.6807e-02, -1.3818e-02],\n [ 1.9176e-02, 5.0845e-02, 5.4972e-02, 2.7127e-02, -6.7752e-04],\n [-2.5190e-02, 1.3671e-01, -2.2166e-03, -8.9856e-02, 1.0663e-01],\n [-1.3365e-03, 1.0261e-02, -7.5918e-02, -7.2554e-02, 1.6060e-01],\n [ 3.5451e-02, -1.0672e-01, -1.1914e-01, -1.1996e-02, 1.1065e-01]]]],\n device='cuda:0', requires_grad=True)\n conv2.bias \t\t Parameter containing:\n tensor([ 0.0367, -0.0361, 0.0427, -0.0476, -0.0237, -0.0378, -0.0382, -0.0035,\n -0.0622, -0.0295, 0.0189, -0.0617, -0.0585, 0.0742, -0.0272, -0.0856,\n 0.0027, -0.0772, -0.0160, 0.0287], device='cuda:0',\n requires_grad=True)\n fc1.weight \t\t Parameter containing:\n tensor([[-0.0432, -0.0451, -0.0249, ..., 0.0730, 0.1586, 0.0473],\n [-0.0010, -0.0796, -0.0384, ..., 0.0267, 0.0399, 0.0416],\n [-0.0410, 0.0048, -0.0199, ..., 0.0208, 0.0421, 0.0883],\n ...,\n [ 0.0060, 0.0307, 0.0497, ..., 0.0487, 0.0009, -0.1537],\n [ 0.0091, -0.0079, 0.0224, ..., 0.0122, 0.0358, 0.0011],\n [ 0.0710, 0.0095, -0.0194, ..., -0.0837, -0.0367, -0.0426]],\n device='cuda:0', requires_grad=True)\n fc1.bias \t\t Parameter containing:\n tensor([ 0.0613, 0.0407, 0.0155, 0.0150, 0.0309, 0.0106, 0.0054, -0.0210,\n 0.0523, 0.0213, 0.0222, 0.0860, -0.0160, 0.0199, 0.0120, -0.0289,\n 0.0813, 0.0469, 0.0737, -0.0129, 0.0415, 0.0347, -0.0314, 0.0559,\n 0.0566, -0.0036, 0.0901, 0.0016, -0.0195, -0.0144, -0.0129, 0.0454,\n 0.0228, -0.0215, -0.0232, 0.0994, 0.0363, -0.0543, 0.0440, -0.0139,\n 0.0309, 0.0982, 0.0504, -0.0240, 0.0036, 0.0419, -0.0238, -0.0261,\n 0.0587, 0.0734], device='cuda:0', requires_grad=True)\n fc2.weight \t\t Parameter containing:\n tensor([[-0.0770, -0.1595, 0.1351, 0.2024, -0.2046, -0.0559, -0.2167, -0.1508,\n -0.1405, -0.2049, -0.2397, -0.1481, -0.1323, 0.2162, 0.2514, 0.1620,\n 0.1507, 0.2602, 0.0773, -0.1474, -0.1545, -0.1898, -0.1575, -0.2840,\n -0.1066, -0.2594, -0.2433, -0.2415, -0.0065, 0.2663, -0.1490, -0.1689,\n 0.2494, 0.1705, -0.1686, 0.2222, 0.1110, 0.0254, 0.1353, -0.1895,\n -0.1554, -0.2286, 0.1516, -0.1718, -0.0450, 0.2561, -0.1185, -0.1254,\n 0.2117, 0.2056],\n [-0.0848, 0.1615, -0.2497, 0.1739, 0.2169, 0.2023, -0.2229, 0.1366,\n -0.0154, -0.1704, 0.0203, 0.2291, -0.1161, -0.1862, -0.0103, -0.2400,\n 0.0898, -0.0933, -0.2255, 0.1298, -0.1904, -0.0456, 0.2154, 0.1804,\n 0.2146, -0.2637, -0.2916, 0.2599, 0.1945, 0.0025, 0.2085, -0.1374,\n -0.2011, -0.2394, 0.2196, -0.0438, -0.1560, -0.1370, 0.1107, 0.2482,\n -0.0658, 0.1573, -0.1563, -0.2429, 0.2284, -0.1126, -0.1980, 0.2051,\n -0.2658, 0.0168],\n [-0.1404, -0.0575, -0.0845, 0.0459, -0.1437, 0.2079, 0.1644, 0.0901,\n 0.2253, 0.0987, -0.0707, 0.2670, 0.2101, 0.1916, 0.1845, 0.1214,\n 0.0693, -0.0954, -0.1760, -0.2644, -0.0889, 0.2360, -0.1462, -0.1980,\n -0.1323, -0.0768, -0.2093, 0.0373, -0.2495, -0.0680, -0.0913, -0.0934,\n 0.0082, -0.1509, 0.2156, 0.1513, -0.0354, -0.0843, 0.1131, 0.2053,\n 0.1530, 0.2225, -0.1567, -0.0362, 0.1276, 0.2084, -0.0470, 0.2165,\n -0.1776, 0.1935],\n [ 0.0686, 0.2199, 0.1628, -0.2300, -0.0377, -0.1835, 0.1080, 0.0971,\n 0.0159, 0.1072, -0.0561, 0.2397, -0.1396, -0.0541, 0.0243, -0.0987,\n -0.0591, -0.0057, -0.0581, 0.1788, 0.2598, 0.2532, 0.0263, -0.0743,\n -0.2499, -0.1444, 0.1748, -0.0812, 0.2674, -0.1471, -0.2817, 0.2889,\n -0.1538, 0.1557, 0.0027, 0.0118, 0.1995, 0.0018, -0.2316, -0.0878,\n 0.1925, 0.2329, -0.1893, 0.1155, 0.1720, -0.0418, -0.1206, 0.0616,\n -0.1526, 0.1656],\n [ 0.1730, 0.1422, -0.1862, 0.0096, 0.2001, 0.1987, 0.1697, -0.1730,\n -0.1993, -0.1957, 0.2586, 0.0346, 0.2881, -0.1817, -0.0468, 0.1523,\n -0.2472, -0.2026, -0.1039, -0.1498, -0.1765, -0.1061, 0.2256, 0.2049,\n 0.1544, 0.2332, 0.0706, -0.0103, -0.0603, -0.1319, 0.1248, 0.2409,\n -0.2055, -0.2770, -0.0963, -0.2107, -0.1407, 0.3512, 0.1461, -0.0733,\n -0.2674, -0.1546, 0.1557, 0.0370, -0.1891, -0.0432, -0.1020, -0.2026,\n 0.2063, -0.1723],\n [ 0.1598, -0.0730, 0.1404, -0.1735, -0.0179, -0.1517, -0.1803, -0.1802,\n 0.2437, -0.2384, 0.2235, -0.0767, -0.1797, -0.1854, -0.1730, -0.1093,\n -0.2429, 0.2715, 0.2525, 0.1776, 0.2537, -0.1637, -0.1420, 0.0761,\n 0.0716, -0.1806, 0.1693, -0.1261, 0.2359, 0.1229, -0.0288, 0.2561,\n -0.0967, 0.1562, 0.0155, 0.2064, 0.2224, 0.0146, -0.1664, -0.0880,\n -0.1780, -0.0518, 0.1445, -0.1330, -0.0926, -0.0189, 0.3200, -0.0487,\n 0.1479, -0.1094],\n [-0.3489, -0.1620, -0.2170, -0.0465, -0.1727, 0.1675, -0.3525, 0.1213,\n 0.1768, -0.2231, 0.2609, -0.1075, -0.0460, -0.2762, 0.1885, 0.1626,\n -0.3093, 0.3085, 0.2147, 0.1412, 0.0041, -0.1516, -0.1457, -0.1537,\n -0.1125, -0.1490, -0.2117, -0.1257, 0.2457, -0.0554, 0.2266, -0.1785,\n -0.0963, -0.1160, -0.1390, 0.2343, -0.1983, 0.3407, 0.1277, 0.2792,\n -0.3473, -0.3041, 0.2161, -0.0725, -0.1508, 0.1769, 0.3222, -0.1744,\n 0.2086, -0.0700],\n [ 0.1591, 0.1763, 0.1291, 0.0565, 0.2101, -0.1105, 0.1304, -0.0745,\n -0.0414, 0.1086, -0.1657, 0.1979, 0.2833, 0.1809, -0.0767, -0.1970,\n 0.0938, -0.1430, -0.1066, -0.2779, -0.1583, -0.0441, -0.1019, 0.1044,\n -0.1490, 0.1786, -0.2080, 0.2644, -0.0823, 0.2341, -0.1082, -0.0964,\n 0.2276, 0.0994, 0.1615, -0.2566, 0.0278, 0.0046, -0.3285, -0.0794,\n 0.1802, 0.2310, -0.0778, 0.3170, 0.1598, -0.1058, -0.0574, 0.2149,\n -0.0050, -0.1879],\n [ 0.1664, -0.1925, -0.1088, -0.1680, -0.1033, -0.0306, 0.1316, 0.1653,\n 0.2366, -0.1538, 0.0030, -0.0815, -0.0727, -0.0674, 0.2187, -0.1217,\n 0.1088, -0.0614, 0.2317, 0.1549, 0.2566, -0.1011, -0.1174, 0.1953,\n 0.1449, 0.0785, 0.1695, -0.1087, -0.1225, -0.0174, 0.2054, -0.0347,\n -0.0904, -0.0991, -0.0884, 0.2446, -0.2397, -0.1355, -0.0758, 0.0294,\n 0.1791, 0.2207, -0.0206, -0.0545, -0.1589, 0.2189, -0.0284, -0.0618,\n 0.1710, 0.1154],\n [ 0.2035, -0.1901, 0.1341, -0.0971, 0.1880, -0.2517, 0.1564, -0.1532,\n -0.2116, 0.1176, 0.2459, -0.1790, -0.0989, -0.0323, -0.1042, 0.1491,\n 0.1211, -0.0858, 0.2408, -0.0567, 0.1421, -0.1653, 0.1628, 0.1945,\n 0.0267, 0.1994, 0.1740, -0.0651, 0.0132, 0.0120, -0.1598, 0.2490,\n -0.0856, 0.1622, -0.1611, -0.1080, 0.0214, -0.0880, 0.0757, -0.0944,\n 0.1685, -0.0691, -0.2191, 0.3712, -0.2077, -0.1536, -0.1108, -0.0291,\n 0.1971, -0.1638]], device='cuda:0', requires_grad=True)\n fc2.bias \t\t Parameter containing:\n tensor([ 0.0205, 0.1291, -0.0242, -0.1210, -0.0541, 0.1059, -0.2361, -0.1569,\n 0.1555, -0.1171], device='cuda:0', requires_grad=True)\n\n\n\n```python\nparam\n```\n\n\n\n\n Parameter containing:\n tensor([ 0.0205, 0.1291, -0.0242, -0.1210, -0.0541, 0.1059, -0.2361, -0.1569,\n 0.1555, -0.1171], device='cuda:0', requires_grad=True)\n\n\n\nSample Adversarial Examples\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nRemember the idea of no free lunch? In this case, as epsilon increases\nthe test accuracy decreases **BUT** the perturbations become more easily\nperceptible. In reality, there is a tradeoff between accuracy\ndegredation and perceptibility that an attacker must consider. Here, we\nshow some examples of successful adversarial examples at each epsilon\nvalue. Each row of the plot shows a different epsilon value. The first\nrow is the $\\epsilon=0$ examples which represent the original\n“clean” images with no perturbation. The title of each image shows the\n“original classification -> adversarial classification.” Notice, the\nperturbations start to become evident at $\\epsilon=0.15$ and are\nquite evident at $\\epsilon=0.3$. However, in all cases humans are\nstill capable of identifying the correct class despite the added noise.\n\n\n\n\n\n```python\n# Plot several examples of adversarial samples at each epsilon\ncnt = 0\nplt.figure(figsize=(8,10))\nfor i in range(len(epsilons)):\n for j in range(len(examples[i])):\n cnt += 1\n plt.subplot(len(epsilons),len(examples[0]),cnt)\n plt.xticks([], [])\n plt.yticks([], [])\n if j == 0:\n plt.ylabel(\"Eps: {}\".format(epsilons[i]), fontsize=14)\n orig,adv,ex = examples[i][j]\n plt.title(\"{} -> {}\".format(orig, adv))\n plt.imshow(ex, cmap=\"gray\")\nplt.tight_layout()\nplt.show()\n```\n\nWhere to go next?\n-----------------\n\nHopefully this tutorial gives some insight into the topic of adversarial\nmachine learning. There are many potential directions to go from here.\nThis attack represents the very beginning of adversarial attack research\nand since there have been many subsequent ideas for how to attack and\ndefend ML models from an adversary. In fact, at NIPS 2017 there was an\nadversarial attack and defense competition and many of the methods used\nin the competition are described in this paper: `Adversarial Attacks and\nDefences Competition `__. The work\non defense also leads into the idea of making machine learning models\nmore *robust* in general, to both naturally perturbed and adversarially\ncrafted inputs.\n\nAnother direction to go is adversarial attacks and defense in different\ndomains. Adversarial research is not limited to the image domain, check\nout `this `__ attack on\nspeech-to-text models. But perhaps the best way to learn more about\nadversarial machine learning is to get your hands dirty. Try to\nimplement a different attack from the NIPS 2017 competition, and see how\nit differs from FGSM. Then, try to defend the model from your own\nattacks.\n\n\n\n", "meta": {"hexsha": "74b6b49628ea38e37a7d55f06ee00d50a8a4f40e", "size": 91198, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fgsm_tutorial_scaleCIFAR.ipynb", "max_stars_repo_name": "aliborji/ReLU_defense", "max_stars_repo_head_hexsha": "22ea90e7a9e91a1c54c96d7bbbb6020a3495f580", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-30T13:14:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T19:11:54.000Z", "max_issues_repo_path": "fgsm_tutorial_scaleCIFAR.ipynb", "max_issues_repo_name": "aliborji/ReLU_defense", "max_issues_repo_head_hexsha": "22ea90e7a9e91a1c54c96d7bbbb6020a3495f580", "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": "fgsm_tutorial_scaleCIFAR.ipynb", "max_forks_repo_name": "aliborji/ReLU_defense", "max_forks_repo_head_hexsha": "22ea90e7a9e91a1c54c96d7bbbb6020a3495f580", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-29T11:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T18:15:02.000Z", "avg_line_length": 67.5540740741, "max_line_length": 27680, "alphanum_fraction": 0.6529748459, "converted": true, "num_tokens": 20585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.12592277139559052, "lm_q1q2_score": 0.06197769409799162}} {"text": " **Chapter 4: [Spectroscopy](CH4-Spectroscopy.ipynb)** \n\n
    \n\n\n\n# Analysing Low-Loss Spectra with Drude Theory\n\n[Download](https://raw.githubusercontent.com/gduscher/MSE672-Introduction-to-TEM/main/Spectroscopy/CH4_03-Drude.ipynb)\n \n[](\n https://colab.research.google.com/github/gduscher/MSE672-Introduction-to-TEM/blob/main/Spectroscopy/CH4_03-Drude.ipynb)\n\n\npart of \n\n **[MSE672: Introduction to Transmission Electron Microscopy](../_MSE672_Intro_TEM.ipynb)**\n\nby Gerd Duscher, Spring 2021\n\nMicroscopy Facilities
    \nJoint Institute of Advanced Materials
    \nMaterials Science & Engineering
    \nThe University of Tennessee, Knoxville\n\nBackground and methods to analysis and quantification of data acquired with transmission electron microscopes.\n\n## Content\nThe main feature in a low-loss EELS spectrum is the ``volume plasmon`` peak.\n\nThis ``volume plasmon`` and all other features in the ``low-loss`` region of an EELS spectrum are described by Dielectric Theory of Electrodynamics.\n\nThe simplest theory to interprete this energy range is the Drude theory. \n\nAnother easy to observe component is the multiple scattering of this plasmon peak, which we can correct for or use for thickness determination.\n\n## Load important packages\n\n### Check Installed Packages\n\n\n\n```python\nimport sys\nfrom pkg_resources import get_distribution, DistributionNotFound\n\ndef test_package(package_name):\n \"\"\"Test if package exists and returns version or -1\"\"\"\n try:\n version = get_distribution(package_name).version\n except (DistributionNotFound, ImportError) as err:\n version = '-1'\n return version\n\n# Colab setup ------------------\nif 'google.colab' in sys.modules:\n !pip install pyTEMlib -q\n# pyTEMlib setup ------------------\nelse:\n if test_package('sidpy') < '0.0.5':\n print('installing pyTEMlib')\n !{sys.executable} -m pip install --upgrade pyTEMlib -q\n if test_package('pyTEMlib') < '0.2021.4.10':\n print('installing pyTEMlib')\n !{sys.executable} -m pip install --upgrade pyTEMlib -q\n# ------------------------------\nprint('done')\n```\n\n done\n\n\n### Import all relevant libraries\n\nPlease note that the EELS_tools package from pyTEMlib is essential.\n\n\n```python\nimport sys\nif 'google.colab' in sys.modules:\n %pylab --no-import-all inline\nelse: \n %pylab --no-import-all notebook\n %gui qt\n \nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# additional package \nimport ipywidgets as ipyw\nfrom scipy.optimize import leastsq ## fitting routine of scipy\n\n# Import libraries from the book\nimport pyTEMlib\nimport pyTEMlib.file_tools as ft # File input/ output library\nfrom pyTEMlib import eels_tools \nimport pyTEMlib.KinsCat as ks # Kinematic sCattering Library\n # Atomic form factors from Kirklands book\n\n# For archiving reasons it is a good idea to print the version numbers out at this point\nprint('pyTEM version: ',pyTEMlib.__version__)\n```\n\n Populating the interactive namespace from numpy and matplotlib\n Using KinsCat library version 0.5 by G.Duscher\n spglib not installed; Symmetry functions of spglib disabled\n pyTEM version: 0.2021.04.02\n\n\n## Dielectric Theory\n\n### Comparison to Optical Spectroscopy\n\nThe interaction of a transmitted electron with a solid is here described in terms of\na dielectric response function $\\varepsilon(q, \\omega))$. \n\nThe same response function $\\varepsilon(q, \\omega))$ describes\nthe interaction of any electro-magnetic wave (such as photons) with a solid, so this formalism allows energy-loss data to be compared with the results of optical measurements.\n\nThe difference is that there is no momentum transfer in an optical transition and, therefore, the relevant dielectric function is $\\varepsilon(q=0, \\omega))$.\n\n\nThe optical dielectric function (permittivity) is a transverse property of the medium, in the sense that the electric field of an electromagnetic wave displaces electrons in a direction perpendicular to the direction of propagation, the electron density remaining\nunchanged. \n\nThe relation between the ac conductivity $\\sigma$ (for dc conductivity the in metals $\\varepsilon$ can go to $\\inf$ and is therefore not well described) and $\\varepsilon$ is :\n$$ \\varepsilon = 1 + \\frac{4\\pi \\ i \\sigma}{\\omega} $$\n\nThe relation between the complex refractive index $n+i\\kappa$ and dielectric function is:\n$$ n^2-\\kappa^2 ={\\bf Re}(\\varepsilon), \\ \\ 2n\\kappa = {\\bf Im}(\\varepsilon) $$\n\nOptical absorption spectrum is obtained through\nABS= ${\\bf Im}( \\varepsilon(q→0,\\omega) )$\n\n>\n>So, the dielectric function describes the electrical and optical response of a material almost completely. \n>\n\n\n### Dispersion \nFrom the Fourier representation of the Maxwell equations in the source free case, we get:\n$$\\frac{\\epsilon_i \\mu_i}{c^2} = k^2$$\n\nwhich we transform into:\n\n$$k = \\frac{\\omega}{c} \\sqrt{\\varepsilon_1 \\mu}$$\n\nwhich gives for non-magnetic materials:\n\n$$k = \\frac{\\omega}{c} \\sqrt{\\varepsilon_1 }$$\n\nfor $\\varepsilon_1 > 0$ the wavenumber $k$ is a real function of real $\\omega$.\n\nwhile for $\\varepsilon_1 < 0$ the wavenumber $k$ is purely imaginary.\n\n\nfor light in vacuum the permittivity $\\varepsilon_1$ is a constant with value 1 and we get the equation for light line:\n\n$$k = \\frac{\\omega}{c}$$\n\n### Cross Section\n\n$$ \\frac{d^2\\sigma}{dE d\\Omega} = \\frac{1}{\\pi a_0 m_0 v^2 n_a} \n {\\rm Im} \\left[ \\frac{-1}{\\varepsilon(q,E)} \\right]\n \\left( \\frac{1}{\\theta^2+\\theta_E^2}\\right)$$\n \nThe partial cross section $\\frac{d^2\\sigma}{dE d\\Omega}$ gives us the probability that an incident electron will be scattered into angle $q$ with energy-loss $E$.\n\nThere are three compenents, first a term that depends on the ``atom density`` $n_a$ (atoms per volume).\n\nAnd the third term is the (Lorentzian) ``angle dependence`` with the characteristic angle $$\\theta_E = E_E/(\\gamma m_0v^2)$$\n\nThe second term is the ``loss-function``.\n\nThe loss function of a dielectric function $\\varepsilon = \\varepsilon_1+ i*\\varepsilon_2$ is\n$$ {\\rm Im} \\left[ \\frac{-1}{\\varepsilon(q,E)} \\right] = \\frac{\\varepsilon_1(q,E)}{\\varepsilon_1^2(q,E) + \\varepsilon_2^2(q,E)}$$\nAt large energy loss and $q\\approx 0$, $\\varepsilon_2$ is small\nand $\\varepsilon_1$ close to 1, the loss function becomes proportional to\n$\\varepsilon_2$ and (apart from a factor of E$^{−3}$) the energy-loss spectrum is proportional to the X-ray absorption spectrum.\n\n## Load and plot a spectrum\nplease see [Loading an EELS Spectrum](LoadEELS.ipynb) for details\n\n\n```python\n# Load file\nfilename = '../example_data/AL-DFoffset0.00.dm3'\neels_dataset = ft.open_file(filename)\nif eels_dataset.data_type.name != 'SPECTRUM':\n print('We need an EELS spectrum for this notebook')\n\n#######################################\n## Important Experimental Parameters ##\n#######################################\neels_dataset.metadata = eels_tools.read_dm3_eels_info(eels_dataset.original_metadata)\n\n\nsum_spectrum = eels_dataset.sum()\n\neels_dataset = eels_dataset/sum_spectrum*100.\neels_dataset.units = '%'\neels_dataset.quantity = 'scattering probability'\n\neels_dataset.plot()\n```\n\n Cannot overwrite file. Using: AL_DFoffset0.00-1.hf5\n\n\n\n \n\n\n\n\n\n\n### Fix energy scale and resolution function\nplease see [Fitting the Zero-Loss Peak](FitZeroLoss.ipynb) for details\n\n### Relative Thickness Determination\n\nThe probabaility of an low-loss function in a solid angle is then:\n$$\\frac{\\partial^2 P}{(\\partial E \\partial \\Omega) }= t* \\frac{e}{\\pi^2 a_0 m_0 v^2} {\\rm Im} \\left[ \\frac{-1}{\\varepsilon(q,E)} \\right]\n \\left( \\frac{1}{\\theta^2+\\theta_E^2}\\right)$$\n \nPlease see [Kroeger Formalism](CH4_04-Kroeger.ipynb) for inclusion of retardation effects, and surface plasmons.\n\nThe integration over the (effective) collection angle gives:\n$$\\frac{\\partial P}{\\partial E} = \\int_0^{\\theta_c}\\frac{\\partial^2 P}{(\\partial E \\partial \\Omega) }(E,\\theta)\\sin \\theta\\ d \\theta$$\n\nSo we need to get the loss-function, calculate $\\frac{\\partial^2 P}{(\\partial E \\partial \\Omega) }$ and then integrate over the angles, then we fit this to the spectrum with the sole variable of the thickness $t$.\n\nThe specimen thickness $t$, it is actually the total scattering\nand mass thickness that is measured by EELS. If the physical density of a\nmaterial were reduced by a factor $f$, the scattering per atom would remain the same\n(according to an atomic model) and the mean free path should increase by a factor $f$.\n\nThe big problem hoewver, is that one has to know the **dielectric function**. \nIn the case of the Drude theory, that means we need to know the electron density.\n\nAny approximation, therefore, needs to approximate this dielectric function, which cannot be generally applicable.\n\n\nThe relative thickness $ t_{rel} = t/\\lambda$, in contrast, is relatively easy to determine. All the above problems are hidden in value of the inelastic mean free path (IMFP) $\\lambda$, which is the inverse of the cross section above.\n\n>When you use a tabulated value for the IMFP, be aware that this value depends on:\n> * acceleration voltage\n> * effective collection angle\n> * material density\n \n>**and may not be applicable for your experimental setup.**\n\n\n\nThe measurement of the relative thickness $t_{rel}$ is relative easy:\n\nWe already did this in the [Fit Zero-Loss](FitZeroLoss.ipynb) part.\n\nThe inelastic scattering can be viewed in terms of independent collisions, whose occurrences obey Poisson statistics. The probability that a transmitted electron suffers $n$ collisions is \n\\begin{equation} \\Large\nP_n = (1/n!)m^n \\exp(-m)\n\\end{equation}\n\nwhere $m$ is the number of average collisions for electrons travel through this sample area. The number $m$ can be set to the scattering parameter $t/\\lambda$. $P_n$ is represented in the EELS spectrum by the ration of the energy-integrated intensity $I_n$ of $n$-fold scattering divided by the {\\bf total} integrated intensity $I_t$:\n\\begin{equation} \\Large\n\\label{equ:poisson}\nP_n = I_n/I_t (1/n!) (t/\\lambda)^n \\exp(-t/\\lambda)\n\\end{equation}\n\nFor a given order $n$ of scattering, the intensity is highest when $t/\\lambda =n$\nIn the case of the unscattered (n=0) component (zero--loss peak), the intensity is highest at t=0 and decreases exponentially with specimen thickness. For $n=0$, equation \\ref{equ:poisson} gives equation \n\\ref{equ:relative_thickness}\n\\begin{equation} \\Large\n\\frac{t}{\\lambda}= - \\ln\\left[ \\frac{I_{\\mbox{total}}}{I_{zl}}\\right]\n\\end{equation}\nI just replaced $I_{zl}$ with $I_0$.\n\n\n```python\nFWHM, energy_shift = eels_tools.fix_energy_scale(np.array(eels_dataset), eels_dataset.energy_loss)\n\nprint(f'Zero Loss with energy resolution of {FWHM:.2f} eV at position {energy_shift:.3f} eV')\neels_dataset.energy_loss -= energy_shift\n\nzero_loss, _ = eels_tools.resolution_function(eels_dataset.energy_loss, eels_dataset, .4)\nprint(zero_loss)\nplt.figure()\nplt.plot(eels_dataset.energy_loss, eels_dataset, label='spectrum')\nplt.plot(eels_dataset.energy_loss, zero_loss, label = 'zero-loss')\nplt.plot(eels_dataset.energy_loss, np.array(eels_dataset)-zero_loss , label = 'difference')\n\nplt.title ('Lorentzian Product Fit of Zero-Loss Peak')\n#plt.xlim(-5,30)\nplt.legend();\nIzl = zero_loss.sum()\nItotal = np.array(eels_dataset).sum()\ntmfp = np.log(Itotal/Izl)\nprint(f'Sum of Zero-Loss: {Izl:.0f} counts')\nprint(f'Sum of Spectrum: {Itotal:.0f} counts')\nprint (f'thickness [IMFP]: {tmfp:.5f}')\n\n\n```\n\n Zero Loss with energy resolution of 0.18 eV at position -0.134 eV\n energy_loss: energy-loss (energy_loss) of size (2048,)\n\n\n\n \n\n\n\n\n\n\n Sum of Zero-Loss: 84 counts\n Sum of Spectrum: 100 counts\n thickness [IMFP]: 0.17585\n\n\n\n## Single Scattering Deconvolution\n\nFor thicker samples (relative thickness larger than half the inelastic MFP), the scattered electrons are likely to be scattered a second time by plasmon excitations. This results for thicknesses around 0.5 MFP in more intensity in the high energy tail of the plasmon peak. For thicker areas a second plasmon peak will appear at double the energy loss and for very thick areas we have a whole series of plasmon peaks.\nIn spectra of very thick areas the zero-loss peak may completely vanish. Multiple scattering is easily recognized by the positions of the peaks (multiple of $E_{max}$).\n\nMultiple scattering influences the high energy side of the first plasmon peak, and makes it difficult to quantify the spectra, whether it is in the low-loss or core--loss region. Figure \\ref{fig:ssd} shows how the correction improves the determination of the width of the plasmon width. Fortunately, we can correct this multiple scattering, because mathematically, it is a kind of self-convolution. The procedure is called single scattering deconvolution (SSD).\n\n\nElectrons that lost energy can interact with the sample again. The average path between two interaction is the above introduced IMFP $\\lambda$. This multiple inelaxtic scattering is most obvious in the strongest energ-loss spectrum: the volume plasmon. This multiple scatering follows the Poisson statistic and the $n^{\\rm th}$ scattering has the intensity:\n$$I_n = I_0 P_n = (I_0/n!)(t/λ)^n \\exp(−t/λ)$$\n\nIt can be shown the the single scattering spectrum in fourier space $s(v)$ can be derived by:\n\n$$s(v) = I_0 \\ln[j(v)/z(v)]$$\n\n$z(v)$ beeing the Fourier transformed zero-loss peak (resolution function) and $j(v$ the spectrum in Fourier space.\n\nThe above formula would also correct for any instument broadening and a very noisy spectrum would result, so we need to convolute (multiplication in Fourier space) a new broadening function, which could be a well behaved Gaussian with slightly smaller energy width than the original zero-loss peak.\n\n\n\n```python\n# Single scattering deconvolution\n\n# Use resolution Function as ZL \n\nj = np.fft.fft(np.array(eels_dataset))\nz = np.fft.fft(zero_loss)\nz2 = z ## Could be a different zl i.e. extracted from Spectrum\nj1 = z2*np.log(j/z)\nssd_low_loss =np.fft.ifft(j1).real#,'fourier-log deconvolution')\n\nplt.figure()\n#plt.plot(s.tags['ene'][start:end], zLoss[start:end]/sumSpec*1e2)\nplt.plot(eels_dataset.energy_loss, ssd_low_loss)\nplt.plot(eels_dataset.energy_loss, eels_dataset)\n#plt.xlim(-4,40)\nplt.ylim(-.1,.1);\neels_dataset.metadata['resolution_function'] = zero_loss\n```\n\n\n \n\n\n\n\n\n\n## Volume Plasmon Peak\n\nMost of the inelastically scattered electron arise from interaction with outer shell electrons. These interactions, therefore, have a high intensity and are easy to obtain. The quantification of this region ($<$ 100eV) in an EELS spectrum is rather hard.\n\nThe valence electrons in a solid can be considered as coupled oscillators which interact with each others and with the transmitted electrons. In a first approximation the valence electrons behave like a free electron gas (Fermi sea, jellium). The behavior of the electron gas is described in terms of the dielectric function $\\varepsilon$.\n\n\nThe energy-loss function $F_{el}$ on the other hand is determined by the dielectric function $\\varepsilon$ through:\n\n$$\nF_{el} = \\Im \\left[\\frac{-1}{\\varepsilon(\\omega)} \\right]\n$$\n\nThe maximum of the energy-loss function is the plasmon--peak, which is given by:\n$$\nE_{\\mbox{max}} = \\left[(E_p)^2 - (\\Delta E_p/2)^2\\right]^{1/2}\n$$\n\n### Dielectric Theory\n\nWe investigate the plasmon excitation in the so called jellium model. This model is enough to explain the essence of this excitation, but is not as complicated as the real solid state.\n\n\nThe displacement of a {\\it quasifree} electron (with an effective mass $m$ and not the rest mass $m_0$) due to an electric field $\\vec{E}$ must fulfill the equation :\n\\begin{equation} \\Large\n\\label{equ:motion}\nm\\vec{x}'' + m\\Gamma \\vec{x}' = -e\\vec{E}\n\\end{equation}\n\nThe usage of an effective mass approximates the interaction between the valence electrons and the ion--cores. For the same reason, we introduce $\\Gamma$ a damping constant. Instead of $\\Gamma$, we could also use its reciprocal value $\\tau = 1/\\Gamma$ as in the Drude theory. This is similar to the electronic theory of conduction.\n\n\nFor an oscillatory field $\\vec{E}= \\vec{E} \\exp(-i\\omega t)$ above equation \\ref{equ:motion} has the following solution:\n\\begin{equation} \\Large\n\\label{equ:motion_solution}\n\\vec{x} = (e\\vec{E}/m)(\\omega ^2+i\\Gamma \\omega)^{-1}\n\\end{equation}\n\n\nThe displacement gives raise to a polarization $\\vec{P} = -en\\vec{x} =\\varepsilon_0\\chi\\vec{E}$, with $\\chi$ electric susceptibility and $n$ the the number of electron per unit volume. The dielectric function $\\varepsilon(\\omega)=1+\\chi$ can be expressed as:\n\\begin{equation} \\Large\n\\label{equ:dielectric_function}\n\\varepsilon(\\omega)=\\varepsilon_1+i\\varepsilon_2 = 1-\\frac{\\omega_p^2}{\\omega^2+\\Gamma^2}+\\frac{i\\Gamma\\omega^2_p}{\\omega(\\gamma^2+\\Gamma^2)}\n\\end{equation}\nWhere $\\omega$ is the frequency (in rad/s) of forced oscillation and $\\omega_p$ is the Eigen or resonance frequency of the free electron gas, which is given by:\n\\begin{equation} \\Large\n\\label{equ:plasmon_frequency}\n\\omega_p =\\left[ \\frac{ne^2}{\\varepsilon_0 m} \\right]^{1/2}\n\\end{equation}\n\n\nA sudden impulse such as a transmitted electron will contain all angular frequencies (Fourier components). It will also excite the resonance frequency of the jellium. Such an oscillation with frequency $\\omega_p$ can be viewed as a ``pseudoparticle`` with (plasmon) energy $E_p =\\hbar \\omega_p.$ We call this ``pseudoparticle`` a **plasmon**.\n\n### Energy-Loss Function\nThe energy-loss function (elf) is given as shown in the beginning by:\n\\begin{equation} \\Large\n\\label{equ:eels_function2}\nE_{el}= \\left[\\frac{1}{\\varepsilon(\\omega)}\\right] = \\frac{\\varepsilon_2}{\\varepsilon_1^2+\\varepsilon_2^2}=\\frac{\\omega\\Gamma\\omega_p^2}{(\\omega^2-\\omega_p^2)^2 +(\\omega\\Gamma)^2}\n\\end{equation}\nThe energy-loss is represented by $E=\\hbar \\omega$ and we can rewrite equation \n\\ref{equ:eels_function2} as:\n\\begin{equation}\n\\label{equ:eels_function3}\n \\left[\\frac{1}{\\varepsilon(E)}\\right] =\\frac{(E\\hbar/\\tau)E_p^2}{(E^2-E^2)^2 +(E\\hbar/\\tau)^2} %\n =\\frac{(E \\quad \\Delta E_p)E_p^2}{(E^2-E^2)^2 +(E \\quad \\Delta E_p)^2} \n\\end{equation}\n\n\nThe relaxation time $\\tau = 1/\\Gamma$ is directly connected to the FWHM of the energy-loss function which is given by $\\Delta E_p =\\hbar\\Gamma = \\hbar/\\tau$. The effect of the effective mass on the energy-loss function is rather small.\\\\ \nThe maximum of the energy-loss function is given in equation \\ref{equ:plasmon-maximum}.\n\n\nThe relaxation time $\\tau$ represents the time for plasmon oscillations to decay in energy by a factor $\\exp(-1)=0.37$. The number of oscillations which occur within this time is $\\omega_p\\tau/(2\\pi)=E_p/(2\\pi/\\Delta E_p)$. Using experimental values for $E_p$ and $\\Delta E_p$ result in 5 to 0.4 oscillations. The plasmon oscillations are, therefore, heavily damped, which depends on the band structure of the material. \n\n### Plasmon Energies\n\nThe calculated plasmon energies of the Jellium model with equation \\ref{equ:plasmon_frequency} are already quite good as can be seen in table \\ref{tbl:plasmon_frequencies}.\nOnly the number of valence electrons per unit area $n$ and the dielectric constant $\\varepsilon_0$ are necessary for these calculations.\n\n\n\n| Material | $E_p$ (experimental) | $E_P$ (theoretical)|\n|----------|-----------------------|--------------------|\n|Li | 7.1 eV | 8.0 eV|\n|Diamond | 34 eV | 31 eV|\n|Si | 16.5 eV | 16.6 eV| \n|Ge | 16.0 eV | 15.6 eV|\n|InSb | 12.9 eV | 12.7 eV|\n|GaAs | 15.8 eV | 15.7 eV|\n|NaCl | 15.5 eV | 15.7 eV|\n\nA more sophisticated way of comparing the valence loss spectra to theory is to calculate the dielectric function. {\\it Ab initio} density functional theory can be used to do these calculations. To obtain the dielectric function the valence band has to be convoluted with the conduction band. A comparison between experiment and theory is shown in the figure below. \n\n\n\n*Plasmon--Loss peak of Li (black circles), Gibbson et al Phys.~Rev.~B {\\bf 13}:2451 (1979) and calculated energy-loss function by S.~Ramachandran et al. (unpublished)}*\n\nThe plasmon--loss enables us to determine the plasmon energy, a materials parameter.\nThe width plasmon peak is also a characteristic of the material and is needed to determine the plasmon energy.\n\n\n\n*Plasmon--Loss peak of SrTiO$_3$ with highlighted FWHM*\n\nThe spectrum here is quite complicated due to the surface plasmon--peak which shows up to the left of the volume plasmon--peak. We measure the energy of the maximum of the plasmon--peak (here $E_{\\mbox{max}} = 31$ eV) and the width of the plasmon--peak (here $\\Delta E_P = 5.3$ eV). While it is easy to determine the plasmon--peak energy , the plasmon--peak width can only be determined approximately, because we don't know how to subtract the background.\n\nUsing equation above, we find that the plasmon energy is 30.5 eV for SrTiO$_3$.\n\n\n\nThis spectrum shows the high dynamic range of an EELS spectrum. The valence loss part of the spectrum is noisy, but the zero-loss peak is not saturated. The surface plasmon peak is strong, which indicates a rather thin area. May be a little too thin. Without loss of information we can get spectra from thicker areas.\n\n\nNot only the plasmon energy (or the plasmon maximum) can be used for an identification of materials,\nbut also the shape, especially the width of the plasmon peak.\n\nAs seen above, it is rather difficult to determine the FWHM of a plasmon peak. However, it is much easier after subtraction of the zero-loss peak, as can be seen in figure below.\n\n\n\n*Plasmon--Loss peak of Ni (black) after subtraction of the zero-loss peak and with highlighted FWHM. The original spectrum and the zero-loss peak are displayed in the background.*\n\nA comparison of the plasmon peak width of Ni (above) and Si (figure below)\n makes it apparent how different the shape of plasmon peaks can be. The Si plasmon peak is sharp (FWHM: 7.3 eV) and has a well defined maximum, while the Ni plasmon peak is very broad (FWHM: 40 eV).\n\n\n*Plasmon--Loss peak of Si (black) after subtraction of the zero-loss peak and with highlighted FWHM. The original spectrum and the zero-loss peak are displayed in the background.*\n\nThe Si plasmon peak is obtained from a rather thin area, which also makes it easier to determine the width, because the right hand tail is not broadened by the thicker sample (please see section above about single scattering deconvolution). \n\n## Drude Function\n\nThe dielectric function in the Drude theory is given by two input parameters the position of the plasmon energy $E_p$\nand the width of the plasmon $\\Gamma$\n\n$$ ε(ω) = ε1 + iε2 = 1 + χ = 1 − \\frac{\\omega_p^2}{\\omega^2+\\Gamma^2} + \\frac{i\\Gamma \\omega_p^2}{\\omega(\\omega^2+\\Gamma^2)}$$\nHere $\\omega$ is the angular frequency (rad/s) of forced oscillation and $\\omega_p$ is the natural or resonance frequency for plasma oscillation, given by\n$$ ω_p = \\sqrt{\\frac{ne^2}{(ε_0m_0)}} $$\nA transmitted electron represents a sudden impulse of applied electric field, containing\nall angular frequencies (Fourier components). Setting up a plasma oscillation of the loosely bound outer-shell electrons in a solid is equivalent to creating a pseudoparticle of energy $E_p = \\hbar \\omega_p$, known as a plasmon (Pines, 1963).\n\n\n```python\nE_p = plasmon_energy = 13. # in eV\nE_w = plasmon_gamma = 3. # in eV\nenergy_scale = eels_dataset.energy_loss+1e-18 #= np.linspace(0,50,1024)+1e-18\n\ndef Drude(E,E_p,E_w):\n eps = 1 - E_p**2/(E**2+E_w**2) +1j* E_w* E_p**2/E/(E**2+E_w**2)\n elf = (-1/eps).imag\n return eps,elf\n\neps,elf = Drude(energy_scale, plasmon_energy, plasmon_gamma)\n\nplt.figure()\nplt.plot(energy_scale, eps.real, label='Re($\\epsilon_{Drude}$)')\nplt.plot(energy_scale, eps.imag, label='Im($\\epsilon_{Drude}$)')\nplt.plot(energy_scale, elf, label='loss function$_{Drude}$')\nplt.plot([0,energy_scale[-1]],[0,0],c='black')\n\nplt.legend()\nplt.gca().set_ylim(-2,max(elf)*1.05);\nplt.xlim(-1,40);\nplt.xlabel('energy loss (eV)')\n```\n\n\n \n\n\n\n\n\n\n\n\n\n Text(0.5, 0, 'energy loss (eV)')\n\n\n\n## Fitting a Drude Function to Plasmon\n\nThe position and the width are important materials parameters and we can derive them by fitting the Drude function to the volume plasmon region.\n\n\n```python\nfrom scipy.optimize import leastsq\n\ndef Drude(E,Ep,Ew):\n eps = 1 - Ep**2/(E**2+Ew**2) +1j* Ew* Ep**2/E/(E**2+Ew**2)\n elf = (-1/eps).imag\n return eps,elf\n\ndef errfDrude(p, y, x):\n eps,elf = Drude(x,p[0],p[1])\n err = y - p[2]*elf\n #print (p,sum(np.abs(err)))\n return np.abs(err)#/np.sqrt(y)\n\n\npin2 = np.array([15,1,.7])\nE = energy_scale\nstartFit =np.argmin(abs(energy_scale-13))\nendFit = np.argmin(abs(energy_scale-18))\n \np2, lsq = leastsq(errfDrude, pin2, args=(ssd_low_loss[startFit:endFit], energy_scale[startFit:endFit]), maxfev=2000)\n\neps, elf =Drude(energy_scale,p2[0],p2[1])\ndrudePSD = p2[2]* elf\nplt.figure()\n\nplt.plot(energy_scale,eels_dataset)\nplt.plot(energy_scale,drudePSD)\nplt.plot(energy_scale,eels_dataset-drudePSD)\nplt.axhline(0, color='black')\n\nplt.gca().set_xlim(0,40)\nplt.gca().set_ylim(-0.01,0.2)\nprint(f\"Drude Theory with Plamson Energy: {p2[0]:2f} eV and plasmon Width {p2[1]:.2f} eV\") \nprint(f\"Max of Plasmon at {energy_scale[drudePSD.argmax(0)]:.2f} eV\")\nprint(f\"Amplitude of {p2[2]:.2f} was deteremined by fit \")\n\n```\n\n\n \n\n\n\n\n\n\n Drude Theory with Plamson Energy: 15.047837 eV and plasmon Width 0.72 eV\n Max of Plasmon at 15.04 eV\n Amplitude of 0.01 was deteremined by fit \n\n\n\n```python\nplt.figure()\nplt.title ('Drude Fit: Dielectric Function - Permittivity')\nplt.plot(energy_scale,eps.real,label = 'Re($\\epsilon)$')\nplt.plot(energy_scale,eps.imag,label = 'Im($\\epsilon)$')\nplt.plot(energy_scale,drudePSD,label = 'loss-function$_{Drude}$')\nplt.plot(energy_scale,eels_dataset,label = 'loss-function$_{exp}$')\nplt.axhline(0, color='black')\n\nplt.gca().set_xlim(0,40)\nplt.gca().set_ylim(-2.5,5.3)\n\nplt.legend();\n```\n\n\n \n\n\n\n\n\n\n### Plasmon Frequency and Phase Identification\n\n\nPlasmon peaks occurring in EELS is directly related to valence electron density and can thereby be used as a means for materials characterization and phase identification. Free-electron metals have very sharp plasmon peaks as compared to semiconductors and insulators with broader peaks, where the valence electrons are no longer free (covalent or ionic bonding). While many materials properties are a function of valence electron density, knowing the plasmon energy can prove to be a useful tool in identifying micro structures.\n\n\nMicrostructural phases are observed by shifts in the plasmon energy. Examples of phase identification are observed easily in alloys and also precipitate structures. A common textbook example is EELS low loss comparison of diamond and graphite. The example given in Figure is a line scan showing the variation of plasmon energies with position. The plasmon energies range from 21 to 23 eV, corresponding to SiC (20.8 eV) and SiN3 (22.5 eV) respectively. Figure \\ref{plasmon-ls2} is a reconstructed map of the plasmon energies. Blue regions correspond to SiC, while the red regions correspond to SiN3. \n \n \nAppendix C in Egerton's Electron Energy Loss Spectroscopy in the Electron Microscope lists plasmon energies of some elements and compounds [Egerton-1999].\n\n## Surface Plasmon\n\nSpectra from thin specimen show the excitations of the surface plasmons on each side of the specimen. For any normal specimen these surface plasmons do interact, but this is not true for extremely thick specimen ($>> 10$nm).\nThe surface plasmon frequency $\\omega_S$ for thin specimen is related to the bulk plasmon frequency $\\omega_P$ by Ritchie [Ritchie-PR1957]: \n$$\n\\omega_S=\\omega_P\\left[ \\frac{1\\pm \\exp(-q_st) }{1+\\varepsilon} \\right]^{1/2}\n$$\n\n\nThe symmetric mode, where like charges face one another, corresponds to the higher angular frequency $q_s$. Please note, that this relationship does only apply for large $q_s$\n\nThe differential probability for surface excitation at both surfaces of a sample with thickness $t$ can be expressed (normal incident, no retardation effects) by:\n$$\n\\frac{d^2 P_s}{d\\Omega d E}=\\frac{2\\hbar}{\\pi^2 \\gamma a_0 m_0^2 \\mu^3}\\frac{\\theta}{(\\theta^2+\\theta^2_E)^2} \\Im\\left[ \\frac{(\\varepsilon_a - \\varepsilon_b)^2 } {\\varepsilon_a^2 \\varepsilon_b}\\right]\n$$\nwith \n$$\nR_c = \\frac{\\varepsilon_a \\sin^2(tE/2\\hbar\\mu)}{\\varepsilon_b + \\varepsilon_z }\\tanh (q_s t/2) \n+ \\frac{\\varepsilon_a \\cos^2(tE/2\\hbar\\mu)}{\\varepsilon_b + \\varepsilon_a} \\coth (q_s t/2) \n$$\nand $\\varepsilon_a$ and $\\varepsilon_b$ are the permitivities of the two surfaces.\n\n\nA secondary effect of the surface excitation is the reduced intensity of the bulk plasmon peak. The effect is usually smaller than 1\\%, but can be larger for spectra with small collection angle, because the preferred scattering of surfuce losses into small angles.\nThe correction for surface plasmon will be discussed in the Kramers--Kronig Analysis.\n\n\n\n## Summary\n\nThe beauty of ``Low--Loss spectroscopy`` is its derivation of the dielectric function to high energies without prior knowledge of the composition. The signal is strong and the acquisition time is mostly restricted by the dynamic range of the spectrum.\n\n>\n>Think of low-loss spectroscopy as Electrodynamics\n>\n\nThe advantages of EELS is the derivation of these values spatially resolved.\nAnd from a linescan across an Si/SiO$_2$ interface the dielectric function per pixel can be obtained. From that we can calculate the dielectric polarizability $\\alpha_e (E)$, which may be a measure of the dielectric strength.\n\n\nWe obtain more or less easily:\n- relative thickness\n- absolute thickness \n- inelastic mean free path\n- plasmon frequency\n- plasmon width\n- band gap\n- dielectric function\n- reflectivity \n- absorption\n- effective number of electrons per atoms \n \n\n\nThe analysis of the optical data requires the exact knowledge of the zero-loss peak. Because of the weighting in the Fourier Analysis, the low energy part contributes heavily to the dielectric function. Therefore, energy resolution is critical for an exact determination of all the optical values from EELS. The new monochromated TEMs are now able to achieve an energy resolution of 10 meV (one is at the oak Ridge National Laboratory), which allows for a sharper zero-loss peak. Such a sharp zero-loss peak will enable us to extract this low energy data more accurately. The dielectric function and the parameters derived from it, can be more precisely determined from such EELS spectra.\n\n\n## Navigation\n- **Up Chapter 4: [Imaging](CH4_00-Spectroscopy.ipynb)** \n- **Back: [Overview](CH4_02-Fit_Zero_Loss.ipynb)** \n- **Next: [Simulation of Momentum Resolved EELS](CH4_04-Kroeger.ipynb)** \n- **List of Content: [Front](../_MSE672_Intro_TEM.ipynb)** \n\n\n```python\n\n```\n", "meta": {"hexsha": "feb36e0d7f245a36fa718658edd1724495ce0af6", "size": 796915, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Spectroscopy/CH4_03-Drude.ipynb", "max_stars_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_stars_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-22T18:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T20:17:34.000Z", "max_issues_repo_path": "Spectroscopy/CH4_03-Drude.ipynb", "max_issues_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_issues_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "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": "Spectroscopy/CH4_03-Drude.ipynb", "max_forks_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_forks_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-01-26T16:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T14:53:16.000Z", "avg_line_length": 115.7970066841, "max_line_length": 90455, "alphanum_fraction": 0.7746949173, "converted": true, "num_tokens": 8587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.16238004072020704, "lm_q1q2_score": 0.06190244869201329}} {"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# Operators and observables\n\n\n \n \n \n \n
    \n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
    \n\n\n```\ntry:\n import cirq\nexcept ImportError:\n print(\"installing cirq...\")\n !pip install --quiet cirq\n print(\"installed cirq.\")\n import cirq\n \nimport numpy as np\nimport sympy.parsing.sympy_parser as sympy_parser\n```\n\nThis guide is directed at those already familiar with quantum operations (operators) and observables who want to know how to use them in Cirq. The following table shows an overview of operators.\n\n| Operator | Cirq representation | Guides | Examples | \n|-----|-------|--------|-----|\n| Unitary operators | Any class implementing the `_unitary_` and `_has_unitary_` protocol | [Protocols](protocols.ipynb), [Gates and operations](gates.ipynb), [Custom gates](custom_gates.ipynb) | `cirq.Gate`
    `cirq.X(qubit)`
    `cirq.CNOT(q0, q1)`
    `cirq.MatrixGate.on(qubit)`
    `cirq.Circuit` (if it only contains unitary operations) |\n| Measurements | `cirq.measure` and `cirq.MeasurementGate` | [Gates and operations](gates.ipynb) | `cirq.measure(cirq.LineQubit(0))` | \n| Quantum channels |
    • Kraus operators (any class implementing the `_kraus_` and `_has_kraus_` protocol)
    • Unitary mixtures (any class implementing the `_mixture_` and `_has_mixture_` protocol)
    | [Protocols](protocols.ipynb) | `cirq.DepolarizingChannel(p=0.2)(q0)`
    `cirq.X.with_probability(0.5)`|\n\nCirq also supports observables on qubits that can be used to calculate expectation values on a given state.\n\n* You can use `cirq.PauliString` to express them,\n* Or you can use `cirq.PauliSum` with real coefficients.\n\n## Operators\n\nQuantum operations (or just *operators*) include unitary gates, measurements, and noisy channels. Operators that act on a given set of qubits implement `cirq.Operation` which supports the Kraus operator representation\n\n$$\n\\rho \\mapsto \\sum_{k} A_k \\rho A_k^\\dagger .\n$$\n\nHere, $\\sum_{k} A_k^\\dagger A_k = I$ and $\\rho$ is a quantum state. Operators are defined in the `cirq.ops` module.\n\n### Unitary operators\n\nStandard unitary operators used in quantum information can be found in `cirq.ops`, for example Pauli-$X$ as shown below.\n\n\n```\nqubit = cirq.LineQubit(0)\nunitary_operation = cirq.ops.X.on(qubit) # cirq.X can also be used for cirq.ops.X\nprint(unitary_operation)\n```\n\nCirq makes a distinction between gates (independent of qubits) and operations (gates acting on qubits). Thus `cirq.X` is a gate where `cirq.X.on(qubit)` is an operation. See the [guide on gates](gates.ipynb) for more details and additional common unitaries defined in Cirq.\n\n> **Note**: The method `cirq.X.on_each` is a utility to apply `cirq.X` to multiple qubits. Similarly for other operations.\n\nEvery `cirq.Operation` supports the `cirq.channel` protocol which returns its Kraus operators. (Read more about [protocols](protocols.ipynb) in Cirq.)\n\n\n```\nkraus_ops = cirq.kraus(unitary_operation)\nprint(f\"Kraus operators of {unitary_operation.gate} are:\", *kraus_ops, sep=\"\\n\")\n```\n\nUnitary operators also support the `cirq.unitary` protocol.\n\n\n```\nunitary = cirq.unitary(cirq.ops.X)\nprint(f\"Unitary of {unitary_operation.gate} is:\\n\", unitary)\n```\n\nUnitary gates can be raised to powers, for example to implement a $\\sqrt{X}$ operation.\n\n\n```\nsqrt_not = cirq.X ** (1 / 2)\nprint(cirq.unitary(sqrt_not))\n```\n\nAny gate can be controlled via `cirq.ControlledGate` as follows.\n\n\n```\ncontrolled_hadamard = cirq.ControlledGate(sub_gate=cirq.H, num_controls=1)\nprint(cirq.unitary(controlled_hadamard).round(3))\n```\n\nCustom gates can be defined as described in [this guide](custom_gates.ipynb). Some common subroutines which consist of several operations are pre-defined - e.g., `cirq.qft` returns the operations to implement the quantum Fourier transform.\n\n### Measurements\n\nCirq supports measurements in the computational basis.\n\n\n```\nmeasurement = cirq.MeasurementGate(num_qubits=1, key=\"key\")\nprint(\"Measurement:\", measurement)\n```\n\nThe `key` can be used to identify results of measurements when [simulating circuits](simulation.ipynb). A measurement gate acting on a qubit forms an operation.\n\n\n```\nmeasurement_operation = measurement.on(qubit)\nprint(measurement_operation)\n```\n\n> **Note**: The function `cirq.measure` is a utility to measure a single qubit, and the function `cirq.measure_each` is a utility to measure multiple qubits.\n\nAgain measurement operations implement `cirq.Operation` so the `cirq.channel` protocol can be used to get the Kraus operators.\n\n\n```\nkraus_ops = cirq.kraus(measurement)\nprint(f\"Kraus operators of {measurement} are:\", *kraus_ops, sep=\"\\n\\n\")\n```\n\nThe functions `cirq.measure_state_vector` and `cirq.measure_density_matrix` can be used to perform computational basis measurements on state vectors and density matrices, respectively, represented by NumPy arrays.\n\n\n```\npsi = np.ones(shape=(2,)) / np.sqrt(2)\nprint(\"Wavefunction:\\n\", psi.round(3))\n```\n\n\n```\nresults, psi_prime = cirq.measure_state_vector(psi, indices=[0])\n\nprint(\"Measured:\", results[0])\nprint(\"Resultant state:\\n\", psi_prime)\n```\n\n\n```\nrho = np.ones(shape=(2, 2)) / 2.0\nprint(\"State:\\n\", rho)\n```\n\n\n```\nmeasurements, rho_prime = cirq.measure_density_matrix(rho, indices=[0])\n\nprint(\"Measured:\", measurements[0])\nprint(\"Resultant state:\\n\", rho_prime)\n```\n\nThese functions do not modify the input state (`psi` or `rho`) unless the optional argument `out` is provided as the input state.\n\n### Noisy channels\n\nLike common unitary gates, Cirq defines many common noisy channels, for example the depolarizing channel below.\n\n\n```\ndepo_channel = cirq.DepolarizingChannel(p=0.01, n_qubits=1)\nprint(depo_channel)\n```\n\nJust like unitary gates and measurements, noisy channels implement `cirq.Operation`, and we can always use `cirq.channel` to get the Kraus operators.\n\n\n```\nkraus_ops = cirq.kraus(depo_channel)\nprint(f\"Kraus operators of {depo_channel} are:\", *[op.round(2) for op in kraus_ops], sep=\"\\n\\n\")\n```\n\nSome channels can be written\n\n$$\n\\rho \\mapsto \\sum_k p_k U_k \\rho U_k ^\\dagger\n$$\n\nwhere real numbers $p_k$ form a probability distribution and $U_k$ are unitary. Such a *probabilistic mixture* of unitaries supports the `cirq.mixture` protocol which returns $p_k$ and $U_k$. An example is shown below for the bit-flip channel $\\rho \\mapsto (1 - p) \\rho + p X \\rho X$.\n\n\n```\nbit_flip = cirq.bit_flip(p=0.05)\nprobs, unitaries = cirq.mixture(bit_flip)\n\nfor prob, unitary in cirq.mixture(bit_flip):\n print(f\"With probability {prob}, apply \\n{unitary}\\n\")\n```\n\n> **Note**: Any unitary gate/operation supports `cirq.mixture` because it can be interpreted as applying a single unitary with probability one.\n\nCustom noisy channels can be defined as described in [this guide](noise.ipynb).\n\n### In circuits\n\nAny `cirq.Operation` (pre-defined or user-defined) can be placed in a `cirq.Circuit`. An example with a unitary, noisy channel, and measurement is shown below.\n\n\n```\ncircuit = cirq.Circuit(\n cirq.H(qubit),\n cirq.depolarize(p=0.01).on(qubit),\n cirq.measure(qubit)\n)\nprint(circuit)\n```\n\nThe general input to the circuit constructor is a `cirq.OP_TREE`, i.e., an operation or nested collection of operations. Circuits can be manipulated as described in the [circuits guide](circuits.ipynb) and simulated as described in the [simulation guide](simulation.ipynb).\n\n### Alternate representations\n\nIn addition to the above representations for operators. Cirq also supports some more non-standard representations as well. To convert a set of kraus operators to a choi representation you can do:\n\n\n```\ndepo_channel = cirq.DepolarizingChannel(p=0.01, n_qubits=1)\nkraus_rep = cirq.kraus(depo_channel)\nprint(kraus_rep)\n```\n\n\n```\nchoi_rep = cirq.kraus_to_choi(kraus_rep)\nprint(choi_rep)\n```\n\nAnd to get the superoperator representation you can do:\n\n\n```\nsuper_rep = cirq.kraus_to_superoperator(kraus_rep)\nprint(super_rep)\n```\n", "meta": {"hexsha": "44742228deffb85dc53f75e4ee839a3140b0642b", "size": 17336, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/operators.ipynb", "max_stars_repo_name": "BearerPipelineTest/Cirq", "max_stars_repo_head_hexsha": "e00767a2ef1233e82e9089cf3801a77e4cc3aea3", "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/operators.ipynb", "max_issues_repo_name": "BearerPipelineTest/Cirq", "max_issues_repo_head_hexsha": "e00767a2ef1233e82e9089cf3801a77e4cc3aea3", "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/operators.ipynb", "max_forks_repo_name": "BearerPipelineTest/Cirq", "max_forks_repo_head_hexsha": "e00767a2ef1233e82e9089cf3801a77e4cc3aea3", "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": 26.5889570552, "max_line_length": 359, "alphanum_fraction": 0.5836409783, "converted": true, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.13296424019782926, "lm_q1q2_score": 0.06181528420443949}} {"text": "

    Table of Contents

    \n\n\n\n```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', '..', 'notebook_format'))\n\nfrom formats import load_style\nload_style(plot_style=False)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nos.chdir(path)\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format='retina'\n\nimport time\nimport fasttext\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# prevent scientific notations\npd.set_option('display.float_format', lambda x: '%.3f' % x)\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,fasttext,scipy\n```\n\n Ethen 2020-05-21 22:08:36 \n \n CPython 3.6.4\n IPython 7.9.0\n \n numpy 1.16.5\n pandas 0.25.0\n matplotlib 3.1.1\n fasttext n\u0007\n scipy 1.4.1\n\n\n# Product Quantization for Model Compression\n\n**Product Quantization** or often times PQ for short is an extremely popular algorithm for compressing vectors/embeddings and performing approximate nearest neighborhood search. In this example, we'll be using fasttext to illustrate the concept. The library and the data preparation step has already been introduced in another [documentation](http://ethen8181.github.io/machine-learning/deep_learning/multi_label/fasttext.html), hence we won't be spending too much on them.\n\n## Data Preparation and Model\n\n\n```python\n# download the data and un-tar it under the 'data' folder\n\n# -P or --directory-prefix specifies which directory to download the data to\n!wget https://dl.fbaipublicfiles.com/fasttext/data/cooking.stackexchange.tar.gz -P data\n# -C specifies the target directory to extract an archive to\n!tar xvzf data/cooking.stackexchange.tar.gz -C data\n```\n\n --2020-05-21 22:08:36-- https://dl.fbaipublicfiles.com/fasttext/data/cooking.stackexchange.tar.gz\n Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.75.142, 104.22.74.142\n Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.75.142|:443... connected.\n HTTP request sent, awaiting response... 200 OK\n Length: 457609 (447K) [application/x-tar]\n Saving to: ‘data/cooking.stackexchange.tar.gz.3’\n \n cooking.stackexchan 100%[===================>] 446.88K --.-KB/s in 0.1s \n \n 2020-05-21 22:08:36 (4.43 MB/s) - ‘data/cooking.stackexchange.tar.gz.3’ saved [457609/457609]\n \n x cooking.stackexchange.id\n x cooking.stackexchange.txt\n x readme.txt\n\n\n\n```python\n!head -n 3 data/cooking.stackexchange.txt\n```\n\n __label__sauce __label__cheese How much does potato starch affect a cheese sauce recipe?\r\n __label__food-safety __label__acidity Dangerous pathogens capable of growing in acidic environments\r\n __label__cast-iron __label__stove How do I cover up the white spots on my cast iron stove?\r\n\n\n\n```python\n# train/test split\nfrom fasttext_module.split import train_test_split_file\nfrom fasttext_module.utils import prepend_file_name\n\ndata_dir = 'data'\ntest_size = 0.2\ninput_path = os.path.join(data_dir, 'cooking.stackexchange.txt')\ninput_path_train = prepend_file_name(input_path, 'train')\ninput_path_test = prepend_file_name(input_path, 'test')\nrandom_state = 1234\nencoding = 'utf-8'\n\ntrain_test_split_file(input_path, input_path_train, input_path_test,\n test_size, random_state, encoding)\nprint('train path: ', input_path_train)\nprint('test path: ', input_path_test)\n```\n\n train path: data/train_cooking.stackexchange.txt\n test path: data/test_cooking.stackexchange.txt\n\n\n\n```python\n# train the fasttext model\nfasttext_params = {\n 'input': input_path_train,\n 'lr': 0.1,\n 'lrUpdateRate': 1000,\n 'thread': 8,\n 'epoch': 15,\n 'wordNgrams': 1,\n 'dim': 80,\n 'loss': 'ova'\n}\nmodel = fasttext.train_supervised(**fasttext_params)\n\nprint('vocab size: ', len(model.words))\nprint('label size: ', len(model.labels))\nprint('example vocab: ', model.words[:5])\nprint('example label: ', model.labels[:5])\n\nmodel_checkpoint = os.path.join('model', 'model.fasttext')\nmodel.save_model(model_checkpoint)\n```\n\n vocab size: 14496\n label size: 733\n example vocab: ['', 'to', 'a', 'How', 'the']\n example label: ['__label__baking', '__label__food-safety', '__label__substitutions', '__label__equipment', '__label__bread']\n\n\n\n```python\n# model.get_input_matrix().shape\nprint('output matrix shape: ', model.get_output_matrix().shape)\nmodel.get_output_matrix()\n```\n\n output matrix shape: (733, 80)\n\n\n\n\n\n array([[ 0.7556045 , -0.0944011 , -0.21562839, ..., -2.333261 ,\n -0.8223824 , 1.4007478 ],\n [ 0.8890684 , -0.35554123, -2.706871 , ..., 1.2450662 ,\n 0.05990526, -2.0757916 ],\n [ 0.40264592, -1.7393613 , 1.3168088 , ..., -3.8272636 ,\n 1.9295563 , 1.6614803 ],\n ...,\n [ 1.0975604 , -0.8535318 , 0.24365285, ..., -0.5385103 ,\n -0.5356003 , 0.6660056 ],\n [ 1.1728309 , -0.92786735, 0.30251437, ..., -0.60272974,\n -0.5144258 , 0.7182006 ],\n [ 1.1421866 , -0.89937526, 0.29751846, ..., -0.6316411 ,\n -0.570792 , 0.7465125 ]], dtype=float32)\n\n\n\n## Product Quantization from Scratch\n\nThe main goal behind compression is that after training our model, the model size is too large for deployment. e.g. when deploying on edge devices where we have limited memory at hand or would require using a bigger machine which ultimately incur more infrastructure costs. \n\nIn this situation, **product quantization** is a compression technique for compressing embeddings. It has been shown that it significantly reduce the size of the model without hurting the performance by much. And without further a due, we'll dive right into how this technique works.\n\n### Learning Code Book\n\nOur first step is to split the a $d$ dimensional vectors/matrix $\\mathbf{X}$ into $m$ distinct subvectors $u_j$, $1 \\leq j \\leq m$ of dimension $d^* = d / m$, where $d$ should ideally be multiple of $m$.\n\nAs an example, say our original embedding has a dimension of 1000x80, we can split it into 4 subvectors, each having a dimension of 1000x20.\n\n\n\nNext, we'll run a k-means clustering algorithm on each subvectors. Upon computing the cluster centroid for each of $k$ cluster and $m$ subvectors, we would have on our hand, $m$ cluster centroids, each of size $k \\times d^*$. In other words, reducing the dimension from $n \\times d$ into $m \\times k \\times d^* = k \\times d$\n\n\n\nSo we'll apply k-means on our 1000x20 subvectors. If $k$ is 10, we would end up having 10 cluster centroids each of size 20. Since we have 4 subvectors, we would have 4 of those.\n\nInformation theory nomenclature is often times used to explain these concepts. Where:\n\n- The cluster centroids is referred to as **codebook**.\n- The cluster index is called a **code**, a **reproduction value**, a **reconstruction value**.\n\nWe'll be using [scipy vector quantization module's k-means clustering](https://docs.scipy.org/doc/scipy/reference/cluster.vq.html) implementation in the example code.\n\n\n```python\nfrom scipy.cluster.vq import kmeans2, vq\n\n\ndef compute_code_books(vectors, sub_size=2, n_cluster=128, n_iter=20, minit='points', seed=123):\n n_rows, n_cols = vectors.shape\n n_sub_cols = n_cols // sub_size\n\n np.random.seed(seed)\n code_books = np.zeros((sub_size, n_cluster, n_sub_cols), dtype=np.float32)\n for subspace in range(sub_size):\n sub_vectors = vectors[:, subspace * n_sub_cols:(subspace + 1) * n_sub_cols]\n centroid, label = kmeans2(sub_vectors, n_cluster, n_iter, minit=minit)\n code_books[subspace] = centroid\n\n return code_books\n```\n\n\n```python\nsub_size = 2 # m\nn_cluster = 64 # k\n\n# learning the cluster centroids / code books for our output matrix/embedding\ncode_books = compute_code_books(model.get_output_matrix(), sub_size, n_cluster)\nprint('code book size: ', code_books.shape)\n```\n\n code book size: (2, 64, 40)\n\n\n### Encode\n\nThe cluster centroids for each of the subvectors represents the average/common pattern of each subvectors, and what we're going to do is to replace the original vector with the cluster centroid of each subvectors. The effect of doing so is instead of storing the original floating values for every record in our dataset, we'll be replacing it with the closest cluster centroid id within each subvectors.\n\ni.e. At the end, we'll be \"compressing\" our original vector of size $n \\times d$ into a size of $n \\times m$\n\n\n\n\n```python\ndef encode(vectors, code_books):\n n_rows, n_cols = vectors.shape\n sub_size = code_books.shape[0]\n n_sub_cols = n_cols // sub_size\n\n codes = np.zeros((n_rows, sub_size), dtype=np.int32)\n for subspace in range(sub_size):\n sub_vectors = vectors[:, subspace * n_sub_cols:(subspace + 1) * n_sub_cols]\n code, dist = vq(sub_vectors, code_books[subspace])\n codes[:, subspace] = code\n\n return codes\n```\n\n\n```python\n# our original embedding now becomes the cluster centroid for each subspace\nvector_codes = encode(model.get_output_matrix(), code_books)\nprint('encoded vector codes size: ', vector_codes.shape)\nvector_codes\n```\n\n encoded vector codes size: (733, 2)\n\n\n\n\n\n array([[34, 61],\n [29, 19],\n [ 7, 4],\n ...,\n [42, 52],\n [42, 47],\n [42, 52]], dtype=int32)\n\n\n\nWe can calculate the potential size/memory savings if we were to go from storing the original vector into storing the encoded codes and the code book.\n\n\n```python\n(vector_codes.nbytes + code_books.nbytes) / model.get_output_matrix().nbytes\n```\n\n\n\n\n 0.11231241473396998\n\n\n\nInstead of directly compressing the original embedding, we can also learn the codebooks and compress all new incoming embeddings on the fly.\n\n## Computing Query Distance\n\nWe can also compute nearest neighbors using the compressed vectors.\n\n\n```python\n# we'll get one of the labels to find its nearest neighbors \nlabel_id = 0\nprint(model.labels[label_id])\n\nquery = model.get_output_matrix()[label_id]\nquery.shape\n```\n\n __label__baking\n\n\n\n\n\n (80,)\n\n\n\n\n```python\n# printing out the shape of the code book to hopefully make it easier\ncode_books.shape\n```\n\n\n\n\n (2, 64, 40)\n\n\n\nTo do so, we'll be computing the distance between each subspace of the query with the cluster centroid of each subspace, giving us a $m \\times k$ distance table, where each one denotes the squared Euclidean distance between the $m_{th}$ subvector of the query and the $k_{th}$ code/cluster centroid for that $m_{th}$ subvector.\n\n\n```python\ndef query_dist_table(query, code_books):\n sub_size, n_cluster, n_sub_cols = code_books.shape\n\n dist_table = np.zeros((sub_size, n_cluster))\n for subspace in range(sub_size):\n sub_query = query[subspace * n_sub_cols:(subspace + 1) * n_sub_cols]\n\n diff = code_books[subspace] - sub_query.reshape(1, -1)\n diff = np.sum(diff ** 2, axis=1)\n dist_table[subspace, :] = diff\n\n return dist_table\n```\n\n\n```python\ndist_table = query_dist_table(query, code_books)\nprint(dist_table.shape)\ndist_table[:, :5]\n```\n\n (2, 64)\n\n\n\n\n\n array([[ 99.99280548, 67.29737854, 127.93981934, 110.84047699,\n 128.75978088],\n [108.44404602, 209.63134766, 87.0813446 , 129.2036438 ,\n 158.81433105]])\n\n\n\nThen assuming for original vector is already encoded in advance, we can lookup the distances for each cluster centroid and add them up.\n\n\n```python\n# lookup the distance\ndists = np.sum(dist_table[range(sub_size), vector_codes], axis=1)\ndists[:5]\n```\n\n\n\n\n array([ 42.44870567, 408.77243042, 256.50379944, 247.31576538,\n 172.66897583])\n\n\n\n\n```python\n# the numpy indexing trick is equivalent to the following loop approach\nn_rows = vector_codes.shape[0]\ndists = np.zeros(n_rows).astype(np.float32)\nfor n in range(n_rows):\n for m in range(sub_size):\n dists[n] += dist_table[m][vector_codes[n][m]]\n\ndists[:5]\n```\n\n\n\n\n array([ 42.448708, 408.77243 , 256.50378 , 247.31577 , 172.66898 ],\n dtype=float32)\n\n\n\n\n```python\n# find the nearest neighbors and \"translate\" it to the original labels\nk = 5\nnearest = np.argsort(dists)[:k]\n[model.labels[label] for label in nearest]\n```\n\n\n\n\n ['__label__baking',\n '__label__cake',\n '__label__baking-powder',\n '__label__baking-soda',\n '__label__cookies']\n\n\n\nThe approach illustrated here is more of a naive approach as it still involves calculating the distances to all the vectors, which can still be inefficient for large $n$ (number of data points). We won't be discussing how to speed up the nearest neighborhood search process for product quantization as this documentation is more focused on the compression aspect of it.\n\n## Fasttext Product Quantization\n\nFasttext comes with built-in capabilities for doing model compression using product quantization. We'll experiment with different options/parameter and measure the model performance and model size. i.e. compression ratio v.s. model performance dip.\n\nThe next couple of code chunks defines the functions to measure the model performance and model file size.\n\n\n```python\nfrom typing import Dict\n\n\ndef score(input_path_train: str,\n input_path_test: str,\n model: fasttext.FastText._FastText,\n k: int,\n round_digits: int=3) -> Dict[str, float]:\n\n file_path_dict = {\n 'train': input_path_train,\n 'test': input_path_test\n }\n\n result = {}\n for group, file_path in file_path_dict.items():\n num_records, precision_at_k, recall_at_k = model.test(file_path, k)\n f1_at_k = 2 * (precision_at_k * recall_at_k) / (precision_at_k + recall_at_k)\n metric = {\n f'{group}_precision@{k}': round(precision_at_k, round_digits),\n f'{group}_recall@{k}': round(recall_at_k, round_digits),\n f'{group}_f1@{k}': round(f1_at_k, round_digits)\n }\n result.update(metric)\n\n return result\n```\n\n\n```python\nk = 1\nresult = score(input_path_train, input_path_test, model, k)\nresult\n```\n\n\n\n\n {'train_precision@1': 0.638,\n 'train_recall@1': 0.277,\n 'train_f1@1': 0.386,\n 'test_precision@1': 0.489,\n 'test_recall@1': 0.211,\n 'test_f1@1': 0.295}\n\n\n\n\n```python\ndef compute_file_size(file_path: str) -> str:\n \"\"\"\n Calculate the file size and format it into a human readable string.\n\n References\n ----------\n https://stackoverflow.com/questions/2104080/how-can-i-check-file-size-in-python\n \"\"\"\n file_size = compute_raw_file_size(file_path)\n file_size_str = convert_bytes(file_size)\n return file_size_str\n\n\ndef compute_raw_file_size(file_path: str) -> int:\n \"\"\"Calculate the file size in bytes.\"\"\"\n file_info = os.stat(file_path)\n return file_info.st_size\n\n\ndef convert_bytes(num: int) -> str:\n \"\"\"Convert bytes into more human readable MB, GB, etc.\"\"\"\n for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']:\n if num < 1024.0:\n return \"%3.1f %s\" % (num, unit)\n num /= 1024.0\n```\n\n\n```python\ncompute_file_size(model_checkpoint)\n```\n\n\n\n\n '4.9 MB'\n\n\n\nFor this part of the experiment, we'll tweak the parameter, dimension of subvector, `dsub`. Remember that this is one of main parameter that controls the tradeoff between the compression ratio and amount of distortion (deviation from the original vector).\n\n\n```python\ndsubs = [-1, 2, 4, 8]\n\nresults = []\nfor dsub in dsubs:\n # ensure we are always loading from the original model,\n # i.e. do not over-ride the model_checkpoint variable\n fasttext_model = fasttext.load_model(model_checkpoint)\n if dsub > 0:\n dir_name = os.path.dirname(model_checkpoint)\n model_path = os.path.join(dir_name, f'model_quantized_dsub{dsub}.fasttext')\n\n # qnorm, normalized the vector and quantize it\n fasttext_model.quantize(dsub=dsub, qnorm=True)\n fasttext_model.save_model(model_path)\n else:\n model_path = model_checkpoint\n\n result = score(input_path_train, input_path_test, fasttext_model, k)\n result['dsub'] = dsub\n result['file_size'] = compute_raw_file_size(model_path)\n results.append(result)\n \ndf_results = pd.DataFrame.from_dict(results)\ndf_results\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
    train_precision@1train_recall@1train_f1@1test_precision@1test_recall@1test_f1@1dsubfile_size
    00.6380.2770.3860.4890.2110.295-15143093
    10.6380.2770.3860.4870.2100.29421181690
    20.6300.2740.3810.4830.2090.2914891770
    30.5870.2550.3550.4700.2030.2838746810
    \n
    \n\n\n\nWe can visualize the table results. Our main observation is that setting `dsub` to 2 seems to give the most memory reduction while preserving most of the model's performance.\n\n\n```python\n# change default style figure and font size\nplt.rcParams['figure.figsize'] = 15, 6\nplt.rcParams['font.size'] = 12\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nfig.suptitle('Fasttext Quantization Experiments')\n\nax1.plot(df_results['dsub'], df_results['file_size'])\nax1.set_title('dsub versus file size')\nax1.set_xlabel('dsub')\nax1.set_ylabel('file size (bytes)')\n\nax2.plot(df_results['dsub'], df_results['test_precision@1'])\nax2.set_title('dsub versus test precision@1')\nax2.set_xlabel('dsub')\nax2.set_ylabel('precision@1')\n\nplt.show()\n```\n\nThe `.quantize` method also provide other options that we did not use here such as:\n\n- Whether to quantize the output matrix, `qout`\n- Whether to retrain the model's vector after doing the quantization, `retrain`.\n\nHere we also list down the other compression tidbits from the original paper.\n\n- **Quantize the Norm** fasttext has a parameter `qnorm` to normalize of the vector and also quantize that norm. This often times leads to a lesser drop in accuracy.\n- **Retrain after Quantization:** This suggests a bottom-up learning strategy where we first quantize the input matrix, then retrain and quantize the output matrix (the input matrix being frozen).\n- **Vocabulary Pruning:** Upon training the model, we can remove features that do not play a large role in the model. For each document, we verify if it is already covered by a retained feature and, if not, we add the feature with the highest norm to our set of retained features. If the number of features is below some user specified threshold, we add the features with the highest norm that have not yet been picked.\n- **Choice of subvectors:** We observe in practice that using $k = d/2$ subvectors, i.e., half of the components of the embeddings, works well in practice. Using less subquantizers significantly decreases the performance for a small memory gain.\n\n## Product Quantization Recap\n\nTo wrap up, we'll do a recap of product quantization, this time using a bit more notation.\n\nThe idea behind product quantization is to compress our original matrix into compact codes, where the comparison of the compact codes approximates the comparison in the original space. In the process of doing so, we are essentially retaining the most useful information within our matrix while discarding the less-relevant ones.\n\nWe have an original matrix $\\mathbf{X} = [\\mathbf{x}^1, \\mathbf{x}^2, ..., \\mathbf{x}^d]$, where $\\mathbf{x}^i \\in \\mathbb{R}^n$. The input matrix will first be splitted into $m$ distinct sub-matrix, $\\mathbf{U}^j$, $1 \\leq j \\leq m$, each of dimension $d^* = d / m$, where $d$ should ideally be multiple of $m$.\n\n\\begin{align}\n\\underbrace{\\mathbf{x}^1, ..., \\mathbf{x}^{d^*}}_{\\mathbf{U}^1}, ..., \\underbrace{\\mathbf{x}^{d - d^* + 1}, ..., \\mathbf{x}^{d}}_{\\mathbf{U}^m}\n\\end{align}\n\nThen a product quantizer function, $q(\\cdot)$, is defined as a concatenation of sub-quantizer.\n\n\\begin{align}\nq(\\mathbf{X}) = \\big[q^1(\\mathbf{U}^1), q^2(\\mathbf{U}^2), ..., q^M(\\mathbf{U}^m)\\big]\n\\end{align}\n\nWhere each sub-quantizer, $q^j$, is usually a low complexity quantizer/clustering algorithm, such as k-means. In other words, each sub-quantizer learns a sub-codebook/sub-cluster centroids $C^j$ comprises of $k$ centroids each of size $d^*$. Then the quantizer would map an input into its respective code/centroid under each sub-matrix and the final representation would be the concatenation of $m$ centroids.\n\n\\begin{align}\n\\mathbf{c} = [\\mathbf{c}^1, \\mathbf{c}^2, ..., \\mathbf{c}^m] \\in C = C^1 \\times C^2, ..., C^m\n\\end{align}\n\nTypically, the number of cluster centroids, $k$, is set to 256 so that each code/centroid can be represented by 8 bits.\n\n# Reference\n\n- [Github: Nano Product Quantization (nanopq)](https://github.com/matsui528/nanopq)\n- [Blog: Product Quantizers for k-NN Tutorial Part 1](http://mccormickml.com/2017/10/13/product-quantizer-tutorial-part-1)\n- [Paper: A. Joulin, E. Grave, P. Bojanowski, M. Douze, H. Jegou, T. Mikolov - FastText.zip: Compressing text classification models (2016)](https://arxiv.org/abs/1612.03651)\n- [Paper: H. Jegou, M. Douze, and C. Schmid. - Product quantization for nearest neighbor search (2011)](https://lear.inrialpes.fr/pubs/2011/JDS11/jegou_searching_with_quantization.pdf)\n", "meta": {"hexsha": "286b031a519260ee7eb0dbe26ab0d04b07957389", "size": 161498, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "deep_learning/multi_label/product_quantization.ipynb", "max_stars_repo_name": "JiaxiangBU/machine-learning", "max_stars_repo_head_hexsha": "1f71423da54bfde24de7528a3ef0f5c9e694f4b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-21T01:06:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-21T01:06:31.000Z", "max_issues_repo_path": "deep_learning/multi_label/product_quantization.ipynb", "max_issues_repo_name": "Infinite-Impact-Insights/machine-learning", "max_issues_repo_head_hexsha": "1f71423da54bfde24de7528a3ef0f5c9e694f4b7", "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": "deep_learning/multi_label/product_quantization.ipynb", "max_forks_repo_name": "Infinite-Impact-Insights/machine-learning", "max_forks_repo_head_hexsha": "1f71423da54bfde24de7528a3ef0f5c9e694f4b7", "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": 117.0275362319, "max_line_length": 114928, "alphanum_fraction": 0.8379360735, "converted": true, "num_tokens": 8116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12940274334274965, "lm_q1q2_score": 0.06167071426897004}} {"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# SSTO Earth Launch\n\nThis example is based on the _Time-Optimal Launch of a Titan II_\nexample given in Appendix B of Longuski {cite}`longuski2014optimal`.\nIt finds the pitch profile for a single-stage-to-orbit launch vehicle that minimizes the time\nrequired to reach orbit insertion under constant thrust.\n\n\n\nThe vehicle dynamics are given by\n\n\\begin{align}\n \\frac{dx}{dt} &= v_x \\\\\n \\frac{dy}{dt} &= v_y \\\\\n \\frac{dv_x}{dt} &= \\frac{1}{m} (T \\cos \\theta - D \\cos \\gamma) \\\\\n \\frac{dv_y}{dt} &= \\frac{1}{m} (T \\sin \\theta - D \\sin \\gamma) - g \\\\\n \\frac{dm}{dt} &= \\frac{T}{g I_{sp}}\n\\end{align}\n\nThe initial conditions are\n\n\\begin{align}\n x_0 &= 0 \\\\\n y_0 &= 0 \\\\\n v_{x0} &= 0 \\\\\n v_{y0} &= 0 \\\\\n m_0 &= 117000 \\rm{\\,kg}\n\\end{align}\n\nand the final conditions are\n\n\\begin{align}\n x_f &= \\rm{free} \\\\\n y_f &= 185 \\rm{\\,km} \\\\\n v_{xf} &= V_{circ} \\\\\n v_{yf} &= 0 \\\\\n m_f &= \\rm{free}\n\\end{align}\n\n## Defining the ODE\n\nGenerally, one could define the ODE system as a composite group of multile components.\nThe atmosphere component computes density ($\\rho$).\nThe eom component computes the state rates.\nDecomposing the ODE into smaller calculations makes it easier to derive the analytic derivatives.\n\n\n\nHowever, for this example we will demonstrate the use of complex-step differentiation and define the ODE as a single component.\nThis saves time up front in the deevlopment of the ODE at a minor cost in execution time.\n\nThe unconnected inputs to the EOM at the top of the diagram are provided by the Dymos phase as states, controls, or time values.\nThe outputs, including the state rates, are shown on the right side of the diagram.\nThe Dymos phases use state rate values to ensure that the integration technique satisfies the dynamics of the system.\n\n\n```python\nimport openmdao.api as om\nimport numpy as np\n\n\nclass LaunchVehicleODE(om.ExplicitComponent):\n\n def initialize(self):\n self.options.declare('num_nodes', types=int,\n desc='Number of nodes to be evaluated in the RHS')\n\n self.options.declare('g', types=float, default=9.80665,\n desc='Gravitational acceleration, m/s**2')\n\n self.options.declare('rho_ref', types=float, default=1.225,\n desc='Reference atmospheric density, kg/m**3')\n\n self.options.declare('h_scale', types=float, default=8.44E3,\n desc='Reference altitude, m')\n\n self.options.declare('CD', types=float, default=0.5,\n desc='coefficient of drag')\n\n self.options.declare('S', types=float, default=7.069,\n desc='aerodynamic reference area (m**2)')\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_input('y',\n val=np.zeros(nn),\n desc='altitude',\n units='m')\n\n self.add_input('vx',\n val=np.zeros(nn),\n desc='x velocity',\n units='m/s')\n\n self.add_input('vy',\n val=np.zeros(nn),\n desc='y velocity',\n units='m/s')\n\n self.add_input('m',\n val=np.zeros(nn),\n desc='mass',\n units='kg')\n\n self.add_input('theta',\n val=np.zeros(nn),\n desc='pitch angle',\n units='rad')\n\n self.add_input('thrust',\n val=2100000 * np.ones(nn),\n desc='thrust',\n units='N')\n\n self.add_input('Isp',\n val=265.2 * np.ones(nn),\n desc='specific impulse',\n units='s')\n # Outputs\n self.add_output('xdot',\n val=np.zeros(nn),\n desc='velocity component in x',\n units='m/s')\n\n self.add_output('ydot',\n val=np.zeros(nn),\n desc='velocity component in y',\n units='m/s')\n\n self.add_output('vxdot',\n val=np.zeros(nn),\n desc='x acceleration magnitude',\n units='m/s**2')\n\n self.add_output('vydot',\n val=np.zeros(nn),\n desc='y acceleration magnitude',\n units='m/s**2')\n\n self.add_output('mdot',\n val=np.zeros(nn),\n desc='mass rate of change',\n units='kg/s')\n\n self.add_output('rho',\n val=np.zeros(nn),\n desc='density',\n units='kg/m**3')\n\n # Setup partials\n # Complex-step derivatives\n self.declare_coloring(wrt='*', method='cs', show_sparsity=True)\n\n def compute(self, inputs, outputs):\n\n theta = inputs['theta']\n cos_theta = np.cos(theta)\n sin_theta = np.sin(theta)\n vx = inputs['vx']\n vy = inputs['vy']\n m = inputs['m']\n F_T = inputs['thrust']\n Isp = inputs['Isp']\n y = inputs['y']\n\n g = self.options['g']\n rho_ref = self.options['rho_ref']\n h_scale = self.options['h_scale']\n\n CDA = self.options['CD'] * self.options['S']\n\n outputs['rho'] = rho_ref * np.exp(-y / h_scale)\n outputs['xdot'] = vx\n outputs['ydot'] = vy\n outputs['vxdot'] = (F_T * cos_theta - 0.5 * CDA * outputs['rho'] * vx**2) / m\n outputs['vydot'] = (F_T * sin_theta - 0.5 * CDA * outputs['rho'] * vy**2) / m - g\n outputs['mdot'] = -F_T / (g * Isp)\n\n```\n\n## Solving the problem\n\n\n```python\nimport matplotlib.pyplot as plt\nimport openmdao.api as om\nimport dymos as dm\n\n#\n# Setup and solve the optimal control problem\n#\np = om.Problem(model=om.Group())\np.driver = om.pyOptSparseDriver()\np.driver.declare_coloring(tol=1.0E-12)\n\nfrom dymos.examples.ssto.launch_vehicle_ode import LaunchVehicleODE\n\n#\n# Initialize our Trajectory and Phase\n#\ntraj = dm.Trajectory()\n\nphase = dm.Phase(ode_class=LaunchVehicleODE,\n transcription=dm.GaussLobatto(num_segments=12, order=3, compressed=False))\n\ntraj.add_phase('phase0', phase)\np.model.add_subsystem('traj', traj)\n\n#\n# Set the options for the variables\n#\nphase.set_time_options(fix_initial=True, duration_bounds=(10, 500))\n\nphase.add_state('x', fix_initial=True, ref=1.0E5, defect_ref=10000.0,\n rate_source='xdot')\nphase.add_state('y', fix_initial=True, ref=1.0E5, defect_ref=10000.0,\n rate_source='ydot')\nphase.add_state('vx', fix_initial=True, ref=1.0E3, defect_ref=1000.0,\n rate_source='vxdot')\nphase.add_state('vy', fix_initial=True, ref=1.0E3, defect_ref=1000.0,\n rate_source='vydot')\nphase.add_state('m', fix_initial=True, ref=1.0E3, defect_ref=100.0,\n rate_source='mdot')\n\nphase.add_control('theta', units='rad', lower=-1.57, upper=1.57, targets=['theta'])\nphase.add_parameter('thrust', units='N', opt=False, val=2100000.0, targets=['thrust'])\n\n#\n# Set the options for our constraints and objective\n#\nphase.add_boundary_constraint('y', loc='final', equals=1.85E5, linear=True)\nphase.add_boundary_constraint('vx', loc='final', equals=7796.6961)\nphase.add_boundary_constraint('vy', loc='final', equals=0)\n\nphase.add_objective('time', loc='final', scaler=0.01)\n\np.model.linear_solver = om.DirectSolver()\n\n#\n# Setup and set initial values\n#\np.setup(check=True)\n\np.set_val('traj.phase0.t_initial', 0.0)\np.set_val('traj.phase0.t_duration', 150.0)\np.set_val('traj.phase0.states:x', phase.interp('x', [0, 1.15E5]))\np.set_val('traj.phase0.states:y', phase.interp('y', [0, 1.85E5]))\np.set_val('traj.phase0.states:vy', phase.interp('vx', [1.0E-6, 0]))\np.set_val('traj.phase0.states:m', phase.interp('vy', [117000, 1163]))\np.set_val('traj.phase0.controls:theta', phase.interp('theta', [1.5, -0.76]))\np.set_val('traj.phase0.parameters:thrust', 2.1, units='MN')\n\n#\n# Solve the Problem\n#\ndm.run_problem(p)\n\n#\n# Get the explicitly simulated results\n#\nexp_out = traj.simulate()\n\n#\n# Plot the results\n#\nfig, axes = plt.subplots(nrows=2, ncols=1, figsize=(10, 8))\n\naxes[0].plot(p.get_val('traj.phase0.timeseries.states:x'),\n p.get_val('traj.phase0.timeseries.states:y'),\n marker='o',\n ms=4,\n linestyle='None',\n label='solution')\n\naxes[0].plot(exp_out.get_val('traj.phase0.timeseries.states:x'),\n exp_out.get_val('traj.phase0.timeseries.states:y'),\n marker=None,\n linestyle='-',\n label='simulation')\n\naxes[0].set_xlabel('range (m)')\naxes[0].set_ylabel('altitude (m)')\naxes[0].set_aspect('equal')\n\naxes[1].plot(p.get_val('traj.phase0.timeseries.time'),\n p.get_val('traj.phase0.timeseries.controls:theta'),\n marker='o',\n ms=4,\n linestyle='None')\n\naxes[1].plot(exp_out.get_val('traj.phase0.timeseries.time'),\n exp_out.get_val('traj.phase0.timeseries.controls:theta'),\n linestyle='-',\n marker=None)\n\naxes[1].set_xlabel('time (s)')\naxes[1].set_ylabel('theta (deg)')\n\nplt.suptitle('Single Stage to Orbit Solution Using Linear Tangent Guidance')\nfig.legend(loc='lower center', ncol=2)\n\nplt.show()\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 143, tolerance=0.05)\nassert_near_equal(p.get_val('traj.phase0.timeseries.states:y')[-1], 1.85E5, 1e-4)\nassert_near_equal(p.get_val('traj.phase0.timeseries.states:vx')[-1], 7796.6961, 1e-4)\nassert_near_equal(p.get_val('traj.phase0.timeseries.states:vy')[-1], 0, 1e-4)\n```\n\n## References\n\n```{bibliography}\n:filter: docname in docnames\n```\n", "meta": {"hexsha": "d71cf4e57cc8a5e979ec46053e05fb7a0b9bb01f", "size": 15569, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/examples/ssto_earth/ssto_earth.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/ssto_earth/ssto_earth.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/ssto_earth/ssto_earth.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": 35.8732718894, "max_line_length": 137, "alphanum_fraction": 0.4905260453, "converted": true, "num_tokens": 2791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.13477592089824647, "lm_q1q2_score": 0.06161102198682653}} {"text": "\n# PHY321: Classical Mechanics 1\n\n \n**Homework 4, due Monday February 10**\n\nDate: **Feb 8, 2021**\n\n### Practicalities about homeworks and projects\n\n1. You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. **Remember to write your name(s)**!\n\n2. Homeworks are available Wednesday/Thursday the week before the deadline. The deadline is at the Friday lecture.\n\n3. How do I(we) hand in? You can hand in the paper and pencil exercises as a hand-written document. For this homework this applies to exercises 1-5. Alternatively, you can hand in everyhting (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical exercise(s) (exercise 6 here) should always be handed in as a jupyter notebook by the deadline at D2L. \n\n### Introduction to homework 4\n\nThis week's sets of classical pen and paper and computational\nexercises deal with simple motion problems and conservation laws; energy, momentum and angular momentum. These conservation laws are central in Physics and understanding them properly lays the foundation for understanding and analyzing more complicated physics problems.\nThe relevant reading background is\n1. chapters 3, 4.1, 4.2 and 4.3 of Taylor (there are many good examples there) and\n\n2. chapters 10-13 of Malthe-Sørenssen.\n\nIn both textbooks there are many nice worked out examples. Malthe-Sørenssen's text contains also several coding examples you may find useful. \n\nThe numerical homework focuses on another motion problem where you can\nuse the code you developed in homework 3, almost entirely. Please take\na look at the posted solution (jupyter-notebook) for homework 3. You\nneed only to change the forces at play. The problem at hand is a\nclassic, the gravitational force acting between the Sun and the\nEarth. Here you will notice also that the standard Euler-integration\nalgorithm is not the best choice and we will introduce the so-called\nEuler-Cromer method and the Velocity-Verlet method. These methods will\ngive much more stable numerical results with only few additions to\nyour code.\n\nThe code you develop here will also be reused when we analyze energy\nconservation in homework set 5. And for those of you doing the honors project, it serves as a starting point for the solar system variant.\n\n### Exercise 1 (10 pt), Conservation laws, Energy and momentum\n\n* 1a (2pt) How do we define a conservative force?\n\nA conservative force is a force whose property is that the total work\ndone in moving an object between two points is independent of the\ntaken path. This means that the work on an object under the influence\nof a conservative force, is independent on the path of the object. It\ndepends only on the spatial degrees of freedom and it is possible to\nassign a numerical value for the potential at any point. It leads to\nconservation of energy. The gravitational force is an example of a\nconservative force.\n\nIf you wish to read more about conservative forces or not, Feyman's lectures from 1963 are quite interesting.\nHe states for example that **All fundamental forces in nature appear to be conservative**.\nThis statement was made while developing his argument that *there are no nonconservative forces*.\nYou may enjoy the link to [Feynman's lecture](http://www.feynmanlectures.caltech.edu/I_14.html).\n\nAn important condition for the final work to be independent of the path is that the **curl** of the force is zero, that\nis\n\n$$\n\\boldsymbol{\\nabla} \\times \\boldsymbol{F}=0\n$$\n\n* 1b (4pt) Use the work-energy theorem to show that energy is conserved with a conservative force.\n\nThe work-energy theorem states that the work done $W$ by a force $\\boldsymbol{F}$ that moves an object from a position $\\boldsymbol{r}_0$ to a new position $\\boldsymbol{r}_1$\n\n$$\nW=\\int_{\\boldsymbol{r}_0}^{\\boldsymbol{r}_1}\\boldsymbol{F}\\boldsymbol{dr}=\\frac{1}{2}mv_1^2-\\frac{1}{2}mv_0^2,\n$$\n\nwhere $v_1^2$ is the velocity squared at a time $t_1$ and $v_0^2$ the corresponding quantity at a time $t_0$.\nThe work done is thus the difference in kinetic energies. We can rewrite the above equation as\n\n$$\n\\frac{1}{2}mv_1^2=\\int_{\\boldsymbol{r}_0}^{\\boldsymbol{r}_1}\\boldsymbol{F}\\boldsymbol{dr}+\\frac{1}{2}mv_0^2,\n$$\n\nthat is the final kinetic energy is equal to the initial kinetic energy plus the work done by the force over a given path from a position $\\boldsymbol{r}_0$ at time $t_0$ to a final position position $\\boldsymbol{r}_1$ at a later time $t_1$.\n\n\n\n* 1c (4pt) Assume that you have only internal two-body forces acting on $N$ objects in an isolated system. The force from object $i$ on object $j$ is $\\boldsymbol{f}_{ij}$. Show that the linear momentum is conserved.\n\nHere we use Newton's third law and assume that our system is only\naffected by so-called internal forces. This means that the force\n$\\boldsymbol{f}_{ij}$ from object $i$ acting on object $j$ is equal to the\nforce acting on object $j$ from object $i$ but with opposite sign,\nthat is $\\boldsymbol{f}_{ij}=-\\boldsymbol{f}_{ji}$.\n\nThe total linear momentum is defined as\n\n$$\n\\boldsymbol{P}=\\sum_{i=1}^N\\boldsymbol{p}_i=\\sum_{i=1}^Nm_i\\boldsymbol{v}_i,\n$$\n\nwhere $i$ runs over all objects, $m_i$ is the mass of object $i$ and $\\boldsymbol{v}_i$ its corresponding velocity.\n\nThe force acting on object $i$ from all the other objects is (lower\ncase letters for individual objects and upper case letters for total\nquantities)\n\n$$\n\\boldsymbol{f}_i=\\sum_{j=1}^N\\boldsymbol{f}_{ji}.\n$$\n\nSumming over all objects the net force is\n\n$$\n\\sum_{i=1}^N\\boldsymbol{f}_i=\\sum_{i=1}^N\\sum_{j=1;j\\ne i}^N\\boldsymbol{f}_{ji}.\n$$\n\nWe are summing freely over all objects with the constraint that $i\\ne j$ (no self-interactions). \nWe can now manipulate the double sum as\n\n$$\n\\sum_{i=1}^N\\sum_{j=1;j\\ne i}^N\\boldsymbol{f}_{ji}=\\sum_{i=1}^N\\sum_{j>i}^N(\\boldsymbol{f}_{ji}+\\boldsymbol{f}_{ij}).\n$$\n\nConvince yourself about this by setting $N=2$ and $N=3$. Nweton's third law says\n$\\boldsymbol{f}_{ij}=-\\boldsymbol{f}_{ji}$, which means we have\n\n$$\n\\sum_{i=1}^N\\sum_{j=1;j\\ne i}^N\\boldsymbol{f}_{ji}=\\sum_{i=1}^N\\sum_{j>i}^N(\\boldsymbol{f}_{ji}-\\boldsymbol{f}_{ji})=0.\n$$\n\nThe total force due to internal degrees of freedom only is thus $0$.\nIf we then use the definition that\n\n$$\n\\sum_{i=1}^N\\boldsymbol{f}_i=\\sum_{i=1}^Nm_i\\frac{d\\boldsymbol{v}_i}{dt}=\\sum_{i=1}^N\\frac{d\\boldsymbol{p}_i}{dt}=\\frac{d \\boldsymbol{P}}{dt}=0,\n$$\n\nwhere we assumed that $m_i$ is independent of time, we see that time derivative of the total momentum is zero.\nWe say then that the linear momentum is a constant of the motion. It is conserved.\n\n\n\n\n\n\n### Exercise 2 (10 pt), Conservation of angular momentum\n\n* 2a (2pt) Define angular momentum and the torque for a single object with external forces only. \n\nThe angular moment $\\boldsymbol{l}_i$ for a given object $i$ is defined as\n\n$$\n\\boldsymbol{l}_i = \\boldsymbol{r}_i \\times \\boldsymbol{p}_i,\n$$\n\nwhere $\\boldsymbol{p}_i=m_i\\boldsymbol{v}_i$. With external forces only defining the acceleration and the mass being time independent, the momentum is the integral over the external force as function of time, that is\n\n$$\n\\boldsymbol{p}_i(t)=\\boldsymbol{p}_i(t_0)+\\int_{t_0}^t \\boldsymbol{f}_i^{\\mathrm{ext}}(t')dt'.\n$$\n\nThe torque for one object is\n\n$$\n\\boldsymbol{\\tau}_i=\\frac{d\\boldsymbol{l}_i}{dt} = \\frac{dt(\\boldsymbol{r}_i \\times \\boldsymbol{p}_i)}{dt}=\\boldsymbol{r}_i \\times \\frac{d\\boldsymbol{p}_i}{dt}=\\boldsymbol{r}_i \\times \\boldsymbol{f}_i,\n$$\n\n* 2b (4pt) Define angular momentum and the torque for a system with $N$ objects/particles with external and internal forces. The force from object $i$ on object $j$ is $\\boldsymbol{F}_{ij}$.\n\nThe total angular momentum $\\boldsymbol{L}$ is defined as\n\n$$\n\\boldsymbol{L}=\\sum_{i=1}^N\\boldsymbol{l}_i = \\sum_{i=1}^N\\boldsymbol{r}_i \\times \\boldsymbol{p}_i.\n$$\n\nand the total torque is (using the expression for one object from 2a)\n\n$$\n\\boldsymbol{\\tau}=\\sum_{i=1}^N\\frac{d\\boldsymbol{l}_i}{dt} = \\sum_{i=1}^N\\boldsymbol{r}_i \\times \\boldsymbol{f}_i.\n$$\n\nThe force acting on one object is $\\boldsymbol{f}_i=\\boldsymbol{f}_i^{\\mathrm{ext}}+\\sum_{j=1}^N\\boldsymbol{f}_{ji}$.\n\n* 2c (4pt) With internal forces only, what is the mathematical form of the forces that allows for angular momentum to be conserved? \n\nUsing the results from 1c, we can rewrite without external forces our torque as\n\n$$\n\\boldsymbol{\\tau}=\\sum_{i=1}^N\\frac{\\boldsymbol{l}_i}{dt} = \\sum_{i=1}^N\\boldsymbol{r}_i \\times \\boldsymbol{f}_i=\\sum_{i=1}^N(\\boldsymbol{r}_i \\times \\sum_{j=1}^N\\boldsymbol{f}_{ji}),\n$$\n\nwhich gives\n\n$$\n\\boldsymbol{\\tau}=\\sum_{i=1}^N\\sum_{j=1;j\\ne i}^N(\\boldsymbol{r}_i \\times \\boldsymbol{f}_{ji}).\n$$\n\nWe can rewrite this as (convince yourself again about this)\n\n$$\n\\boldsymbol{\\tau}=\\sum_{i=1}^N\\sum_{j>i}^N(\\boldsymbol{r}_i \\times \\boldsymbol{f}_{ji}+\\boldsymbol{r}_j \\times \\boldsymbol{f}_{ij}),\n$$\n\nand using Newton's third law we have\n\n$$\n\\boldsymbol{\\tau}=\\sum_{i=1}^N\\sum_{j>i}^N(\\boldsymbol{r}_i -\\boldsymbol{r}_j) \\times \\boldsymbol{f}_{ji}.\n$$\n\nIf the force is proportional to $\\boldsymbol{r}_i -\\boldsymbol{r}_j$ then angular momentum is conserved since the cross-product of a vector with itself is zero. We say thus that angular momentum is a constant of the motion.\n\n### Exsercise 3 (10pt), Example of potential\n\nConsider a particle of mass $m$ moving according to the potential\n\n$$\nV(x,y,z)=A\\exp\\left\\{-\\frac{x^2+z^2}{2a^2}\\right\\}.\n$$\n\n* 3a (2pt) Is energy conserved? If so, why? \n\nIn this exercise $A$ and $a$ are constants. The force is given by the derivative of $V$ with respect to the spatial degrees of freedom and since the potential depends only of these degrees of freedom force is conservative and energy is conserved.\n\n* 3b (4pt) Which of the quantities, $p_x,p_y,p_z$ are conserved?\n\nTaking the derivatives with respect to time shows that only $p_y$ is conserved.\n\n* 3c (4pt) Which of the quantities, $L_x,L_y,L_z$ are conserved?\n\nOnly $L_y$ is conserved. \n\n\n### Exercise 4 (10pt), Angular momentum case\n\nAt $t=0$ we have a single object with position $\\boldsymbol{r}_0=x_0\\boldsymbol{e}_x+y_0\\boldsymbol{e}_y$. We add also a force in the $x$-direction at $t=0$. We assume that the object is at rest at $t=0$.\n\n$$\n\\boldsymbol{F} = F\\boldsymbol{e}_x.\n$$\n\n* 4a (3pt) Find the velocity and momentum at a given time $t$ by integrating over time with the above initial conditions.\n\nThere is no velocity in the $x$- and $y$-directions at $t=0$, thus $\\boldsymbol{v}_0=0$. The force is constant and acting only in the $x$-direction. We have then (dropping vector symbols and setting $t_0=0$)\n\n$$\nv_x(t) = \\int_0^t a(t')dt'=\\int_0^t\\frac{F}{m}dt'=\\frac{F}{m}t.\n$$\n\n* 4b (3pt) Find also the position at a time $t$.\n\nIn the $x$-direction we have then\n\n$$\nx(t) = \\int_0^t v_x(t')dt'=x_0+\\frac{F}{2m}t^2,\n$$\n\nresulting in\n\n$$\n\\boldsymbol{r}(t)=(x_0+\\frac{F}{2m}t^2)\\boldsymbol{e}_x+y_0\\boldsymbol{e}_y.\n$$\n\n* 4c (4pt) Use the position and the momentum to find the angular momentum and the torque. Is angular momentum conserved?\n\nVelocity and position are defined in the $xy$-plane only which means that only angular momentum in the $z$-direction is non-zero. The angular momentum is\n\n$$\n\\boldsymbol{l} = (x(t)v_y(t)-y(t)v_x(t))\\boldsymbol{e}_z=-y_0\\frac{F}{m}t\\boldsymbol{e}_z,\n$$\n\nwhich results in a torque $\\boldsymbol{\\tau}=-y_0\\frac{F}{m}\\boldsymbol{e}_z$, which is not zero. Thus, angular momentum is not conserved.\n\n\n\n### Exercise 5 (10pt), forces and potentials\n\nA particle of mass $m$ has velocity $v=\\alpha/x$, where $x$ is its displacement.\n\n* 5a (3pt) Find the force $F(x)$ responsible for the motion.\n\nHere, since the force is assumed to be conservative (only dependence on $x$), we can use energy conservation.\nAssuming that the total energy at $t=0$ is $E_0$, we have\n\n$$\nE_0=V(x)+\\frac{1}{2}mv^2=V(x)+\\frac{1}{2}m\\frac{\\alpha^2}{x^2}.\n$$\n\nTaking the derivative wrt $x$ we have\n\n$$\n\\frac{dV}{dx}-m\\frac{\\alpha^2}{x^3}=0,\n$$\n\nand since $F(x)=-dV/dx$ we have\n\n$$\nF(x)=-m\\frac{\\alpha^2}{x^3}.\n$$\n\nA particle is thereafter under the influence of a force $F=-kx+kx^3/\\alpha^2$, where $k$ and $\\alpha$ are constants and $k$ is positive.\n\n* 5b (3pt) Determine $V(x)$ and discuss the motion. It can be convenient here to make a sketch/plot of the potential as function of $x$.\n\nWe assume that the potential is zero at say $x=0$. Integrating the force from zero to $x$ gives\n\n$$\nV(x) = \\int_0^x F(x')dx'=\\frac{kx^2}{2}-\\frac{kx^4}{4\\alpha^2}.\n$$\n\nThe following code plots the potential. We have chosen values of $\\alpha=k=1.0$. Feel free to experiment with other values. We plot $V(x)$ for a domain of $x\\in [-2,2]$.\n\n\n```python\n%matplotlib inline\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nx0= -2.0\nxn = 2.1\nDeltax = 0.1\nalpha = 1.0\nk = 1.0\n#set up arrays\nx = np.arange(x0,xn,Deltax)\nn = np.size(x)\nV = np.zeros(n)\nV = 0.5*k*x*x-0.25*k*(x**4)/(alpha*alpha)\nplt.plot(x, V)\nplt.xlabel(\"x\")\nplt.ylabel(\"V\")\nplt.show()\n```\n\nFrom the plot here (with the chosen parameters) \n1. we see that with a given initial velocity we can overcome the potential energy barrier\n\nand leave the potential well for good.\n1. If the initial velocity is smaller (see next exercise) than a certain value, it will remain trapped in the potential well and oscillate back and forth around $x=0$. This is where the potential has its minimum value. \n\n2. If the kinetic energy at $x=0$ equals the maximum potential energy, the object will oscillate back and forth between the minimum potential energy at $x=0$ and the turning points where the kinetic energy turns zero. These are the so-called non-equilibrium points. \n\n* 5c (4pt) What happens when the energy of the particle is $E=(1/4)k\\alpha^2$? Hint: what is the maximum value of the potential energy?\n\nFrom the figure we see that\nthe potential has a minimum at at $x=0$ then rises until $x=\\alpha$ before falling off again. The maximum\npotential, $V(x\\pm \\alpha) = k\\alpha^2/4$. If the energy is higher, the particle cannot be contained in the\nwell. The turning points are thus defined by $x=\\pm \\alpha$. And from the previous plot you can easily see that this is the case ($\\alpha=1$ in the abovementioned Python code). \n\n\n### Exercise 6 (10pt) and 7 (40pt)\n\nThe aim of this exercise (as well as the next) is to study the motion\nof objects under the influence of the gravitational force. We will\nlimit ourselves to the Earth-Sun system. Here we will scale the\nequations and sketch our first algorithm for solving the equations,\nnamely using Euler's method again, as we did in homework 3. This part\ntogether with the numerical part forms also the entry point for the\nsolar system honors project. Furthermore, we will reuse parts of these\nresults when analyzing energy conservation in homework 5.\n\nWe will limit ourselves (in order to test the algorithm) to a\nhypothetical solar system with the Earth only orbiting around the sun.\nThe only force in the problem is gravity. Newton's law of gravitation\nis given by a force $F_G$\n\n$$\nF_G=\\frac{GM_{\\odot}M_{\\mathrm{Earth}}}{r^2},\n$$\n\nwhere $M_{\\odot}$ is the mass of the Sun and $M_{\\mathrm{Earth}}$ is\nthe mass of the Earth. The gravitational constant is $G$ and $r$ is\nthe distance between the Earth and the Sun. The Sun\nhas a mass which is much larger than that of the Earth. We can\ntherefore safely neglect the motion of the Sun in this problem.\n\n\nWe assume that the orbit of the Earth around the Sun \nis co-planar, and we take this to be the $xy$-plane.\nUsing Newton's second law of motion we get the following equations\n\n$$\n\\frac{d^2x}{dt^2}=\\frac{F_{G,x}}{M_{\\mathrm{Earth}}},\n$$\n\nand\n\n$$\n\\frac{d^2y}{dt^2}=\\frac{F_{G,y}}{M_{\\mathrm{Earth}}},\n$$\n\nwhere $F_{G,x}$ and $F_{G,y}$ are the $x$ and $y$ components of the\ngravitational force.\n\nWe will use so-called astronomical units when rewriting our equations.\nUsing astronomical units (AU as abbreviation)it means that one\nastronomical unit of length, known as 1 AU, is the average distance\nbetween the Sun and Earth, that is $1$ AU = $1.5\\times 10^{11}$ m. It\ncan also be convenient to use years instead of seconds since years\nmatch better the time evolution of the solar system. The mass of the\nSun is $M_{\\mathrm{sun}}=M_{\\odot}=2\\times 10^{30}$ kg. The masses of\nall relevant planets and their distances from the sun are listed in\nthe table here in kg and AU.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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
    \n\nIn setting up the equations we limit ourselves to a co-planar\nmotion and use only the $x$ and $y$ coordinates. But you should feel\nfree to extend your equations to three dimensions, it is not very\ndifficult and the data from NASA are all in three dimensions.\n\n[NASA](http://www.nasa.gov/index.html) has an excellent site at .\nFrom there you can extract initial conditions in order to start your differential equation solver.\nAt the above website you need to change from **OBSERVER** to **VECTOR** and then write in the planet you are interested in.\nThe generated data contain the $x$, $y$ and $z$ values as well as their corresponding velocities. The velocities are in units of AU per day.\nAlternatively they can be obtained in terms of km and km/s. \n\nFor the system below involving only the Earth and the Sun, you\ncould just initialize the position with say $x=1$ AU and $y=0$ AU.\n\n\n\nWe assume that mass units can be obtained by using the fact that Earth's orbit is almost circular around the Sun.\n\nFor circular motion we know that the force must obey the following relation\n\n$$\nF_G= \\frac{M_{\\mathrm{Earth}}v^2}{r}=\\frac{GM_{\\odot}M_{\\mathrm{Earth}}}{r^2},\n$$\n\nwhere $v$ is the velocity of Earth. \nThe latter equation can be used to show that\n\n$$\nv^2r=GM_{\\odot}=4\\pi^2\\mathrm{AU}^3/\\mathrm{yr}^2.\n$$\n\n* 6a (5pt) Show how to derive the last equation and use this to scale the differential equations, getting thus rid of the constant $G$ and the two masses. Split the differential equations for the motion in the $x$ and $y$ directions in terms of four coupled differential equations.\n\n* 6b (5pt) Discretize the above differential equations and set up an algorithm for solving these equations using Euler's forward algorithm and the so-called velocity Verlet method [discussed in the lecture notes](https://mhjensen.github.io/Physics321/doc/pub/energyconserv/html/energyconserv.html). Here you can reuse what you did in homework 3, exercises 6 and 7. \n\n### Exercise 7 (40pt), Numerical elements, solving exercise 6 numerically\n\n* 7a (20pt) Write then a program which solves the above differential equations for the Earth-Sun system using Euler's method and the velocity Verlet method. Find out which initial value for the velocity that gives a circular orbit and test the stability of your algorithm as function of different time steps $\\Delta t$. Make a plot of the results you obtain for the position of the Earth (plot the $x$ and $y$ values and/or if you prefer to use three dimensions the $z$-value as well) orbiting the Sun. Discuss eventual differences between the Verlet algorithm and the Euler algorithm. \n\n* 7b (20pt) Consider then a planet which begins at a distance of 1 AU from the sun. Find out by trial and error what the initial velocity must be in order for the planet to escape from the sun. Can you find an exact answer? How does that match your numerical results?\n\n### Answers\n\nWe start with a simpler case first, the Earth-Sun system in two dimensions only. The gravitational force $F_G$ on the earth from the sun is\n\n$$\n\\boldsymbol{F}_G=-\\frac{GM_{\\odot}M_E}{r^3}\\boldsymbol{r},\n$$\n\nwhere $G$ is the gravitational constant,\n\n$$\nM_E=6\\times 10^{24}\\mathrm{Kg},\n$$\n\nthe mass of Earth,\n\n$$\nM_{\\odot}=2\\times 10^{30}\\mathrm{Kg},\n$$\n\nthe mass of the Sun and\n\n$$\nr=1.5\\times 10^{11}\\mathrm{m},\n$$\n\nis the distance between Earth and the Sun. The latter defines what we call an astronomical unit **AU**.\nFrom Newton's second law we have then for the $x$ direction\n\n$$\n\\frac{d^2x}{dt^2}=-\\frac{F_{x}}{M_E},\n$$\n\nand\n\n$$\n\\frac{d^2y}{dt^2}=-\\frac{F_{y}}{M_E},\n$$\n\nfor the $y$ direction.\n\nHere we will use that $x=r\\cos{(\\theta)}$, $y=r\\sin{(\\theta)}$ and\n\n$$\nr = \\sqrt{x^2+y^2}.\n$$\n\nWe can rewrite\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nfor the $y$ direction.\n\n\nWe can rewrite these two equations\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nas four first-order coupled differential equations\n\n$$\n\\frac{dv_x}{dt}=-\\frac{GM_{\\odot}}{r^3}x,\n$$\n\nand\n\n$$\n\\frac{dx}{dt}=v_x,\n$$\n\nand\n\n$$\n\\frac{dv_y}{dt}=-\\frac{GM_{\\odot}}{r^3}y,\n$$\n\nand\n\n$$\n\\frac{dy}{dt}=v_y.\n$$\n\nThe four coupled differential equations\n\n$$\n\\frac{dv_x}{dt}=-\\frac{GM_{\\odot}}{r^3}x,\n$$\n\nand\n\n$$\n\\frac{dx}{dt}=v_x,\n$$\n\nand\n\n$$\n\\frac{dv_y}{dt}=-\\frac{GM_{\\odot}}{r^3}y,\n$$\n\nand\n\n$$\n\\frac{dy}{dt}=v_y,\n$$\n\ncan be turned into dimensionless equations or we can introduce astronomical units with $1$ AU = $1.5\\times 10^{11}$. \n\nUsing the equations from circular motion (with $r =1\\mathrm{AU}$)\n\n$$\n\\frac{M_E v^2}{r} = F = \\frac{GM_{\\odot}M_E}{r^2},\n$$\n\nwe have\n\n$$\nGM_{\\odot}=v^2r,\n$$\n\nand using that the velocity of Earth (assuming circular motion) is\n$v = 2\\pi r/\\mathrm{yr}=2\\pi\\mathrm{AU}/\\mathrm{yr}$, we have\n\n$$\nGM_{\\odot}= v^2r = 4\\pi^2 \\frac{(\\mathrm{AU})^3}{\\mathrm{yr}^2}.\n$$\n\nThe four coupled differential equations can then be discretized using Euler's method as (with step length $h$)\n\n$$\nv_{x,i+1}=v_{x,i}-h\\frac{4\\pi^2}{r_i^3}x_i,\n$$\n\nand\n\n$$\nx_{i+1}=x_i+hv_{x,i},\n$$\n\nand\n\n$$\nv_{y,i+1}=v_{y,i}-h\\frac{4\\pi^2}{r_i^3}y_i,\n$$\n\nand\n\n$$\ny_{i+1}=y_i+hv_{y,i},\n$$\n\nThe code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays.\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nDeltaT = 0.01\n#set up arrays \ntfinal = 10 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using Euler's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using Euler's forward method\n v[i+1] = v[i] + DeltaT*a\n r[i+1] = r[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('x[m]')\nax.set_xlabel('y[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunEuler\")\nplt.show()\n```\n\nWe notice here that Euler's method doesn't give a stable orbit with for example $\\Delta t =0.01$. It\nmeans that we cannot trust Euler's method. Euler's method does not conserve energy. It is an\nexample of an integrator which is not\n[symplectic](https://en.wikipedia.org/wiki/Symplectic_integrator).\n\nHere we present thus two methods, which with simple changes allow us\nto avoid these pitfalls. The simplest possible extension is the\nso-called Euler-Cromer method. The changes we need to make to our\ncode are indeed marginal here. We need simply to replace\n\n\n```python\n r[i+1] = r[i] + DeltaT*v[i]\n```\n\nin the above code with the velocity at the new time $t_{i+1}$\n\n\n```python\n r[i+1] = r[i] + DeltaT*v[i+1]\n```\n\nBy this simple caveat we get stable orbits. Below we derive the\nEuler-Cromer method as well as one of the most utlized algorithms for\nsolving the above type of problems, the so-called Velocity-Verlet\nmethod.\n\n\nLet us repeat Euler's method.\nWe have a differential equation\n\n\n
    \n\n$$\n\\begin{equation}\n y'(t_i)=f(t_i,y_i) \n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nand if we truncate at the first derivative, we have from the Taylor expansion\n\n\n
    \n\n$$\n\\begin{equation}\n y_{i+1}=y(t_i) + (\\Delta t) f(t_i,y_i) + O(\\Delta t^2), \\label{eq:euler} \\tag{2}\n\\end{equation}\n$$\n\nwhich when complemented with $t_{i+1}=t_i+\\Delta t$ forms\nthe algorithm for the well-known Euler method. \nNote that at every step we make an approximation error\nof the order of $O(\\Delta t^2)$, however the total error is the sum over all\nsteps $N=(b-a)/(\\Delta t)$ for $t\\in [a,b]$, yielding thus a global error which goes like\n$NO(\\Delta t^2)\\approx O(\\Delta t)$. \n\nTo make Euler's method more precise we can obviously\ndecrease $\\Delta t$ (increase $N$), but this can lead to loss of numerical precision.\nEuler's method is not recommended for precision calculation,\nalthough it is handy to use in order to get a first\nview on how a solution may look like.\n\nEuler's method is asymmetric in time, since it uses information about the derivative at the beginning\nof the time interval. This means that we evaluate the position at $y_1$ using the velocity\nat $v_0$. A simple variation is to determine $x_{n+1}$ using the velocity at\n$v_{n+1}$, that is (in a slightly more generalized form)\n\n\n
    \n\n$$\n\\begin{equation} \n y_{n+1}=y_{n}+ v_{n+1}+O(\\Delta t^2)\n\\label{_auto2} \\tag{3}\n\\end{equation}\n$$\n\nand\n\n\n
    \n\n$$\n\\begin{equation}\n v_{n+1}=v_{n}+(\\Delta t) a_{n}+O(\\Delta t^2).\n\\label{_auto3} \\tag{4}\n\\end{equation}\n$$\n\nThe acceleration $a_n$ is a function of $a_n(y_n, v_n, t_n)$ and needs to be evaluated\nas well. This is the Euler-Cromer method. It is easy to change the above code and see that with the same \ntime step we get stable results.\n\n\nLet us stay with $x$ (position) and $v$ (velocity) as the quantities we are interested in.\n\nWe have the Taylor expansion for the position given by\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_i+O((\\Delta t)^3).\n$$\n\nThe corresponding expansion for the velocity is\n\n$$\nv_{i+1} = v_i+(\\Delta t)a_i+\\frac{(\\Delta t)^2}{2}v^{(2)}_i+O((\\Delta t)^3).\n$$\n\nVia Newton's second law we have normally an analytical expression for the derivative of the velocity, namely\n\n$$\na_i= \\frac{d^2 x}{dt^2}\\vert_{i}=\\frac{d v}{dt}\\vert_{i}= \\frac{F(x_i,v_i,t_i)}{m}.\n$$\n\nIf we add to this the corresponding expansion for the derivative of the velocity\n\n$$\nv^{(1)}_{i+1} = a_{i+1}= a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2)=a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2),\n$$\n\nand retain only terms up to the second derivative of the velocity since our error goes as $O(h^3)$, we have\n\n$$\n(\\Delta t)v^{(2)}_i\\approx a_{i+1}-a_i.\n$$\n\nWe can then rewrite the Taylor expansion for the velocity as\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left( a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\nOur final equations for the position and the velocity become then\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_{i}+O((\\Delta t)^3),\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left(a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\nNote well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate \nthe position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time\n$t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well. \n\nWe can now easily add the Verlet method to our original code as\n\n\n```python\nDeltaT = 0.01\n#set up arrays \ntfinal = 10\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up forces, air resistance FD, note now that we need the norm of the vecto\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n rabs = sqrt(sum(r[i+1]*r[i+1]))\n anew = -4*(pi**2)*r[i+1]/(rabs**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('y[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunVV\")\nplt.show()\n```\n\nYou can easily generalize the calculation of the forces by defining a function\nwhich takes in as input the various variables. We leave this as a challenge to you.\n\nRunning the above code for various time steps we see that the Velocity-Verlet is fully stable for various time steps.\n\nWe can also play around with different initial conditions in order to find the escape velocity from an orbit around the sun with distance one astronomical unit, 1 AU. The theoretical value for the escape velocity, is given by\n\n$$\nv = \\sqrt{8\\pi^2}{r},\n$$\n\nand with $r=1$ AU, this means that the escape velocity is $2\\pi\\sqrt{2}$ AU/yr. To obtain this we required that the kinetic energy of Earth equals the potential energy given by the gravitational force.\n\nSetting\n\n$$\n\\frac{1}{2}M_{\\mathrm{Earth}}v^2=\\frac{G\\M_{\\odot}}{r},\n$$\n\nand with $G\\M_{\\odot}=4\\pi^2$ we obtain the above relation for the velocity. Setting an initial velocity say equal to $9$ in the above code, yields a planet (Earth) which escapes a stable orbit around the sun, as seen by running the ode here.\n\n\n```python\nDeltaT = 0.01\n#set up arrays \ntfinal = 100\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\n# setting initial velocity larger than escape velocity\nv0 = np.array([0.0,9.0])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up forces, air resistance FD, note now that we need the norm of the vecto\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n rabs = sqrt(sum(r[i+1]*r[i+1]))\n anew = -4*(pi**2)*r[i+1]/(rabs**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('y[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EscapeEarthSunVV\")\nplt.show()\n```\n", "meta": {"hexsha": "baf8a965e603949e6bbf7aba915b5f58984c0b0b", "size": 52818, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw4-checkpoint.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw4-checkpoint.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw4-checkpoint.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 30.0102272727, "max_line_length": 601, "alphanum_fraction": 0.5521602484, "converted": true, "num_tokens": 10429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117322376181564, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.061492777763886036}} {"text": "# Getting Started With Python\n\n## Installation\n\nThere are various ways to install Python. Assuming the reader is not (yet) well versed in programming, I suggest to download the Anaconda distribution, which works for all major operating systems (Mac OS X, Windows, Linux) and provides a fully fledged Python installation including necessary libraries and Jupyter notebooks. \n\n* Go to https://www.anaconda.com/distribution/#download-section\n* Download latest version corresponding to your OS\n* Run .exe/.pkg file. \n - Make sure to set flag \"Add Anaconda to my PATH environment variable\" and \n - \"Register Anaconda as my default Python 3.x\"\n\nBe sure to download the latest Python 3.x version (not 2.x; backward compability is not always given!). \n\nThe installation should not cause any problems. If you wisch a step-by-step guide (incl. some further insights) see [Cyrille Rossants excellent notebook](http://nbviewer.jupyter.org/github/ipython-books/minibook-2nd-code/blob/master/chapter1/12-installation.ipynb) or simply the [Jupyter Documentation](https://jupyter.org/documentation) on the topic.\n\n## IPyton / Jupyter Notebooks\n\nWhat you see here is a so called Jupyter notebook. It makes it possible to interactively combine code with output (results, graphics), markdown text and LaTeX (for mathematical expressions). All codes discussed in this course will be provided through such notebooks and you soon will understand and appreciate the functionality they provide.\n\n* The basic markdown commands are well summarized [here](http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html). \n* LaTeX is a typesetting language with extensive capabilities to typeset math. For a basic introductin to math in LaTeX see sections 3.3 - 3.4 (p. 22 - 33) of *More Math into LaTeX* by Grätzer (2007), [available as pdf here](http://static.latexstudio.net/wp-content/uploads/2014/09/math.into_.Latex_.4ed.pdf)\n\n\nIf you are keen on learning more about IPython/Jupyter, consider [this notebook](http://nbviewer.jupyter.org/github/ipython-books/minibook-2nd-code/blob/master/chapter1/13-nbui.ipynb) - a well written introduction by Cyrille Rossant - or watch this video.\n\n\n```python\nfrom IPython.display import YouTubeVideo\nfrom datetime import timedelta\n\nYouTubeVideo('jZ952vChhuI')\n```\n\n\n\n\n\n\n\n\n\n\n## Data Types in Python\n\n### Building Blocks\n\nTo analyze data in Python, data has to be stored as some kind of data type. These data types form the structure of the data and make data easily accessible. Python's basic building blocks are:\n* Numbers (integer, floating point, and complex)\n* Booleans (true/false)\n* Strings\n* Lists\n* Dictionaries\n* Tuples\n\nWe will discuss the first four data types above as these are relevant for us.\n\nPython is a dynamically typed language, meaning that - unlike in static languages such as VBA, C, Java etc. - you do not explicitly need to assign a data type to a variable. Python will do that for you. A few examples will explain this best: \n\n\n```python\na = 42 # In VBA you would first have to define data type, only then the value: Dim a as integer; a = 42\nb = 10.3 # VBA: Dim b as Double; b = 10.3\nc = 'hello' # VBA: Dim c as String; c = \"hello\"\nd = True # VBA: Dim d as Boolean; d = True\n\nprint('a: ', (a))\nprint('b: ', type(b))\nprint('c: ', type(c))\nprint('d: ', type(d))\n```\n\n a: 42\n b: \n c: \n d: \n\n\n### Running Code in Jupyter\n\nHow did I execute this code section? If I only want to run a code cell, I select the cell and hit `ctrl + enter`. If you wish to run the entire notebook, go to Kernel (dropdown menu) and select \"Restart & Run All\". There are lots of shortcuts that let you handle a Jupyter notebook just from the keyboard. Press `H` on your keyboard (or go to Help/Keyboard Shortcuts) to see all of the shortcuts. \n\n### Simple Arithmetics\nSimple arithmetic operations are straight forward:\n\n\n```python\na = 2 + 4 - 8 # Addition & Subtraction\nb = 6 * 7 / 3 - 2 # Multiplication & Division\nc = 2**(1/2) # Exponents & Square root\nd = 10 % 3 # Modulus\ne = 10 // 3 # Floor division\n\nprint(' a =', a, '\\n',\n 'b =', b, '\\n',\n 'c =', c, '\\n',\n 'd =', d, '\\n',\n 'e =', e)\n```\n\n a = -2 \n b = 12.0 \n c = 1.4142135623730951 \n d = 1 \n e = 3\n\n\nWe can even use arithmetic operators to concatenate strings:\n\n\n```python\na = 'Hello'\nb = 'World!'\nprint(a + ' ' + b)\n\nprint(a * 3)\n```\n\n Hello World!\n HelloHelloHello\n\n\n### Lists\nNow let's look at lists. Lists are capable of combining multiple data types.\n\n\n```python\ne = ['Calynn', 'Dillon', '10.3', c, d]\nprint('e: ', type(e))\nprint([type(item) for item in e])\n```\n\n e: \n [, , , , ]\n\n\nNote that the third element in list `e` is set in quotation marks and thus Python interprets this as string.\n\n## NumPy Arrays\n\n### NumPy Arrays from Lists\n\nFor as useful list appear, its flexibility come at a high cost. Because each element contains not only the value itself but also information about the data type, storing data in list consumes a lot of memory. For this reason the Python community introduced NumPy (short for Numerical Python). Among other things, this package provides **fixed-type arrays** which are more efficient to store and operate on dense data than simple lists. \n\nFixed-type arrays are dense arrays of uniform type. Uniform here means that all entries of the array have the same data type, e.g. all are floating point numbers. We start by importing the NumPy package (following general convention we import this package under the alias name `np`) and create some simple NumPy arrays form Python lists.\n\n\n```python\nimport numpy as np\n\n# Integer array\nnp.array([3, 18, 12])\n```\n\n\n\n\n array([ 3, 18, 12])\n\n\n\n\n```python\n# Floating point array\nnp.array([3., 18, 12])\n```\n\n\n\n\n array([ 3., 18., 12.])\n\n\n\nSimilarly, we can explicitly set the data type:\n\n\n```python\nnp.array([3, 18, 12], dtype='float32') \n```\n\n\n\n\n array([ 3., 18., 12.], dtype=float32)\n\n\n\n\n```python\n# Multidimensional arrays\nnp.array([range(i, i + 3) for i in [1, 2, 3]])\n```\n\n\n\n\n array([[1, 2, 3],\n [2, 3, 4],\n [3, 4, 5]])\n\n\n\nWe've seen above that we can define the data type for NumPy arrays. A list of available data types can be found in the [NumPy documentation](https://docs.scipy.org/doc/numpy/user/basics.types.html).\n\n\n### NumPy Arrays from Scratch\nSometimes it is helpful to create arrays from scratch. Here are some examples:\n\n\n```python\n# Integer array with 8 zeros \nnp.zeros(shape=8, dtype='int')\n```\n\n\n\n\n array([0, 0, 0, 0, 0, 0, 0, 0])\n\n\n\n\n```python\n# 2x3 floating-point array filled with 1s\nnp.ones((2, 3), 'float32')\n```\n\n\n\n\n array([[1., 1., 1.],\n [1., 1., 1.]], dtype=float32)\n\n\n\nNote that I do not need to use `np.ones(shape=(2, 3), dtype='float32')` to define the shape. It's ok to go with the short version as long as the order is correct, Python will understand. However, going with the explicit version helps to make your code more readable and I encourage students to follow this advice.\n\nEach predefined function is documented in a help page. One can search for it by calling `?np.ones`, `np.ones?` or `help(np.ones)`. If it is not clear how the function is precisely called, it is best to use * (wildcard character) - as in `np.*ne*?`. This will list all functions in the NumPy library which contain 'ne' in their name. In our example `np.ones?` shows the following details:\n\n\n```python\n# np.ones?\n```\n\nThe function description also shows examples of how the function can be used. Often this is very helpful, but for the sake of brevity, these are omitted here.\n\nIn the function description we see that the order of arguments is `shape, dtype, order`. If our inputs are in this order, one does not need to specify the argument. Furthermore, we see that `dtype` and `order` is optional, meaning that if left undefined, Python will simply use the default argument. This makes for a very short code. However, going with the longer explicit version helps to make your code more readable and I encourage students to follow this advice.\n\n\n```python\n# 3x2 array filled with 2.71\nnp.full(shape=(3, 2), fill_value=2.71)\n```\n\n\n\n\n array([[2.71, 2.71],\n [2.71, 2.71],\n [2.71, 2.71]])\n\n\n\n\n```python\n# 3x3 boolean array filled with 'True'\nnp.full((2, 2), 1, bool)\n```\n\n\n\n\n array([[ True, True],\n [ True, True]])\n\n\n\n\n```python\n# Array filled with linear sequence\nnp.arange(start = 0, stop = 1, step = 0.1) # or simply np.arrange(0, 1, 0.1)\n```\n\n\n\n\n array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])\n\n\n\n\n```python\n# Array of evenly spaced values\nnp.linspace(start = 0, stop = 1, num = 4)\n```\n\n\n\n\n array([0. , 0.33333333, 0.66666667, 1. ])\n\n\n\nArrays with random variables are easily created. Below three examples. See the [numpy.random documentation page](https://docs.scipy.org/doc/numpy/reference/routines.random.html) for details on how to generate other random variable-arrays.\n\n\n```python\n# 4x4 array of uniformly distributed random variables\nnp.random.random((4, 4))\n```\n\n\n\n\n array([[0.95282824, 0.65194764, 0.18336745, 0.79707386],\n [0.90011522, 0.09318048, 0.23252546, 0.27295939],\n [0.05777291, 0.22659345, 0.25981756, 0.03744564],\n [0.2129678 , 0.46855791, 0.40119633, 0.53802224]])\n\n\n\n\n```python\n# 3x3 array of normally distributed random variables (with mean = 4, sd = 6)\nnp.random.normal(loc = 4, scale = 6, size = (3, 3))\n```\n\n\n\n\n array([[ 9.267651 , 7.39315744, 5.39772066],\n [ 4.83828668, -2.72195724, 5.76856645],\n [-3.51746614, 0.29227648, -4.76363532]])\n\n\n\n\n```python\n# 3x3 array of random integers in interval [0, 15)\nnp.random.randint(low = 0, high = 15, size = (3, 3))\n```\n\n\n\n\n array([[12, 3, 10],\n [ 9, 7, 14],\n [13, 3, 6]])\n\n\n\n\n```python\n# 4x4 identity matrix\nnp.eye(4)\n```\n\n\n\n\n array([[1., 0., 0., 0.],\n [0., 1., 0., 0.],\n [0., 0., 1., 0.],\n [0., 0., 0., 1.]])\n\n\n\n### NumPy Array Attributes\nEach NumPy array has certain attributes.\n\nHere are some attributes we can call:\n\n| Attribute | Description |\n|-----------|------------------------|\n| `ndim` | No. of dimensions |\n| `shape` | Size of each dimension |\n| `size` | Total size of array |\n| `dtype` | Data type of array |\n| `itemsize` | Size (in bytes) |\n| `nbytes` | Total size (in bytes) |\n\nTo show how one can access them we'll define three arrays.\n\n\n```python\nnp.random.seed(1234) # Set seed for reproducibility\n\nx = np.random.randint(10, size = 6) # 1-dimensional array (vector)\ny = np.random.randint(10, size = (3, 4)) # 2-dimensional array (matrix)\nz = np.random.randint(10, size = (3, 4, 5)) # 3-dimensional array\n```\n\nAnd here's how we call for these properties:\n\n\n```python\nprint(' ', x, '\\n\\n', y, '\\n\\n', z)\n```\n\n [3 6 5 4 8 9] \n \n [[1 7 9 6]\n [8 0 5 0]\n [9 6 2 0]] \n \n [[[5 2 6 3 7]\n [0 9 0 3 2]\n [3 1 3 1 3]\n [7 1 7 4 0]]\n \n [[5 1 5 9 9]\n [4 0 9 8 8]\n [6 8 6 3 1]\n [2 5 2 5 6]]\n \n [[7 4 3 5 6]\n [4 6 2 4 2]\n [7 9 7 7 2]\n [9 7 4 9 0]]]\n\n\n\n```python\nprint('ndim: ', z.ndim)\nprint('shape: ', z.shape)\nprint('size: ', z.size)\nprint('data type: ', z.dtype)\nprint('itemsize: ', z.itemsize)\nprint('nbytes: ', z.nbytes)\n```\n\n ndim: 3\n shape: (3, 4, 5)\n size: 60\n data type: int32\n itemsize: 4\n nbytes: 240\n\n\n### Index: How to Access Elements\nWhat might be a bit counterintuitive at the beginning is that **Python's indexing starts at 0**. Other than that, accessing the $i$'th element (starting at 0) of a list or a array is straight forward. \n\n\n```python\nprint(e, '\\n') # List from above\nprint(x, '\\n') # One dimensional np array from above\nprint(y, '\\n') # Two dimensional np array from above\n```\n\n ['Calynn', 'Dillon', '10.3', 1.4142135623730951, 1] \n \n [3 6 5 4 8 9] \n \n [[1 7 9 6]\n [8 0 5 0]\n [9 6 2 0]] \n \n\n\n\n```python\ne[2]\n```\n\n\n\n\n '10.3'\n\n\n\n\n```python\ne[2] * 2\n```\n\n\n\n\n '10.310.3'\n\n\n\n\n```python\nx[5]\n```\n\n\n\n\n 9\n\n\n\n\n```python\ny[2, 0] # Note again that [m, n] starts counting for both rows (m) as well as columns (n) from 0\n```\n\n\n\n\n 9\n\n\n\nTo access the end of an array, you can also use negative indices:\n\n\n```python\ne[-1]\n```\n\n\n\n\n 1\n\n\n\n\n```python\ny[-2, 2]\n```\n\n\n\n\n 5\n\n\n\nArrays are also possible as inputs:\n\n\n```python\nind = [3, 5, -4]\nx[ind]\n```\n\n\n\n\n array([4, 9, 5])\n\n\n\n\n```python\nx = np.arange(12).reshape((3, 4))\nprint(x)\nrow = np.array([1, 2])\ncol = np.array([0, 3])\nx[row, col]\n```\n\n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\n\n\n\n\n array([ 4, 11])\n\n\n\nKnowing the index we can also replace elements of an array:\n\n\n```python\nx[0] = 99\nx\n```\n\n\n\n\n array([[99, 99, 99, 99],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n\n\n\n**IMPORTANT NOTE: **\n\n**NumPy arrays have a fixed type. This means that e.g. if you insert a floating-point value to an integer array, the value will be truncated!**\n\n\n\n```python\nx[0] = 3.14159; x\n```\n\n\n\n\n array([[ 3, 3, 3, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n\n\n\n### Array Slicing\nWe can also use square brackets to access a subset of the data. The syntax is:\n\n`x[start:stop:step]`\n\nThe default values are: `start=0`, `stop='size of dimension'`, `step=1` \n\n\n```python\nx = np.arange(10)\nx\n```\n\n\n\n\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n\n\n\n```python\nx[:3] # First three elements\n```\n\n\n\n\n array([0, 1, 2])\n\n\n\n\n```python\nx[7:] # Elements AFTER 7th element\n```\n\n\n\n\n array([7, 8, 9])\n\n\n\n\n```python\nx[4:8] # Element 5, 6, 7 and 8\n```\n\n\n\n\n array([4, 5, 6, 7])\n\n\n\n\n```python\nx[::2] # Even elements\n```\n\n\n\n\n array([0, 2, 4, 6, 8])\n\n\n\n\n```python\nx[1::2] # Odd elements\n```\n\n\n\n\n array([1, 3, 5, 7, 9])\n\n\n\n\n```python\nx[::-1] # All elements reversed\n```\n\n\n\n\n array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])\n\n\n\n\n```python\nx[::-2] # Odd elements reversed\n```\n\n\n\n\n array([9, 7, 5, 3, 1])\n\n\n\nArray slicing works the same for multidimensional arrays.\n\n\n```python\ny # from above\n```\n\n\n\n\n array([[1, 7, 9, 6],\n [8, 0, 5, 0],\n [9, 6, 2, 0]])\n\n\n\n\n```python\ny[:2, :3] # Rows 0 and 1, columns 0, 1, 2\n```\n\n\n\n\n array([[1, 7, 9],\n [8, 0, 5]])\n\n\n\n\n```python\ny[:, 2] # Third column\n```\n\n\n\n\n array([9, 5, 2])\n\n\n\n\n```python\ny[0, :] # First row\n```\n\n\n\n\n array([1, 7, 9, 6])\n\n\n\n**IMPORTANT NOTE:**\n\n**When slicing and assigning part of an existing array to a new variable, the new variable will only hold a \"view\" but not a copy. This means, that if you change a value in the new array, the original array will also be changed. The idea behind this is to save memory. But fear not: with the \".copy()\" method, you still can get a true copy.**\n\nHere a few corresponding examples for better understanding:\n\n\n```python\nySub = y[:2, :2]\nprint(ySub)\n```\n\n [[1 7]\n [8 0]]\n\n\n\n```python\nySub[0, 0] = 99\nprint(ySub, '\\n')\nprint(y)\n```\n\n [[99 7]\n [ 8 0]] \n \n [[99 7 9 6]\n [ 8 0 5 0]\n [ 9 6 2 0]]\n\n\n\n```python\nySubCopy = y[:2, :2].copy()\nySubCopy[0, 0] = 33\nprint(ySubCopy, '\\n')\nprint(y)\n```\n\n [[33 7]\n [ 8 0]] \n \n [[99 7 9 6]\n [ 8 0 5 0]\n [ 9 6 2 0]]\n\n\n### Concatenating, Stacking and Splitting\nOften it is useful to combine multiple arrays into one or to split a single array into multiple arrays. To accomplish this, we can use NumPy's `concatenate` and `vstack`/`hstack` function.\n\n\n```python\nx = np.array([1, 2, 3])\ny = np.array([11, 12, 13])\nz = np.array([21, 22, 23])\nnp.concatenate([x, y, z])\n```\n\n\n\n\n array([ 1, 2, 3, 11, 12, 13, 21, 22, 23])\n\n\n\n\n```python\n# Stack two vectors horizontally\nnp.hstack([x, y])\n```\n\n\n\n\n array([ 1, 2, 3, 11, 12, 13])\n\n\n\n\n```python\n# Stack two vectors vertically\nnp.vstack([x, y])\n```\n\n\n\n\n array([[ 1, 2, 3],\n [11, 12, 13]])\n\n\n\n\n```python\n# Stack matrix with column vector\nm = np.arange(0, 9, 1).reshape((3, 3))\nnp.vstack([m, z])\n```\n\n\n\n\n array([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n [21, 22, 23]])\n\n\n\n\n```python\n# Stack matrix with row vector\nnp.hstack([m, z.reshape(3, 1)])\n```\n\n\n\n\n array([[ 0, 1, 2, 21],\n [ 3, 4, 5, 22],\n [ 6, 7, 8, 23]])\n\n\n\nThe opposite of concatenating is splitting. Numpy has `np.split`, `np.hsplit` and `np.vsplit` functions. Each of these takes a list of indices, giving the split points, as input.\n\n\n```python\nx = np.arange(8.0)\na, b, c = np.split(x, [3, 5])\nprint(a, b, c)\n```\n\n [0. 1. 2.] [3. 4.] [5. 6. 7.]\n\n\n\n```python\nx = np.arange(16).reshape(4, 4)\nupper, lower = np.vsplit(x, [3])\nprint(upper, '\\n\\n', lower)\n```\n\n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]] \n \n [[12 13 14 15]]\n\n\n\n```python\nleft, right = np.hsplit(x, [2])\nprint(left, '\\n\\n', right)\n```\n\n [[ 0 1]\n [ 4 5]\n [ 8 9]\n [12 13]] \n \n [[ 2 3]\n [ 6 7]\n [10 11]\n [14 15]]\n\n\n## Conditions\n\n### Boolean Operators\n\nBoolean operators check an input and return either `True` (equals 1 as value) or `False` (equals 0). This is often very helpful if one wants to check for conditions or sort out part of a data set which meet a certain condition. Here are the common comparison operators:\n\n| **Operator** | **Description** |\n|:------------:|----------------------------|\n| == | equal ($=$) |\n| != | not equal ($\\neq$) |\n| < | less than ($<$) |\n| <= | less or equal ($\\leq$) |\n| > | greater ($>$) |\n| >= | greater or equal ($\\geq$) |\n| & | Mathematical AND ($\\land$) |\n| | | Mathematical OR ($\\lor$) |\n| `in` | element of ($\\in$) |\n\nThe following sections give a glimpse of how these operators can be used.\n\n\n```python\nx = np.arange(start=0, stop=8, step=1)\nprint(x)\nprint(x == 2)\nprint(x != 3)\nprint((x < 2) | (x > 6))\n```\n\n [0 1 2 3 4 5 6 7]\n [False False True False False False False False]\n [ True True True False True True True True]\n [ True True False False False False False True]\n\n\n\n```python\n# Notice the difference\nprint(x[x <= 4])\nprint(x <= 4)\n```\n\n [0 1 2 3 4]\n [ True True True True True False False False]\n\n\n#### If ... else statements\n\nThese statements check a given condition and depending on the result (`True`, `False`) execute a subsequent code. As usual, an example will do. Notice that indentation is necessary for Python to correctly compile the code. \n\n\n```python\nx = 3\n\nif x%2 == 0:\n print(x, 'is an even number')\nelse:\n print(x, 'is an odd number')\n \n```\n\n 3 is an odd number\n\n\nIt is also possible to have more than one condition as the next example shows.\n\n\n```python\nx = 20\n\nif x > 0:\n print(x, 'is positive')\nelif x < 0:\n print(x, 'is negative')\nelse:\n print(x, 'is neither strictly positive nor strictly negative')\n```\n\n 20 is positive\n\n\nCombining these two statements would make for a nested if ... else statement.\n\n\n```python\nx = -3\nif x > 0:\n if (x%2) == 0:\n print(x, 'is positive and even')\n else:\n print(x, 'is positive and odd')\nelif x < 0:\n if (x%2) == 0:\n print(x, 'is negative and even')\n else:\n print(x, 'is negative and odd')\nelse:\n print(x, 'is 0')\n```\n\n -3 is negative and odd\n\n\n### Loops\n\n#### \"For\" Loops\n\n\"For\" loops iterate over a given sequence. They are very easy to implement as the following example shows. We start with an example and give some explanations afterwards. \n\nFor our example, let's assume you ought to sum up the integer values of a sequence from 10 to 1 with a loop. There are obviously more efficient ways of doing this but this serves well as an introductory example. From primary school we know the result is easily calculated as\n\n$$\n\\begin{equation}\n \\sum_{i=1}^n x_i = \\dfrac{n (n+1)}{2} \\qquad -> \\qquad \\dfrac{10 \\cdot 11}{2} = 55\n\\end{equation}\n$$\n\n\n```python\nseq = np.arange(start=10, stop=0, step=-1)\nseqSum = 0\nfor value in seq:\n seqSum = seqSum + value\n\nseqSum\n```\n\n\n\n\n 55\n\n\n\nA few imprtant notes:\n* Indentation is not just here for better readability of the code but it is actually necessary for Python to correctly interpret the code.\n* Though it is not necessary, we initiate `seqSum = 0` here. Otherwise, if we run the code repeatedly we add to the previous total!\n* `value` takes on every value in array `seq`. In the first loop `value=10`, second loop `value=9`, etc. \n\nLoops can be nested, too. Here's an example.\n\n\n```python\nseq = seq.reshape(2, 5)\nseqSum = 0\nrow, col = seq.shape\n\nfor rowIndex in range(0, row):\n for colIndex in range(0, col):\n seqSum = seqSum + seq[rowIndex, colIndex]\n \nseqSum\n```\n\n\n\n\n 55\n\n\n\n#### \"While\" Loops\n\n\"While\" loops execute as long as a certain boolean condition is met. Picking up the above example we can formulate the following loop:\n\n\n```python\nseqSum = 0\ni = 10\nwhile i >= 1:\n seqSum = seqSum + i\n i = i - 1 # Also: i -= 1\n \nprint(seqSum)\n```\n\n 55\n\n\n### Functions\n\nFunctions come into play when either a task needs to be performed more than once or when it helps to reduce the complexity of a code. \n\nFollowing up on our play examples from above, let us assume we are tasked to write a function which sums up all even and all odd integers of a vector. \n\n\n```python\ndef sumOddEven(vector):\n \"\"\"Calculates sum of odd and even numbers in array.\n \n Args:\n vector: NumPy array of length n\n \n Returns:\n odd: Sum of odd numbers\n even: Sum of even numbers\n \"\"\"\n \n # Initiate values\n odd = 0\n even = 0\n \n # Loop through values of array; check for each\n # value whether it is odd or even and add to \n # previous total.\n for value in vector:\n if (value % 2) == 0:\n even = even + value\n else:\n odd = odd + value\n \n return odd, even\n\n# Initiate array [1, 2, ..., 99, 100]\nseq = np.arange(1, 101, 1)\n\n# Apply function and print results\nodd, even = sumOddEven(seq)\nprint('Odd: ', odd, ', ', 'Even: ', even) \n```\n\n Odd: 2500 , Even: 2550\n\n\n## Commenting\n\nAbove code snippet not only shows how functions are set up but also displays the importance of comments. Comments are preceeded by a hash sign (#), such that the interpreter will not parse what follows the hash. When programming, you should always comment your code to notate your work. This details your steps/thoughts/ideas not only for other developers but also for you when you pick up your code some time after writing it. Good programmers make heavy use of commenting and I strongly encourage the reader to follow this standard. \n\n## Slowness of Loops\n\nIt is at this point important to note that loops should only be used as a last resort. Below we show why. The first code runs our previously defined function. The second code uses NumPy's built-in function. \n\n\n```python\n%%timeit\nseq = np.arange(1,10001, 1)\nsumOddEven(seq)\n```\n\n 7.66 ms ± 728 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n\n\n```python\n%%timeit\nseq[(seq % 2) == 0].sum()\nseq[(seq % 2) == 1].sum()\n```\n\n 13.8 µs ± 356 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\nAbove timing results show what was hinted before: In 9'999 out of a 10'000 cases it is significantly faster using already built in functions compared to loops. The simple reason is that modules such as NumPy or Pandas use (at their core) optimized compile code to calculate the results and this is most certainly faster than a loop. \n\nSo in summary: Above examples helped introduce if statements, loops and functions. In real life, however, you should check if Python does not already offer a built-in function for your task. If yes, make sure to use it.\n\n## Broadcasting\n\n### Computations on Arrays\n\nIn closing this chapter we briefly introduce NumPy's broadcasting functionality. Rules for matrix arithmetic apply to NumPy arrays as one would expect and it is left to the reader to explore it. Broadcasting, however, goes one step further in that it allows for element-by-element operations on arrays (and matrices) of different dimensions - which under normal rules would not be compatible. An example shows this best.\n\n\n```python\nM = np.ones(shape=(3, 3))\nv = np.array([1, 2, 3])\nM + v\n```\n\n\n\n\n array([[2., 3., 4.],\n [2., 3., 4.],\n [2., 3., 4.]])\n\n\n\n\n```python\n# Notice the difference\nvecAdd = v + v\nbroadAdd = v.reshape((3, 1)) + v\n\nprint(vecAdd, '\\n')\nprint(broadAdd)\n```\n\n [2 4 6] \n \n [[2 3 4]\n [3 4 5]\n [4 5 6]]\n\n\n## Further Resources\n\nThe following ressources, which were consulted to write this notebook, are recommended to better acquaint yourself with Python and NumPy:\n\n* Vanderplas, Jake, 2016, *Python Data Science Handbook* (O'Reilly Media, Sebastopol, CA).\n* Sheppard, Kevin, 2017, Introduction to Python for Econometrics, Statistics and Data Analysis from Website https://www.kevinsheppard.com/images/b/b3/Python_introduction-2016.pdf, 07/07/2017.\n* Paarsch, Harry J., and Golyaev, Konstantin, 2016, *A Gentle Introduction to Effective Computing in Quantitative Research: What Every Research Assistant Should Know*, MIT Press, Cambridge, MA.\n", "meta": {"hexsha": "a4788bf42f5595f57b628f8eef7dd52ebbe4b9fc", "size": 77426, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0101_GettingStartedWithPython.ipynb", "max_stars_repo_name": "bMzi/ML_in_Finance", "max_stars_repo_head_hexsha": "9b92e9bdf371d22b279d76556364f4645b080803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-02-16T10:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T13:56:57.000Z", "max_issues_repo_path": "0101_GettingStartedWithPython.ipynb", "max_issues_repo_name": "bMzi/ML_in_Finance", "max_issues_repo_head_hexsha": "9b92e9bdf371d22b279d76556364f4645b080803", "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": "0101_GettingStartedWithPython.ipynb", "max_forks_repo_name": "bMzi/ML_in_Finance", "max_forks_repo_head_hexsha": "9b92e9bdf371d22b279d76556364f4645b080803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T08:19:46.000Z", "avg_line_length": 37.0636668262, "max_line_length": 27157, "alphanum_fraction": 0.6589130266, "converted": true, "num_tokens": 7868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.171061193791558, "lm_q1q2_score": 0.061473257329621216}} {"text": "```python\nfrom IPython.display import HTML\n\nHTML('''\n
    ''')\n```\n\n\n\n\n\n
    \n\n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n\n\n''')\n```\n\n\n\n\n\n\n\n\n\n\n\n# Benchmark Problem 4: Elastic Precipitate\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''{% include jupyter_benchmark_table.html num=\"[4]\" revision=1 %}''')\n```\n\n\n\n\n{% include jupyter_benchmark_table.html num=\"[4]\" revision=1 %}\n\n\n\nSee the journal publication entitled [\"Phase Field Benchmark Problems for Dendritic Growth and Linear Elasticity\"][paper] for more details about the benchmark problems. Furthermore, read [the extended essay][benchmarks] for a discussion about the need for benchmark problems.\n\n[benchmarks]: ../\n[paper]: https://doi.org/10.1016/j.commatsci.2018.03.015\n\n## Overview\n\nPrecipitates are a key microstructural feature impacting the strength of alloys [[1][chawla1999mechanical]], and they are often elastically stressed, which affects their shape and their microstructure evolution during service. Elasticity has long been incorporated into phase field models: indeed, Cahn's seminal paper on spinodal decomposition [[2][cahn1961spinodal]] incorporates elastic strains due to composition fluctuations. Eshelby presents an analytical solution for the elastic field of a single coherent, elastically stressed precipitate in an infinite matrix [[3][eshelby1957determination]], but the generalized problem of multiple interacting precipitates in a matrix with arbitrary crystal structure, lattice parameter misfit and elastic stiffnesses can only be solved numerically. Sharp-interface approaches provide insight into equilibrium elastic shapes and coarsening under the influence of elastic stress [[4][voorhees1992morphological], [5][thompson1994equilibrium], [6][su1996dynamicsI], [7][su1996dynamicsII], [8][akaiwa2001large]], but these approaches have difficulty simulating precipitate splitting or merging. Early phase field formulations studying elastically stressed precipitates demonstrate the power of the method (e.g., Refs. [[9][wang1993shape], [10][wang1994effect], [11][wang1995shape]]), and present-day studies have expanded to 3D simulations (e.g., Refs. [[12][goerler2017topological], [13][radhakrishnan2016phase], [14][shi2015microstructure], [15][cottura2015role]]) and formulations that include plasticity (e.g., Refs. [[16][cottura2016coupling], [17][ammar2014modelling], [18][guo2008elastoplastic]]).\n\n[chawla1999mechanical]: https://dx.doi.org/10.1016/S1369-7021(09)70086-0\n[cahn1961spinodal]: https://dx.doi.org/10.1002/9781118788295.ch11\n[eshelby1957determination]: https://dx.doi.org/10.1098/rspa.1957.0133\n[voorhees1992morphological]: https://dx.doi.org/10.1016/0956-7151(92)90462-N\n[thompson1994equilibrium]: https://dx.doi.org/10.1016/0956-7151(94)90036-1\n[su1996dynamicsI]: https://dx.doi.org/10.1016/1359-6454(95)00284-7\n[su1996dynamicsII]: https://dx.doi.org/10.1016/1359-6454(95)00285-5\n[akaiwa2001large]: https://dx.doi.org/10.1006/jcph.2001.6842 \n[wang1994effect]: https://dx.doi.org/10.1016/0956-716X(94)90130-9\n[wang1995shape]: https://dx.doi.org/10.1111/j.1151-2916.1993.tb06605.x\n[goerler2017topological]: https://dx.doi.org/10.1016/j.actamat.2016.10.059\n[radhakrishnan2016phase]: https://dx.doi.org/10.1007/s11661-016-3746-6\n[shi2015microstructure]: https://dx.doi.org/10.1016/j.actamat.2015.04.050\n[cottura2015role]: https://dx.doi.org/10.1016/j.actamat.2015.04.034\n[cottura2016coupling]: https://dx.doi.org/10.1016/j.jmps.2016.05.016\n[ammar2014modelling]: https://dx.doi.org/10.1007/s11012-014-0011-1\n[guo2008elastoplastic]: https://dx.doi.org/10.1016/j.jnucmat.2008.05.008\n\n\n## Model Formulation\n\nIn this formulation, one phenomenological order parameter, $\\eta$, is evolved, which has a value of 0 in the matrix and a value of 1 in the precipitate for an unstressed system with planar interfaces. This choice makes interpolation of materials properties between phases straightforward. The free energy of the system, $\\mathcal{F}$, includes contributions from interfacial and elastic energy and is expressed as \n\n\\begin{equation}\n\\mathcal{F}=\\int_{V}\\left(f_{\\text{bulk}}\\left(\\eta\\right) + \\frac{\\kappa}{2}|\\nabla \\eta|^{2} + f_{\\text{el}}\\left(\\eta\\right) \\right)dV,\n\\end{equation}\n\nwhere $f_{\\text{bulk}}$ is the bulk free energy density, $\\kappa$ is the gradient energy coefficient, and $f_{\\text{el}}$ is the local elastic free energy density. The $f_{\\text{bulk}}$ term is a symmetric double-well with minima of zero, such that its contribution is only to the interfacial energy. As discussed in Ref. [[1][jokisaari2017superalloy]], we choose $f_{\\text{bulk}}$ to have a 10th-order polynomial form,\n\n\\begin{equation}\nf_{\\text{bulk}}=w\\sum_{j=0}^{10}a_j\\eta^j,\n\\end{equation}\n\nwhich makes the energy wells of the matrix and precipitate phases deep and narrow. This prevents the actual value of $\\eta$ in each phase from shifting significantly from its equilibrium value due to the presence of a curved interface or elastic strain. The height of the energy barrier is controlled by $w$. The $f_{\\text{bulk}}$ coefficients are given in the following table, and ensure that $f_{\\text{bulk}}\\left(0\\right)=f_{\\text{bulk}}\\left(1\\right)=f_{\\text{bulk}}'\\left(0\\right)=f_{\\text{bulk}}'\\left(1\\right)=0$ and that the energy curve remains concave down between the two energy wells.\n\n| Parameter | Value |\n|:-----:|-----------------|\n| $a_0$ | 0 | \n| $a_1$ | 0 | \n| $a_2$ | 8.072789087 |\n| $a_3$ | -81.24549382 |\n| $a_4$ | 408.0297321 |\n| $a_5$ | -1244.129167 |\n| $a_6$ | 2444.046270 |\n| $a_7$ | -3120.635139 |\n| $a_8$ | 2506.663551 |\n| $a_9$ | -1151.003178 |\n| $a_{10}$ | 230.2006355 |\n\nThe large number of significant digits are necessary to ensure that the first derivative of $f_{\\text{bulk}}$ is zero at $\\eta=0$ and $\\eta=1$.\n\nThe elastic energy density is given as [[1][jokisaari2017superalloy]]\n\n\\begin{equation}\nf_{\\text{el}}\\left(\\eta\\right)=\\frac{1}{2}\\sigma_{ij} \\epsilon_{ij}^{\\text{el}},\n\\end{equation}\n\nwhere $\\sigma_{ij}=C_{ijkl}\\left(\\eta\\right) \\epsilon_{ij}^{\\text{el}}$ is the elastic stress, $\\epsilon_{ij}^{\\text{el}}$ is the elastic strain, and $C_{ijkl}\\left(\\eta\\right)$ is the elastic stiffness tensor such that the system is mechanically stable (the Einstein summation convention is used). To incorporate the dependence of the elastic stiffness on the phase, the stiffness is interpolated smoothly from one phase to the other across the diffuse interface, \n\n\\begin{equation}\nC_{ijkl}\\left(\\eta\\right)= C_{ijkl}^{\\text{matrix}}\\left[1-h\\left(\\eta\\right)\\right]+C_{ijkl}^{\\text{precip}} \\, h\\left(\\eta\\right),\n\\end{equation}\nwhere $C_{ijkl}^{\\text{matrix}}$ and $C_{ijkl}^{\\text{precip}}$ are the stiffness tensors of the matrix and precipitate phases, respectively, and $h\\left(\\eta\\right)=\\eta^3\\left(6\\eta^2-15\\eta+10\\right)$ is a smooth interpolation function that ensures that $h\\left( 0 \\right ) = h'\\left( 0 \\right)=h'\\left( 1 \\right)=0$ and $h\\left(1\\right) = 1$ [[2][leo1998diffuse]]. \n\nBecause the lattice parameters of the two phases are different, the elastic strain differs from the total strain, $\\epsilon_{ij}^{\\text{total}}$, as [[3][eshelby1957determination]]\n\n\\begin{equation}\n\\epsilon_{ij}^{\\text{el}}=\\epsilon_{ij}^{\\text{total}}-\\epsilon_{ij}^{0}\\left(\\eta\\right),\n\\end{equation}\n\nwhere $\\epsilon_{ij}^{0}$ is the local stress-free strain. It is calculated as \n\n\\begin{equation}\n\\epsilon_{ij}^0\\left(\\eta\\right)= \\epsilon_{ij}^T \\, h\\left(\\eta\\right),\n\\end{equation}\n\nwhere $\\epsilon_{ij}^{T}$ is the crystallographic misfit strain tensor between the matrix and precipitate phases defined with respect to the matrix. Finally, the total strain is related to the displacements, $u_i$, as [[3][eshelby1957determination]]\n\n\\begin{equation}\n\\epsilon_{ij}^{\\text{total}}=\\frac{1}{2}\\left[\\frac{\\partial u_i}{\\partial x_j}+\\frac{\\partial u_j}{\\partial x_i}\\right].\n\\end{equation}\n\nIn this problem, precipitate shapes must evolve to their equilibrium shape while remaining as small particles embedded in a much larger matrix. To do so, we employ the Cahn-Hilliard equation to perform fictive time evolution [[2][leo1998diffuse], [1][jokisaari2017superalloy]], which conserves the total integral of $\\eta$ within the simulation. The evolution of $\\eta$ is given as \n\n\\begin{equation}\n\\frac{\\partial\\eta}{\\partial t}=\\nabla\\cdot\\left[M\\nabla\\left\\{ \\frac{\\delta \\mathcal{F}}{\\delta\\eta}\\right\\} \\right],\n\\end{equation}\n\nwhere $M$ is the mobility and the chemical potential is \n\n\\begin{equation}\n\\mu \\equiv \\frac{\\delta \\mathcal{F}}{\\delta\\eta}=\\frac{\\partial f_{\\text{chem}}}{\\partial\\eta}+\\frac{\\partial f_{\\text{elastic}}}{\\partial\\eta}-\\kappa\\nabla^{2}\\eta.\n\\end{equation}\n\nWe have flexibility in choosing $M$, as we are only interested in the final state of the system. Furthermore, we assume that the relaxation dynamics for elasticity are much faster than for the diffusion of $\\eta$, as is generally the case for phase field models. As such, we solve the time-independent equation for mechanical equilibrium at each time step, \n\n\\begin{equation}\n\\nabla\\cdot\\sigma_{ij} = 0.\n\\end{equation}\n\n\n[jokisaari2017superalloy]: https://arxiv.org/abs/1709.02010\n[leo1998diffuse]: https://doi.org/10.1016/S1359-6454(97)00377-7\n[eshelby1957determination]: https://doi.org/10.1098/rspa.1957.0133\n\n\n\n\n\n\n## Parameterization and simulation conditions\n\nThis problem is solved in two dimensions to reduce computational costs, but note that we do not utilize symmetry to further reduce the problem size. The matrix and precipitate phases have cubic symmetry, such that three independent elastic stiffnesses exist for each phase: $C_{1111}$, $C_{1122}$, and $C_{1212}$ [[1][nye1957physical]], and we take $C_{ijkl}^{\\text{precip}}=1.1C_{ijkl}^{\\text{matrix}}$. In addition, the precipitate misfit strain takes the form $\\epsilon^T_{11}=\\epsilon^T_{22} > 0$, $\\epsilon^T_{12}=0$. Because this benchmark problem relies on the balance between interfacial and elastic energy, we use dimensional units of attojoules and nanometers. The diffuse interface width is chosen as 5 nm for $0.05 < \\eta < 0.95$ and the interfacial energy is chosen as 50 aJ/nm$^2$ (equivalent to 50 mJ/m$^2$). The model parameters are given in the following table.\n\n### Parameter values for all variants\n\n| Quantity | Symbol | Value |\n|:------------------------------|:-----------------------------------:|--------------------|\n| Gradient energy coefficient | $\\kappa$ | 0.29 aJ/nm |\n| Well height | $w$ | 0.1 aJ/nm$^3$ |\n| Mobility | $M$ | 5 |\n| Misfit strain | $\\epsilon^T_{11}$=$\\epsilon^T_{22}$ | 0.5 % |\n| Elastic stiffness matrix | $C^{\\text{matrix}}_{1111}$ | 250 aJ/nm$^3$ |\n| Elastic stiffness matrix | $C^{\\text{matrix}}_{1122}$ | 150 aJ/nm$^3$ |\n| Elastic stiffness matrix | $C^{\\text{matrix}}_{1212}$ | 100 aJ/nm$^3$ |\n\nNote that 1 aJ/nm$^3$ is equivalent to 1 GPa.\n\nWe utilize both circular and elliptical initial precipitate shapes for a given initial precipitate area [[2][thompson1994equilibrium], [3][li2004two]]; all initial precipitates have a diffuse interface width of 5 nm. To have an equal area for an ellipse as a circle with radius $r$, we choose ellipse axes as $a_{[10]}=r/0.9$ and $a_{[01]}=0.9r$. Simulations are performed for two initial precipitate sizes: a smaller one with an area of $20^2 \\pi \\textrm{ nm}^2$ and a larger one with an area of $75^2 \\pi \\textrm{ nm}^2$. The center of each precipitate is embedded in the center of a square computational domain, which is given the coordinate (0,0). The computational domain is $(400 \\textrm{ nm})^2$ for the smaller precipitates and $(1500 \\textrm{ nm})^2$ for the larger precipitates to allow long-range elastic fields to decay. No-stress boundary conditions are applied for the displacements, and no-flux boundary conditions are applied for $\\eta$. Because our implementation is based on solving for displacements rather than strain, we specify $u_{[10]}=0$ at the top, middle, and bottom of the $y=0$ axis ($e.g.,$ in the [01] direction) and $u_{[01]}=0$ at the top, middle, and bottom of the $x=0$ axis ($e.g.,$ in the [10] direction) to remove the nullspace in the solution. Simulations are run until equilibrium is achieved.\n\nThe presence of elastic strain energy or a curved interface will increase the final value of $\\eta$ in both the matrix and precipitate phases from the equilibrium value given by the common tangent of $f_{\\text{bulk}}$. In addition, the precipitate may change size during the course of the energy relaxation because of the shifting balance between the $f_{\\text{bulk}}$ and $f_{\\text{el}}$ energy contributions. Because the precipitate volume within the computational domain is much smaller than that of the matrix, a precipitate may shrink entirely away in the process achieving the equilibrium value of $\\eta$ in the matrix. To avoid this, the initial value of $\\eta$ in the matrix should be set slightly greater than zero. For the simulations with the small particles, we set $\\eta^{\\text{matrix}}_0=0.0065$, while for the large particles, $\\eta^{\\text{matrix}}_0=0.005$. In addition, we set $\\eta^{\\text{precip}}_0=1$ for all simulations. \n\n\n[nye1957physical]: https://doi.org/10.1029/EO064i045p00643-01\n[thompson1994equilibrium]: https://doi.org/10.1016/0956-7151(94)90036-1\n[li2004two]: https://doi.org/10.1016/j.actamat.2004.08.041\n\nOverall, there are 8 different parameter variations for this problem. These are labeled (a) through (h).\n\n### Parameter values for (a) through (h)\n\n| Quantity | Symbol | Value (a) | Value (b) | Value (c) | Value (d) | Value (e) | Value (f) | Value (g) | Value (h) |\n|:-------------------------|:--------------------------:|--------------------------:|--------------------------:|--------------------------:|--------------------------:|--------------------------:|--------------------------:|--------------------------:|--------------------------:|\n| Radius | $r$ | 20 $\\textrm{nm}$ | 75 $\\textrm{nm}$ | 20 $\\textrm{nm}$ | 75 $\\textrm{nm}$ | 20 $\\textrm{nm}$ | 75 $\\textrm{nm}$ | 20 $\\textrm{nm}$ | 75 $\\textrm{nm}$ |\n| Eclipse axes (10) | $a_{[10]}$ | $r$ | $r$ | $r$ | $r$ | $r$ / 0.9 | $r$ / 0.9 | $r$ / 0.9 | $r$ / 0.9 |\n| Eclipse axes (01) | $a_{[01]}$ | $r$ | $r$ | $r$ | $r$ | 0.9 $r$ | 0.9 $r$ | 0.9 $r$ | 0.9 $r$ |\n| Precipitate area | | 20$^2 \\pi \\textrm{ nm}^2$ | 75$^2 \\pi \\textrm{ nm}^2$ | 20$^2 \\pi \\textrm{ nm}^2$ | 75$^2 \\pi \\textrm{ nm}^2$ | 20$^2 \\pi \\textrm{ nm}^2$ | 75$^2 \\pi \\textrm{ nm}^2$ | 20$^2 \\pi \\textrm{ nm}^2$ | 75$^2 \\pi \\textrm{ nm}^2$ |\n| Domain size | | $\\text{(400 nm)}^2$ | $\\text{(1500 nm)}^2$ | $\\text{(400 nm)}^2$ | $\\text{(1500 nm)}^2$ | $\\text{(400 nm)}^2$ | $\\text{(1500 nm)}^2$ | $\\text{(400 nm)}^2$ | $\\text{(1500 nm)}^2$ |\n| Order Parameter (matrix) | $\\eta^{\\text{matrix}}_0$ | 0.0065 | 0.005 | 0.0065 | 0.005 | 0.0065 | 0.005 | 0.0065 | 0.005 |\n| Order Parameter (precip) | $\\eta^{\\text{precip}}_0$ | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |\n| Elastic stiffness precip | $C^{\\text{precip}}_{1111}$ | $\\text{250 aJ/nm}^3$ | $\\text{250 aJ/nm}^3$ | $\\text{275 aJ/nm}^3$ | $\\text{275 aJ/nm}^3$ | $\\text{250 aJ/nm}^3$ | $\\text{250 aJ/nm}^3$ | $\\text{275 aJ/nm}^3$ | $\\text{275 aJ/nm}^3$ |\n| Elastic stiffness precip | $C^{\\text{precip}}_{1122}$ | $\\text{150 aJ/nm}^3$ | $\\text{150 aJ/nm}^3$ | $\\text{165 aJ/nm}^3$ | $\\text{165 aJ/nm}^3$ | $\\text{150 aJ/nm}^3$ | $\\text{150 aJ/nm}^3$ | $\\text{165 aJ/nm}^3$ | $\\text{165 aJ/nm}^3$ |\n| Elastic stiffness precip | $C^{\\text{precip}}_{1212}$ | $\\text{100 aJ/nm}^3$ | $\\text{100 aJ/nm}^3$ | $\\text{110 aJ/nm}^3$ | $\\text{110 aJ/nm}^3$ | $\\text{100 aJ/nm}^3$ | $\\text{100 aJ/nm}^3$ | $\\text{110 aJ/nm}^3$ | $\\text{110 aJ/nm}^3$ |\n\n\n## Example Result at Equilibrium\n\nThe final morphologies of the precipitates for problems (a), (c), (e) and (g). The dark pink curve is for variant (a) and (e) and the light pink is for variant (c) and (g). The results indicate that the shape of the initial precipitate does not influence the final shape of the precipitate for the smaller precipitate variant.\n\n\n\n## Submission Guidelines\n\nAll benchmark solutions should be run to equilibrium. The following data should be collected for each upload.\n\n - Global quantities as the simulation evolves including\n \n * the total free energy, $\\;\\;\\mathcal{F}\\;\\;$\n \n * the interfacial free energy, $\\;\\;\\mathcal{F}_{\\text{grad}}=\\int_V \\frac{\\kappa}{2} |\\nabla \\eta|^2 \\; dV\\;\\;$\n \n * the elastic free energy, $\\;\\;\\mathcal{F}_{\\text{el}} = \\int_V f_{\\text{el}} \\; dV\\;\\;$\n \n * the area of the precipitate $\\;\\;\\int_V \\eta dV\\;\\;$ and\n \n * the precipitate lengths $a_{10}$, $a_{01}$ and $a_d$ measured from the center of the drop to the $\\eta=0.5$ contour in the $x$ ([10]), $y$ ([01]) and diagonal directions, respectively. The angle used for the diagonal direction is given by $\\theta_d$ such that $\\tan\\theta_d=a_{01}/a_{10}$.\n \n - The $\\eta=0.5$ level set contour position at equilibrium or the latest time step.\n \n\n \n### Evolving Data Format\n\nThe evolving data should be stored in a CSV file with columns labeled as `time`, `a_01`, `a_10`, `a_d`,`elastic_free_energy`,`gradient_free_energy`, `precipitate_area` and `total_free_energy`. The CSV file should be formatted as a table and have the following form (note that the column ordering is inconsequential),\n\n```\na_01,a_10,a_d,elastic_free_energy,gradient_free_energy,precipitate_area,time,total_free_energy\n19.97429316515008,19.974293165149973,20.140688631434397,6.185957746168657,4.510418048831537,1264.0,0.1,17.72178588199252\n19.86315763877582,19.863157638775874,20.098536436029132,6.054959230125162,2.9620862374085544,1264.0,1.1,17.207555522195793\n19.906346454363486,19.906346454363465,20.134576060150618,6.021500927987024,2.736582255973086,1264.0,2.1,17.204113636263912\n...\n```\n\nThe data should be collected frequently during the simulation, but greater than 20 data points at a minimum (more than 1000 data points is unnecessary and won't improve resolution). The data should be named `all_data` in the \"Short name of data\" box located in the \"Data Files\" section of the [upload form]. The 2D radio button should be checked, the entry in the \"Name of the x-axis column\" box should be `time` and the entry in the \"Name of y-axis column\" should be `total_free_energy`. Only one \"Data Files\" section upload is required for the evolving data.\n\n### Equilibrium Data Format\n\nThe equilibrium data should be stored in either a CSV file with columns labeled as `x` and `y`. The CSV file should be formatted as a table and have the following form (note that the column ordering is inconsequential),\n\n```\nx,y\n-9.5,-18.615967564796016\n-8.5,-18.84790477132558\n-7.5,-19.030286708741155\n-6.5,-19.158255175095714\n```\n\nThe contour data should be in a sequence that enables an ordered traversal of the contour line. The data should be named `contour` in the \"Short name of data\" box located in the \"Data Files\" section of the [upload form]. The 2D radio button should be checked, the entry in the \"Name of the x-axis column\" box should be `x` and the entry in the \"Name of y-axis column\" should be `y`. Only one \"Data Files\" section upload is required for the evolving data.\n\n\nPlease use the [upload form] to upload your results.\n\n[upload form]: ../../simulations/upload_form/\n\n\n```python\n\n```\n", "meta": {"hexsha": "9012d70d4105a1ae1de9e4a578d431750ccc6e4a", "size": 26904, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "benchmarks/benchmark4.ipynb", "max_stars_repo_name": "wd15/chimad-phase-field", "max_stars_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "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": "benchmarks/benchmark4.ipynb", "max_issues_repo_name": "wd15/chimad-phase-field", "max_issues_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-02-06T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-12T17:39:56.000Z", "max_forks_repo_path": "benchmarks/benchmark4.ipynb", "max_forks_repo_name": "wd15/chimad-phase-field", "max_forks_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "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.9253731343, "max_line_length": 1722, "alphanum_fraction": 0.5782783229, "converted": true, "num_tokens": 6379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988313272769, "lm_q2_score": 0.14804719991116141, "lm_q1q2_score": 0.0614246102244166}} {"text": "# Markdown\nActually, the best way to make a notebook look nice ist to **extensively use markdown**. For example, we can generate a nice static table of contents like this:\n\n1. [jupyter_contrib_nbextensions](#nbext)\n * [Table of contents 2](#toc2)\n * [LaTeX_envs](#tex)\n * [Exercise](#ex)\n * [Python in markdown](#mark)\n\n2. [Interactive and animated plots](#plot)\n * [Data](#data)\n * [maplotlib notebook](#matnb)\n * [Animated plots](#ani)\n\n3. [Nbconvert](#nbcon)\n\nLinks are generally written like this link to [nbextension.readthedocs](http://jupyter-contrib-nbextensions.readthedocs.io).\n\n# jupyter_contrib_nbextensions\nThis PyMOTW is about [jupyter_contrib_nbextensions](https://github.com/ipython-contrib/jupyter_contrib_nbextensions), a repository containing a collection of extensions that add functionality to the Jupyter notebook. These extensions are mostly written in Javascript and will be loaded locally in your browser.\n\nLINKS:\n* https://github.com/ipython-contrib/jupyter_contrib_nbextensions\n* http://jupyter-contrib-nbextensions.readthedocs.io\n\n\nThe notebook extensions can be selected and configured in your Jupyter home tree via the tab *Nbextensions* (http://localhost:8888/tree#nbextensions_configurator).\n\n## Table of contents 2 (toc2) \nThe toc2 extension enables to collect all running headers and display them in a floating window, as a sidebar or with a navigation menu. The extension is also draggable, resizable, collapsable, dockable and features automatic numerotation with unique links ids, and an optional toc cell.\n\nHave a look at the options in the Nbextensions tab. **NOTE:** When using toc2 you may not use ``!\n\n### Conclusion\n**I love this**. Simple and easy. Look at the sidebar table of contents. Neat, right? Let's you jump to different sections quite easy and also shows you which section is currently selected and which section is queued to run.\n\n## LaTeX_envs\n\n### Equations, `\\ref{eq:}`, theorem environments\nThe following code\nThe dot-product is defined by equation (\\ref{eq:dotp}) in theorem \\ref{theo:dotp} just below:\n\\begin{theorem}[Dot Product] \\label{theo:dotp}\nLet $u$ and $v$ be two vectors of $\\mathbb{R}^n$. The dot product can be expressed as\n\\begin{equation}\n\\label{eq:dotp}\nu^Tv = |u||v| \\cos \\theta,\n\\end{equation}\nwhere $\\theta$ is the angle between $u$ and $v$ ...\n\\end{theorem}\nrenders like this:\n\nThe dot-product is defined by equation (\\ref{eq:dotp}) in theorem \\ref{theo:dotp} just below:\n\\begin{theorem}[Dot Product] \\label{theo:dotp}\nLet $u$ and $v$ be two vectors of $\\mathbb{R}^n$. The dot product can be expressed as\n\\begin{equation}\n\\label{eq:dotp}\nu^Tv = |u||v| \\cos \\theta,\n\\end{equation}\nwhere $\\theta$ is the angle between $u$ and $v$ ...\n\\end{theorem}\n\n### Citations, bibliography and references\nIt seems, that you can place a `.bib` file in the same directory as the notebook and use `\\cite{}` to generate citations. Let's see if it works: \\cite{Thomson1887}, \\cite{Hebb1949}\n\nUnfortunately, it does not really work for me, maybe because nbextensions said that latex_envs was *possibly incompatible*. My output after clicking *Read bibliography and generate references section* is the following:\n\n#### References\n\n[Thomson1887] !! _This reference was not found in library.bib _ !!\n\n[Hebb1949] !! _This reference was not found in library.bib _ !!\n\n\n\n### Conclusions\nProbably awesome if it works. Especially citations would be great to have. However, I don't know if I really need the environments. Math works alright in markdown also without this extension.\n\n## Exercise and Exercise2\nThese are two extensions for Jupyter, for hiding/showing solutions cells.\n\n### Exercise\n\\begin{exercise}[Laplace Equation]\nWrite the Laplace equation $\\Delta\\Phi=0$ in spherical coordinates.\n\\end{exercise}\n\nSOLUTION\n\n\\begin{equation}\n\\frac{1}{r^2}\\frac{\\partial}{\\partial r} \\left( r^2 \\frac{\\partial}{\\partial r} \\Phi \\right) + \\frac{1}{r^2 \\sin\\theta}\\frac{\\partial}{\\partial \\theta} \\left( \\sin\\theta \\frac{\\partial}{\\partial \\theta} \\Phi \\right) + \\frac{1}{r^2 \\sin^2\\theta}\\frac{\\partial}{\\partial \\phi^2} \\Phi\n\\end{equation}\n\n### Exercise2\n\\begin{exercise}[Laplace Equation]\nWrite the Laplace equation $\\Delta\\Phi=0$ in spherical coordinates.\n\\end{exercise}\n\nSOLUTION\n\n\\begin{equation}\n\\frac{1}{r^2}\\frac{\\partial}{\\partial r} \\left( r^2 \\frac{\\partial}{\\partial r} \\Phi \\right) + \\frac{1}{r^2 \\sin\\theta}\\frac{\\partial}{\\partial \\theta} \\left( \\sin\\theta \\frac{\\partial}{\\partial \\theta} \\Phi \\right) + \\frac{1}{r^2 \\sin^2\\theta}\\frac{\\partial}{\\partial \\phi^2} \\Phi\n\\end{equation}\n\n### Conclusions\nI encounter some bugs with Exercise2, the solution shows up after reloading the notebook. Therefore the winner is Exercise! Could be useful for workshops..\n\n## Python in markdown\n\n\n```python\na=3.765\n```\n\nPrint the value of the variable in markdown using \na={{a}}\na={{a}}\n\n### Conclusion\n `¯\\_(ツ)_/¯`\n\n# Interactive and animated plots\n## Some random data to plot\n\n\n```python\nimport numpy as np\nimport elephant\nimport neo\nimport quantities as pq\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom IPython.display import HTML\nimport matplotlib.animation as animation\n```\n\n /home/papen/.local/lib/python2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n\n\n\n```python\n# Load block from ANDA data\nblock = np.load('/home/papen/git_repos/ANDA2017/data/data2.npy').item()\n\n# Get spiketrain of first regular trial\nsts = []\nidx = block.annotations['all_trial_ids']\nsts.append(block.filter(targdict={'trial_id': idx[0]}, objects=neo.Segment)[0].spiketrains)\n\n# Generate binned time series of spike counts and apply PCA\nbinsize = 100*pq.ms\nbinned = elephant.conversion.BinnedSpikeTrain(sts[0], binsize=binsize).to_array()\npca = PCA(n_components=3)\npca.fit(binned.T)\nPC = np.matmul(pca.components_,binned)[:3,:]\nt = np.arange(len(PC[0,:]))*binsize\n```\n\n## Matplotlib notebook\nUsing `%matplotlib notebook` activates the nbagg backend added in matplotlib 1.4, which will include a javascript interface for interaction with inline figures in the notebook. Apparently for Python2 one can also use `%matplotlib nbagg`.\n\n\n```python\n%matplotlib notebook\n```\n\n\n```python\nfig = plt.figure(figsize=(10,5))\nax = fig.add_subplot(121, projection='3d')\nax.plot(PC[0,:], PC[1,:], PC[2,:], '-k')\nax.set_xlabel('Comp. 1')\nax.set_ylabel('Comp. 2')\nax.set_zlabel('Comp. 3')\n\nax = fig.add_subplot(122)\nfor i in xrange(len(PC[:,0])):\n ax.plot(t, PC[i,:], '-', label='PC {}'.format(i))\nax.set_xlabel('time [ms]')\nax.set_ylabel('PC')\nplt.legend()\n```\n\n\n \n\n\n\n\n\n\n\n\n\n \n\n\n\n## Animated plots with HTML\n\nThe following example is taken from https://matplotlib.org/examples/animation/simple_anim.html\n\n\n```python\n%matplotlib inline\n\ndef test(binned):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n line, = ax.plot(t, binned[0,:])\n\n def animate(i, title_num=None):\n line.set_ydata(binned[i,:]) # update the data\n ax = plt.gca()\n ax.set_title('Spike counts of unit {}'.format(i))\n return line,\n\n # Init only required for blitting to give a clean slate.\n def init():\n line.set_ydata([])\n return line,\n\n ani = animation.FuncAnimation(fig, animate, np.arange(1, len(binned[:,0])), init_func=init,\n interval=500, blit=True)\n return ani, ax\n\nani, ax = test(binned)\n\nax.set_xlabel('time [ms]')\nax.set_ylabel('spike count')\n\nHTML(ani.to_html5_video())\n```\n\n# Nbconvert\nDetailed information can be found here: https://github.com/jupyter/nbconvert\n\nIn order to cenvert to LaTeX, use:\n\n`jupyter nbconvert --to latex_with_lenvs --LenvsLatexExporter.removeHeaders=True PyMOTW_nbextensions.ipynb`\n\nYou can also convert your notebook to a prsentation, e.g. using reveal.js like this (Note, first you need to arrange slides by clicking View -> Cell -> Slideshow):\n\n`jupyter nbconvert --to slides --post serve PyMOTW_nbextensions.ipynb`\n\n\n```python\n\n```\n", "meta": {"hexsha": "8e6088c6797083366f7c2ce28f006b5ff3cdf9e5", "size": 936695, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "session09_nbextensions/PyMOTW_nbextensions.ipynb", "max_stars_repo_name": "morales-gregorio/Python-Module-of-the-Week", "max_stars_repo_head_hexsha": "2c68e20be3e174be9b91c92ac872806dd982e7d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-06-22T11:57:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:34:07.000Z", "max_issues_repo_path": "session09_nbextensions/PyMOTW_nbextensions.ipynb", "max_issues_repo_name": "morales-gregorio/Python-Module-of-the-Week", "max_issues_repo_head_hexsha": "2c68e20be3e174be9b91c92ac872806dd982e7d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-10-16T10:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-09T09:24:48.000Z", "max_forks_repo_path": "session09_nbextensions/PyMOTW_nbextensions.ipynb", "max_forks_repo_name": "morales-gregorio/Python-Module-of-the-Week", "max_forks_repo_head_hexsha": "2c68e20be3e174be9b91c92ac872806dd982e7d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-10-07T12:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T11:15:04.000Z", "avg_line_length": 93.0091351405, "max_line_length": 93189, "alphanum_fraction": 0.8346238637, "converted": true, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.1847675084034608, "lm_q1q2_score": 0.061180169274451426}} {"text": "\n# Computational Physics: Introduction to Many-body Theory and Hartree-Fock theory\n\n \n**Morten Hjorth-Jensen**, [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/) and [Department of Physics and Astronomy](https://www.pa.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA and Department of Physics, University of Oslo, Oslo, Norway\n\nDate: **Jan 16, 2020**\n\nCopyright 2013-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n## Quantum Many-particle Methods\n\n* Large-scale diagonalization (Iterative methods, Lanczo's method, dimensionalities $10^{10}$ states)\n\n* Coupled cluster theory, favoured method in quantum chemistry, molecular and atomic physics. Applications to ab initio calculations in nuclear physics as well for large nuclei\n\n* Perturbative many-body methods\n\n* Density functional theories/Mean-field theory and Hartree-Fock theory\n\n* Monte-Carlo methods (Only in FYS4411, Computational quantum mechanics)\n\n* Green's function theories\n\n* and other. The physics of the system hints at which many-body methods to use.\n\n## Selected Texts and Many-body theory\n\n* Blaizot and Ripka, *Quantum Theory of Finite systems*, MIT press 1986\n\n* Negele and Orland, *Quantum Many-Particle Systems*, Addison-Wesley, 1987.\n\n* Fetter and Walecka, *Quantum Theory of Many-Particle Systems*, McGraw-Hill, 1971.\n\n* Helgaker, Jorgensen and Olsen, *Molecular Electronic Structure Theory*, Wiley, 2001.\n\n* Mattuck, *Guide to Feynman Diagrams in the Many-Body Problem*, Dover, 1971.\n\n* Dickhoff and Van Neck, *Many-Body Theory Exposed*, World Scientific, 2006.\n\n\n## Definitions\n\nAn operator is defined as $\\hat{O}$ throughout. Unless otherwise specified the number of particles is\nalways $N$ 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 isobars $\\Delta$ or various\nhyperons such as $\\Lambda$ or $\\Sigma$, one needs to add their\ndefinitions. Hereafter, $N$ is reserved for the total number of\nparticles, unless otherwise specificied. \n\n\n## Definitions\n\nThe quantum numbers of a single-particle state in coordinate space are\ndefined by the variable\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 $\\int dx = \\sum_{\\sigma}\\int d^dr = \\sum_{\\sigma}\\int d\\boldsymbol{r}$,\nand\n\n$$\n\\int d^Nx= \\int dx_1\\int dx_2\\dots\\int dx_N.\n$$\n\n## Definitions\n\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_N),\n$$\n\nwith $x_i=(\\boldsymbol{r}_i,\\sigma_i)$ and the projection of $\\sigma_i$ takes the values\n$\\{-1/2,+1/2\\}$ for particles with spin $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_N).\n$$\n\n## Definitions\n\nSince the solution $\\Psi_{\\lambda}$ seldomly can be found in closed form, approximations are sought. Here 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_N),\n$$\n\nwith\n\n$$\n\\Phi_0=\\Phi_0(x_1,x_2,\\dots,x_N),\n$$\n\nbeing the ansatz to the ground state. \n\n\n\n## Definitions\n\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}_N:= {\\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\n$\\in {\\mathbb{R}}^{d}\\oplus (\\sigma)$\nresulting in\n\n$$\n{\\cal H}_1:= L^2(\\mathbb{R}^{d}\\oplus (\\sigma)).\n$$\n\n## Definitions\n\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_N)$ 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_N)=\n\\beta\\Psi_{\\lambda}(x_1, x_2, \\dots,x_j,\\dots,x_i,\\dots,x_N),\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## Definitions and notations\n\nThe Schrodinger equation reads\n\n\n
    \n\n$$\n\\begin{equation}\n\\hat{H}(x_1, x_2, \\dots , x_N) \\Psi_{\\lambda}(x_1, x_2, \\dots , x_N) = \nE_\\lambda \\Psi_\\lambda(x_1, x_2, \\dots , x_N), \\label{eq:basicSE1} \\tag{1}\n\\end{equation}\n$$\n\nwhere the vector $x_i$ represents the coordinates (spatial and spin) of particle $i$, $\\lambda$ stands for all the quantum\nnumbers needed to classify a given $N$-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## Definitions and notations\n\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}^N \\frac{\\mathbf{p}_i^2}{2m_i} = \\sum_{i=1}^N \\left( -\\frac{\\hbar^2}{2m_i} \\mathbf{\\nabla_i}^2 \\right) =\n\t\t\\sum_{i=1}^N 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}^N \\hat{u}_{\\mathrm{ext}}(x_i) + \\sum_{j < i=1}^N v(x_i,x_j)+\\sum_{i< j < k=1}^Nv(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## Definitions and notations\n\nIf one does quantum chemistry, after having introduced the Born-Oppenheimer approximation which effectively freezes out the nucleonic degrees of freedom, the Hamiltonian for $N=n_e$ electrons takes the following form\n\n$$\n\\hat{H} = \\sum_{i=1}^{n_e} t(x_i) - \\sum_{i=1}^{n_e} k\\frac{Z}{r_i} + \\sum_{i < j}^{n_e} \\frac{k}{r_{ij}},\n$$\n\nwith $k=1.44$ eVnm\n\n\n\n## Definitions and notations\n\nWe can rewrite this as\n\n\n
    \n\n$$\n\\begin{equation}\n \\hat{H} = \\hat{H}_0 + \\hat{H}_I \n = \\sum_{i=1}^{n_e}\\hat{h}_0(x_i) + \\sum_{i < j}^{n_e}\\frac{1}{r_{ij}},\n\\label{H1H2} \\tag{3}\n\\end{equation}\n$$\n\nwhere we have defined\n\n$$\nr_{ij}=| \\boldsymbol{r}_i-\\boldsymbol{r}_j|,\n$$\n\nand\n\n\n
    \n\n$$\n\\begin{equation}\n \\hat{h}_0(x_i) = \\hat{t}(x_i) - \\frac{Z}{x_i}.\n\\label{hi} \\tag{4}\n\\end{equation}\n$$\n\nThe first term of Eq. ([3](#H1H2)), $H_0$, is the sum of the $N$\n*one-body* Hamiltonians $\\hat{h}_0$. Each individual\nHamiltonian $\\hat{h}_0$ contains the kinetic energy operator of an\nelectron and its potential energy due to the attraction of the\nnucleus. The second term, $H_I$, is the sum of the $n_e(n_e-1)/2$\ntwo-body interactions between each pair of electrons. Note that the double sum carries a restriction $i < j$.\n\n\n\n## Definitions and notations\n\nThe potential energy term due to the attraction of the nucleus defines the onebody field $u_i=u_{\\mathrm{ext}}(x_i)$ of Eq. ([2](#eq:firstv)).\nWe have moved this term into the $\\hat{H}_0$ part of the Hamiltonian, instead of keeping it in $\\hat{V}$ as in Eq. ([2](#eq:firstv)).\nThe reason is that we will hereafter treat $\\hat{H}_0$ as our non-interacting Hamiltonian. For a many-body wavefunction $\\Phi_{\\lambda}$ defined by an \nappropriate single-particle basis, we may solve exactly the non-interacting eigenvalue problem\n\n$$\n\\hat{H}_0\\Phi_{\\lambda}= w_{\\lambda}\\Phi_{\\lambda},\n$$\n\nwith $w_{\\lambda}$ being the non-interacting energy. This energy is defined by the sum over single-particle energies to be defined below.\nFor atoms the single-particle energies could be the hydrogen-like single-particle energies corrected for the charge $Z$. For nuclei and quantum\ndots, these energies could be given by the harmonic oscillator in three and two dimensions, respectively.\n\n\n## Definitions and notations\n\nWe will assume that the interacting part of the Hamiltonian\ncan be approximated by a two-body interaction.\nThis means that our Hamiltonian is written as\n\n\n
    \n\n$$\n\\begin{equation}\n \\hat{H} = \\hat{H}_0 + \\hat{H}_I \n = \\sum_{i=1}^N \\hat{h}_0(x_i) + \\sum_{i < j}^N V(r_{ij}),\n\\label{Hnuclei} \\tag{5}\n\\end{equation}\n$$\n\nwith\n\n\n
    \n\n$$\n\\begin{equation}\n H_0=\\sum_{i=1}^N \\hat{h}_0(x_i) = \\sum_{i=1}^N\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right).\n\\label{hinuclei} \\tag{6}\n\\end{equation}\n$$\n\nThe onebody part $u_{\\mathrm{ext}}(x_i)$ is normally approximated by a harmonic oscillator potential or the Coulomb interaction an electron feels from the nucleus. However, other potentials are fully possible, such as \none derived from the self-consistent solution of the Hartree-Fock equations.\n\n\n\n## Definitions and notations\n\nOur Hamiltonian is invariant under the permutation (interchange) of two particles. % (exercise here, prove it)\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_N)$ 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_N)=\n\\beta\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_N),\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## Definitions and notations\n\nIn our case we assume that we can approximate the exact eigenfunction with a Slater determinant\n\n\n
    \n\n$$\n\\begin{equation}\n \\Phi(x_1, x_2,\\dots ,x_N,\\alpha,\\beta,\\dots, \\sigma)=\\frac{1}{\\sqrt{N!}}\n\\left| \\begin{array}{ccccc} \\psi_{\\alpha}(x_1)& \\psi_{\\alpha}(x_2)& \\dots & \\dots & \\psi_{\\alpha}(x_N)\\\\\n \\psi_{\\beta}(x_1)&\\psi_{\\beta}(x_2)& \\dots & \\dots & \\psi_{\\beta}(x_N)\\\\ \n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n \\psi_{\\sigma}(x_1)&\\psi_{\\sigma}(x_2)& \\dots & \\dots & \\psi_{\\sigma}(x_N)\\end{array} \\right|, \\label{eq:HartreeFockDet} \\tag{7}\n\\end{equation}\n$$\n\nwhere $x_i$ stand for the coordinates and spin values of a particle $i$ and $\\alpha,\\beta,\\dots, \\gamma$ \nare quantum numbers needed to describe remaining quantum numbers. \n\n\n## Definitions and notations\n\nThe single-particle function $\\psi_{\\alpha}(x_i)$ are eigenfunctions of the onebody\nHamiltonian $h_i$, that is\n\n$$\n\\hat{h}_0(x_i)=\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i),\n$$\n\nwith eigenvalues\n\n$$\n\\hat{h}_0(x_i) \\psi_{\\alpha}(x_i)=\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right)\\psi_{\\alpha}(x_i)=\\varepsilon_{\\alpha}\\psi_{\\alpha}(x_i).\n$$\n\nThe energies $\\varepsilon_{\\alpha}$ are the so-called non-interacting single-particle energies, or unperturbed energies. \nThe total energy is in this case the sum over all single-particle energies, if no two-body or more complicated\nmany-body interactions are present.\n\n\n## Definitions and notations\n\nLet us denote the ground state energy by $E_0$. According to the\nvariational principle we have\n\n$$\nE_0 \\le E[\\Phi] = \\int \\Phi^*\\hat{H}\\Phi d\\mathbf{\\tau}\n$$\n\nwhere $\\Phi$ is a trial function which we assume to be normalized\n\n$$\n\\int \\Phi^*\\Phi d\\mathbf{\\tau} = 1,\n$$\n\nwhere we have used the shorthand $d\\mathbf{\\tau}=d\\mathbf{r}_1d\\mathbf{r}_2\\dots d\\mathbf{r}_N$.\n\n\n\n## Brief reminder on some linear algebra properties\n\nBefore we proceed with a more compact representation of a Slater determinant, we would like to repeat some linear algebra properties which will be useful for our derivations of the energy as function of a Slater determinant, Hartree-Fock theory and later the nuclear shell model.\n\nThe inverse of a matrix is defined by\n\n$$\n\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n$$\n\nA unitary matrix $\\mathbf{A}$ is one whose inverse is its adjoint\n\n$$\n\\mathbf{A}^{-1}=\\mathbf{A}^{\\dagger}\n$$\n\nA real unitary matrix is called orthogonal and its inverse is equal to its transpose.\nA hermitian matrix is its own self-adjoint, that is\n\n$$\n\\mathbf{A}=\\mathbf{A}^{\\dagger}.\n$$\n\n## Basic Matrix Features\n\n Matrix Properties Reminder\n\n\n\n\n\n\n\n\n\n\n\n\n
    Relations Name matrix elements
    $A = A^{T}$ symmetric $a_{ij} = a_{ji}$
    $A = \\left (A^{T} \\right )^{-1}$ real orthogonal $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$
    $A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$
    $A = A^{\\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$
    $A = \\left (A^{\\dagger} \\right )^{-1}$ unitary $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$
    \n\n\n\n\n## Basic Matrix Features\n\nIf we deal with Fermions (identical and indistinguishable particles) we will \nform an ansatz for a given state in terms of so-called Slater determinants determined\nby a chosen basis of single-particle functions. \n\nFor a given $n\\times n$ matrix $\\mathbf{A}$ we can write its determinant\n\n$$\ndet(\\mathbf{A})=|\\mathbf{A}|=\n\\left| \\begin{array}{ccccc} a_{11}& a_{12}& \\dots & \\dots & a_{1n}\\\\\n a_{21}&a_{22}& \\dots & \\dots & a_{2n}\\\\ \n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n a_{n1}& a_{n2}& \\dots & \\dots & a_{nn}\\end{array} \\right|,\n$$\n\nin a more compact form as\n\n$$\n|\\mathbf{A}|= \\sum_{i=1}^{n!}(-1)^{p_i}\\hat{P}_i a_{11}a_{22}\\dots a_{nn},\n$$\n\nwhere $\\hat{P}_i$ is a permutation operator which permutes the column indices $1,2,3,\\dots,n$\nand the sum runs over all $n!$ permutations. The quantity $p_i$ represents the number of transpositions of column indices that are needed in order to bring a given permutation back to its initial ordering, in our case given by $a_{11}a_{22}\\dots a_{nn}$ here.\n\n\n\n## Basic Matrix Features, simple $2 \\times 2$ determinant\n\nA simple $2\\times 2$ determinant illustrates this. We have\n\n$$\ndet(\\mathbf{A})=\n\\left| \\begin{array}{cc} a_{11}& a_{12}\\\\\n a_{21}&a_{22}\\end{array} \\right|= (-1)^0a_{11}a_{22}+(-1)^1a_{12}a_{21},\n$$\n\nwhere in the last term we have interchanged the column indices $1$ and $2$. The natural ordering we have chosen is $a_{11}a_{22}$. \n\n\n\n\n## Definitions and notations\n\nWith the above we can rewrite our Slater determinant in a more compact form.\nIn the Hartree-Fock method the trial function is the Slater\ndeterminant of Eq. ([7](#eq:HartreeFockDet)) which can be rewritten as\n\n$$\n\\Phi(x_1,x_2,\\dots,x_N,\\alpha,\\beta,\\dots,\\nu) = \\frac{1}{\\sqrt{N!}}\\sum_{P} (-)^P\\hat{P}\\psi_{\\alpha}(x_1)\n \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_N)=\\sqrt{N!}\\hat{A}\\Phi_H,\n$$\n\nwhere we have introduced the antisymmetrization operator $\\hat{A}$ defined by the \nsummation over all possible permutations of two particles.\n\n\n## Definitions and notations\n\nIt is defined as\n\n\n
    \n\n$$\n\\begin{equation}\n \\hat{A} = \\frac{1}{N!}\\sum_{p} (-)^p\\hat{P},\n\\label{antiSymmetryOperator} \\tag{8}\n\\end{equation}\n$$\n\nwith $p$ standing for the number of permutations. We have introduced for later use the so-called\nHartree-function, defined by the simple product of all possible single-particle functions\n\n$$\n\\Phi_H(x_1,x_2,\\dots,x_N,\\alpha,\\beta,\\dots,\\nu) =\n \\psi_{\\alpha}(x_1)\n \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_N).\n$$\n\n## Definitions and notations\n\nBoth $\\hat{H}_0$ and $\\hat{H}_I$ are invariant under all possible permutations of any two particles\nand hence commute with $\\hat{A}$\n\n\n
    \n\n$$\n\\begin{equation}\n [H_0,\\hat{A}] = [H_I,\\hat{A}] = 0. \\label{commutionAntiSym} \\tag{9}\n\\end{equation}\n$$\n\nFurthermore, $\\hat{A}$ satisfies\n\n\n
    \n\n$$\n\\begin{equation}\n \\hat{A}^2 = \\hat{A}, \\label{AntiSymSquared} \\tag{10}\n\\end{equation}\n$$\n\nsince every permutation of the Slater\ndeterminant reproduces it. \n\n\n## Definitions and notations\n\nThe expectation value of $\\hat{H}_0$\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau} \n = N! \\int \\Phi_H^*\\hat{A}\\hat{H}_0\\hat{A}\\Phi_H d\\mathbf{\\tau}\n$$\n\nis readily reduced to\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau} \n = N! \\int \\Phi_H^*\\hat{H}_0\\hat{A}\\Phi_H d\\mathbf{\\tau},\n$$\n\nwhere we have used Eqs. ([9](#commutionAntiSym)) and\n([10](#AntiSymSquared)). The next step is to replace the antisymmetrization\noperator by its definition and to\nreplace $\\hat{H}_0$ with the sum of one-body operators\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau}\n = \\sum_{i=1}^N \\sum_{p} (-)^p\\int \n \\Phi_H^*\\hat{h}_0\\hat{P}\\Phi_H d\\mathbf{\\tau}.\n$$\n\n## Definitions and notations\n\nThe integral vanishes if two or more particles are permuted in only one\nof the Hartree-functions $\\Phi_H$ because the individual single-particle wave functions are\northogonal. We obtain then\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau}= \\sum_{i=1}^N \\int \\Phi_H^*\\hat{h}_0\\Phi_H d\\mathbf{\\tau}.\n$$\n\nOrthogonality of the single-particle functions allows us to further simplify the integral, and we\narrive at the following expression for the expectation values of the\nsum of one-body Hamiltonians\n\n\n
    \n\n$$\n\\begin{equation}\n \\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau}\n = \\sum_{\\mu=1}^N \\int \\psi_{\\mu}^*(\\mathbf{r})\\hat{h}_0\\psi_{\\mu}(\\mathbf{r})\n d\\mathbf{r}.\n\\label{H1Expectation} \\tag{11}\n\\end{equation}\n$$\n\n## Definitions and notations\n\nWe introduce the following shorthand for the above integral\n\n$$\n\\langle \\mu | \\hat{h}_0 | \\mu \\rangle = \\int \\psi_{\\mu}^*(\\mathbf{r})\\hat{h}_0\\psi_{\\mu}(\\mathbf{r}) d\\mathbf{r},\n$$\n\nand rewrite Eq. ([11](#H1Expectation)) as\n\n\n
    \n\n$$\n\\begin{equation}\n \\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau}\n = \\sum_{\\mu=1}^N \\langle \\mu | \\hat{h}_0 | \\mu \\rangle.\n\\label{H1Expectation1} \\tag{12}\n\\end{equation}\n$$\n\n## Definitions and notations\n\nThe expectation value of the two-body part of the Hamiltonian is obtained in a\nsimilar manner. We have\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n = N! \\int \\Phi_H^*\\hat{A}\\hat{H}_I\\hat{A}\\Phi_H d\\mathbf{\\tau},\n$$\n\nwhich reduces to\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n = \\sum_{i\\le j=1}^N \\sum_{p} (-)^p\\int \n \\Phi_H^*V(r_{ij})\\hat{P}\\Phi_H d\\mathbf{\\tau},\n$$\n\nby following the same arguments as for the one-body\nHamiltonian. \n\n\n## Definitions and notations\n\nBecause of the dependence on the inter-particle distance $r_{ij}$, permutations of\nany two particles no longer vanish, and we get\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n = \\sum_{i < j=1}^N \\int \n \\Phi_H^*V(r_{ij})(1-P_{ij})\\Phi_H d\\mathbf{\\tau}.\n$$\n\nwhere $P_{ij}$ is the permutation operator that interchanges\nparticle $i$ and particle $j$. Again we use the assumption that the single-particle wave functions\nare orthogonal. \n\n\n\n## Definitions and notations\n\nWe obtain\n\n\n
    \n\n$$\n\\begin{equation}\n \\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n = \\frac{1}{2}\\sum_{\\mu=1}^N\\sum_{\\nu=1}^N\n \\left[ \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)V(r_{ij})\\psi_{\\mu}(x_i)\\psi_{\\nu}(x_j)\n dx_idx_j \\right.\n\\label{_auto1} \\tag{13}\n\\end{equation}\n$$\n\n\n
    \n\n$$\n\\begin{equation} \n \\left.\n - \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\n V(r_{ij})\\psi_{\\nu}(x_i)\\psi_{\\mu}(x_j)\n dx_idx_j\n \\right]. \\label{H2Expectation} \\tag{14}\n\\end{equation}\n$$\n\nThe first term is the so-called direct term. It is frequently also called the Hartree term, \nwhile the second is due to the Pauli principle and is called\nthe exchange term or just the Fock term.\nThe factor $1/2$ is introduced because we now run over\nall pairs twice. \n\n\n## Definitions and notations\n\nThe last equation allows us to introduce some further definitions. \nThe single-particle wave functions $\\psi_{\\mu}(x)$, defined by the quantum numbers $\\mu$ and $x$\nare defined as the overlap\n\n$$\n\\psi_{\\alpha}(x) = \\langle x | \\alpha \\rangle .\n$$\n\n## Definitions and notations\n\nWe introduce the following shorthands for the above two integrals\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle = \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)V(r_{ij})\\psi_{\\mu}(x_i)\\psi_{\\nu}(x_j)\n dx_idx_j,\n$$\n\nand\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\nu\\mu\\rangle = \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\n V(r_{ij})\\psi_{\\nu}(x_i)\\psi_{\\mu}(x_j)\n dx_idx_j.\n$$\n\n## Definitions and notations\n\nThe direct and exchange matrix elements can be brought together if we define the antisymmetrized matrix element\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}= \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle-\\langle \\mu\\nu|\\hat{v}|\\nu\\mu\\rangle,\n$$\n\nor for a general matrix element\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}= \\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle-\\langle \\mu\\nu|\\hat{v}|\\tau\\sigma\\rangle.\n$$\n\nIt has the symmetry property\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}= -\\langle \\mu\\nu|\\hat{v}|\\tau\\sigma\\rangle_{\\mathrm{AS}}=-\\langle \\nu\\mu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}.\n$$\n\n## Definitions and notations\n\nThe antisymmetric matrix element is also hermitian, implying\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}= \\langle \\sigma\\tau|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}.\n$$\n\nWith these notations we rewrite Eq. ([14](#H2Expectation)) as\n\n\n
    \n\n$$\n\\begin{equation}\n \\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n = \\frac{1}{2}\\sum_{\\mu=1}^N\\sum_{\\nu=1}^N \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}.\n\\label{H2Expectation2} \\tag{15}\n\\end{equation}\n$$\n\n## Definitions and notations\n\nCombining Eqs. ([12](#H1Expectation1)) and\n([15](#H2Expectation2)) we obtain the energy functional\n\n\n
    \n\n$$\n\\begin{equation}\n E[\\Phi] \n = \\sum_{\\mu=1}^N \\langle \\mu | \\hat{h}_0 | \\mu \\rangle +\n \\frac{1}{2}\\sum_{{\\mu}=1}^N\\sum_{{\\nu}=1}^N \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}.\n\\label{FunctionalEPhi} \\tag{16}\n\\end{equation}\n$$\n\nwhich we will use as our starting point for the Hartree-Fock calculations. \n\n\n\n\n## Why Hartree-Fock?\n\nHartree-Fock (HF) theory is an algorithm for finding an approximative expression for the ground state of a given Hamiltonian. The basic ingredients are\n * Define a single-particle basis $\\{\\psi_{\\alpha}\\}$ so that\n\n$$\n\\hat{h}^{\\mathrm{HF}}\\psi_{\\alpha} = \\varepsilon_{\\alpha}\\psi_{\\alpha}\n$$\n\nwith the Hartree-Fock Hamiltonian defined as\n\n$$\n\\hat{h}^{\\mathrm{HF}}=\\hat{t}+\\hat{u}_{\\mathrm{ext}}+\\hat{u}^{\\mathrm{HF}}\n$$\n\n* The term $\\hat{u}^{\\mathrm{HF}}$ is a single-particle potential to be determined by the HF algorithm.\n\n * The HF algorithm means to choose $\\hat{u}^{\\mathrm{HF}}$ in order to have\n\n$$\n\\langle \\hat{H} \\rangle = E^{\\mathrm{HF}}= \\langle \\Phi_0 | \\hat{H}|\\Phi_0 \\rangle\n$$\n\nthat is to find a local minimum with a Slater determinant $\\Phi_0$ being the ansatz for the ground state. \n * The variational principle ensures that $E^{\\mathrm{HF}} \\ge E_0$, with $E_0$ the exact ground state energy.\n\n## Why Hartree-Fock?\n\nWe will show that the Hartree-Fock Hamiltonian $\\hat{h}^{\\mathrm{HF}}$ equals our definition of the operator $\\hat{f}$ discussed in connection with the new definition of the normal-ordered Hamiltonian (see later lectures), that is we have, for a specific matrix element\n\n$$\n\\langle p |\\hat{h}^{\\mathrm{HF}}| q \\rangle =\\langle p |\\hat{f}| q \\rangle=\\langle p|\\hat{t}+\\hat{u}_{\\mathrm{ext}}|q \\rangle +\\sum_{i\\le F} \\langle pi | \\hat{V} | qi\\rangle_{AS},\n$$\n\nmeaning that\n\n$$\n\\langle p|\\hat{u}^{\\mathrm{HF}}|q\\rangle = \\sum_{i\\le F} \\langle pi | \\hat{V} | qi\\rangle_{AS}.\n$$\n\nThe so-called Hartree-Fock potential $\\hat{u}^{\\mathrm{HF}}$ brings an explicit medium dependence due to the summation over all single-particle states below the Fermi level $F$. It brings also in an explicit dependence on the two-body interaction (in nuclear physics we can also have complicated three- or higher-body forces). The two-body interaction, with its contribution from the other bystanding fermions, creates an effective mean field in which a given fermion moves, in addition to the external potential $\\hat{u}_{\\mathrm{ext}}$ which confines the motion of the fermion. For systems like nuclei, there is no external confining potential. Nuclei are examples of self-bound systems, where the binding arises due to the intrinsic nature of the strong force. For nuclear systems thus, there would be no external one-body potential in the Hartree-Fock Hamiltonian. \n\n\n\n## Example system for fermions: quantum dots\n\nWe will deal only with systems where all possible single-particle states below a certain level are filled up. Such systems are called closed shell systems, a naming inspired from atomic and nuclear physics. These closed shell systems define what is frequently named **magic numbers**. Quantum dots exhibit also magic numbers, meaning that the addition or removal of one eletron requires more energy than systems where the lowest-lying shells are not filled. Using the harmonic oscillator in two dimensions as basis functions (with degenerate single-particle energies) the magic numbers are $N=2$, $N=6$, $N=12$, $N=20$ etc, where $N$ is the number of electrons. See the table below for more details. \n\nWe write our Hamiltonian as a one-body part\n\n$$\n\\hat{H}_0=\\sum_{i=1}^{N_e}\\left(-{\\frac{1}{2}}\\nabla^2_{i}+\\frac{ \\omega^2}{2}r^2_{i} \\right),\n$$\n\nand an interacting part\n\n$$\n\\hat{V}=\\sum_{i < j}^{N_e}\\frac{1}{|\\boldsymbol{r}_i-\\boldsymbol{r}_j|}.\n$$\n\nThe unperturbed part of the Hamiltonian yields the single-particle energies\n\n$$\n\\epsilon_i = \\omega\\left(2n+|m| + 1\\right),\n$$\n\nwhere $n = 0,1,2,3,..$ and $m = 0, \\pm 1, \\pm 2,..$. The index $i$ runs from $0,1,2,\\dots$.\n\n\n\n\n\n\n\n## Our integrals\n\nThe integral\n\n$$\n\\langle pq \\vert \\hat{v} \\vert rs \\rangle = A\\int_{-\\infty}^{\\infty}\\int_{-\\infty}^{\\infty}\\int_{-\\infty}^{\\infty}\\int_{-\\infty}^{\\infty} \\exp{[-(x_1^2+x_2^2+y_1^2+y_2^2)/2]}f(x_1,y_1,x_2,y_2)dx_1dy_1dx_2dy_2,\n$$\n\ncan be calculate in analytical form if we switch to polar coordinates. \n\n\n\n\n## Single-particle functions in polar coordinates\n\nInstead of Hermite polynomials it is convenient for the Hartree-Fock calculations to use polar coordinates.\n\n\nUsing polar coordinates\n\n\n
    \n\n$$\n\\begin{equation}\nx = r \\cos \\theta \n\\label{_auto2} \\tag{17}\n\\end{equation}\n$$\n\n\n
    \n\n$$\n\\begin{equation} \ny = r \\sin \\theta \n\\label{_auto3} \\tag{18}\n\\end{equation}\n$$\n\n\n
    \n\n$$\n\\begin{equation} \nr = \\sqrt{x^2 + y^2},\n\\label{_auto4} \\tag{19}\n\\end{equation}\n$$\n\nthe normalized solution for the angular part in two dimensions is\n\n\n
    \n\n$$\nY(\\theta) = \\frac{1}{\\sqrt{2\\pi}} e^{im\\theta}\n \\label{normalized angular part} \\tag{20}\n$$\n\nThe total wavefunction must satisfy the physical condition that $\\psi(r,\\theta) = \\psi(r,\\theta+2\\pi)$ This makes a restriction on the quantum number $m$ which can take integral values\n\n$$\nm = 0, \\pm 1, \\pm 2, ...\n$$\n\n\n## Eigenfunctions in two dimensions\n\nThe time-independent part of the wave function is separated in an angular and a radial part\n\n$$\n\\psi(r,\\theta) = R(r) \\frac{1}{\\sqrt{2\\pi}} e^{im\\theta}, \\qquad m=0,\\pm 1, \\pm 2,...\n$$\n\nThe solution of the radial equation is\n\n$$\nR_{nm}(r) = \\sqrt{\\frac{2n!}{(n+|m|)!}}\\beta^{\\frac{1}{2}(|m|+1)}r^{|m|}e^{-\\frac{1}{2}\\beta r^2} L_n^{|m|} (\\beta r^2)\n$$\n\nHere the subscript $n$ denote the principal quantum number, and $m$ is the angular momentum number\n\n\n
    \n\n$$\n\\begin{equation}\n n = 0, 1, 2, 3, .... \n\\label{_auto5} \\tag{21}\n\\end{equation}\n$$\n\n\n
    \n\n$$\n\\begin{equation} \n m = 0, \\pm 1, \\pm, 2, \\pm 3,...\n\\label{_auto6} \\tag{22}\n\\end{equation}\n$$\n\n$L_n^{|m|}$ is the associated Laguerre polynomials discussed above, and $\\beta$ is defined as\n\n$$\n\\beta = \\frac{m\\omega}{\\hbar}\n$$\n\n## Final expression for the eigenfunction\n\nThe final eigenfunction for an electron moving in a two-dimensional harmonic oscillator is then\n\n$$\n\\psi(r,\\theta) = \\sqrt{\\frac{n!}{\\pi(n+|m|)!}}\\beta^{\\frac{1}{2}(|m|+1)}r^{|m|}e^{-\\frac{1}{2}\\beta r^2} L_n^{|m|} (\\beta r^2) e^{im\\theta},\n$$\n\nwith the eigenvalue\n\n$$\nE = \\hbar \\omega(2n+|m|+1)\n$$\n\nwhich is the same as the energy with cartesian coordinates but now in terms of $n_x$ and $n_y$, that is\n\n$$\nE = \\hbar \\omega(n_x+n_y+1).\n$$\n\n## [Program for computing the Coulomb interaction in polar coordinates](https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/QDCoulombPotential)\n\nThe program is based on the analytical expression given by [Anisimova and Matulis](http://iopscience.iop.org/article/10.1088/0953-8984/10/3/013/pdf). It returns the value of the integral (without checking for spin values, you need to add this test) using as input the quantum numbers\n$n_i$ and $m_i$, that is\n\n$$\n\\langle pq \\vert \\hat{v} \\vert rs \\rangle =\\langle (n_pm_p)(n_qm_q) \\vert \\hat{v} \\vert (n_rm_r)(n_sm_s) \\rangle,\n$$\n\nand the main code is (click on the above link for the full code)\n\n #include \"Coulomb_Functions.hpp\"\n \n int main(int argc, char * argv[])\n {\n if(argc != 10){ std::cerr << \"Wrong Input: should be ./QD_Coulomb hw n1 ml1 n2 ml2 n3 ml3 n4 ml4\" << std::endl; exit(1); }\n double hw = std::atof(argv[1]);\n int n1 = std::atoi(argv[2]);\n int ml1 = std::atoi(argv[3]);\n int n2 = std::atoi(argv[4]);\n int ml2 = std::atoi(argv[5]);\n int n3 = std::atoi(argv[6]);\n int ml3 = std::atoi(argv[7]);\n int n4 = std::atoi(argv[8]);\n int ml4 = std::atoi(argv[9]);\n \n double TBME = Coulomb_HO(hw, n1, ml1, n2, ml2, n3, ml3, n4, ml4);\n std::cout << std::setprecision(12);\n std::cout << \"< \" << n1 << \",\" << ml1 << \" ; \" << n2 << \",\" << ml2 << \" || V || \" << n3 << \",\" << ml3 << \" ; \" << n4 << \",\" << ml4 << \" > = \" << TBME << std::endl;\n \n return 0;\n }\n\n\n## Conserved quantum numbers\n\nWhen setting up the matrix elements\n\n$$\n\\langle pq \\vert \\hat{v} \\vert rs \\rangle =\\langle (n_pm_p)(n_qm_q) \\vert \\hat{v} \\vert (n_rm_r)(n_sm_s) \\rangle,\n$$\n\nyou need to take into account that there are conserved two-electron quantum numbers since the Hamiltonian is invariant under rotations, namely\n\n$$\nm_p+m_q = M = m_r+m_s,\n$$\n\nand the total spin projection which is not included in the above code. You need to add this as a test, that is check that\n\n$$\n\\sigma_p+\\sigma_q = S_z = \\sigma_r+\\sigma_s.\n$$\n\nFinally, you need to ensure that the single-particle spinors satisfy $\\sigma_p=\\sigma_r$ \nand $\\sigma_q=\\sigma_s$. Pay in particular attention to this when you compute the exchange matrix elements. \n\n## Reminder on Variational Calculus and Lagrangian Multipliers\n\nThe calculus of variations involves \nproblems where the quantity to be minimized or maximized is an integral. \n\nIn the general case we have an integral of the type\n\n$$\nE[\\Phi]= \\int_a^b f(\\Phi(x),\\frac{\\partial \\Phi}{\\partial x},x)dx,\n$$\n\nwhere $E$ is the quantity which is sought minimized or maximized.\nThe problem is that although $f$ is a function of the variables $\\Phi$, $\\partial \\Phi/\\partial x$ and $x$, the exact dependence of\n$\\Phi$ on $x$ is not known. This means again that even though the integral has fixed limits $a$ and $b$, the path of integration is\nnot known. In our case the unknown quantities are the single-particle wave functions and we wish to choose an integration path which makes\nthe functional $E[\\Phi]$ stationary. This means that we want to find minima, or maxima or saddle points. In physics we search normally for minima.\nOur task is therefore to find the minimum of $E[\\Phi]$ so that its variation $\\delta E$ is zero subject to specific\nconstraints. In our case the constraints appear as the integral which expresses the orthogonality of the single-particle wave functions.\nThe constraints can be treated via the technique of Lagrangian multipliers\n\n\n\n## Variational Calculus and Lagrangian Multipliers, simple example\n\nLet us specialize to the expectation value of the energy for one particle in three-dimensions.\nThis expectation value reads\n\n$$\nE=\\int dxdydz \\psi^*(x,y,z) \\hat{H} \\psi(x,y,z),\n$$\n\nwith the constraint\n\n$$\n\\int dxdydz \\psi^*(x,y,z) \\psi(x,y,z)=1,\n$$\n\nand a Hamiltonian\n\n$$\n\\hat{H}=-\\frac{1}{2}\\nabla^2+V(x,y,z).\n$$\n\nWe will, for the sake of notational convenience, skip the variables $x,y,z$ below, and write for example $V(x,y,z)=V$.\n\n\n## Manipulating terms\n\nThe integral involving the kinetic energy can be written as, with the function $\\psi$ vanishing\nstrongly for large values of $x,y,z$ (given here by the limits $a$ and $b$),\n\n$$\n\\int_a^b dxdydz \\psi^* \\left(-\\frac{1}{2}\\nabla^2\\right) \\psi dxdydz = \\psi^*\\nabla\\psi|_a^b+\\int_a^b dxdydz\\frac{1}{2}\\nabla\\psi^*\\nabla\\psi.\n$$\n\nWe will drop the limits $a$ and $b$ in the remaining discussion. \nInserting this expression into the expectation value for the energy and taking the variational minimum we obtain\n\n$$\n\\delta E = \\delta \\left\\{\\int dxdydz\\left( \\frac{1}{2}\\nabla\\psi^*\\nabla\\psi+V\\psi^*\\psi\\right)\\right\\} = 0.\n$$\n\n## Adding the Lagrangian multiplier\n\nThe constraint appears in integral form as\n\n$$\n\\int dxdydz \\psi^* \\psi=\\mathrm{constant},\n$$\n\nand multiplying with a Lagrangian multiplier $\\lambda$ and taking the variational minimum we obtain the final variational equation\n\n$$\n\\delta \\left\\{\\int dxdydz\\left( \\frac{1}{2}\\nabla\\psi^*\\nabla\\psi+V\\psi^*\\psi-\\lambda\\psi^*\\psi\\right)\\right\\} = 0.\n$$\n\nWe introduce the function $f$\n\n$$\nf = \\frac{1}{2}\\nabla\\psi^*\\nabla\\psi+V\\psi^*\\psi-\\lambda\\psi^*\\psi=\n\\frac{1}{2}(\\psi^*_x\\psi_x+\\psi^*_y\\psi_y+\\psi^*_z\\psi_z)+V\\psi^*\\psi-\\lambda\\psi^*\\psi,\n$$\n\nwhere we have skipped the dependence on $x,y,z$ and introduced the shorthand $\\psi_x$, $\\psi_y$ and $\\psi_z$ for the various derivatives.\n\n\n## And with the Euler-Lagrange equations we get\n\nFor $\\psi^*$ the Euler-Lagrange equations yield\n\n$$\n\\frac{\\partial f}{\\partial \\psi^*}- \\frac{\\partial }{\\partial x}\\frac{\\partial f}{\\partial \\psi^*_x}-\\frac{\\partial }{\\partial y}\\frac{\\partial f}{\\partial \\psi^*_y}-\\frac{\\partial }{\\partial z}\\frac{\\partial f}{\\partial \\psi^*_z}=0,\n$$\n\nwhich results in\n\n$$\n-\\frac{1}{2}(\\psi_{xx}+\\psi_{yy}+\\psi_{zz})+V\\psi=\\lambda \\psi.\n$$\n\nWe can then identify the Lagrangian multiplier as the energy of the system. The last equation is \nnothing but the standard \nSchroedinger equation and the variational approach discussed here provides \na powerful method for obtaining approximate solutions of the wave function.\n\n\n\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nIn deriving the Hartree-Fock equations, we will expand the single-particle functions in a known basis and vary the coefficients, \nthat is, the new single-particle wave function is written as a linear expansion\nin terms of a fixed chosen orthogonal basis (for example the well-known harmonic oscillator functions or the hydrogen-like functions etc).\nWe define our new Hartree-Fock single-particle basis by performing a unitary transformation \non our previous basis (labelled with greek indices) as\n\n\n
    \n\n$$\n\\begin{equation}\n\\psi_p^{HF} = \\sum_{\\lambda} C_{p\\lambda}\\phi_{\\lambda}. \\label{eq:newbasis} \\tag{23}\n\\end{equation}\n$$\n\nIn this case we vary the coefficients $C_{p\\lambda}$. If the basis has infinitely many solutions, we need\nto truncate the above sum. We assume that the basis $\\phi_{\\lambda}$ is orthogonal. A unitary transformation keeps the orthogonality, as discussed in exercise 1 below. \n\n\n## More on linear algebra\n\nIn the previous slide we stated that a unitary transformation keeps the orthogonality, as discussed in exercise 1 below. To see this consider first a basis of vectors $\\mathbf{v}_i$,\n\n$$\n\\mathbf{v}_i = \\begin{bmatrix} v_{i1} \\\\ \\dots \\\\ \\dots \\\\v_{in} \\end{bmatrix}\n$$\n\nWe assume that the basis is orthogonal, that is\n\n$$\n\\mathbf{v}_j^T\\mathbf{v}_i = \\delta_{ij}.\n$$\n\nAn orthogonal or unitary transformation\n\n$$\n\\mathbf{w}_i=\\mathbf{U}\\mathbf{v}_i,\n$$\n\npreserves the dot product and orthogonality since\n\n$$\n\\mathbf{w}_j^T\\mathbf{w}_i=(\\mathbf{U}\\mathbf{v}_j)^T\\mathbf{U}\\mathbf{v}_i=\\mathbf{v}_j^T\\mathbf{U}^T\\mathbf{U}\\mathbf{v}_i= \\mathbf{v}_j^T\\mathbf{v}_i = \\delta_{ij}.\n$$\n\n## Coefficients of a wave function expansion\n\nThis means that if the coefficients $C_{p\\lambda}$ belong to a unitary or orthogonal trasformation (using the Dirac bra-ket notation)\n\n$$\n\\vert p\\rangle = \\sum_{\\lambda} C_{p\\lambda}\\vert\\lambda\\rangle,\n$$\n\northogonality is preserved, that is $\\langle \\alpha \\vert \\beta\\rangle = \\delta_{\\alpha\\beta}$\nand $\\langle p \\vert q\\rangle = \\delta_{pq}$. \n\nThis propertry is extremely useful when we build up a basis of many-body Stater determinant based states. \n\n**Note also that although a basis $\\vert \\alpha\\rangle$ contains an infinity of states, for practical calculations we have always to make some truncations.** \n\n\n\n\n## More Basic Matrix Features, simple $2 \\times 2$ determinant, useful property of determinants\n\nBefore we develop the Hartree-Fock equations, there is another very useful property of determinants that we will use both in connection with Hartree-Fock calculations and later shell-model calculations. \n\nConsider the following determinant\n\n$$\n\\left| \\begin{array}{cc} \\alpha_1b_{11}+\\alpha_2sb_{12}& a_{12}\\\\\n \\alpha_1b_{21}+\\alpha_2b_{22}&a_{22}\\end{array} \\right|=\\alpha_1\\left|\\begin{array}{cc} b_{11}& a_{12}\\\\\n b_{21}&a_{22}\\end{array} \\right|+\\alpha_2\\left| \\begin{array}{cc} b_{12}& a_{12}\\\\b_{22}&a_{22}\\end{array} \\right|\n$$\n\n## More Basic Matrix Features, $n \\times n$ determinant\n\nWe can generalize this to an $n\\times n$ matrix and have\n\n$$\n\\left| \\begin{array}{cccccc} a_{11}& a_{12} & \\dots & \\sum_{k=1}^n c_k b_{1k} &\\dots & a_{1n}\\\\\na_{21}& a_{22} & \\dots & \\sum_{k=1}^n c_k b_{2k} &\\dots & a_{2n}\\\\\n\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\na_{n1}& a_{n2} & \\dots & \\sum_{k=1}^n c_k b_{nk} &\\dots & a_{nn}\\end{array} \\right|=\n\\sum_{k=1}^n c_k\\left| \\begin{array}{cccccc} a_{11}& a_{12} & \\dots & b_{1k} &\\dots & a_{1n}\\\\\na_{21}& a_{22} & \\dots & b_{2k} &\\dots & a_{2n}\\\\\n\\dots & \\dots & \\dots & \\dots & \\dots & \\dots\\\\\n\\dots & \\dots & \\dots & \\dots & \\dots & \\dots\\\\\na_{n1}& a_{n2} & \\dots & b_{nk} &\\dots & a_{nn}\\end{array} \\right| .\n$$\n\nThis is a property we will use in our Hartree-Fock discussions. \n\n\n\n\n\n\n## More Basic Matrix Features, a general $n \\times n$ determinant\n\nWe can generalize the previous results, now \nwith all elements $a_{ij}$ being given as functions of \nlinear combinations of various coefficients $c$ and elements $b_{ij}$,\n\n$$\n\\left| \\begin{array}{cccccc} \\sum_{k=1}^n b_{1k}c_{k1}& \\sum_{k=1}^n b_{1k}c_{k2} & \\dots & \\sum_{k=1}^n b_{1k}c_{kj} &\\dots & \\sum_{k=1}^n b_{1k}c_{kn}\\\\\n\\sum_{k=1}^n b_{2k}c_{k1}& \\sum_{k=1}^n b_{2k}c_{k2} & \\dots & \\sum_{k=1}^n b_{2k}c_{kj} &\\dots & \\sum_{k=1}^n b_{2k}c_{kn}\\\\\n\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n\\dots & \\dots & \\dots & \\dots & \\dots &\\dots \\\\\n\\sum_{k=1}^n b_{nk}c_{k1}& \\sum_{k=1}^n b_{nk}c_{k2} & \\dots & \\sum_{k=1}^n b_{nk}c_{kj} &\\dots & \\sum_{k=1}^n b_{nk}c_{kn}\\end{array} \\right|=det(\\mathbf{C})det(\\mathbf{B}),\n$$\n\nwhere $det(\\mathbf{C})$ and $det(\\mathbf{B})$ are the determinants of $n\\times n$ matrices\nwith elements $c_{ij}$ and $b_{ij}$ respectively. \nThis is a property we will use in our Hartree-Fock discussions. Convince yourself about the correctness of the above expression by setting $n=2$. \n\n\n\n\n\n## A general Slater determinant\n\nWith our definition of the new basis in terms of an orthogonal basis we have\n\n$$\n\\psi_p(x) = \\sum_{\\lambda} C_{p\\lambda}\\phi_{\\lambda}(x).\n$$\n\nIf the coefficients $C_{p\\lambda}$ belong to an orthogonal or unitary matrix, the new basis\nis also orthogonal. \nOur Slater determinant in the new basis $\\psi_p(x)$ is written as\n\n$$\n\\frac{1}{\\sqrt{A!}}\n\\left| \\begin{array}{ccccc} \\psi_{p}(x_1)& \\psi_{p}(x_2)& \\dots & \\dots & \\psi_{p}(x_A)\\\\\n \\psi_{q}(x_1)&\\psi_{q}(x_2)& \\dots & \\dots & \\psi_{q}(x_A)\\\\ \n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n \\psi_{t}(x_1)&\\psi_{t}(x_2)& \\dots & \\dots & \\psi_{t}(x_A)\\end{array} \\right|=\\frac{1}{\\sqrt{A!}}\n\\left| \\begin{array}{ccccc} \\sum_{\\lambda} C_{p\\lambda}\\phi_{\\lambda}(x_1)& \\sum_{\\lambda} C_{p\\lambda}\\phi_{\\lambda}(x_2)& \\dots & \\dots & \\sum_{\\lambda} C_{p\\lambda}\\phi_{\\lambda}(x_A)\\\\\n \\sum_{\\lambda} C_{q\\lambda}\\phi_{\\lambda}(x_1)&\\sum_{\\lambda} C_{q\\lambda}\\phi_{\\lambda}(x_2)& \\dots & \\dots & \\sum_{\\lambda} C_{q\\lambda}\\phi_{\\lambda}(x_A)\\\\ \n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n \\sum_{\\lambda} C_{t\\lambda}\\phi_{\\lambda}(x_1)&\\sum_{\\lambda} C_{t\\lambda}\\phi_{\\lambda}(x_2)& \\dots & \\dots & \\sum_{\\lambda} C_{t\\lambda}\\phi_{\\lambda}(x_A)\\end{array} \\right|,\n$$\n\nwhich is nothing but $det(\\mathbf{C})det(\\Phi)$, with $det(\\Phi)$ being the determinant given by the basis functions $\\phi_{\\lambda}(x)$. \n\n\n\n\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nIt is normal to choose a single-particle basis defined as the eigenfunctions\nof parts of the full Hamiltonian. The typical situation consists of the solutions of the one-body part of the Hamiltonian, that is we have\n\n$$\n\\hat{h}_0\\phi_{\\lambda}=\\epsilon_{\\lambda}\\phi_{\\lambda}.\n$$\n\nThe single-particle wave functions $\\phi_{\\lambda}(\\boldsymbol{r})$, defined by the quantum numbers $\\lambda$ and $\\boldsymbol{r}$\nare defined as the overlap\n\n$$\n\\phi_{\\lambda}(\\boldsymbol{r}) = \\langle \\boldsymbol{r} | \\lambda \\rangle .\n$$\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nIn our discussions hereafter we will use our definitions of single-particle states above and below the Fermi ($F$) level given by the labels\n$ijkl\\dots \\le F$ for so-called single-hole states and $abcd\\dots > F$ for so-called particle states.\nFor general single-particle states we employ the labels $pqrs\\dots$. \n\n\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nIn Eq. ([16](#FunctionalEPhi)), restated here\n\n$$\nE[\\Phi] \n = \\sum_{\\mu=1}^A \\langle \\mu | h | \\mu \\rangle +\n \\frac{1}{2}\\sum_{{\\mu}=1}^A\\sum_{{\\nu}=1}^A \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{AS},\n$$\n\nwe found the expression for the energy functional in terms of the basis function $\\phi_{\\lambda}(\\boldsymbol{r})$. We then varied the above energy functional with respect to the basis functions $|\\mu \\rangle$. \nNow we are interested in defining a new basis defined in terms of\na chosen basis as defined in Eq. ([23](#eq:newbasis)). We can then rewrite the energy functional as\n\n\n
    \n\n$$\n\\begin{equation}\n E[\\Phi^{HF}] \n = \\sum_{i=1}^A \\langle i | h | i \\rangle +\n \\frac{1}{2}\\sum_{ij=1}^A\\langle ij|\\hat{v}|ij\\rangle_{AS}, \\label{FunctionalEPhi2} \\tag{24}\n\\end{equation}\n$$\n\nwhere $\\Phi^{HF}$ is the new Slater determinant defined by the new basis of Eq. ([23](#eq:newbasis)). \n\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nUsing Eq. ([23](#eq:newbasis)) we can rewrite Eq. ([24](#FunctionalEPhi2)) as\n\n\n
    \n\n$$\n\\begin{equation}\n E[\\Psi] \n = \\sum_{i=1}^A \\sum_{\\alpha\\beta} C^*_{i\\alpha}C_{i\\beta}\\langle \\alpha | h | \\beta \\rangle +\n \\frac{1}{2}\\sum_{ij=1}^A\\sum_{{\\alpha\\beta\\gamma\\delta}} C^*_{i\\alpha}C^*_{j\\beta}C_{i\\gamma}C_{j\\delta}\\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle_{AS}. \\label{FunctionalEPhi3} \\tag{25}\n\\end{equation}\n$$\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nWe wish now to minimize the above functional. We introduce again a set of Lagrange multipliers, noting that\nsince $\\langle i | j \\rangle = \\delta_{i,j}$ and $\\langle \\alpha | \\beta \\rangle = \\delta_{\\alpha,\\beta}$, \nthe coefficients $C_{i\\gamma}$ obey the relation\n\n$$\n\\langle i | j \\rangle=\\delta_{i,j}=\\sum_{\\alpha\\beta} C^*_{i\\alpha}C_{i\\beta}\\langle \\alpha | \\beta \\rangle=\n\\sum_{\\alpha} C^*_{i\\alpha}C_{i\\alpha},\n$$\n\nwhich allows us to define a functional to be minimized that reads\n\n\n
    \n\n$$\n\\begin{equation}\n F[\\Phi^{HF}]=E[\\Phi^{HF}] - \\sum_{i=1}^A\\epsilon_i\\sum_{\\alpha} C^*_{i\\alpha}C_{i\\alpha}.\n\\label{_auto7} \\tag{26}\n\\end{equation}\n$$\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nMinimizing with respect to $C^*_{i\\alpha}$, remembering that the equations for $C^*_{i\\alpha}$ and $C_{i\\alpha}$\ncan be written as two independent equations, we obtain\n\n$$\n\\frac{d}{dC^*_{i\\alpha}}\\left[ E[\\Phi^{HF}] - \\sum_{j}\\epsilon_j\\sum_{\\alpha} C^*_{j\\alpha}C_{j\\alpha}\\right]=0,\n$$\n\nwhich yields for every single-particle state $i$ and index $\\alpha$ (recalling that the coefficients $C_{i\\alpha}$ are matrix elements of a unitary (or orthogonal for a real symmetric matrix) matrix)\nthe following Hartree-Fock equations\n\n$$\n\\sum_{\\beta} C_{i\\beta}\\langle \\alpha | h | \\beta \\rangle+\n\\sum_{j=1}^A\\sum_{\\beta\\gamma\\delta} C^*_{j\\beta}C_{j\\delta}C_{i\\gamma}\\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle_{AS}=\\epsilon_i^{HF}C_{i\\alpha}.\n$$\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nWe can rewrite this equation as (changing dummy variables)\n\n$$\n\\sum_{\\beta} \\left\\{\\langle \\alpha | h | \\beta \\rangle+\n\\sum_{j}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}\\right\\}C_{i\\beta}=\\epsilon_i^{HF}C_{i\\alpha}.\n$$\n\nNote that the sums over greek indices run over the number of basis set functions (in principle an infinite number).\n\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nDefining\n\n$$\nh_{\\alpha\\beta}^{HF}=\\langle \\alpha | h | \\beta \\rangle+\n\\sum_{j=1}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS},\n$$\n\nwe can rewrite the new equations as\n\n\n
    \n\n$$\n\\begin{equation}\n\\sum_{\\gamma}h_{\\alpha\\beta}^{HF}C_{i\\beta}=\\epsilon_i^{HF}C_{i\\alpha}. \\label{eq:newhf} \\tag{27}\n\\end{equation}\n$$\n\nThe latter is nothing but a standard eigenvalue problem. \n\nIt suffices to tabulate the matrix elements $\\langle \\alpha | h | \\beta \\rangle$ and $\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}$ once and for all. Successive iterations require thus only a look-up in tables over one-body and two-body matrix elements. These details will be discussed below when we solve the Hartree-Fock equations numerically. \n\n\n## Hartree-Fock algorithm\n\nOur Hartree-Fock matrix is thus\n\n$$\n\\hat{h}_{\\alpha\\beta}^{HF}=\\langle \\alpha | \\hat{h}_0 | \\beta \\rangle+\n\\sum_{j=1}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\nThe Hartree-Fock equations are solved in an iterative waym starting with a guess for the coefficients $C_{j\\gamma}=\\delta_{j,\\gamma}$ and solving the equations by diagonalization till the new single-particle energies\n$\\epsilon_i^{\\mathrm{HF}}$ do not change anymore by a prefixed quantity. \n\n\n## Hartree-Fock algorithm\n\nNormally we assume that the single-particle basis $|\\beta\\rangle$ forms an eigenbasis for the operator\n$\\hat{h}_0$, meaning that the Hartree-Fock matrix becomes\n\n$$\n\\hat{h}_{\\alpha\\beta}^{HF}=\\epsilon_{\\alpha}\\delta_{\\alpha,\\beta}+\n\\sum_{j=1}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\nThe Hartree-Fock eigenvalue problem\n\n$$\n\\sum_{\\beta}\\hat{h}_{\\alpha\\beta}^{HF}C_{i\\beta}=\\epsilon_i^{\\mathrm{HF}}C_{i\\alpha},\n$$\n\ncan be written out in a more compact form as\n\n$$\n\\hat{h}^{HF}\\hat{C}=\\epsilon^{\\mathrm{HF}}\\hat{C}.\n$$\n\n## Hartree-Fock algorithm\n\nThe Hartree-Fock equations are, in their simplest form, solved in an iterative way, starting with a guess for the\ncoefficients $C_{i\\alpha}$. We label the coefficients as $C_{i\\alpha}^{(n)}$, where the subscript $n$ stands for iteration $n$.\nTo set up the algorithm we can proceed as follows:\n\n * We start with a guess $C_{i\\alpha}^{(0)}=\\delta_{i,\\alpha}$. Alternatively, we could have used random starting values as long as the vectors are normalized. Another possibility is to give states below the Fermi level a larger weight.\n\n * The Hartree-Fock matrix simplifies then to (assuming that the coefficients $C_{i\\alpha} $ are real)\n\n$$\n\\hat{h}_{\\alpha\\beta}^{HF}=\\epsilon_{\\alpha}\\delta_{\\alpha,\\beta}+\n\\sum_{j = 1}^A\\sum_{\\gamma\\delta} C_{j\\gamma}^{(0)}C_{j\\delta}^{(0)}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\n## Hartree-Fock algorithm\n\nSolving the Hartree-Fock eigenvalue problem yields then new eigenvectors $C_{i\\alpha}^{(1)}$ and eigenvalues\n$\\epsilon_i^{HF(1)}$. \n * With the new eigenvalues we can set up a new Hartree-Fock potential\n\n$$\n\\sum_{j = 1}^A\\sum_{\\gamma\\delta} C_{j\\gamma}^{(1)}C_{j\\delta}^{(1)}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\nThe diagonalization with the new Hartree-Fock potential yields new eigenvectors and eigenvalues.\nThis process is continued till for example\n\n$$\n\\frac{\\sum_{p} |\\epsilon_i^{(n)}-\\epsilon_i^{(n-1)}|}{m} \\le \\lambda,\n$$\n\nwhere $\\lambda$ is a user prefixed quantity ($\\lambda \\sim 10^{-8}$ or smaller) and $p$ runs over all calculated single-particle\nenergies and $m$ is the number of single-particle states.\n\n\n## Analysis of Hartree-Fock equations and Koopman's theorem\n\nWe can rewrite the ground state energy by adding and subtracting $\\hat{u}^{HF}(x_i)$\n\n$$\nE_0^{HF} =\\langle \\Phi_0 | \\hat{H} | \\Phi_0\\rangle = \n\\sum_{i\\le F}^A \\langle i | \\hat{h}_0 +\\hat{u}^{HF}| j\\rangle+ \\frac{1}{2}\\sum_{i\\le F}^A\\sum_{j \\le F}^A\\left[\\langle ij |\\hat{v}|ij \\rangle-\\langle ij|\\hat{v}|ji\\rangle\\right]-\\sum_{i\\le F}^A \\langle i |\\hat{u}^{HF}| i\\rangle,\n$$\n\nwhich results in\n\n$$\nE_0^{HF}\n = \\sum_{i\\le F}^A \\varepsilon_i^{HF} + \\frac{1}{2}\\sum_{i\\le F}^A\\sum_{j \\le F}^A\\left[\\langle ij |\\hat{v}|ij \\rangle-\\langle ij|\\hat{v}|ji\\rangle\\right]-\\sum_{i\\le F}^A \\langle i |\\hat{u}^{HF}| i\\rangle.\n$$\n\nOur single-particle states $ijk\\dots$ are now single-particle states obtained from the solution of the Hartree-Fock equations.\n\n\n## Analysis of Hartree-Fock equations and Koopman's theorem\n\nUsing our definition of the Hartree-Fock single-particle energies we obtain then the following expression for the total ground-state energy\n\n$$\nE_0^{HF}\n = \\sum_{i\\le F}^A \\varepsilon_i - \\frac{1}{2}\\sum_{i\\le F}^A\\sum_{j \\le F}^A\\left[\\langle ij |\\hat{v}|ij \\rangle-\\langle ij|\\hat{v}|ji\\rangle\\right].\n$$\n\nThis form will be used in our discussion of Koopman's theorem.\n\n\n## Analysis of Hartree-Fock equations and Koopman's theorem\n Atomic physics case\nWe have\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)] \n = \\sum_{i=1}^H \\langle i | \\hat{h}_0 | i \\rangle +\n \\frac{1}{2}\\sum_{ij=1}^N\\langle ij|\\hat{v}|ij\\rangle_{AS},\n$$\n\nwhere $\\Phi^{\\mathrm{HF}}(N)$ is the new Slater determinant defined by the new basis of Eq. ([23](#eq:newbasis))\nfor $N$ electrons (same $Z$). If we assume that the single-particle wave functions in the new basis do not change \nwhen we remove one electron or add one electron, we can then define the corresponding energy for the $N-1$ systems as\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N-1)] \n = \\sum_{i=1; i\\ne k}^N \\langle i | \\hat{h}_0 | i \\rangle +\n \\frac{1}{2}\\sum_{ij=1;i,j\\ne k}^N\\langle ij|\\hat{v}|ij\\rangle_{AS},\n$$\n\nwhere we have removed a single-particle state $k\\le F$, that is a state below the Fermi level. \n\n\n## Analysis of Hartree-Fock equations and Koopman's theorem\n\nCalculating the difference\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)]- E[\\Phi^{\\mathrm{HF}}(N-1)] = \\langle k | \\hat{h}_0 | k \\rangle +\n \\frac{1}{2}\\sum_{i=1;i\\ne k}^N\\langle ik|\\hat{v}|ik\\rangle_{AS} \\frac{1}{2}\\sum_{j=1;j\\ne k}^N\\langle kj|\\hat{v}|kj\\rangle_{AS},\n$$\n\nwe obtain\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)]- E[\\Phi^{\\mathrm{HF}}(N-1)] = \\langle k | \\hat{h}_0 | k \\rangle +\n \\frac{1}{2}\\sum_{j=1}^N\\langle kj|\\hat{v}|kj\\rangle_{AS}\n$$\n\nwhich is just our definition of the Hartree-Fock single-particle energy\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)]- E[\\Phi^{\\mathrm{HF}}(N-1)] = \\epsilon_k^{\\mathrm{HF}}\n$$\n\n## Analysis of Hartree-Fock equations and Koopman's theorem\n\nSimilarly, we can now compute the difference (we label the single-particle states above the Fermi level as $abcd > F$)\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N+1)]- E[\\Phi^{\\mathrm{HF}}(N)]= \\epsilon_a^{\\mathrm{HF}}.\n$$\n\nThese two equations can thus be used to the electron affinity or ionization energies, respectively. \nKoopman's theorem states that for example the ionization energy of a closed-shell system is given by the energy of the highest occupied single-particle state. If we assume that changing the number of electrons from $N$ to $N+1$ does not change the Hartree-Fock single-particle energies and eigenfunctions, then Koopman's theorem simply states that the ionization energy of an atom is given by the single-particle energy of the last bound state. In a similar way, we can also define the electron affinities. \n\n\n## Analysis of Hartree-Fock equations and Koopman's theorem\n\nAs an example, consider a simple model for atomic sodium, Na. Neutral sodium has eleven electrons, \nwith the weakest bound one being confined the $3s$ single-particle quantum numbers. The energy needed to remove an electron from neutral sodium is rather small, 5.1391 eV, a feature which pertains to all alkali metals.\nHaving performed a Hartree-Fock calculation for neutral sodium would then allows us to compute the\nionization energy by using the single-particle energy for the $3s$ states, namely $\\epsilon_{3s}^{\\mathrm{HF}}$. \n\nFrom these considerations, we see that Hartree-Fock theory allows us to make a connection between experimental \nobservables (here ionization and affinity energies) and the underlying interactions between particles. \nIn this sense, we are now linking the dynamics and structure of a many-body system with the laws of motion which govern the system. Our approach is a reductionistic one, meaning that we want to understand the laws of motion \nin terms of the particles or degrees of freedom which we believe are the fundamental ones. Our Slater determinant, being constructed as the product of various single-particle functions, follows this philosophy.\n\n\n\n\n\n## Developing a Hartree-Fock program\n\n\nThe Hamiltonian for a system of $N$ electrons confined in a\nharmonic potential reads\n\n$$\n\\hat{H} = \\sum_{i=1}^{N} \\frac{\\hat{p}_{i}^{2}}{2m}+\\sum_{i=1}^{N} \\frac{1}{2} m\\omega {r}_{i}^{2}+\\sum_{i\n
    \n\n$$\n\\begin{equation}\n\\rho_{\\gamma\\delta}=\\sum_{i=1}^{N}\\langle\\gamma|i\\rangle\\langle i|\\delta\\rangle = \\sum_{i=1}^{N}C_{i\\gamma}C^*_{i\\delta}.\n\\label{_auto8} \\tag{28}\n\\end{equation}\n$$\n\nIt means that we can rewrite the Hartree-Fock Hamiltonian as\n\n$$\n\\hat{h}_{\\alpha\\beta}^{HF}=\\epsilon_{\\alpha}\\delta_{\\alpha,\\beta}+\n\\sum_{\\gamma\\delta} \\rho_{\\gamma\\delta}\\langle \\alpha\\gamma|V|\\beta\\delta\\rangle_{AS}.\n$$\n\nIt is convenient to use the density matrix since we can precalculate in every iteration the product of two eigenvector components $C$. \n\n\n## [Program for computing the Coulomb interaction in polar coordinates](https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/HFcode/python/hf.py)\n\nHere we show a simple code in python for a Hartree-Fock calculation using precalculated matrix elements.\n\n\n```\nimport numpy as np \nfrom decimal import Decimal\n# expectation value for the one body part, Harmonic oscillator in three dimensions\ndef onebody(i, n, l):\n\thomega = 10.0\n\treturn homega*(2*n[i] + l[i] + 1.5)\n\nif __name__ == '__main__':\n\t\n Nparticles = 16\n\t\"\"\" Read quantum numbers from file \"\"\"\n index = []\n\tn = []\n l = []\n j = []\t\n mj = []\n tz = []\n\tspOrbitals = 0\n\twith open(\"nucleispnumbers.dat\", \"r\") as qnumfile:\n\t\tfor line in qnumfile:\n\t\t\tnums = line.split()\n\t\t\tif len(nums) != 0:\n\t\t\t\tindex.append(int(nums[0]))\n\t\t\t\tn.append(int(nums[1]))\n\t\t\t\tl.append(int(nums[2]))\n\t\t\t\tj.append(int(nums[3]))\n\t\t\t\tmj.append(int(nums[4]))\n\t\t\t\ttz.append(int(nums[5]))\n\t\t\t\tspOrbitals += 1\n\n\n\t\"\"\" Read two-nucleon interaction elements (integrals) from file, brute force 4-dim array \"\"\"\n\tnninteraction = np.zeros([spOrbitals, spOrbitals, spOrbitals, spOrbitals])\n\twith open(\"nucleitwobody.dat\", \"r\") as infile:\n\t\tfor line in infile:\n\t\t\tnumber = line.split()\n\t\t\ta = int(number[0]) - 1\n\t\t\tb = int(number[1]) - 1\n\t\t\tc = int(number[2]) - 1\n\t\t\td = int(number[3]) - 1\n\t\t\t#print a, b, c, d, float(l[4])\n\t\t\tnninteraction[a][b][c][d] = Decimal(number[4])\n\t\"\"\" Set up single-particle integral \"\"\"\n\tsingleparticleH = np.zeros(spOrbitals)\n\tfor i in range(spOrbitals):\n\t\tsingleparticleH[i] = Decimal(onebody(i, n, l))\n\t\n\t\"\"\" Star HF-iterations, preparing variables and density matrix \"\"\"\n\n \"\"\" Coefficients for setting up density matrix, assuming only one along the diagonals \"\"\"\n\tC = np.eye(spOrbitals) # HF coefficients\n DensityMatrix = np.zeros([spOrbitals,spOrbitals])\n for gamma in range(spOrbitals):\n for delta in range(spOrbitals):\n sum = 0.0\n for i in range(Nparticles):\n sum += C[gamma][i]*C[delta][i]\n DensityMatrix[gamma][delta] = Decimal(sum)\n maxHFiter = 100\n epsilon = 1.0e-5 \n difference = 1.0\n\thf_count = 0\n\toldenergies = np.zeros(spOrbitals)\n\tnewenergies = np.zeros(spOrbitals)\n\twhile hf_count < maxHFiter and difference > epsilon:\n\t\tprint \"############### Iteration %i ###############\" % hf_count\n \t HFmatrix = np.zeros([spOrbitals,spOrbitals])\t\t\n\t\tfor alpha in range(spOrbitals):\n\t\t\tfor beta in range(spOrbitals):\n \"\"\" If tests for three-dimensional systems, including isospin conservation \"\"\"\n if l[alpha] != l[beta] and j[alpha] != j[beta] and mj[alpha] != mj[beta] and tz[alpha] != tz[beta]: continue\n \"\"\" Setting up the Fock matrix using the density matrix and antisymmetrized NN interaction in m-scheme \"\"\"\n \t\t sumFockTerm = 0.0\n for gamma in range(spOrbitals):\n for delta in range(spOrbitals):\n if (mj[alpha]+mj[gamma]) != (mj[beta]+mj[delta]) and (tz[alpha]+tz[gamma]) != (tz[beta]+tz[delta]): continue\n sumFockTerm += DensityMatrix[gamma][delta]*nninteraction[alpha][gamma][beta][delta]\n HFmatrix[alpha][beta] = Decimal(sumFockTerm)\n \"\"\" Adding the one-body term, here plain harmonic oscillator \"\"\"\n if beta == alpha: HFmatrix[alpha][alpha] += singleparticleH[alpha]\n\t\tspenergies, C = np.linalg.eigh(HFmatrix)\n \"\"\" Setting up new density matrix in m-scheme \"\"\"\n DensityMatrix = np.zeros([spOrbitals,spOrbitals])\n for gamma in range(spOrbitals):\n for delta in range(spOrbitals):\n sum = 0.0\n for i in range(Nparticles):\n sum += C[gamma][i]*C[delta][i]\n DensityMatrix[gamma][delta] = Decimal(sum)\n\t\tnewenergies = spenergies\n \"\"\" Brute force computation of difference between previous and new sp HF energies \"\"\"\n sum =0.0\n for i in range(spOrbitals):\n sum += (abs(newenergies[i]-oldenergies[i]))/spOrbitals\n difference = sum\n oldenergies = newenergies\n print \"Single-particle energies, ordering may have changed \"\n for i in range(spOrbitals):\n print('{0:4d} {1:.4f}'.format(i, Decimal(oldenergies[i])))\n\t\thf_count += 1\n```\n\n\n## Practicalities with the Hartree-Fock code development, basis construction\nWhen setting up the Hartree-Fock algorithm you will find it convenient to number the basis states\nby filling the lowest subshells. For the first two shells we could then have the following mapping.\n\n$$\n\\begin{align*}\n \\vert 0\\rangle & = \\{n=0, m=0, m_s = -0.5\\} \\\\ \n \\vert 1\\rangle & = \\{n=0, m=0, m_s = 0.5\\} \\\\\n \\vert 2\\rangle & = \\{n=0, m=-1, m_s = -0.5\\} \\\\\n \\vert 3\\rangle & = \\{n=0, m=-1, m_s = 0.5\\} \\\\\n \\vert 4\\rangle & = \\{n=0, m=+1, m_s = -0.5\\} \\\\\n \\vert 5\\rangle & = \\{n=0, m=+1, m_s = 0.5\\} \n\\end{align*}\n$$\n\n\n## Practicalities with the Hartree-Fock code development, two-body basis construction, brute force\nIn the setup of the two-body matrix elements we can typically opt between two alternatives. We can read the matrix elements from file or calculate the matrix elements on the fly. The latter requires simply that we \ncall the abovementioned function for setting up the two-body matrix elements when we run our Hartree-Fock code. \n\nIf we however wish to read from file, we can store the matrix elements in two ways:\n* Brute force\n\n* Organize according to conserved two-body quantum numbers\n\nThe brute force way is easy to implement. \n\n\n## Two-body interaction, brute force part I\nWe can read in from file the two-body interaction matrix elements or compute once and for all and store in\nmemory.\nThe elements are\n\n$$\n\\langle pr | \\hat{v}|qs\\rangle.\n$$\n\nThe time-consuming part in the Hartree-Fock calculations\ninvolves the calculation of the two-body matrix. Furthermore, the\nstorage of these matrix elements plays also an important role, in\nparticular we wish to access the table of matrix elements as fast as\npossible. \n\n\n## Two-body interaction, brute force part II\nIn a brute force algorithm for storing the matrix elements, if we have $d$ basis functions, we end up with the need of storing \n$d^4$ matrix elements. We can reduce this considerably by the following considerations.\nIn the calculation of the two-body matrix elements $\\langle pr | \\hat{v}|qs\\rangle$ we have the following symmetries\n\n1. Invariance under permutations, that is\n\n$$\n\\langle pq | \\hat{v}|rs\\rangle = \\langle qp | \\hat{v}|sr\\rangle.\n$$\n\n1. The functions entering the evaluation of the integrals are all real, meaning that if we interchange $p\\leftrightarrow q$ or $r\\leftrightarrow s$, we end up with the same matrix element.\n\nThis reduces by a factor of eight the total number of matrix elements to be stored if we also use that \nwe can store only for $p < q$ and $ r < s$. \n\n\n\n## Two-body interaction, brute force part III\n\nFurthermore, in setting up a table for the two-body matrix elements we can convert the need of using four indices $pqrs$ of\n\n$$\n\\langle pr | \\hat{v}|qs\\rangle,\n$$\n\nwhich in a brute forces way could be coded as a four-dimensional array, to \na two-dimensional array $V_{lm}$, where $l$ and $m$ stand for all possible two-body configurations $pq$.\n\nEach number $l$ and $m$ in $V_{lm}$ should then point to a set of single-particle states $(p,q)$ and $(r,s)$. \n\nIn our case, since we have \nsymmetries which allow us to set $p\\le q$, we have, with $d$ single particle states a total of $d(d+1)/2$ two-body configurations.\n\n\n## Two-body interaction, brute force part IV\n\nHow do we store such a matrix? The simplest thing to do is to convert it into a one-dimensional array. How do we achieve that? \n\nWe now have a matrix $V$ of dimension $n\\times n$ and we want to store the elements $V_{lm}$ as a one-dimensional array $A$ using\n$0 \\le l \\le m \\le n-1$. For\n1. $l=0$ we have $n$ elements\n\n2. $l=1$ we have $n-1$ elements\n\n3. $\\dots$\n\n4. $l=\\nu$ we have $n-\\nu$ elements\n\n5. $\\dots$\n\n6. $l=n-1$ we have $1$ element,\n\nand the total number is\n\n$$\n\\sum_{\\nu =0}^{n-1}\\left(n-\\nu\\right)=\\frac{n(n+1)}{2}.\n$$\n\n\n## Two-body interaction, brute force part V\n\nTo find the number ($\\mathrm{number}(l,m)$) in a one-dimensional array $A$ which corresponds to a matrix element $V_{lm}$, we note that\n\n$$\n\\mathrm{number}(l,m)=\\sum_{\\nu =0}^{l-1}\\left(n-\\nu\\right)+m-l=\\frac{l(2n-l-1)}{2}+m.\n$$\n\nThe first matrix element $V(0,0)$ is obviously given by the element $A(0)$. \n\nWe have thus reduced a four dimensional array to a one-dimensional array, where the given pairs $(p,q)$ and $(r,s)$ point to the matrix indices $l$\nand $m$, respectively. The latter are used to find the explicit number $\\mathrm{number}(l,m)$ which points to the desired matrix element stored \nin a one-dimensional array.\n\n\n\n## Practicalities with the Hartree-Fock code development, two-body basis construction\n\nAnother way to store the matrix elements is to organize the matrix elements according to conserved quantum numbers.\nThis means setting up a block structure and to look up matrix elements using two-body conserved quantum numbers.\nFor quantum dots, the two-body quantum numbers that are conserved are\nThe total orbital momentum projection\n\n$$\nM = m_1 + m_2,\n$$\n\nand the total spin projection\n\n$$\nM_s = m_{s_1} + m_{s_2}\n$$\n\n\n## Two-body basis construction\n\nFor 2 shells we have\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    $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$
    \nIn this table we have paired orbitals with same $M$ and $M_s$. Where $\\alpha \\in \\{0,...,N\\}$ and $N$ is the number of pairs $\\{M,M_s\\}$. Notice that for $\\alpha = 1$ we only have one pair, and for $\\alpha = 4$, we have two pairs.\n\n\n\n\n## Hartree-Fock code\nIn developing our Hartree-Fock code, we can define a configuration class with the following mapping for a single-particle state\n\n$$\n\\vert \\alpha\\rangle \\rightarrow \\vert n m m_s\\rangle,\n$$\n\nand a similar mapping for a two-body state\n\n$$\n\\vert \\alpha \\beta\\rangle \\rightarrow \\vert M M_s\\rangle,\n$$\n\nwhere $M$ is the total angualar momentum\n\n$$\nM = m_\\alpha + m_\\beta,\n$$\n\nand the $M_s$ is the total spin\n\n$$\nM_s = m_{s_1} + m_{s_2}.\n$$\n\n\n## Hartree-Fock code, setting up tables of matrix elements\nThe single-particle part is diagonal for the harmonic oscillator basis, that is\n\n$$\n\\langle \\alpha\\vert \\hat{h}_0\\vert \\beta\\rangle = \\delta_{\\alpha \\beta} \\epsilon_\\alpha\n$$\n\nwith\n\n$$\n\\epsilon_\\alpha = \\hbar\\omega (2n_{\\alpha}+\\vert m_{\\alpha}\\vert +1).\n$$\n\nThe two-body matrix elements are diagonal in the $M$ and $M_s$, that is\n\n$$\n\\langle M M_s\\vert \\hat{v}\\vert M' M_s'\\rangle = \\delta_{M,M'}\\delta_{M_s,M_s'}\\langle MM_s\\vert \\hat{v}\\vert MM_s\\rangle.\n$$\n\n\n## Example calculations, $N=6$ and $\\omega =1.0$ a.u.\n\nWe list here some selected Hartree-Fock results for $N=6$ electrons as function of the number of major shells $R$\nincluded. Here we have $\\omega =1$ a.u.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    $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
    \nThe results are practically converged for approximately $R=10-13$. \n\n\n\n\n## Example calculations, $N=6$ and $\\omega =0.1$ a.u.\n\nWe list here some selected Hartree-Fock results for $N=6$ electrons as function of the number of major shells $R$\nincluded. Here we have $\\omega =0.1$ a.u.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    $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
    \nAgain, the results are practically converged for approximately $R=10-13$.\n", "meta": {"hexsha": "064a2f0727709b8fe68bdaf0e1caeac8ae6728eb", "size": 118164, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/basicMB/ipynb/basicMB.ipynb", "max_stars_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_stars_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 87, "max_stars_repo_stars_event_min_datetime": "2015-01-21T08:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:11:53.000Z", "max_issues_repo_path": "doc/pub/basicMB/ipynb/basicMB.ipynb", "max_issues_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_issues_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-18T10:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T13:15:42.000Z", "max_forks_repo_path": "doc/pub/basicMB/ipynb/basicMB.ipynb", "max_forks_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_forks_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2015-02-09T10:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T10:44:14.000Z", "avg_line_length": 32.0575149213, "max_line_length": 882, "alphanum_fraction": 0.5263447412, "converted": true, "num_tokens": 24154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.1847675061589216, "lm_q1q2_score": 0.06118016853124019}} {"text": "```python\n\"\"\"Tutorial: Symmetry-Adapted Perturbation Theory (SAPT0)\"\"\"\n\n__author__ = [\"Daniel G. A. Smith\", \"Konrad Patkowski\"]\n__credit__ = [\"Daniel G. A. Smith\", \"Konrad Patkowski\"]\n\n__copyright__ = \"(c) 2014-2017, The Psi4NumPy Developers\"\n__license__ = \"BSD-3-Clause\"\n__date__ = \"2017-06-24\"\n```\n\n# Symmetry-Adapted Perturbation Theory (SAPT0)\n\nSymmetry-adapted perturbation theory (SAPT) is a perturbation theory aimed specifically at calculating the interaction energy between two molecules. Compared to the more conventional supermolecular approach where the interaction energy is computed as the difference between the electronic energy of the complex and the sum of electronic energies for the individual molecules (monomers), $E_{\\rm int}=E_{\\rm AB}-E_{\\rm A}-E_{\\rm B}$, SAPT obtains the interaction energy directly - no subtraction of similar terms is needed. Even more important, the result is obtained as a sum of separate corrections accounting for the electrostatic, induction, dispersion, and exchange contributions to interaction energy, so the SAPT decomposition facilitates the understanding and physical interpretation of results. \nIn the wavefunction-based variant presented here [Jeziorski:1994], SAPT is actually a triple perturbation theory. The zeroth-order Hamiltonian is the sum of the monomer Fock operators, $H_0=F_{\\rm A}+F_{\\rm B}$, and the perturbation correction $E^{(nkl)}$ corresponds to $n$th, $k$th, and $l$th order effects, respectively, of the intermolecular interaction operator $V$, the monomer-A Moller-Plesset fluctuation potential $W_{\\rm A}=H_{\\rm A}-F_{\\rm A}$, and an analogous monomer-B potential $W_{\\rm B}$. Thus, the SAPT correction $E^{(nkl)}$ is of the $n$th order in the *intermolecular interaction* and of the $(k+l)$th order in the *intramolecular correlation*.\nIn this example, we will calculate the interaction energy between two molecules at the simplest, SAPT0 level of theory [Parker:2014]. In SAPT0, intramolecular correlation is neglected, and intermolecular interaction is included through second order. Specifically,\n\n\\begin{equation}\nE_{\\rm int}^{\\rm SAPT0}=E^{(100)}_{\\rm elst}+E^{(100)}_{\\rm exch}+E^{(200)}_{\\rm ind,resp}+E^{(200)}_{\\rm exch-ind,resp}+E^{(200)}_{\\rm disp}+E^{(200)}_{\\rm exch-disp}\n\\end{equation}\n\nIn this equation, the consecutive corrections account for the electrostatic, first-order exchange, induction, exchange induction, dispersion, and exchange dispersion effects, respectively. The additional subscript ``resp'' denotes that these corrections are computed including the monomer relaxation (response) effects at the coupled-perturbed Hartree-Fock (CPHF) level of theory.\nBefore we proceed to the computation of the individual SAPT0 corrections, let us make two comments on the specifics of the calculation of the exchange corrections. The exchange terms stem from the symmetry adaptation, specifically, from the presence of the $(N_{\\rm A}+N_{\\rm B})$-electron antisymmetrizer ${\\cal A}$ that enforces the antisymmetry of the wavefunction upon an interchange of a pair of electrons between the monomers. Typically, the full operator ${\\cal A}$ in SAPT is approximated as ${\\cal A}=1+{\\cal P}$, where the *single-exchange operator* ${\\cal P}=\\sum_{a\\in {\\rm A}}\\sum_{b\\in {\\rm B}}P_{ab}$ collects all transpositions of a single pair of electrons between the interacting molecules. This approach is known as the *single exchange approximation* or the *$S^2$ approximation* --- the latter name refers to keeping terms that are quadratic in the intermolecular overlap integrals $S$ and neglecting terms that vanish like $S^4$, $S^6$, $\\ldots$. In Psi4,the $E^{(100)}_{\\rm exch}$ correction can be computed without the $S^2$ approximation, and the nonapproximated formulas for $E^{(200)}_{\\rm exch-ind,resp}$ and $E^{(200)}_{\\rm exch-disp}$ have also been derived [Schaffer:2013]. Nevertheless, in this example we will employ the $S^2$ approximation in all exchange corrections. Second, there exist two formalisms for the derivation of SAPT exchange corrections: the second-quantization approach [Moszynski:1994a] and the density matrix formalism [Moszynski:1994b]. The two methodologies lead to completely different SAPT expressions which, however, lead to identical results as long as the full dimer basis set is employed. Below, we will adopt the density formalism that is more general (valid in dimer and monomer basis sets) and exhibits more favorable computational scaling (however, more different types of two-electron integrals are required).\n\n\n# 1. Preparation of the matrix elements\n\nThe expressions for SAPT0 corrections contain similar quantities as the ones for other correlated electronic structure theories: one- and two-electron integrals over molecular orbitals (MOs), Hartree-Fock (HF) orbital energies, and various amplitudes and intermediates. The feature unique to SAPT is that one has two sets of occupied and virtual (unoccupied) MOs, one for molecule A and one for molecule B (the MOs for the two molecules are not mutually orthogonal, and they may span the same one-electron space but do not have to do so). The most direct consequence of having two sets of MOs is a large number of different MO-basis two-electron integrals $(xy\\mid zw)$: each of the four indices can be an occupied orbital of A, a virtual orbital of A, an occupied orbital of B, or a virtual orbital of B. Even when we account for all possible index symmetries, a few dozen types of MO integrals are possible, and we need a code for the integral transformation from atomic orbitals (AOs) to MOs that can produce all of these types. This transformation, and a number of other useful routines, is present in the `helper_SAPT` module that one has to load at the beginning of the SAPT run.\n\n\n\n```python\n# A simple Psi 4 input script to compute SAPT interaction energies\n#\n# Created by: Daniel G. A. Smith\n# Date: 12/1/14\n# License: GPL v3.0\n#\n\nimport time\nimport numpy as np\nfrom helper_SAPT import *\nnp.set_printoptions(precision=5, linewidth=200, threshold=2000, suppress=True)\nimport psi4\n\n# Set Psi4 & NumPy Memory Options\npsi4.set_memory('2 GB')\npsi4.core.set_output_file('output.dat', False)\n\nnumpy_memory = 2\n\n\n```\n\nNext, we specify the geometry of the complex (in this example, it will be the water dimer). Note that we have to let Psi4 know which atoms belong to molecule A and which ones are molecule B. We then call the `helper_SAPT` function to initialize all quantities that will be needed for the SAPT corrections. In particular, the HF calculations will be performed for molecules A and B separately, and the two sets of orbital energies and MO coefficients will be waiting for SAPT to peruse.\n\n\n\n```python\n# Set molecule to dimer\ndimer = psi4.geometry(\"\"\"\nO -0.066999140 0.000000000 1.494354740\nH 0.815734270 0.000000000 1.865866390\nH 0.068855100 0.000000000 0.539142770\n--\nO 0.062547750 0.000000000 -1.422632080\nH -0.406965400 -0.760178410 -1.771744500\nH -0.406965400 0.760178410 -1.771744500\nsymmetry c1\n\"\"\")\n\npsi4.set_options({'basis': 'jun-cc-pVDZ',\n 'e_convergence': 1e-8,\n 'd_convergence': 1e-8})\n\nsapt = helper_SAPT(dimer, memory=8)\n\n```\n\nBefore we start computing the SAPT0 corrections, we still need to specify the pertinent notation and define the matrix elements that we will be requesting from `helper_SAPT`. In the classic SAPT papers [Rybak:1991], orbital indices $a,a',a'',\\ldots$ and $b,b',b'',\\ldots$ denote occupied orbitals of monomers A and B, respectively. The virtual orbitals of monomers A and B are denoted by $r,r',r'',\\ldots$ and $s,s',s'',\\ldots$, respectively. The overlap integral $S^x_y=\\langle x|\\rangle y$ reduces to a Kronecker delta when two orbitals from the same monomer are involved, for example, $S^a_{a'}=\\delta_{aa'}$, $S^a_r=0$, however, the intermolecular overlap integrals cannot be simplified in any general fashion. Any kind of overlap integral can be requested by calling `sapt.s`, for example, `sapt.s('ab')` gives the $S^a_b$ matrix. For the convenience of implementation, the one-electron (nuclear attraction) $(v_{\\rm X})^x_y$ (X = A or B) and nuclear repulsion $V_0$ contributions are usually folded into the two-electron integrals $v^{xy}_{zw}\\equiv (xz|yw)$ forming the *dressed* integrals $\\tilde{v}$:\n\n\\begin{equation}\n\\tilde{v}^{xy}_{zw}=v^{xy}_{zw}+(v_{\\rm A})^{y}_{w}S^{x}_{z}/N_{\\rm A}+(v_{\\rm B})^{x}_{z}S^{y}_{w}/N_{\\rm B}+V_0S^{x}_{z}S^{y}_{w}/N_{\\rm A}N_{\\rm B},\n\\end{equation}\n\nwhere $N_{\\rm X}$, X=A,B, is the number of electrons in monomer X. An arbitrary *dressed* integral $\\tilde{v}^{xy}_{zw}$ can be requested by calling `sapt.vt('xyzw')`. Finally, the HF orbital energy for either monomer can be obtained by calling `sapt.eps`; for example, `sapt.eps('r')` returns a 1D array of virtual orbital energies for monomer A.\n\n\n# 2. Electrostatic energy\n\nThe SAPT0 electrostatic energy $E^{(100)}_{\\rm elst}$ is simply the expectation value of the intermolecular interaction operator $V$ over the zeroth-order wavefunction which is the product of HF determinants for monomers A and B. For the interaction of two closed-shell systems, this energy is obtained by a simple summation of *dressed* two-electron integrals over occupied orbitals of A and B:\n\n\\begin{equation}\nE^{(100)}_{\\rm elst}=4\\tilde{v}^{ab}_{ab}.\n\\end{equation}\n\n\n\n\n```python\n\n### Start E100 Electrostatics\nelst_timer = sapt_timer('electrostatics')\nElst10 = 4 * np.einsum('abab', sapt.vt('abab'))\nelst_timer.stop()\n### End E100 Electrostatics\n\n\n```\n\n# 3. First-order exchange energy\n\nThe SAPT0 first-order exchange energy $E^{(100)}_{\\rm exch}$ within the $S^2$ approximation and the density matrix formalism is given by Eq. (40) of [Moszynski:1994b]:\n\n\\begin{align}\nE^{(100)}_{\\rm exch}=&-2\\left[\\tilde{v}^{ba}_{ab}+S^b_{a'}\\left(2\\tilde{v}^{aa'}_{ab}-\\tilde{v}^{a'a}_{ab}\\right)+S^{a}_{b'}\\left(2\\tilde{v}^{b'b}_{ab}-\\tilde{v}^{bb'}_{ab}\\right)\\right.\\\\ &\\left.-2S^b_{a'}S^{a'}_{b'}\\tilde{v}^{ab'}_{ab}-2S^{b'}_{a'}S^{a}_{b'}\\tilde{v}^{a'b}_{ab}+S^b_{a'}S^{a}_{b'}\\tilde{v}^{a'b'}_{ab}\\right]\n\\end{align}\n\nand involves several different types of *dressed* MO integrals as well as some intermolecular overlap integrals (not that all indices still pertain to occupied orbitals in this formalism). In Psi4NumPy, each tensor contraction in the above expression can be performed with a single `np.einsum` call:\n\n\n\n```python\n### Start E100 Exchange\nexch_timer = sapt_timer('exchange')\nvt_abba = sapt.vt('abba')\nvt_abaa = sapt.vt('abaa')\nvt_abbb = sapt.vt('abbb')\nvt_abab = sapt.vt('abab')\ns_ab = sapt.s('ab')\n\nExch100 = np.einsum('abba', vt_abba)\n\ntmp = 2 * vt_abaa - vt_abaa.swapaxes(2, 3)\nExch100 += np.einsum('Ab,abaA', s_ab, tmp)\n\ntmp = 2 * vt_abbb - vt_abbb.swapaxes(2, 3)\nExch100 += np.einsum('Ba,abBb', s_ab.T, tmp)\n\nExch100 -= 2 * np.einsum('Ab,BA,abaB', s_ab, s_ab.T, vt_abab)\nExch100 -= 2 * np.einsum('AB,Ba,abAb', s_ab, s_ab.T, vt_abab)\nExch100 += np.einsum('Ab,Ba,abAB', s_ab, s_ab.T, vt_abab)\n\nExch100 *= -2\nexch_timer.stop()\n### End E100 (S^2) Exchange\n\n\n```\n\n# 4. Dispersion energy\n\nThe SAPT0 dispersion energy $E^{(200)}_{\\rm disp}$ is given by the formula\n\n\\begin{equation}\nE^{(200)}_{\\rm disp}=4t^{rs}_{ab}v^{ab}_{rs}\n\\end{equation}\n\nwhere the *dispersion amplitude* $t^{rs}_{ab}$, representing a single excitation on A and a single excitation on B, involves a two-electron integral and an excitation energy denominator:\n\n\\begin{equation}\nt^{rs}_{ab}=\\frac{v_{ab}^{rs}}{\\epsilon_a+\\epsilon_b-\\epsilon_r-\\epsilon_s}\n\\end{equation}\n\nNote that for this particular type of integral $\\tilde{v}^{ab}_{rs}=v^{ab}_{rs}$: therefore, `sapt.v` instead of `sapt.vt` is used to prepare this tensor.\n\n\n\n```python\n### Start E200 Disp\ndisp_timer = sapt_timer('dispersion')\nv_abrs = sapt.v('abrs')\nv_rsab = sapt.v('rsab')\ne_rsab = 1/(-sapt.eps('r', dim=4) - sapt.eps('s', dim=3) + sapt.eps('a', dim=2) + sapt.eps('b'))\n\nDisp200 = 4 * np.einsum('rsab,rsab,abrs->', e_rsab, v_rsab, v_abrs)\n### End E200 Disp\n\n\n```\n\n# 5. Exchange dispersion energy\n\nSome of the formulas for the SAPT0 exchange-dispersion energy $E^{(200)}_{\\rm exch-disp}$ in the original papers contained errors. The corrected formula for this term is given by e.g. Eq. (10) of [Patkowski:2007]:\n\n\\begin{align}\nE^{(200)}_{\\rm exch-disp}=&-2t^{ab}_{rs}\\left[\\tilde{v}^{sr}_{ab}+S^s_a (2\\tilde{v}^{a'r}_{a'b}-\\tilde{v}^{ra'}_{a'b})+ S^s_{a'} (2\\tilde{v}^{ra'}_{ab}-\\tilde{v}^{a'r}_{ab})\\right.\\\\ &+ S^r_b (2\\tilde{v}^{sb'}_{ab'}-\\tilde{v}^{b's}_{ab'})+ S^r_{b'} (2\\tilde{v}^{b's}_{ab}-\\tilde{v}^{sb'}_{ab}) \\\\ &+S^{r}_{b} S^{b'}_{a'} \\tilde{v}^{a's}_{ab'}-2 S^{r}_{b'} S^{b'}_{a'} \\tilde{v}^{a's}_{ab}-2 S^{r}_{b} S^{b'}_{a} \\tilde{v}^{a's}_{a'b'}+4 S^{r}_{b'} S^{b'}_{a} \\tilde{v}^{a's}_{a'b} \\\\ &-2 S^{s}_{a} S^{a'}_{b} \\tilde{v}^{rb'}_{a'b'}+4 S^{s}_{a'} S^{a'}_{b} \\tilde{v}^{rb'}_{ab'}+ S^{s}_{a} S^{a'}_{b'} \\tilde{v}^{rb'}_{a'b}-2 S^{s}_{a'} S^{a'}_{b'} \\tilde{v}^{rb'}_{ab} \\\\ &+ S^{r}_{b'} S^{s}_{a'} \\tilde{v}^{a'b'}_{ab}-2 S^{r}_{b} S^{s}_{a'} \\tilde{v}^{a'b'}_{ab'}-2 S^{r}_{b'} S^{s}_{a} \\tilde{v}^{a'b'}_{a'b} \\\\ &\\left. + S^{a'}_{b} S^{b'}_{a} \\tilde{v}^{rs}_{a'b'}-2 S^{a'}_{b} S^{b'}_{a'} \\tilde{v}^{rs}_{ab'}-2 S^{a'}_{b'} S^{b'}_{a} \\tilde{v}^{rs}_{a'b}\\right]\n\\end{align}\n\nThe corresponding Psi4NumPy code first recreates the dispersion amplitudes $t^{rs}_{ab}$ and then prepares the tensor `xd_absr` that is equal to the entire expression in brackets. The additional two intermediates `h_abrs` and `q_abrs` collect terms involving one and two overlap integrals, respectively.\n\n\n\n```python\n### Start E200 Exchange-Dispersion\n\n# Build t_rsab\nt_rsab = np.einsum('rsab,rsab->rsab', v_rsab, e_rsab)\n\n# Build h_abrs\nvt_abar = sapt.vt('abar')\nvt_abra = sapt.vt('abra')\nvt_absb = sapt.vt('absb')\nvt_abbs = sapt.vt('abbs')\n\ntmp = 2 * vt_abar - vt_abra.swapaxes(2, 3)\nh_abrs = np.einsum('as,AbAr->abrs', sapt.s('as'), tmp)\n\ntmp = 2 * vt_abra - vt_abar.swapaxes(2, 3)\nh_abrs += np.einsum('As,abrA->abrs', sapt.s('as'), tmp)\n\ntmp = 2 * vt_absb - vt_abbs.swapaxes(2, 3)\nh_abrs += np.einsum('br,aBsB->abrs', sapt.s('br'), tmp)\n\ntmp = 2 * vt_abbs - vt_absb.swapaxes(2, 3)\nh_abrs += np.einsum('Br,abBs->abrs', sapt.s('br'), tmp)\n\n# Build q_abrs\nvt_abas = sapt.vt('abas')\nq_abrs = np.einsum('br,AB,aBAs->abrs', sapt.s('br'), sapt.s('ab'), vt_abas)\nq_abrs -= 2 * np.einsum('Br,AB,abAs->abrs', sapt.s('br'), sapt.s('ab'), vt_abas)\nq_abrs -= 2 * np.einsum('br,aB,ABAs->abrs', sapt.s('br'), sapt.s('ab'), vt_abas)\nq_abrs += 4 * np.einsum('Br,aB,AbAs->abrs', sapt.s('br'), sapt.s('ab'), vt_abas)\n\nvt_abrb = sapt.vt('abrb')\nq_abrs -= 2 * np.einsum('as,bA,ABrB->abrs', sapt.s('as'), sapt.s('ba'), vt_abrb)\nq_abrs += 4 * np.einsum('As,bA,aBrB->abrs', sapt.s('as'), sapt.s('ba'), vt_abrb)\nq_abrs += np.einsum('as,BA,AbrB->abrs', sapt.s('as'), sapt.s('ba'), vt_abrb)\nq_abrs -= 2 * np.einsum('As,BA,abrB->abrs', sapt.s('as'), sapt.s('ba'), vt_abrb)\n\nvt_abab = sapt.vt('abab')\nq_abrs += np.einsum('Br,As,abAB->abrs', sapt.s('br'), sapt.s('as'), vt_abab)\nq_abrs -= 2 * np.einsum('br,As,aBAB->abrs', sapt.s('br'), sapt.s('as'), vt_abab)\nq_abrs -= 2 * np.einsum('Br,as,AbAB->abrs', sapt.s('br'), sapt.s('as'), vt_abab)\n\nvt_abrs = sapt.vt('abrs')\nq_abrs += np.einsum('bA,aB,ABrs->abrs', sapt.s('ba'), sapt.s('ab'), vt_abrs)\nq_abrs -= 2 * np.einsum('bA,AB,aBrs->abrs', sapt.s('ba'), sapt.s('ab'), vt_abrs)\nq_abrs -= 2 * np.einsum('BA,aB,Abrs->abrs', sapt.s('ba'), sapt.s('ab'), vt_abrs)\n\n# Sum it all together\nxd_absr = sapt.vt('absr')\nxd_absr += h_abrs.swapaxes(2, 3)\nxd_absr += q_abrs.swapaxes(2, 3)\nExchDisp20 = -2 * np.einsum('absr,rsab->', xd_absr, t_rsab)\n\ndisp_timer.stop()\n### End E200 Exchange-Dispersion\n\n\n```\n\n# 6. CPHF coefficients and induction energy\n\nAs already mentioned, the induction and exchange-induction contributions to SAPT0 are calculated including the relaxation of one molecule's HF orbitals in the electrostatic potential generated by the other molecule. Mathematically, this relaxation is taken into account by computing the CPHF coefficients $C^a_r$ for monomer A [Caves:1969] that specify the linear response of the HF orbitals of A to the electrostatic potential $\\omega_{\\rm B}$ generated by the nuclei and electrons of the (unperturbed) monomer B and the analogous coefficients $C^b_s$ that describe the response of B to the electrostatic potential of A. The CPHF coefficients are computed by solving the system of equations\n\n\\begin{equation}\n(\\epsilon_r-\\epsilon_a)C^a_r+(2v^{ar'}_{ra'}-v^{r'a}_{ra'})C^{a'}_{r'}+(2v^{aa'}_{rr'}-v^{a'a}_{rr'})C^{r'}_{a'}=-2\\tilde{v}^{ab}_{rb}. \n\\end{equation}\n\nand similarly for monomer B. Once the CPHF coefficients are ready, the SAPT0 induction energy $E^{(200)}_{\\rm ind,resp}$ can be computed very easily:\n\n\\begin{equation}\nE^{(200)}_{\\rm ind,resp}=4\\tilde{v}^{rb}_{ab}C^a_r+4\\tilde{v}^{as}_{ab}C^b_s\n\\end{equation}\n\nThe call to the `helper_SAPT` function `sapt.chf` generates the corresponding contribution to $E^{(200)}_{\\rm ind,resp}$ as a byproduct of the calculation of the CPHF coefficients $C^a_r$/$C^b_s$.\n\n\n\n```python\n\n### Start E200 Induction and Exchange-Induction\n\n# E200Induction and CPHF orbitals\nind_timer = sapt_timer('induction')\n\nCPHF_ra, Ind20_ba = sapt.chf('B', ind=True)\nsapt_printer('Ind20,r (A<-B)', Ind20_ba)\n\nCPHF_sb, Ind20_ab = sapt.chf('A', ind=True)\nsapt_printer('Ind20,r (A->B)', Ind20_ab)\n\nInd20r = Ind20_ba + Ind20_ab\n\n\n```\n\n# 7. Exchange induction energy\n\nJust like for induction energy, the SAPT0 exchange-induction energy $E^{(200)}_{\\rm exch-ind,resp}$ decomposes into two parts describing the exchange quenching of the polarization of A by B and of the polarization of B by A:\n\n\\begin{equation}\nE^{(200)}_{\\rm exch-ind,resp}=E^{(200)}_{\\rm exch-ind,resp}({\\rm A}\\leftarrow{\\rm B})+E^{(200)}_{\\rm exch-ind,resp}({\\rm B}\\leftarrow{\\rm A})\n\\end{equation}\n\nNow, the formula for the A$\\leftarrow$B part is given e.g. by Eq. (5) of [Patkowski:2007]:\n\n\\begin{align}\nE^{(200)}_{\\rm exch-ind,resp}({\\rm A}\\leftarrow {\\rm B})=&-2 C^a_r \\left[\\tilde{v}^{br}_{ab}+2S^b_a\\tilde{v}^{a'r}_{a'b}+2S^b_{a'}\\tilde{v}^{ra'}_{ab}-S^b_a\\tilde{v}^{ra'}_{a'b}-S^b_{a'}\\tilde{v}^{a'r}_{ab}+2S^r_{b'}\\tilde{v}^{b'b}_{ab}\\right.\\\\ &-S^r_{b'}\\tilde{v}^{bb'}_{ab}-2S^b_a S^r_{b'}\\tilde{v}^{a'b'}_{a'b}-2S^b_{a'}S^{a'}_{b'}\\tilde{v}^{rb'}_{ab}-2S^{b'}_{a'}S^r_{b'}\\tilde{v}^{a'b}_{ab}-2S^{b'}_a S^{a'}_{b'}\\tilde{v}^{rb}_{a'b}\\\\ & \\left.+S^b_{a'}S^r_{b'}\\tilde{v}^{a'b'}_{ab}+S^b_a S^{a'}_{b'}\\tilde{v}^{rb'}_{a'b}\\right]\n\\end{align}\n\nand the corresponding formula for the B$\\leftarrow$A part is obtained by interchanging the symbols pertaining to A with those of B $(a\\leftrightarrow b,r\\leftrightarrow s)$ in the above expression. In this example, the CPHF coefficients $C^a_r$ and $C^b_s$ obtained in the previous section are combined with *dressed* two-electron integrals and overlap integrals to compute the $E^{(200)}_{\\rm exch-ind,resp}$ expression term by term.\n\n\n\n```python\n# Exchange-Induction\n\n# A <- B\nvt_abra = sapt.vt('abra')\nvt_abar = sapt.vt('abar')\nExchInd20_ab = np.einsum('ra,abbr', CPHF_ra, sapt.vt('abbr'))\nExchInd20_ab += 2 * np.einsum('rA,Ab,abar', CPHF_ra, sapt.s('ab'), vt_abar)\nExchInd20_ab += 2 * np.einsum('ra,Ab,abrA', CPHF_ra, sapt.s('ab'), vt_abra)\nExchInd20_ab -= np.einsum('rA,Ab,abra', CPHF_ra, sapt.s('ab'), vt_abra)\n\nvt_abbb = sapt.vt('abbb')\nvt_abab = sapt.vt('abab')\nExchInd20_ab -= np.einsum('ra,Ab,abAr', CPHF_ra, sapt.s('ab'), vt_abar)\nExchInd20_ab += 2 * np.einsum('ra,Br,abBb', CPHF_ra, sapt.s('br'), vt_abbb)\nExchInd20_ab -= np.einsum('ra,Br,abbB', CPHF_ra, sapt.s('br'), vt_abbb)\nExchInd20_ab -= 2 * np.einsum('rA,Ab,Br,abaB', CPHF_ra, sapt.s('ab'), sapt.s('br'), vt_abab)\n\nvt_abrb = sapt.vt('abrb')\nExchInd20_ab -= 2 * np.einsum('ra,Ab,BA,abrB', CPHF_ra, sapt.s('ab'), sapt.s('ba'), vt_abrb)\nExchInd20_ab -= 2 * np.einsum('ra,AB,Br,abAb', CPHF_ra, sapt.s('ab'), sapt.s('br'), vt_abab)\nExchInd20_ab -= 2 * np.einsum('rA,AB,Ba,abrb', CPHF_ra, sapt.s('ab'), sapt.s('ba'), vt_abrb)\n\nExchInd20_ab += np.einsum('ra,Ab,Br,abAB', CPHF_ra, sapt.s('ab'), sapt.s('br'), vt_abab)\nExchInd20_ab += np.einsum('rA,Ab,Ba,abrB', CPHF_ra, sapt.s('ab'), sapt.s('ba'), vt_abrb)\n\nExchInd20_ab *= -2\nsapt_printer('Exch-Ind20,r (A<-B)', ExchInd20_ab)\n\n# B <- A\nvt_abbs = sapt.vt('abbs')\nvt_absb = sapt.vt('absb')\nExchInd20_ba = np.einsum('sb,absa', CPHF_sb, sapt.vt('absa'))\nExchInd20_ba += 2 * np.einsum('sB,Ba,absb', CPHF_sb, sapt.s('ba'), vt_absb)\nExchInd20_ba += 2 * np.einsum('sb,Ba,abBs', CPHF_sb, sapt.s('ba'), vt_abbs)\nExchInd20_ba -= np.einsum('sB,Ba,abbs', CPHF_sb, sapt.s('ba'), vt_abbs)\n\nvt_abaa = sapt.vt('abaa')\nvt_abab = sapt.vt('abab')\nExchInd20_ba -= np.einsum('sb,Ba,absB', CPHF_sb, sapt.s('ba'), vt_absb)\nExchInd20_ba += 2 * np.einsum('sb,As,abaA', CPHF_sb, sapt.s('as'), vt_abaa)\nExchInd20_ba -= np.einsum('sb,As,abAa', CPHF_sb, sapt.s('as'), vt_abaa)\nExchInd20_ba -= 2 * np.einsum('sB,Ba,As,abAb', CPHF_sb, sapt.s('ba'), sapt.s('as'), vt_abab)\n\nvt_abas = sapt.vt('abas')\nExchInd20_ba -= 2 * np.einsum('sb,Ba,AB,abAs', CPHF_sb, sapt.s('ba'), sapt.s('ab'), vt_abas)\nExchInd20_ba -= 2 * np.einsum('sb,BA,As,abaB', CPHF_sb, sapt.s('ba'), sapt.s('as'), vt_abab)\nExchInd20_ba -= 2 * np.einsum('sB,BA,Ab,abas', CPHF_sb, sapt.s('ba'), sapt.s('ab'), vt_abas)\n\nExchInd20_ba += np.einsum('sb,Ba,As,abAB', CPHF_sb, sapt.s('ba'), sapt.s('as'), vt_abab)\nExchInd20_ba += np.einsum('sB,Ba,Ab,abAs', CPHF_sb, sapt.s('ba'), sapt.s('ab'), vt_abas)\n\nExchInd20_ba *= -2\nsapt_printer('Exch-Ind20,r (A->B)', ExchInd20_ba)\nExchInd20r = ExchInd20_ba + ExchInd20_ab\n\nind_timer.stop()\n### End E200 Induction and Exchange-Induction\n\n\n```\n\n# 8. Summary table\n\nAll the SAPT0 interaction energy contributions have been calculated. All that is left to do is to print out the contributions and the total energy, and to compare the results with the SAPT0 corrections calculated directly by Psi4.\n\n\n\n```python\nprint('SAPT0 Results')\nprint('-' * 70)\nsapt_printer('Exch10 (S^2)', Exch100)\nsapt_printer('Elst10', Elst10)\nsapt_printer('Disp20', Disp200)\nsapt_printer('Exch-Disp20', ExchDisp20)\nsapt_printer('Ind20,r', Ind20r)\nsapt_printer('Exch-Ind20,r', ExchInd20r)\n\nprint('-' * 70)\nsapt0 = Exch100 + Elst10 + Disp200 + ExchDisp20 + Ind20r + ExchInd20r\nsapt_printer('Total SAPT0', sapt0)\n\n# ==> Compare to Psi4 <==\npsi4.set_options({'df_basis_sapt':'aug-cc-pvtz-ri'})\npsi4.energy('sapt0')\nEelst = psi4.get_variable('SAPT ELST ENERGY')\nEexch = psi4.get_variable('SAPT EXCH10(S^2) ENERGY')\nEind = psi4.get_variable('SAPT IND20,R ENERGY')\nEexind = psi4.get_variable('SAPT EXCH-IND20,R ENERGY')\nEdisp = psi4.get_variable('SAPT DISP20 ENERGY')\nEexdisp = psi4.get_variable('SAPT EXCH-DISP20 ENERGY')\npsi4.compare_values(Eelst, Elst10, 6, 'Elst100')\npsi4.compare_values(Eexch, Exch100, 6, 'Exch100(S^2)')\npsi4.compare_values(Edisp, Disp200, 6, 'Disp200')\npsi4.compare_values(Eexdisp, ExchDisp20, 6, 'Exch-Disp200')\npsi4.compare_values(Eind, Ind20r, 6, 'Ind200,r')\npsi4.compare_values(Eexind, ExchInd20r, 6, 'Exch-Ind200,r')\n\n\n```\n\n## References\n\n1. The classic review paper on SAPT: \"Perturbation Theory Approach to Intermolecular Potential Energy Surfaces of van der Waals Complexes\"\n\t> [[Jeziorski:1994](http://pubs.acs.org/doi/abs/10.1021/cr00031a008)] B. Jeziorski, R. Moszynski, and K. Szalewicz, *Chem. Rev.* **94**, 1887 (1994)\n2. The definitions and practical comparison of different levels of SAPT: \"Levels of symmetry adapted perturbation theory (SAPT). I. Efficiency and performance for interaction energies\"\n\t> [[Parker:2014](http://aip.scitation.org/doi/10.1063/1.4867135)] T. M. Parker, L. A. Burns, R. M. Parrish, A. G. Ryno, and C. D. Sherrill, *J. Chem. Phys.* **140**, 094106 (2014)\n3. Second-order SAPT exchange corrections without the $S^2$ approximation: \"Single-determinant-based symmetry-adapted perturbation theory without single-exchange approximation\"\n\t> [[Schaffer:2013](http://www.tandfonline.com/doi/abs/10.1080/00268976.2013.827253)] R. Schäffer and G. Jansen, *Mol. Phys.* **111**, 2570 (2013)\n4. Alternative, second-quantization based approach to SAPT exchange corrections: \"Many‐body theory of exchange effects in intermolecular interactions. Second‐quantization approach and comparison with full configuration interaction results\"\n\t> [[Moszynski:1994a](http://aip.scitation.org/doi/abs/10.1063/1.466661)] R. Moszynski, B. Jeziorski, and K. Szalewicz, *J. Chem. Phys.* **100**, 1312 (1994)\n5. The density-matrix formalism for SAPT exchange corrections employed in this work: \"Many‐body theory of exchange effects in intermolecular interactions. Density matrix approach and applications to He–F$^−$, He–HF, H$_2$–HF, and Ar–H$_2$ dimers\"\n\t> [[Moszynski:1994b](http://aip.scitation.org/doi/abs/10.1063/1.467225)] R. Moszynski, B. Jeziorski, S. Rybak, K. Szalewicz, and H. L. Williams, *J. Chem. Phys.* **100**, 5080 (1994)\n6. A classic paper with derivations of many SAPT corrections: \"Many‐body symmetry‐adapted perturbation theory of intermolecular interactions. H$_2$O and HF dimers\"\n\t> [[Rybak:1991](http://aip.scitation.org/doi/abs/10.1063/1.461528)] S. Rybak, B. Jeziorski, and K. Szalewicz, *J. Chem. Phys.* **95**, 6576 (1991)\n7. A paper about the frozen-core approximation in SAPT, containing the corrected formula for the exchange dispersion energy: \"Frozen core and effective core potentials in symmetry-adapted perturbation theory\"\n\t> [[Patkowski:2007](http://aip.scitation.org/doi/10.1063/1.2784391)] K. Patkowski and K. Szalewicz, *J. Chem. Phys.* **127**, 164103 (2007)\n8. A classic paper about the CPHF equations: \"Perturbed Hartree–Fock Theory. I. Diagrammatic Double‐Perturbation Analysis\"\n\t> [[Caves:1969](http://aip.scitation.org/doi/abs/10.1063/1.1671609)] T. C. Caves and M. Karplus, *J. Chem. Phys.* **50**, 3649 (1969)\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "db3db8d7debaca9abf05800a80bc29b755be6eba", "size": 32273, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorials/07_Symmetry_Adapted_Perturbation_Theory/7a_sapt0_mo.ipynb", "max_stars_repo_name": "konpat/psi4numpy", "max_stars_repo_head_hexsha": "dc0b51d9a05286023474e1e5b4828705676bf60d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tutorials/07_Symmetry_Adapted_Perturbation_Theory/7a_sapt0_mo.ipynb", "max_issues_repo_name": "konpat/psi4numpy", "max_issues_repo_head_hexsha": "dc0b51d9a05286023474e1e5b4828705676bf60d", "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": "Tutorials/07_Symmetry_Adapted_Perturbation_Theory/7a_sapt0_mo.ipynb", "max_forks_repo_name": "konpat/psi4numpy", "max_forks_repo_head_hexsha": "dc0b51d9a05286023474e1e5b4828705676bf60d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.9324090121, "max_line_length": 1899, "alphanum_fraction": 0.6211693986, "converted": true, "num_tokens": 8971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.14608724890715238, "lm_q1q2_score": 0.061166279613699616}} {"text": "```python\n%matplotlib inline\n\nimport os\nimport re\nimport urllib.request\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport itertools\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\n```\n\nIn this notebook you will work with a deep generative language model that maps words from a continuous latent space. We will use text data (we will work on the character level) in Spanish and pytorch. \n\nThe first section concerns data manipulation and data loading classes necessary for our implementation. You do not need to modify anything in this part of the code.\n\nLet's first download the SIGMORPHON dataset that we will be using for this notebook: these are inflected Spanish words together with some morphosyntactic descriptors. For this notebook we will ignore the morphosyntactic descriptors.\n\n\n```python\nurl = \"https://raw.githubusercontent.com/ryancotterell/sigmorphon2016/master/data/\"\ntrain_file = \"spanish-task1-train\"\nval_file = \"spanish-task1-dev\"\ntest_file = \"spanish-task1-test\"\n\nprint(\"Downloading data files...\")\nif not os.path.isfile(train_file):\n urllib.request.urlretrieve(url + train_file, filename=train_file)\nif not os.path.isfile(val_file):\n urllib.request.urlretrieve(url + val_file, filename=val_file)\nif not os.path.isfile(test_file):\n urllib.request.urlretrieve(url + test_file, filename=test_file)\nprint(\"Download complete.\")\n```\n\n Downloading data files...\n Download complete.\n\n\n# Data\n\nIn order to work with text data, we need to transform the text into something that our algorithms can work with. The first step of this process is converting words into word ids. We do this by constructing a vocabulary from the data, assigning a new word id to each new word it encounters.\n\n\n```python\nUNK_TOKEN = \"?\"\nPAD_TOKEN = \"_\"\nSOW_TOKEN = \">\"\nEOW_TOKEN = \".\"\n\ndef extract_inflected_word(s):\n \"\"\"\n Extracts the inflected words in the SIGMORPHON dataset.\n \"\"\"\n return s.split()[-1]\n\nclass Vocabulary:\n \n def __init__(self):\n self.idx_to_char = {0: UNK_TOKEN, 1: PAD_TOKEN, 2: SOW_TOKEN, 3: EOW_TOKEN}\n self.char_to_idx = {UNK_TOKEN: 0, PAD_TOKEN: 1, SOW_TOKEN: 2, EOW_TOKEN: 3}\n self.word_freqs = {}\n \n def __getitem__(self, key):\n return self.char_to_idx[key] if key in self.char_to_idx else self.char_to_idx[UNK_TOKEN]\n \n def word(self, idx):\n return self.idx_to_char[idx]\n \n def size(self):\n return len(self.char_to_idx)\n \n @staticmethod\n def from_data(filenames):\n \"\"\"\n Creates a vocabulary from a list of data files. It assumes that the data files have been\n tokenized and pre-processed beforehand.\n \"\"\"\n vocab = Vocabulary()\n for filename in filenames:\n with open(filename) as f:\n for line in f:\n \n # Strip whitespace and the newline symbol.\n word = extract_inflected_word(line.strip())\n \n # Split the words into characters and assign ids to each\n # new character it encounters.\n for char in list(word):\n if char not in vocab.char_to_idx:\n idx = len(vocab.char_to_idx)\n vocab.char_to_idx[char] = idx\n vocab.idx_to_char[idx] = char\n \n return vocab\n```\n\n\n```python\n# Construct a vocabulary from the training and validation data.\nprint(\"Constructing vocabulary...\")\nvocab = Vocabulary.from_data([train_file, val_file])\nprint(\"Constructed a vocabulary of %d types\" % vocab.size())\n```\n\n Constructing vocabulary...\n Constructed a vocabulary of 37 types\n\n\n\n```python\n# some examples\nprint('e', vocab['e'])\nprint('é', vocab['é'])\nprint('ș', vocab['ș']) # something UNKNOWN\n```\n\n e 8\n é 24\n ș 0\n\n\nWe also need to load the data files into memory. We create a simple class `TextDataset` that stores the data as a list of words:\n\n\n```python\nclass TextDataset(Dataset):\n \"\"\"\n A simple class that loads a list of words into memory from a text file,\n split by newlines. This does not do any memory optimisation, \n so if your dataset is very large, you might want to use an alternative \n class.\n \"\"\"\n \n def __init__(self, text_file, max_len=30):\n self.data = []\n with open(text_file) as f:\n for line in f:\n word = extract_inflected_word(line.strip())\n if len(list(word)) <= max_len:\n self.data.append(word)\n \n def __len__(self):\n return len(self.data)\n \n def __getitem__(self, idx):\n return self.data[idx]\n```\n\n\n```python\n# Load the training, validation, and test datasets into memory.\ntrain_dataset = TextDataset(train_file)\nval_dataset = TextDataset(val_file)\ntest_dataset = TextDataset(test_file)\n\n# Print some samples from the data:\nprint(\"Sample from training data: \\\"%s\\\"\" % train_dataset[np.random.choice(len(train_dataset))])\nprint(\"Sample from validation data: \\\"%s\\\"\" % val_dataset[np.random.choice(len(val_dataset))])\nprint(\"Sample from test data: \\\"%s\\\"\" % test_dataset[np.random.choice(len(test_dataset))])\n```\n\n Sample from training data: \"fidas\"\n Sample from validation data: \"gozarían\"\n Sample from test data: \"figuraríais\"\n\n\nNow it's time to write a function that converts a word into a list of character ids using the vocabulary we created before. This function is `create_batch` in the code cell below. This function creates a batch from a list of words, and makes sure that each word starts with a start-of-word symbol and ends with an end-of-word symbol. Because not all words are of equal length in a certain batch, words are padded with padding symbols so that they match the length of the largest word in the batch. The function returns an input batch, an output batch, a mask of 1s for words and 0s for padding symbols, and the sequence lengths of each word in the batch. The output batch is shifted by one character, to reflect the predictions that the model is expected to make. For example, for a word\n\\begin{align}\n \\text{e s p e s e m o s}\n\\end{align}\nthe input sequence is\n\\begin{align}\n \\text{SOW e s p e s e m o s}\n\\end{align}\nand the output sequence is\n\\begin{align}\n \\text{e s p e s e m o s EOW}\n\\end{align}\n\nYou can see the output is shifted wrt the input, that's because we will be computing a distribution for the next character in context of its prefix, and that's why we need to shift the sequence this way.\n\n\nLastly, we create an inverse function `batch_to_words` that recovers the list of words from a padded batch of character ids to use during test time.\n\n\n```python\ndef create_batch(words, vocab, device, word_dropout=0.):\n \"\"\"\n Converts a list of words to a padded batch of word ids. Returns\n an input batch, an output batch shifted by one, a sequence mask over\n the input batch, and a tensor containing the sequence length of each\n batch element.\n :param words: a list of words, each a list of token ids\n :param vocab: a Vocabulary object for this dataset\n :param device: \n :param word_dropout: rate at which we omit words from the context (input)\n :returns: a batch of padded inputs, a batch of padded outputs, mask, lengths\n \"\"\"\n tok = np.array([[SOW_TOKEN] + list(w) + [EOW_TOKEN] for w in words])\n seq_lengths = [len(w)-1 for w in tok]\n max_len = max(seq_lengths)\n pad_id = vocab[PAD_TOKEN]\n pad_id_input = [\n [vocab[w[t]] if t < seq_lengths[idx] else pad_id for t in range(max_len)]\n for idx, w in enumerate(tok)]\n \n # Replace words of the input with with p = word_dropout.\n if word_dropout > 0.:\n unk_id = vocab[UNK_TOKEN]\n word_drop = [\n [unk_id if (np.random.random() < word_dropout and t < seq_lengths[idx]) else word_ids[t] for t in range(max_len)] \n for idx, word_ids in enumerate(pad_id_input)]\n \n # The output batch is shifted by 1.\n pad_id_output = [\n [vocab[w[t+1]] if t < seq_lengths[idx] else pad_id for t in range(max_len)]\n for idx, w in enumerate(tok)]\n \n # Convert everything to PyTorch tensors.\n batch_input = torch.tensor(pad_id_input)\n batch_output = torch.tensor(pad_id_output)\n seq_mask = (batch_input != vocab[PAD_TOKEN])\n seq_length = torch.tensor(seq_lengths)\n \n # Move all tensors to the given device.\n batch_input = batch_input.to(device)\n batch_output = batch_output.to(device)\n seq_mask = seq_mask.to(device)\n seq_length = seq_length.to(device)\n \n return batch_input, batch_output, seq_mask, seq_length\n\n\ndef batch_to_words(tensors, vocab: Vocabulary):\n \"\"\"\n Converts a batch of word ids back to words.\n :param tensors: [B, T] word ids\n :param vocab: a Vocabulary object for this dataset\n :returns: an array of strings (each a word).\n \"\"\"\n words = []\n batch_size = tensors.size(0)\n for idx in range(batch_size):\n word = [vocab.word(t.item()) for t in tensors[idx,:]]\n \n # Filter out the start-of-word and padding tokens.\n word = list(filter(lambda t: t != PAD_TOKEN and t != SOW_TOKEN, word))\n \n # Remove the end-of-word token and all tokens following it.\n if EOW_TOKEN in word:\n word = word[:word.index(EOW_TOKEN)]\n \n words.append(\"\".join(word))\n return np.array(words)\n```\n\nIn PyTorch the RNN functions expect inputs to be sorted from long words to shorter ones. Therefore we create a simple wrapper class for the DataLoader class that sorts words from long to short: \n\n\n```python\nclass SortingTextDataLoader:\n \"\"\"\n A wrapper for the DataLoader class that sorts a list of words by their\n lengths in descending order.\n \"\"\"\n\n def __init__(self, dataloader):\n self.dataloader = dataloader\n self.it = iter(dataloader)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n words = None\n for s in self.it:\n words = s\n break\n\n if words is None:\n self.it = iter(self.dataloader)\n raise StopIteration\n \n words = np.array(words)\n sort_keys = sorted(range(len(words)), \n key=lambda idx: len(list(words[idx])), \n reverse=True)\n sorted_words = words[sort_keys]\n return sorted_words\n```\n\n# Model\n\n## Deterministic language model\n\nIn language modelling, we model a word $x = \\langle x_1, \\ldots, x_n \\rangle$ of length $n = |x|$ as a sequence of categorical draws:\n\n\\begin{align}\nX_i|x_{0}$).\n \n \nFor this choice, the KL term in the ELBO is tractable:\n\n\\begin{align}\n\\text{KL}\\left(q(z|x, \\lambda)||p(z)\\right) &= \\sum_{d=1}^D \\text{KL}\\left(q(z_d|x, \\lambda)||p(z_d)\\right) \\\\\n&= \\sum_{d=1}^D \\text{KL}\\left(\\mathcal N(u_d, s^2)|| \\mathcal N(0,1)\\right) \\\\\n&= - \\frac{1}{2} \\sum_{d=1}^D \\left(1 + \\log s_d^2 - u_d^2 - s_d^2 \\right)\n\\end{align}\nwhere $u_d = \\mu_d(x; \\lambda)$ and $s_d = \\sigma_d(x; \\lambda)$.\n\n \nHere's an example design for our inference model:\n\n\\begin{align}\n\\mathbf x_i &= \\text{emb}(x_i; \\lambda_{\\text{emb}}) \\\\\n\\mathbf f_i &= \\text{rnn}(\\mathbf f_{i-1}, \\mathbf x_{i}; \\lambda_{\\text{fwd}}) \\\\\n\\mathbf b_i &= \\text{rnn}(\\mathbf b_{i+1}, \\mathbf x_{i}; \\lambda_{\\text{bwd}}) \\\\\n\\mathbf h &= \\text{dense}([\\mathbf f_{n}, \\mathbf b_1]; \\lambda_{\\text{hid}}) \\\\\n\\mu(x; \\lambda) &= \\text{dense}(\\mathbf h; \\lambda_{\\text{loc}})\\\\\n\\sigma(x; \\lambda) &= \\text{softplus}(\\text{dense}(\\mathbf h; \\lambda_{\\text{scale}}))\n\\end{align}\n\nwhere we use the $\\text{softplus}$ activation to make sure our scales are strictly positive. Note that $\\exp$ would also do that job, though $\\text{softplus}$ is assymptotically linear with its input, which gives us better gradient dynamics.\n \nBecause we have neural networks compute the diagonal Gaussian parameters for us, we call this *amortised* mean field inference.\n\n\n\n### Gradient estimation\n\nWe have to obtain gradients of the ELBO\n\n\\begin{align}\n\\nabla_\\theta \\mathcal E(\\theta, \\lambda|x) &= \\mathbb{E}_{q(z|x)}\\left[\\nabla_\\theta \\log P(x|z, \\theta)\\right] - \\underbrace{\\nabla_\\theta \\text{KL}\\left(q(z|x, \\lambda)||p(z)\\right)}_{=0}\n\\end{align}\n\nand \n\n\\begin{align}\n\\nabla_\\lambda \\mathcal E(\\theta, \\lambda|x) &= \\nabla_\\lambda\\mathbb{E}_{q(z|x)}\\left[\\log P(x|z, \\theta)\\right] - \\nabla_\\lambda \\text{KL}\\left(q(z|x, \\lambda)||p(z)\\right)\n\\end{align}\n\nClearly, the gradient for the generative network is easy to estimate using MC, but the gradient for the inference network is more complicated because we don't have an expected gradient, rather the gradient of an expected value.\n\nBut recall, that we chose a Gaussian for approximate posterior, and Gaussians are what we call a location-scale family. Every Gaussian variable can be *re-expressed* or **reparameterised** in terms of the standard Gaussian (a distribution with fixed parameters), that is:\n\n\\begin{align}\n\\epsilon = \\frac{z - \\mu(x; \\sigma)}{\\sigma(x; \\lambda)} &\\sim \\mathcal N(0, I) \\\\\nz = \\mu(x; \\lambda) + \\sigma(x;\\lambda) \\odot \\epsilon &\\sim \\mathcal N(\\mu(x; \\lambda), \\text{diag}(\\sigma(x; \\lambda)^2))\n\\end{align}\n\nwhere $\\epsilon$ is distributed by a $D$-dimensional standard Gaussian and $\\odot$ denotes elementwise multiplication.\n\nThis means we can rewrite the ELBO as\n\n\\begin{align}\n\\mathcal E(\\theta, \\lambda|x) &= \\mathbb{E}_{\\epsilon \\sim \\mathcal N(0, I)}\\left[\\log P(x|z=\\mu(x; \\lambda) + \\sigma(x; \\lambda) \\odot \\epsilon, \\theta)\\right] - \\text{KL}\\left(q(z|x, \\lambda)||p(z)\\right) \n\\end{align}\n\nand though we could also rewrite the KL term, we will leave as is because it is tractable to compute.\n\nNow our gradients are both very simple:\n\n\\begin{align}\n\\nabla_\\theta \\mathcal E(\\theta, \\lambda|x) &= \\mathbb{E}_{\\epsilon \\sim \\mathcal N(0, I)}\\left[\\nabla_\\theta \\log P(x|z=\\mu(x; \\lambda) + \\sigma(x; \\lambda) \\odot \\epsilon, \\theta)\\right] - \\underbrace{\\nabla_\\theta \\text{KL}\\left(q(z|x, \\lambda)||p(z)\\right)}_{=0} \\\\\n&\\overset{\\text{MC}}{\\approx} \\frac{1}{S} \\sum_{s=1}^S \\nabla_\\theta \\log P(x|z^{(s)}, \\theta) \\\\\n&\\text{where }z^{(s)} = \\mu(x; \\lambda) + \\sigma(x; \\lambda) \\odot \\epsilon^{(s)}\\\\\n&\\text{and }\\epsilon^{(s)} \\sim \\mathcal N(0, I)\n\\end{align}\n\nand \n\n\\begin{align}\n\\nabla_\\lambda \\mathcal E(\\theta, \\lambda|x) &=\\nabla_\\lambda \\mathbb{E}_{\\epsilon \\sim \\mathcal N(0, I)}\\left[\\nabla_\\lambda \\log P(x|z=\\mu(x; \\lambda) + \\sigma(x; \\lambda) \\odot \\epsilon, \\theta)\\right] - \\nabla_\\lambda \\underbrace{\\text{KL}\\left(q(z|x, \\lambda)||p(z)\\right)}_{\\text{tractable}} \\\\\n&\\overset{\\text{MC}}{\\approx} \\left(\\frac{1}{S} \\sum_{s=1}^S \\nabla_\\lambda \\log P(x|z^{(s)}, \\theta)\\right) - \\nabla_\\lambda \\underbrace{\\text{KL}\\left(q(z|x, \\lambda)||p(z)\\right)}_{\\text{tractable}}\\\\\n&\\text{where }z^{(s)} = \\mu(x; \\lambda) + \\sigma(x; \\lambda) \\odot \\epsilon^{(s)}\\\\\n&\\text{and }\\epsilon^{(s)} \\sim \\mathcal N(0, I)\n\\end{align}\n\nand note how both, but especially the second, use this notion of *reparameterised sample* to make all sources of stochasticity independent of the parameters of the network.\n\nGradient estimates of this sort are known in the literature as *reparameterised gradients* and this makes our model an instance of what is known in the literature as a *variational auto-encoder* (VAE).\n\n\n\n\n## Implementation\n\nWe start by implementing our generative model, which requires implementing a Gaussian/Normal distribution:\n\nCheck the [wikipedia page about Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) for information such as the functional form of the pdf. \n\nYou will need the KL divergence for univariate Normal distributions:\n\n\\begin{align}\n\\text{KL}\\left(\\mathcal N(\\mu_1, \\sigma_1^2) || \\mathcal N(\\mu_2, \\sigma_2^2)\\right)\n&= \\frac{1}{2 \\sigma_2^2} \\left((\\mu_1 - \\mu_2)^2 + \\sigma_1^2 - \\sigma_2^2\\right) + \\log \\frac{\\sigma_2}{\\sigma_1}\n\\end{align}\n\n\n\n\n\n```python\nclass Normal:\n \"\"\"\n This is a normal distribution\n N(u, s^2)\n thus specified by a location u and a strictly positive scale.\n \n This class can hold a collection of D independent Gaussian variables\n by having a D-dimensional vector of locations and \n a D-dimensinal vector of scales. \n \"\"\"\n \n def __init__(self, loc, scale):\n \"\"\"\n :param loc: a tensor of locations (real numbers)\n :param scale: a tensor of scales (strictly positive real numbers)\n \"\"\"\n pass\n \n def mean(self):\n \"\"\"For Gaussians this is the location\"\"\"\n pass\n \n def std(self):\n \"\"\"For Gaussians this is the scale\"\"\"\n pass\n \n def sample(self):\n \"\"\"\n Returns a reparameterised sample with the shape of the location parameter.\n \"\"\"\n pass\n \n def log_pdf(self, x):\n \"\"\"\n Assess the log probability density of x.\n \n :param x: a tensor of Gaussian samples (same shape as the location parameter)\n :returns: tensor of log probabilitie densities\n \"\"\"\n pass\n \n def kl(self, other: 'Normal'):\n \"\"\"\n The KL divergence between two Gaussians\n :returns: a tensor of KL values with the same shape as the parameters of self.\n \"\"\"\n pass\n```\n\n\n```python\n# SOLUTION\nimport numpy as np\n\n\nclass Normal:\n \"\"\"\n This is a normal distribution\n N(u, s^2)\n thus specified by a location u and a strictly positive scale.\n \n This class can hold a collection of D independent Gaussian variables\n by having a D-dimensional vector of locations and \n a D-dimensinal vector of scales. \n \"\"\"\n \n def __init__(self, loc, scale):\n \"\"\"\n :param loc: a tensor of locations (real numbers)\n :param scale: a tensor of scales (strictly positive real numbers)\n \"\"\"\n self.loc = loc\n self.scale = scale\n \n def mean(self):\n \"\"\"For Gaussians this is the location\"\"\"\n return self.loc\n \n def std(self):\n \"\"\"For Gaussians this is the scale\"\"\"\n return self.scale\n \n def sample(self):\n \"\"\"\n Returns a reparameterised sample with the shape of the location parameter.\n \"\"\"\n epsilon = torch.randn_like(self.scale)\n return self.loc + epsilon * self.scale\n \n def log_pdf(self, x):\n \"\"\"\n Assess the log probability density of x.\n \n :param x: a tensor of Gaussian samples (same shape as the location parameter)\n :returns: tensor of log probabilitie densities\n \"\"\"\n return -(((x - self.loc) ** 2) / (2 * (self.scale ** 2))) -0.5 * np.log(2 * np.pi) - torch.log(self.scale)\n \n def kl(self, other: 'Normal'):\n \"\"\"\n The KL divergence between two Gaussians\n :returns: a tensor of KL values with the same shape as the parameters of self.\n \"\"\"\n return (1. / (2 * (other.scale**2))) * ((self.loc - other.loc)**2 + self.scale**2 - other.scale**2) + \\\n torch.log(other.scale) - torch.log(self.scale)\n\n```\n\n\n```python\n# tests for Normal\ntorch.manual_seed(0xBADF00D)\ndummy_loc = torch.randn(10, requires_grad=True)\ndummy_scale = torch.linspace(0.1, 5.0, 10, requires_grad=True)\ndummy_samples = Normal(dummy_loc, dummy_scale).sample()\nsample_pdf = Normal(dummy_loc, dummy_scale).log_pdf(dummy_samples)\n\ndummy_grads = torch.autograd.grad(dummy_samples.mean(), [dummy_loc, dummy_scale], allow_unused=True)\nassert all(grad is not None for grad in dummy_grads), \"samples are not differentiable w.r.t. loc and/or scale. \"\\\n \" Make sure you use torch throughout the implementation \"\nassert sample_pdf.shape == dummy_loc.shape\n\n# kl divergence\ndummy_loc_2 = torch.randn(10, requires_grad=True)\n\nnormal1 = Normal(dummy_loc, dummy_scale)\nnormal2 = Normal(dummy_loc_2, 5.1 - dummy_scale)\ndummy_kl = normal1.kl(normal2)\n\ndummy_kl_ref = torch.tensor([3.423, 1.468, 0.8952, 0.4297, 0.1506, 0.2868, 0.8887, 4.5, 21.904, 1355.1639])\nassert dummy_kl.shape == dummy_kl_ref.shape, \"please return a batch of KL divergence with the same shape as self.loc\"\nassert torch.allclose(dummy_kl, dummy_kl_ref, rtol=1e-3, atol=1e-3), \"your KL implementation is off\"\n```\n\nThen we should implement the inference model $q(z | x, \\lambda)$:\n\n\n```python\nclass InferenceModel(nn.Module):\n\n def __init__(self, vocab_size, embedder, hidden_size,\n latent_size, pad_idx, bidirectional=False):\n \"\"\"\n Implement the layers in the inference model.\n \n :param vocab_size: size of the vocabulary of the language\n :param embedder: embedding layer\n :param hidden_size: size of recurrent cell\n :param latent_size: size D of the latent variable\n :param pad_idx: id of the -PAD- token\n :param bidirectional: whether we condition on x via a bidirectional or \n unidirectional encoder \n \"\"\"\n pass\n\n def forward(self, x, seq_mask, seq_len) -> Normal:\n \"\"\"\n Return an inference Gaussian per instance in the mini-batch\n :param x: words [B, T] as token ids\n :param seq_mask: indicates valid positions vs padding positions [B, T]\n :param seq_len: the length of the sequences [B]\n :return: Gaussian approximate posterior\n \"\"\"\n pass\n```\n\n\n```python\n# SOLUTION\nclass InferenceModel(nn.Module):\n\n def __init__(self, vocab_size, embedder, hidden_size,\n latent_size, pad_idx, bidirectional=False):\n \"\"\"\n :param vocab_size: size of the vocabulary of the language\n :param embedder: embedding layer\n :param hidden_size: size of recurrent cell\n :param latent_size: size D of the latent variable\n :param pad_idx: id of the -PAD- token\n :param bidirectional: whether we condition on x via a bidirectional or \n unidirectional encoder \n \"\"\"\n super().__init__()\n self.bidirectional = bidirectional\n \n # We borrow the embedder from the generative model, but we don't\n # want tobackpropagate through it for the inference model. So we\n # need to make sure to call detach on the embeddings later.\n self.embedder = embedder\n emb_size = embedder.embedding_dim\n \n # Create a (bidirectional) LSTM to encode x.\n self.lstm = nn.LSTM(emb_size, hidden_size, batch_first=True, \n bidirectional=bidirectional)\n \n # The output of the LSTM doubles if we use a bidirectional encoder.\n encoding_size = hidden_size * 2 if bidirectional else hidden_size\n \n # We can let features interact once more\n self.combination_layer = nn.Linear(encoding_size, 2 * latent_size)\n \n # Create two affine layers to project the encoder final state to\n # the mean and standard deviation of the diagonal Gaussian that\n # we are predicting.\n self.mu_layer = nn.Linear(2 * latent_size, latent_size)\n self.sigma_layer = nn.Linear(2 * latent_size, latent_size)\n\n def forward(self, x, seq_mask, seq_len) -> Normal:\n \n # Compute word embeddings and detach them so that no gradients\n # from the infererence model flow through. That's done because\n # this embedding layer was borrowed from the generative model\n # thus its parameters a part of the set \\theta\n x_embed = self.embedder(x).detach()\n # Alternatively, we could have construct an independent embedding layer\n # for the inference net, then its parameters would be part of the set\n # \\lambda and we would allow updates \n \n # Encode the sentence using the LSTM.\n hidden = None \n packed_seq = pack_padded_sequence(x_embed, seq_len, batch_first=True)\n _, final = self.lstm(packed_seq, hidden) \n\n # Take the final output h_T from the LSTM, concatenate the forward\n # and backward directions for the bidirectional case.\n h_T = final[0]\n if self.bidirectional:\n h_T_fwd = h_T[0]\n h_T_bwd = h_T[1]\n h_T = torch.cat([h_T_fwd, h_T_bwd], dim=-1)\n \n # We make one more transformation \n # this allows a few more interactions between features\n # and if we have bidirectional features then the two \n # directions also interact\n h_T = torch.tanh(self.combination_layer(h_T))\n\n # Compute the mean and sigma of the diagonal Gaussian distribution.\n # Use a softplus activation for the standard deviation to ensure it's\n # positive.\n mu = self.mu_layer(h_T)\n sigma = F.softplus(self.sigma_layer(h_T))\n \n # Return the inferred Gaussian distribution q(z|x).\n qz = Normal(mu, sigma)\n return qz\n```\n\n\n```python\n# tests for inference model\npad_idx = vocab.char_to_idx[PAD_TOKEN]\n\ndummy_inference_model = InferenceModel(\n vocab_size=vocab.size(),\n embedder=nn.Embedding(vocab.size(), 64, padding_idx=pad_idx),\n hidden_size=128, latent_size=16, pad_idx=pad_idx, bidirectional=True\n).to(device=device)\ndummy_batch_size = 32\ndummy_dataloader = SortingTextDataLoader(DataLoader(train_dataset, batch_size=dummy_batch_size))\ndummy_words = next(dummy_dataloader)\n\nx_in, _, seq_mask, seq_len = create_batch(dummy_words, vocab, device)\n\nq_z_given_x = dummy_inference_model.forward(x_in, seq_mask, seq_len)\nassert isinstance(q_z_given_x, Normal), \"inference model should return a Normal distribution\"\nassert q_z_given_x.loc.shape == q_z_given_x.scale.shape, \"loc and scale must be of the same size\"\nassert q_z_given_x.loc.shape == (dummy_batch_size, 16), \"model must produce [batch_size x latent_size] units.\"\nassert torch.all(q_z_given_x.scale >= 0), \"scale can't be negative\"\n```\n\nThen we should implement the generative model, we call it BowmanLM after one of the [authors of the model](https://arxiv.org/abs/1511.06349).\n\n\n```python\nclass BowmanLM(nn.Module):\n \n def __init__(self, vocab_size, emb_size, hidden_size, latent_size,\n pad_idx, dropout=0.):\n \"\"\"\n :param vocab_size: size of the vocabulary of the language\n :param emb_size: dimensionality of embeddings\n :param hidden_size: dimensionality of recurrent cell\n :param latent_size: this is D the dimensionality of the latent variable z\n :param pad_idx: the id reserved to the -PAD- token\n :param dropout: a dropout rate (you can ignore this for now)\n \"\"\"\n pass\n \n \n def init_hidden(self, z):\n \"\"\"\n Returns the hidden state of the LSTM initialized with a projection of a given z.\n :param z: [B, D]\n :returns: [B, D] hidden state, [B, D] cell state\n \n \"\"\"\n pass\n \n def step(self, prev_x, z, hidden):\n \"\"\"\n Performs a single LSTM step for a given previous word and hidden state.\n Returns the unnormalized log probabilities (logits) over the vocabulary for this time step. \n :param prev_x: [B] id of the previous token\n :param z: [B, D] latent variable\n :param hidden: hidden ([B, H] state, [B, H] cell)\n \"\"\"\n pass\n \n def forward(self, x, z):\n \"\"\"\n Performs an entire forward pass given a sequence of words x and a z.\n :param x: [B, T] token ids \n :param z: [B, D] a latent sample\n \"\"\"\n hidden = self.init_hidden(z)\n outputs = []\n for t in range(x.size(1)):\n prev_x = x[:, t].unsqueeze(-1)\n scores, hidden = self.step(prev_x, z, hidden)\n outputs.append(scores)\n return torch.cat(outputs, dim=1)\n \n def loss(self, scores, targets, pz, qz, free_nats=0., evaluation=False):\n \"\"\"\n Computes the terms in the loss (negative ELBO) given the \n scores (unnormalized log-probabilities), targets,\n the prior distribution p(z), and the approximate posterior distribution q(z|x).\n \n If free_nats is nonzero it will clamp the KL divergence between the posterior\n and prior to that value, preventing gradient propagation via the KL if it's\n below that value. \n \n If evaluation is set to true, the loss will be summed instead\n of averaged over the batch. \n \n Returns the reconstruction loss and the KL. \n \n The loss\n can be computed from those as loss = rec_loss - KL.\n \n :returns: \n negative log likelihood (scalar), KL (scalar)\n (use mean for training mode and sum for evaluation mode)\n \"\"\"\n pass\n```\n\n\n```python\n# SOLUTION\nclass BowmanLM(nn.Module):\n \n def __init__(self, vocab_size, emb_size, hidden_size, latent_size,\n pad_idx, dropout=0.):\n \"\"\"\n :param vocab_size: size of the vocabulary of the language\n :param emb_size: dimensionality of embeddings\n :param hidden_size: dimensionality of recurrent cell\n :param latent_size: this is D the dimensionality of the latent variable z\n :param pad_idx: the id reserved to the -PAD- token\n :param dropout: a dropout rate\n \"\"\"\n super().__init__()\n self.pad_idx = pad_idx\n self.embedder = nn.Embedding(vocab_size, emb_size,\n padding_idx=pad_idx)\n self.lstm = nn.LSTM(emb_size, hidden_size, batch_first=True)\n self.bridge = nn.Linear(latent_size, hidden_size)\n self.projection = nn.Linear(hidden_size, vocab_size, bias=False)\n self.dropout_layer = nn.Dropout(p=dropout)\n \n def init_hidden(self, z):\n \"\"\"\n Returns the hidden state of the LSTM initialized with a projection of a given z.\n :param z: [B, D]\n :returns: [B, D] hidden state, [B, D] cell state\n \n \"\"\"\n h = self.bridge(z).unsqueeze(0)\n c = self.bridge(z).unsqueeze(0)\n return (h, c)\n \n def step(self, prev_x, z, hidden):\n \"\"\"\n Performs a single LSTM step for a given previous word and hidden state.\n Returns the unnormalized probabilities over the vocabulary for this time step. \n :param prev_x: [B] id of the previous token\n :param z: [B, D] latent variable\n :param hidden: hidden ([B, H] state, [B, H] cell)\n \"\"\"\n x_embed = self.dropout_layer(self.embedder(prev_x))\n output, hidden = self.lstm(x_embed, hidden)\n scores = self.projection(self.dropout_layer(output))\n return scores, hidden\n \n def forward(self, x, z):\n \"\"\"\n Performs an entire forward pass given a sequence of words x and a z.\n :param x: [B, T] token ids \n :param z: [B, D] a latent sample\n \"\"\"\n hidden = self.init_hidden(z)\n outputs = []\n for t in range(x.size(1)):\n prev_x = x[:, t].unsqueeze(-1)\n scores, hidden = self.step(prev_x, z, hidden)\n outputs.append(scores)\n return torch.cat(outputs, dim=1)\n \n def loss(self, scores, targets, pz, qz, free_nats=0., evaluation=False):\n \"\"\"\n Computes the terms in the loss (negative ELBO) given the \n scores (unnormalized log-probabilities), targets,\n the prior distribution p(z), and the approximate posterior distribution q(z|x).\n \n If free_nats is nonzero it will clamp the KL divergence between the posterior\n and prior to that value, preventing gradient propagation via the KL if it's\n below that value. \n \n If evaluation is set to true, the loss will be summed instead\n of averaged over the batch. \n \n Returns the reconstruction loss and the KL. \n \n The loss\n can be computed from those as loss = rec_loss - KL.\n \n :returns: \n negative log likelihood (scalar), KL (scalar)\n (use mean for training mode and sum for evaluation mode)\n \"\"\"\n \n # Approximate E[log P(x|z)].\n scores = scores.permute(0, 2, 1)\n reconstruction_loss = F.cross_entropy(scores, targets, \n ignore_index=self.pad_idx, \n reduction=\"none\")\n reconstruction_loss = reconstruction_loss.sum(dim=1)\n \n # Compute the KL divergence and clamp to at least the given amount of free nats.\n KL = qz.kl(pz).sum(dim=1)\n KL = torch.clamp(KL, min=free_nats)\n \n # For evaluation return the sum of individual components, for\n # training return the mean of those components.\n if evaluation:\n return (reconstruction_loss.sum(), KL.sum())\n else:\n return (reconstruction_loss.mean(), KL.mean())\n```\n\nThe code below is used to assess the model and also investigate what it learned. We implemented it for you, so that you can focus on the VAE part. It's useful however to learn from this example: we do interesting things like computing perplexity and sampling novel words!\n\n# Evaluation metrics\n\nDuring training we'd like to keep track of some evaluation metrics on the validation data in order to keep track of how our model is doing and to perform early stopping. One simple metric we can compute is the ELBO on all the validation or test data using a single sample from the approximate posterior $q(z|x)$:\n\n\n```python\ndef eval_elbo(model, inference_model, eval_dataset, vocab, device, batch_size=128):\n \"\"\"\n Computes a single sample estimate of the ELBO on a given dataset.\n \"\"\"\n dl = DataLoader(eval_dataset, batch_size=batch_size)\n sorted_dl = SortingTextDataLoader(dl)\n \n # Make sure the model is in evaluation mode (i.e. disable dropout).\n model.eval()\n \n total_rec_loss = 0.\n total_KL = 0.\n num_words = 0\n \n # We don't need to compute gradients for this.\n with torch.no_grad():\n for words in sorted_dl: \n x_in, x_out, seq_mask, seq_len = create_batch(words, vocab, device)\n \n # Infer the approximate posterior and construct the prior.\n qz = inference_model(x_in, seq_mask, seq_len)\n pz = Normal(torch.zeros_like(qz.mean()), \n torch.ones_like(qz.std()))\n \n # Compute the unnormalized probabilities using a single sample from the\n # approximate posterior.\n z = qz.sample()\n scores = model(x_in, z)\n \n # Compute the reconstruction loss and KL divergence.\n reconstruction_loss, KL = model.loss(scores, x_out, pz, qz,\n free_nats=0.,\n evaluation=True)\n total_rec_loss += reconstruction_loss\n total_KL += KL\n num_words += x_in.size(0)\n\n # Return the average reconstruction loss and KL.\n avg_rec_loss = total_rec_loss / num_words\n avg_KL = total_KL / num_words\n return avg_rec_loss, avg_KL\n```\n\n\n```python\n# test for your BowmanLM implementation with elbo. This may take a few seconds\ndummy_lm = BowmanLM(vocab.size(), emb_size=64, hidden_size=128, \n latent_size=16, pad_idx=pad_idx).to(device=device)\n\n!head -n 128 {val_file} > ./dummy_dataset\ndummy_data = TextDataset('./dummy_dataset')\ndummy_rec_loss, dummy_kl = eval_elbo(dummy_lm, dummy_inference_model,\n dummy_data, vocab, device)\nprint(dummy_rec_loss, dummy_kl)\nassert dummy_rec_loss.item() > 0 and dummy_kl.item() > 0\n```\n\n tensor(36.9271) tensor(1.6146)\n\n\n\nA common metric to evaluate language models is the perplexity per word. The perplexity per word for a dataset is defined as:\n\n\\begin{align}\n \\text{ppl}(\\mathcal{D}) = \\exp\\left(-\\frac{1}{\\sum_{k=1}^{|\\mathcal D|} n^{(k)}} \\sum_{k=1}^{|\\mathcal{D}|} \\log P(x^{(k)})\\right) \n\\end{align}\n\nwhere $n^{(k)} = |x^{(k)}|$ is the number of tokens in a word and $P(x^{(k)})$ is the probability that our model assigns to the datapoint $x^{(k)}$. In order to compute $\\log P(x)$ for our model we need to evaluate the integral:\n\n\\begin{align}\n P(x) = \\int P(x|z) p(z) dz\n\\end{align}\n\nAs this is an integral cannot be compute in closed-form, we have two options: we can use the earlier derived lower-bound on the log-likelihood, which will give us an upper-bound on the perplexity, or we can make an importance sampling estimate using our approximate posterior distribution. The importance sampling (IS) estimate can be done as:\n\n\\begin{align}\n\\hat P(x) &\\overset{\\text{IS}}{\\approx} \\frac{1}{S} \\sum_{s=1}^{S} \\frac{p(z^{(s)})p(x|z^{(s)})}{q(z^{(s)}|x)} & \\text{where }z^{(s)} \\sim q(z|x)\n\\end{align}\n\nwhere $S$ is the number of samples.\n\nThen our perplexity becomes:\n\\begin{align}\n &\\frac{1}{\\sum_{k=1}^{|\\mathcal D|} n^{(k)}} \\sum_{k=1}^{|\\mathcal D|} \\log p(x^{(k)}) \\\\\n &\\approx \\frac{1}{\\sum_{k=1}^{|\\mathcal D|} n^{(k)}} \\sum_{k=1}^{|\\mathcal D|} \\log \\frac{1}{S} \\sum_{s=1}^{S} \\frac{p(z^{(s)})p(x^{(k)}|z^{(s)})}{q(z^{(s)}|x^{(k)})} \\\\\n\\end{align}\n\nWe define the function `eval_perplexity` below that implements this importance sampling estimate:\n\n\n```python\ndef eval_perplexity(model, inference_model, eval_dataset, vocab, device, \n n_samples, batch_size=128):\n \"\"\"\n Estimates the per-word perplexity using importance sampling with the\n given number of samples.\n \"\"\"\n \n dl = DataLoader(eval_dataset, batch_size=batch_size)\n sorted_dl = SortingTextDataLoader(dl)\n \n # Make sure the model is in evaluation mode (i.e. disable dropout).\n model.eval()\n \n log_px = 0.\n num_predictions = 0\n num_words = 0\n \n # We don't need to compute gradients for this.\n with torch.no_grad():\n for words in sorted_dl:\n x_in, x_out, seq_mask, seq_len = create_batch(words, vocab, device)\n \n # Infer the approximate posterior and construct the prior.\n qz = inference_model(x_in, seq_mask, seq_len)\n pz = Normal(torch.zeros_like(qz.mean()), \n torch.ones_like(qz.std()))\n\n # Create an array to hold all samples for this batch.\n batch_size = x_in.size(0)\n log_px_samples = torch.zeros(n_samples, batch_size)\n \n # Sample log P(x) n_samples times.\n for s in range(n_samples):\n \n # Sample a z^s from the posterior.\n z = qz.sample()\n \n # Compute log P(x^k|z^s)\n scores = model(x_in, z)\n cond_log_prob = F.log_softmax(scores, dim=-1)\n cond_log_prob = torch.gather(cond_log_prob, 2, x_out.unsqueeze(-1)).squeeze() # B x T\n cond_log_prob = (cond_log_prob * seq_mask.type_as(cond_log_prob)).sum(dim=1) # B\n \n # Compute log p(z^s) and log q(z^s|x^k)\n prior_log_prob = pz.log_pdf(z).sum(dim=1) # B\n posterior_log_prob = qz.log_pdf(z).sum(dim=1) # B\n \n # Store the sample for log P(x^k) importance weighted with p(z^s)/q(z^s|x^k).\n log_px_sample = cond_log_prob + prior_log_prob - posterior_log_prob\n log_px_samples[s] = log_px_sample\n \n # Average over the number of samples and count the number of predictions made this batch.\n log_px_batch = torch.logsumexp(log_px_samples, dim=0) - \\\n torch.log(torch.Tensor([n_samples]))\n log_px += log_px_batch.sum()\n num_predictions += seq_len.sum()\n num_words += seq_len.size(0)\n\n # Compute and return the perplexity per word.\n perplexity = torch.exp(-log_px / num_predictions)\n NLL = -log_px / num_words\n return perplexity, NLL\n```\n\nLastly, we want to occasionally qualitatively see the performance of the model during training, by letting it reconstruct a given word from the latent space. This gives us an idea of whether the model is using the latent space to encode some semantics about the data. For this we use a deterministic greedy decoding algorithm, that chooses the word with maximum probability at every time step, and feeds that word into the next time step.\n\n\n```python\ndef greedy_decode(model, z, vocab, max_len=50):\n \"\"\"\n Greedily decodes a word from a given z, by picking the word with\n maximum probability at each time step.\n \"\"\"\n \n # Disable dropout.\n model.eval()\n \n # Don't compute gradients.\n with torch.no_grad():\n batch_size = z.size(0)\n \n # We feed the model the start-of-word symbol at the first time step.\n prev_x = torch.ones(batch_size, 1, dtype=torch.long).fill_(vocab[SOW_TOKEN]).to(z.device)\n \n # Initialize the hidden state from z.\n hidden = model.init_hidden(z)\n\n predictions = [] \n for t in range(max_len):\n scores, hidden = model.step(prev_x, z, hidden)\n \n # Choose the argmax of the unnnormalized probabilities as the\n # prediction for this time step.\n prediction = torch.argmax(scores, dim=-1)\n predictions.append(prediction)\n \n prev_x = prediction.view(batch_size, 1)\n \n return torch.cat(predictions, dim=1)\n```\n\n# Training\n\nNow it's time to train the model. We use early stopping on the validation perplexity for model selection.\n\n\n```python\n# Define the model hyperparameters.\nemb_size = 256\nhidden_size = 256 \nlatent_size = 16\nbidirectional_encoder = True\nfree_nats = 5.\nannealing_steps = 11400\ndropout = 0.6\nword_dropout = 0.75\nbatch_size = 64\nlearning_rate = 0.001\nnum_epochs = 20\nn_importance_samples = 3 # 50\n\n# Create the training data loader.\ndl = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\nsorted_dl = SortingTextDataLoader(dl)\n\n# Create the generative model.\nmodel = BowmanLM(vocab_size=vocab.size(), \n emb_size=emb_size, \n hidden_size=hidden_size, \n latent_size=latent_size, \n pad_idx=vocab[PAD_TOKEN],\n dropout=dropout)\nmodel = model.to(device)\n\n# Create the inference model.\ninference_model = InferenceModel(vocab_size=vocab.size(),\n embedder=model.embedder,\n hidden_size=hidden_size,\n latent_size=latent_size,\n pad_idx=vocab[PAD_TOKEN],\n bidirectional=bidirectional_encoder)\ninference_model = inference_model.to(device)\n\n# Create the optimizer.\noptimizer = optim.Adam(itertools.chain(model.parameters(), \n inference_model.parameters()), \n lr=learning_rate)\n\n# Save the best model (early stopping).\nbest_model = \"./best_model.pt\"\nbest_val_ppl = float(\"inf\")\nbest_epoch = 0\n\n# Keep track of some statistics to plot later.\ntrain_ELBOs = []\ntrain_KLs = []\nval_ELBOs = []\nval_KLs = []\nval_perplexities = []\nval_NLLs = []\n\nstep = 0\ntraining_ELBO = 0.\ntraining_KL = 0.\nnum_batches = 0\nfor epoch_num in range(1, num_epochs+1): \n for words in sorted_dl:\n\n # Make sure the model is in training mode (for dropout).\n model.train()\n\n # Transform the words to input, output, seq_len, seq_mask batches.\n x_in, x_out, seq_mask, seq_len = create_batch(words, vocab, device,\n word_dropout=word_dropout)\n\n # Compute the multiplier for the KL term if we do annealing.\n if annealing_steps > 0:\n KL_weight = min(1., (1.0 / annealing_steps) * step)\n else:\n KL_weight = 1.\n \n # Do a forward pass through the model and compute the training loss. We use\n # a reparameterized sample from the approximate posterior during training.\n qz = inference_model(x_in, seq_mask, seq_len)\n pz = Normal(torch.zeros_like(qz.mean()), \n torch.ones_like(qz.std()))\n z = qz.sample()\n scores = model(x_in, z)\n rec_loss, KL = model.loss(scores, x_out, pz, qz, free_nats=free_nats)\n loss = rec_loss + KL_weight * KL\n\n # Backpropagate and update the model weights.\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n # Update some statistics to track for the training loss.\n training_ELBO += -(rec_loss - KL)\n training_KL += KL\n num_batches += 1\n \n # Every 100 steps we evaluate the model and report progress.\n if step % 100 == 0:\n val_rec_loss, val_KL = eval_elbo(model, inference_model, val_dataset, vocab, device)\n val_ELBO = -(val_rec_loss - val_KL)\n print(\"(%d) step %d: training ELBO (KL) = %.2f (%.2f) --\"\n \" KL weight = %.2f --\"\n \" validation ELBO (KL) = %.2f (%.2f)\" % \n (epoch_num, step, training_ELBO/num_batches, \n training_KL/num_batches, KL_weight, val_ELBO, val_KL))\n \n # Update some statistics for plotting later.\n train_ELBOs.append((step, (training_ELBO/num_batches).item()))\n train_KLs.append((step, (training_KL/num_batches).item()))\n val_ELBOs.append((step, val_ELBO.item()))\n val_KLs.append((step, val_KL.item()))\n \n # Reset the training statistics.\n training_ELBO = 0.\n training_KL = 0.\n num_batches = 0\n \n step += 1\n\n # After an epoch we'll compute validation perplexity and save the model\n # for early stopping if it's better than previous models.\n print(\"Finished epoch %d\" % (epoch_num))\n val_perplexity, val_NLL = eval_perplexity(model, inference_model, val_dataset, vocab, device, \n n_importance_samples)\n val_rec_loss, val_KL = eval_elbo(model, inference_model, val_dataset, vocab, device)\n val_ELBO = -(val_rec_loss - val_KL)\n \n # Keep track of the validation perplexities / NLL.\n val_perplexities.append((epoch_num, val_perplexity.item()))\n val_NLLs.append((epoch_num, val_NLL.item()))\n \n # If validation perplexity is better, store this model for early stopping.\n if val_perplexity < best_val_ppl:\n best_val_ppl = val_perplexity\n best_epoch = epoch_num\n torch.save(model.state_dict(), best_model)\n \n # Print epoch statistics.\n print(\"Evaluation epoch %d:\\n\"\n \" - validation perplexity: %.2f\\n\"\n \" - validation NLL: %.2f\\n\"\n \" - validation ELBO (KL) = %.2f (%.2f)\"\n % (epoch_num, val_perplexity, val_NLL, val_ELBO, val_KL))\n\n # Also show some qualitative results by reconstructing a word from the\n # validation data. Use the mean of the approximate posterior and greedy\n # decoding.\n random_word = val_dataset[np.random.choice(len(val_dataset))]\n x_in, _, seq_mask, seq_len = create_batch([random_word], vocab, device)\n qz = inference_model(x_in, seq_mask, seq_len)\n z = qz.mean()\n reconstruction = greedy_decode(model, z, vocab)\n reconstruction = batch_to_words(reconstruction, vocab)[0]\n print(\"-- Original word: \\\"%s\\\"\" % random_word)\n print(\"-- Model reconstruction: \\\"%s\\\"\" % reconstruction)\n```\n\n# Let's plot the training and validation statistics:\n\n\n```python\nsteps, training_ELBO = list(zip(*train_ELBOs))\n_, training_KL = list(zip(*train_KLs))\n_, val_ELBO = list(zip(*val_ELBOs))\n_, val_KL = list(zip(*val_KLs))\nepochs, val_ppl = list(zip(*val_perplexities))\n_, val_NLL = list(zip(*val_NLLs))\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 5))\n\n# Plot training ELBO and KL\nax1.set_title(\"Training ELBO\")\nax1.plot(steps, training_ELBO, \"-o\")\nax2.set_title(\"Training KL\")\nax2.plot(steps, training_KL, \"-o\")\nplt.show()\n\n# Plot validation ELBO and KL\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 5))\nax1.set_title(\"Validation ELBO\")\nax1.plot(steps, val_ELBO, \"-o\", color=\"orange\")\nax2.set_title(\"Validation KL\")\nax2.plot(steps, val_KL, \"-o\", color=\"orange\")\nplt.show()\n\n# Plot validation perplexities.\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 5))\nax1.set_title(\"Validation perplexity\")\nax1.plot(epochs, val_ppl, \"-o\", color=\"orange\")\nax2.set_title(\"Validation NLL\")\nax2.plot(epochs, val_NLL, \"-o\", color=\"orange\")\nplt.show()\nprint()\n```\n\nLet's load the best model according to validation perplexity and compute its perplexity on the test data:\n\n\n```python\n# Load the best model from disk.\nmodel = BowmanLM(vocab_size=vocab.size(), \n emb_size=emb_size, \n hidden_size=hidden_size, \n latent_size=latent_size, \n pad_idx=vocab[PAD_TOKEN],\n dropout=dropout)\nmodel.load_state_dict(torch.load(best_model))\nmodel = model.to(device)\n\n# Compute test perplexity and ELBO.\ntest_perplexity, test_NLL = eval_perplexity(model, inference_model, test_dataset, vocab, \n device, n_importance_samples)\ntest_rec_loss, test_KL = eval_elbo(model, inference_model, test_dataset, vocab, device)\ntest_ELBO = test_rec_loss - test_KL\nprint(\"test ELBO (KL) = %.2f (%.2f) -- test perplexity = %.2f -- test NLL = %.2f\" % \n (test_ELBO, test_KL, test_perplexity, test_NLL))\n```\n\n# Qualitative analysis\n\nLet's have a look at what how our trained model interacts with the learned latent space. First let's greedily decode some samples from the prior to assess the diversity of the model:\n\n\n```python\n# Generate 10 samples from the standard normal prior.\nnum_prior_samples = 10\npz = Normal(torch.zeros(num_prior_samples, latent_size), \n torch.ones(num_prior_samples, latent_size))\nz = pz.sample()\nz = z.to(device)\n\n# Use the greedy decoding algorithm to generate words.\npredictions = greedy_decode(model, z, vocab)\npredictions = batch_to_words(predictions, vocab)\nfor num, prediction in enumerate(predictions):\n print(\"%d: %s\" % (num+1, prediction))\n```\n\nLet's now have a look how good the model is at reconstructing words from the test dataset using the approximate posterior mean and a couple of samples:\n\n\n```python\n# Pick a random test word.\ntest_word = test_dataset[np.random.choice(len(test_dataset))]\n\n# Infer q(z|x).\nx_in, _, seq_mask, seq_len = create_batch([test_word], vocab, device)\nqz = inference_model(x_in, seq_mask, seq_len)\n\n# Decode using the mean.\nz_mean = qz.mean()\nmean_reconstruction = greedy_decode(model, z_mean, vocab)\nmean_reconstruction = batch_to_words(mean_reconstruction, vocab)[0]\n\nprint(\"Original: \\\"%s\\\"\" % test_word)\nprint(\"Posterior mean reconstruction: \\\"%s\\\"\" % mean_reconstruction)\n\n# Decode a couple of samples from the approximate posterior.\nfor s in range(3):\n z = qz.sample()\n sample_reconstruction = greedy_decode(model, z, vocab)\n sample_reconstruction = batch_to_words(sample_reconstruction, vocab)[0]\n print(\"Posterior sample reconstruction (%d): \\\"%s\\\"\" % (s+1, sample_reconstruction))\n```\n\nWe can also qualitatively assess the smoothness of the learned latent space by interpolating between two words in the test set:\n\n\n```python\n# Pick a random test word.\ntest_word_1 = test_dataset[np.random.choice(len(test_dataset))]\n\n# Infer q(z|x).\nx_in, _, seq_mask, seq_len = create_batch([test_word_1], vocab, device)\nqz = inference_model(x_in, seq_mask, seq_len)\nqz_1 = qz.mean()\n\n# Pick a random second test word.\ntest_word_2 = test_dataset[np.random.choice(len(test_dataset))]\n\n# Infer q(z|x) again.\nx_in, _, seq_mask, seq_len = create_batch([test_word_2], vocab, device)\nqz = inference_model(x_in, seq_mask, seq_len)\nqz_2 = qz.mean()\n\n# Now interpolate between the two means and generate words between those.\nnum_words = 5\nprint(\"Word 1: \\\"%s\\\"\" % test_word_1)\nfor alpha in np.linspace(start=0., stop=1., num=num_words):\n z = (1-alpha) * qz_1 + alpha * qz_2\n reconstruction = greedy_decode(model, z, vocab)\n reconstruction = batch_to_words(reconstruction, vocab)[0]\n print(\"(1-%.2f) * qz1.mean + %.2f qz2.mean: \\\"%s\\\"\" % (alpha, alpha, reconstruction))\nprint(\"Word 2: \\\"%s\\\"\" % test_word_2)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a0d60a604a299559145f67ee237b2f87f8e5a59e", "size": 93290, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "WordVAE/WordVAE-Solutions.ipynb", "max_stars_repo_name": "Roxot/vitutorial-exercises", "max_stars_repo_head_hexsha": "89afad877e2254d66d8741e1989182a20c87eaed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-05T11:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T11:42:47.000Z", "max_issues_repo_path": "WordVAE/WordVAE-Solutions.ipynb", "max_issues_repo_name": "Roxot/vitutorial-exercises", "max_issues_repo_head_hexsha": "89afad877e2254d66d8741e1989182a20c87eaed", "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": "WordVAE/WordVAE-Solutions.ipynb", "max_forks_repo_name": "Roxot/vitutorial-exercises", "max_forks_repo_head_hexsha": "89afad877e2254d66d8741e1989182a20c87eaed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-21T10:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-21T10:52:30.000Z", "avg_line_length": 47.6699029126, "max_line_length": 1900, "alphanum_fraction": 0.562107407, "converted": true, "num_tokens": 15220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.12421300024700384, "lm_q1q2_score": 0.061136165023859546}} {"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols, eye, Rational\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Diagonalizing a matrix\n# Powers of a matrix A\n\n## Definition\n\n* If A is a *n*×*n*, then a non-zero vector **x** in ℝn is called an *eigenvector* of the matrix A if A**x** is a scalar multiple of **x**\n* What this suggests is that if you consider the column vector **x** and multiply it by a scalar (here called λ) (which is then parallel to **x**, just of different length) it results in the same solution as multiplying the matrix A by **x**\n* Let's try another explanation: if a matrix A, multiplied with a (column) vector (**x**) results in a scalar multiple of that same (column) vector (and is thus parallel to that (column) vector) then this (column) vector is an eigenvector of the matrix A\n * In essence this multiplication of a matrix with a (column) vector produces another vector on the same line as the original vector\n * Depending on the value of this scalar the resulting vector might point in the opposite direction and be shorter or longer than the original\n* This scalar multiple is called the eigenvalue\n* Matrices can have more than one eigenvalue and eigenvector\n\n## Derivations\n\n* We need to insert an identity matrix of size *n* into the equation that describes the explanation above\n$$ {A}\\underline{x}={\\lambda}\\underline{x} \\\\ {A}\\underline{x}={\\lambda}{I}\\underline{x} \\\\ {A}\\underline{x}-{\\lambda}{I}\\underline{x}=\\underline{0} \\\\ \\left({A}-{\\lambda}{I}\\right)\\underline{x}=\\underline{0} $$\n\n* Look at this carefully and you'll notice that we are suggesting the nullspace (eigenspace) of the matrix (A-λI)\n* This matrix has to be singular, i.e. have a determinant of 0\n$$ \\left|{A}-{\\lambda}{I}\\right|=0 $$\n* Solving this equation (called the characteristic equation) will give us the eigenvalues (λ's)\n* It will always be a polynomial in λ (called the characteristic polynomial of A), with a leading coefficient of 1 and a degree of *n* corresponding to the size of A\n$$ {p}\\left({\\lambda}\\right)={\\lambda}^{n}+{c}_{1}{\\lambda}^{n-1}+\\dots+{c}_{n} $$\n* Substituting them back into...\n$$ \\left({A}\\underline{x}-{\\lambda}{I}\\right)\\underline{x}=\\underline{0} $$\n* ... allows us to calculate the eigenvector(s) **x**\n\n* Let's look at the following matrix A\n$$ A=\\begin{bmatrix} 0 & 0 & -2 \\\\ 1 & 2 & 1 \\\\ 1 & 0 & 3 \\end{bmatrix}\\\\ A-\\lambda I=\\begin{bmatrix} 0 & 0 & -2 \\\\ 1 & 2 & 1 \\\\ 1 & 0 & 3 \\end{bmatrix}-\\begin{bmatrix} \\lambda & 0 & 0 \\\\ 0 & \\lambda & 0 \\\\ 0 & 0 & \\lambda \\end{bmatrix}=\\begin{bmatrix} -\\lambda & 0 & -2 \\\\ 1 & 2-\\lambda & 1 \\\\ 1 & 0 & 3-\\lambda \\end{bmatrix}\\\\ \\begin{vmatrix} -\\lambda & 0 & -2 \\\\ 1 & 2-\\lambda & 1 \\\\ 1 & 0 & 3-\\lambda \\end{vmatrix}=0\\\\ { \\lambda }^{ 3 }-5{ \\lambda }^{ 2 }+8\\lambda -4=0\\\\ { \\lambda }_{ 1 }=1,\\quad { \\lambda }_{ 2 }={ \\lambda }_{ 3 }=2 $$\n\n* Let's start with the first eigenvalue, which is equal to 1 and replace it in A-λI\n\n\n```python\nA = Matrix([[-1, 0 ,-2], [1, 1, 1], [1, 0, 2]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 0 & -2\\\\1 & 1 & 1\\\\1 & 0 & 2\\end{matrix}\\right]$$\n\n\n\n* We now need the nullspace of this matrix\n\n\n```python\nA.nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}-2\\\\1\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n* We knew that this would be 1-dimensional after looking at the row-reduced form\n\n\n```python\nA.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & 2\\\\0 & 1 & -1\\\\0 & 0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* It has rank 2 (two pivot column and 1 free variable\n\n* Now for the other 2 eigenvalues, both equaling 2\n\n\n```python\nA = Matrix([[-2, 0, -2], [1, 0, 1], [1, 0, 1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}-2 & 0 & -2\\\\1 & 0 & 1\\\\1 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}0\\\\1\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}-1\\\\0\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n\n```python\nA.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & 1\\\\0 & 0 & 0\\\\0 & 0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* Only a single pivot column, therefor rank of 1 and two independent (free) variables\n\n* Corresponding to the first eigenvalue we have a single eigenvector that is the basis for a 1-dimensional (line) eigenspace in ℝ3\n* Corresponding to the second (and third) eigenvalues we have two basis vectors for a 2-dimensional plane in ℝ3\n* Since we are talking about subspaces, we must note that the zero vector must be in both eigenspaces (type of nullspace), but isn't an eigenvector\n\n## The eigenvalues of triangular (upper and lower) and diagonal matrices\n\n* The eigenvalue of these type of matrices are exactly the entries along the main diagonal\n\n## Real and complex eigenvalues\n\n* There will be characteristic polynomials resulting in complex roots\n* The consequences of real-valued eigenvalues for a square matrix A of size *n* are the following\n * The system (A-λI)**x**=**0** has non-trivial solutions\n * There is a non-zero vector **x** in ℝn such that A**x**=λ**x**\n\n## The eigenvector matrix S and eigenvalue matrix Λ\n\n* We need to create S from the (column) eigenvectors such that the following holds\n$$ {S}^{-1}{A}{S}=\\Lambda $$\n\n* As such, S should be square of size *n*×*n* and invertible, so we need *n* independent eigenvectors\n\n* Suppose we have *n* linearly independent eigenvectors of A\n* Put them in the columns of S and calculate AS\n$$ AS=A\\begin{bmatrix} \\vdots & \\vdots & \\vdots & \\vdots \\\\ \\vdots & \\vdots & \\vdots & \\vdots \\\\ { x }_{ 1 } & { x }_{ 2 } & \\dots & { x }_{ n } \\\\ \\vdots & \\vdots & \\vdots & \\vdots \\end{bmatrix}=\\begin{bmatrix} \\vdots & \\vdots & \\vdots & \\vdots \\\\ \\vdots & \\vdots & \\vdots & \\vdots \\\\ { { \\lambda }_{ 1 }x }_{ 1 } & { \\lambda }_{ 2 }{ x }_{ 2 } & \\dots & { \\lambda }_{ n }{ x }_{ n } \\\\ \\vdots & \\vdots & \\vdots & \\vdots \\end{bmatrix}=\\begin{bmatrix} \\vdots & \\vdots & \\vdots & \\vdots \\\\ \\vdots & \\vdots & \\vdots & \\vdots \\\\ { x }_{ 1 } & { x }_{ 2 } & \\dots & { x }_{ n } \\\\ \\vdots & \\vdots & \\vdots & \\vdots \\end{bmatrix}\\begin{bmatrix} { \\lambda }_{ 1 } & 0 & 0 & 0 \\\\ 0 & { \\lambda }_{ 2 } & 0 & 0 \\\\ \\vdots & \\vdots & { \\dots } & \\vdots \\\\ 0 & 0 & 0 & { \\lambda }_{ n } \\end{bmatrix}\\\\ AS=S\\Lambda $$\n\n* From this we have the following\n$$ AS=S\\Lambda \\\\ { S }^{ -1 }AS=\\Lambda \\\\ A=S\\Lambda { S }^{ -1 } $$\n* Later I will use the computer variable D for this diagonal matrix Λ\n\n## The power of a matrix (only for *n* independent eigenvectors)\n\n* We saw in the example section of the last lecture that the following holds\n$$ {A}^{2}\\underline{x}={\\lambda}^{2}{x} $$\n* The eigenvectors are the same for A and A2\n* We can also see the following\n$$ { A }^{ 2 }=S\\Lambda { S }^{ -1 }S\\Lambda { S }^{ -1 }=S{ \\Lambda }^{ 2 }{ S }^{ -1 } $$\n\n* The power need not be 2, but any *k* which will have S-1 appearing *k*-1 times\n\n* We thus have the following theorems\n$$ { A }^{ k }\\rightarrow 0\\quad \\because \\quad k\\rightarrow \\infty ;\\quad \\left| { \\lambda }_{ i } \\right| $$\n* ...and...\n* If *k* is a positive integer, λ is an eigenvalue of the matrix A, and **x** is a corresponding eigenvector, then λk is an eigenvalue of Ak and **x** is a corresponding eigenvector\n\n## What makes a matrix diagonalizable\n\n* In discussing diagonalization we are concerned with finding a basis for ℝn that consists of eigenvectors of a given square matrix of size *n*\n* These bases can tell us about geometric properties of A and it can simplify numerical computations involving A\n\n* We need to answer two question (which are actually the same)\n * Given a square matrix of size *n*, is there a basis for ℝn consisting of eigenvectors?\n * Given a square matrix of size *n*, it there and invertible matrix S, such that S-1AS is a diagonal matrix? (It is the same matrix S referred to above)\n* If such a matrix S exists, it is said to diagonalize A (and we will call the resultant diagonal matrix D)\n\n* In short the answer to the above question(s) is yes if A has *n* independent eigenvectors\n * This happens if all λ's are different (none are repeated) (not totally excluded if they are repeated though)\n\n* If they are repeated, we still might have independent eigenvectors, i.e. any size identity matrix (because it is already diagonal)\n\n\n```python\nA = eye(5)\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 0 & 0 & 0 & 0\\\\0 & 1 & 0 & 0 & 0\\\\0 & 0 & 1 & 0 & 0\\\\0 & 0 & 0 & 1 & 0\\\\0 & 0 & 0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}1 : 5\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}1, & 5, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\1\\\\0\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\0\\\\1\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\0\\\\0\\\\1\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\0\\\\0\\\\0\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* Here we look at a triangular matrix, though\n\n\n```python\nA = Matrix([[2, 1], [0, 2]])\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}2 : 2\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}2, & 2, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* We can use python™ code to calculate the diagonalized matrix\n\n\n```python\nA = Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}3 & -2 & 4 & -2\\\\5 & 3 & -3 & -2\\\\5 & -2 & 2 & -2\\\\5 & -2 & -3 & 3\\end{matrix}\\right]$$\n\n\n\n\n```python\nS, D = A.diagonalize()\n```\n\n\n```python\nS # S, such that A = S times D times the inverse of S\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 1 & 1 & 0\\\\1 & 1 & 1 & -1\\\\1 & 1 & 1 & 0\\\\1 & 1 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nD # The diagonal\n```\n\n\n\n\n$$\\left[\\begin{matrix}-2 & 0 & 0 & 0\\\\0 & 3 & 0 & 0\\\\0 & 0 & 5 & 0\\\\0 & 0 & 0 & 5\\end{matrix}\\right]$$\n\n\n\n\n```python\nS * D * S.inv() == A # Checking to see if our statement above is correct\n```\n\n\n\n\n True\n\n\n\n\n```python\nS.inv() * A * S == D # Checking to see if our statement above is correct\n```\n\n\n\n\n True\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}-2 : 1, & 3 : 1, & 5 : 2\\end{Bmatrix}$$\n\n\n\n* Remember Λ from above?\n * The eigenvalues are precisely the entries along the main diagonal of the diagonal matrix\n\n* To produce the required diagonal matrix manually then will require computing *n* linearly independent eigenvectors for matrix A of size *n* (assuming that it is diagonalizable), creating a matrix with its columns equal to these eigenvectors (called matrix S) and performing the equation S-1AS to calculate the diagonal matrix D ( or Λ)\n\n* Back to the topic of what makes a matrix diagonalizable\n\n* Suppose we have an equation that starts with some vector and every subsequent vector is a matrix A time the previous vector\n$$ \\underline{u}_{k+1}={A}\\underline{u}_{k} $$\n\n* From this arises the following\n$$ { \\underline { u } }_{ 1 }=A{ \\underline { u } }_{ 0 }\\\\ { \\underline { u } }_{ 2 }=A{ A\\underline { u } }_{ 0 }={ A }^{ 2 }{ \\underline { u } }_{ 0 }\\\\ { \\underline { u } }_{ k }={ A }^{ k }{ \\underline { u } }_{ 0 } $$\n\n* To really solve this problem, rewrite **u**0 as follows (a certain scalar times an eigenvector)\n$$ { \\underline { u } }_{ 0 }={ c }_{ 1 }\\underline{ x }_{ 1 }+{ c }_{ 2 }\\underline{ x }_{ 2 }+\\dots +{ c }_{ n }\\underline{ x }_{ n } = {S}\\underline{c} $$\n* Where the S**c** is a linear combination of the individual eigenvectors\n\n* Now multiply both sides by A\n$$ A{ \\underline { u } }_{ 0 }={ c }_{ 1 }{A}\\underline{ x }_{ 1 }+{ c }_{ 2 }{A}\\underline{ x }_{ 2 }+\\dots +{ c }_{ n }{A}\\underline{ x }_{ n } \\\\ A{ \\underline { u } }_{ 0 }={ c }_{ 1 }{ \\lambda }_{ 1 }\\underline{ x }_{ 1 }+{ c }_{ 2 }{ \\lambda }_{ 2 }\\underline{ x }_{ 2 }+\\dots +{ c }_{ n }{ \\lambda }_{ n }\\underline{ x }_{ n } $$\n* Taking a power of A now (i.e. *k*) would be akin to taking each eigenvalue to that power\n$$ {A}^{k}{ \\underline { u } }_{ 0 }={ c }_{ 1 }{ \\lambda }_{ 1 }^{k}\\underline{ x }_{ 1 }+{ c }_{ 2 }{ \\lambda }_{ 2 }^{k}\\underline{ x }_{ 2 }+\\dots +{ c }_{ n }{ \\lambda }_{ n }^{k}\\underline{ x }_{ n } $$\n* This can be written as\n$$ \\underline{u}_{k} = {A}^{k}\\underline{u}_{0}={\\Lambda}^{k}{S}\\underline{c} $$\n\n* As an example consider the Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, ...\n* What would the 100th number be?\n* Consider the following\n$$ {F}_{k+2}={F}_{k+1}+{F}_{k} $$\n* This is a (second-order) difference equation; think of this example as similar to a second-order differential equation (without derivatives)\n* By adding a second equation Fk+1=Fk+1, consider **u**k to be the following vector\n$$ \\underline{u}_{k}=\\begin{bmatrix} {F}_{k+1} \\\\ {F}_{k} \\end{bmatrix} $$\n* This means the following\n$$ \\underline{u}_{k+1}=\\begin{bmatrix} 1 & 1 \\\\ 1 & 0 \\end{bmatrix} \\begin{bmatrix} {F}_{k+1} \\\\ {F}_{k} \\end{bmatrix}=\\begin{bmatrix} {F}_{k+1}+{F}_{k} \\\\ {F}_{k+1} \\end{bmatrix} \\\\ \\underline{u}_{k+1}=\\begin{bmatrix} 1 & 1 \\\\ 1 & 0 \\end{bmatrix}\\underline{u}_{k} $$\n\n\n```python\nA = Matrix([[1, 1], [1, 0]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 1\\\\1 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}\\frac{1}{2} + \\frac{\\sqrt{5}}{2} : 1, & - \\frac{\\sqrt{5}}{2} + \\frac{1}{2} : 1\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}\\frac{1}{2} + \\frac{\\sqrt{5}}{2}, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{1}{- \\frac{\\sqrt{5}}{2} + \\frac{1}{2}}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}- \\frac{\\sqrt{5}}{2} + \\frac{1}{2}, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{1}{\\frac{1}{2} + \\frac{\\sqrt{5}}{2}}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\nS, D = A.diagonalize()\n```\n\n\n```python\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{1}{2} + \\frac{\\sqrt{5}}{2} & 0\\\\0 & - \\frac{\\sqrt{5}}{2} + \\frac{1}{2}\\end{matrix}\\right]$$\n\n\n\n* From above we remember the following\n$$ \\underline{u}_{k} = {A}^{k}\\underline{u}_{0}={\\Lambda}^{k}{S}\\underline{c} $$\n* We have **u**0 contains the first two values\n\n\n```python\nu_zero = Matrix([1, 0])\nu_100 = A ** 100 * u_zero\nu_100 # The top value is the 100th Fibonacci number\n```\n\n\n\n\n$$\\left[\\begin{matrix}573147844013817084101\\\\354224848179261915075\\end{matrix}\\right]$$\n\n\n\n\n```python\nu_four = A ** 4 * u_zero\nu_four # If the first number is 0 the the fourth number would be the top value\n```\n\n\n\n\n$$\\left[\\begin{matrix}5\\\\3\\end{matrix}\\right]$$\n\n\n\n## Example problems\n\n### Example problem 1\n\n* Find an equation for Ck where C is given by the following matrix\n$$ $$\n* Calculate C100 when *a*=*b*=-1\n\n#### Solution\n\n\n```python\na, b, k = symbols('a b k')\n```\n\n\n```python\nC = Matrix([[2 * b - a, a - b], [2 * b - 2 * a, 2 * a - b]])\nC\n```\n\n\n\n\n$$\\left[\\begin{matrix}- a + 2 b & a - b\\\\- 2 a + 2 b & 2 a - b\\end{matrix}\\right]$$\n\n\n\n* We remember the following\n$$ {A}^{k}={S}{\\Lambda}^{k}{S}^{-1} $$\n* Where Λ is denoted by the computer variable D\n\n\n```python\nS, D = C.diagonalize()\n```\n\n\n```python\nS\n```\n\n\n\n\n$$\\left[\\begin{matrix}- \\frac{2 a - 2 b}{- 3 a + 3 b + \\sqrt{\\left(a - b\\right)^{2}}} & \\frac{2 a - 2 b}{3 a - 3 b + \\sqrt{\\left(a - b\\right)^{2}}}\\\\1 & 1\\end{matrix}\\right]$$\n\n\n\n* Python™ is not always good at simplifying these\n* If you look at it carefully you will note the following\n\n\n```python\nS = Matrix([[1, Rational(1, 2)], [1, 1]])\nS\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & \\frac{1}{2}\\\\1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{a}{2} + \\frac{b}{2} - \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}} & 0\\\\0 & \\frac{a}{2} + \\frac{b}{2} + \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}}\\end{matrix}\\right]$$\n\n\n\n\n```python\nD = Matrix([[b, 0], [0, a]])\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}b & 0\\\\0 & a\\end{matrix}\\right]$$\n\n\n\n* For the values given, we have the following\n\n\n```python\nC = Matrix([[-1, 0], [0, -1]])\nC\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 0\\\\0 & -1\\end{matrix}\\right]$$\n\n\n\n\n```python\nS, D = C.diagonalize()\n```\n\n\n```python\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 0\\\\0 & -1\\end{matrix}\\right]$$\n\n\n\n\n```python\nD ** 100\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nS * (D ** 100) * S.inv()\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]$$\n\n\n\n* Doing the same, but with eigenvalues and eigenvectors\n\n\n```python\nC = Matrix([[2 * b - a, a - b], [2 * b - 2 * a, 2 * a - b]])\nC\n```\n\n\n\n\n$$\\left[\\begin{matrix}- a + 2 b & a - b\\\\- 2 a + 2 b & 2 a - b\\end{matrix}\\right]$$\n\n\n\n\n```python\nC.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}\\frac{a}{2} + \\frac{b}{2} - \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}} : 1, & \\frac{a}{2} + \\frac{b}{2} + \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}} : 1\\end{Bmatrix}$$\n\n\n\n* This simplifies the λ1 = *b* and λ2 = *a*\n* That makes Λ (or D) the following\n\n\n```python\nD = Matrix([[b, 0], [0, a]])\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}b & 0\\\\0 & a\\end{matrix}\\right]$$\n\n\n\n\n```python\nC.eigenvects() # The solution is two tuples, with each being eigenvalue, eigenvector\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}\\frac{a}{2} + \\frac{b}{2} - \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}}, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{a - b}{- \\frac{3 a}{2} + \\frac{3 b}{2} + \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}}}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}\\frac{a}{2} + \\frac{b}{2} + \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}}, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{a - b}{- \\frac{3 a}{2} + \\frac{3 b}{2} - \\frac{1}{2} \\sqrt{\\left(a - b\\right)^{2}}}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* This simplifies to the following eigenvalue matrix S\n\n\n```python\nS = Matrix([[1, Rational(1, 2)], [1, 1]])\nS\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & \\frac{1}{2}\\\\1 & 1\\end{matrix}\\right]$$\n\n\n\n* We can see if we can get back to C\n\n\n```python\nS * D * S.inv()\n```\n\n\n\n\n$$\\left[\\begin{matrix}- a + 2 b & a - b\\\\- 2 a + 2 b & 2 a - b\\end{matrix}\\right]$$\n\n\n\n\n```python\nS * D * S.inv() == C\n```\n\n\n\n\n True\n\n\n\n* Python™ won't to Dk for you, but it's easy to do yourself\n\n\n```python\nD = Matrix([[b ** k, 0], [0, a ** k]])\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}b^{k} & 0\\\\0 & a^{k}\\end{matrix}\\right]$$\n\n\n\n* Now we can compute SΛS-1\n\n\n```python\nS * D * S.inv()\n```\n\n\n\n\n$$\\left[\\begin{matrix}- a^{k} + 2 b^{k} & a^{k} - b^{k}\\\\- 2 a^{k} + 2 b^{k} & 2 a^{k} - b^{k}\\end{matrix}\\right]$$\n\n\n\n* Placing the given values into this equation will give you the same solution for C100 as above\n\n\n```python\n\n```\n", "meta": {"hexsha": "46760ec8119da1ac055232a4fed996d5f527fc2a", "size": 49826, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_22_Diagonalization_and_Powers.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_22_Diagonalization_and_Powers.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_22_Diagonalization_and_Powers.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": 27.773690078, "max_line_length": 946, "alphanum_fraction": 0.4258820696, "converted": true, "num_tokens": 7586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.1710612001304791, "lm_q1q2_score": 0.06085928026073501}} {"text": "# Code stuff - not slides!\n\n\n```python\n%run ../ML_plots.ipynb\n```\n\n ERROR:root:File `'../ML_plots.ipynb.py'` not found.\n\n\n# Session 12:\n## Supervised learning, part 1\n\n*Andreas Bjerre-Nielsen*\n\n## Agenda\n1. [Modelling data](#Modelling-data)\n1. [A familiar regression model](#A-familiar-regression-model)\n1. [The curse of overfitting](#The-curse-of-overfitting)\n1. [Important details](#Implementation-details)\n\n## Vaaaamos\n\n\n```python\nimport warnings\nfrom sklearn.exceptions import ConvergenceWarning\nwarnings.filterwarnings(action='ignore', category=ConvergenceWarning)\n\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport pandas as pd \nimport seaborn as sns\n\nplt.style.use('default') # set style (colors, background, size, gridlines etc.)\nplt.rcParams['figure.figsize'] = 10, 4 # set default size of plots\nplt.rcParams.update({'font.size': 18})\n```\n\n## Supervised problems (1)\n*How do we distinguish between problems?*\n\n\n```python\nf_identify_question\n```\n\n## Supervised problems (2)\n*The two canonical problems*\n\n\n```python\nf_identify_answer\n```\n\n## Supervised problems (3)\n*Which models have we seen for classification?*\n\n- .\n\n- .\n\n- .\n\n# Modelling data\n\n## Model complexity (1)\n*What does a model of low complexity look like?*\n\n\n```python\nf_complexity[0]\n```\n\n## Model complexity (2)\n*What does medium model complexity look like?*\n\n\n```python\nf_complexity[1]\n```\n\n## Model complexity (3)\n*What does high model complexity look like?*\n\n\n```python\nf_complexity[2]\n```\n\n## Model fitting (1)\n*Quiz (1 min.): Which model fitted the data best?*\n\n\n```python\nf_bias_var['regression'][2]\n```\n\n## Model fitting (2)\n*What does underfitting and overfitting look like for classification?*\n\n\n```python\nf_bias_var['classification'][2]\n```\n\n## Two agendas (1)\n\nWhat are the objectives of empirical research? \n\n1. *causation*: what is the effect of a particular variable on an outcome? \n2. *prediction*: find some function that provides a good prediction of $y$ as a function of $x$\n\n## Two agendas (2)\n\nHow might we express the agendas in a model?\n\n$$ y = \\alpha + \\beta x + \\varepsilon $$\n\n- *causation*: interested in $\\hat{\\beta}$ \n\n- *prediction*: interested in $\\hat{y}$ \n\n\n## Two agendas (3)\n\nMight these two agendas be related at a deeper level? \n\nCan prediction quality inform us about how to make causal models?\n\n# A familiar regression model\n\n## Estimation (1)\n*Do we know already some ways to estimate regression models?*\n\n- Social scientists know all about the Ordinary Least Squares (OLS).\n - OLS estimate both parameters and their standard deviation.\n - Is best linear unbiased estimator under regularity conditions. \n \n\n*How is OLS estimated?*\n\n- $\\beta=(\\textbf{X}^T\\textbf{X})^{-1}\\textbf{X}^T\\textbf{y}$\n- computation requires non perfect multicollinarity.\n\n## Estimation (2)\n*How might we estimate a linear regression model?*\n\n- first order method (e.g. gradient descent)\n- second order method (e.g. Newton-Raphson)\n\n*So what the hell was gradient descent?*\n\n- compute errors, multiply with features and update\n\n## Estimation (3)\n*Can you explain that in details?*\n\n- Yes, like with Adaline, we minimize the sum of squared errors (SSE): \n\\begin{align}SSE&=\\boldsymbol{e}^{T}\\boldsymbol{e}\\\\\\boldsymbol{e}&=\\textbf{y}-\\textbf{X}\\textbf{w}\\end{align}\n\n\n```python\nX = np.random.normal(size=(3,2))\ny = np.random.normal(size=(3))\nw = np.random.normal(size=(3))\n\ne = y-(w[0]+X.dot(w[1:]))\nSSE = e.T.dot(e)\n```\n\n## Estimation (4)\n*And what about the updating..? What is it something about the first order deritative?*\n\n\\begin{align}\n\\frac{\\partial SSE}{\\partial\\hat{w}}=&\\textbf{X}^T\\textbf{e},\\\\\n \\Delta\\hat{w}=&\\eta\\cdot\\textbf{X}^T\\textbf{e}=\\eta\\cdot\\textbf{X}^T(\\textbf{y}-\\hat{\\textbf{y}})\n\\end{align}\n\n\n```python\neta = 0.001 # learning rate\nfod = X.T.dot(e)\nupdate_vars = eta*fod\nupdate_bias = eta*e.sum()\n```\n\n## Estimation (5)\n*What might some advantages be relative to OLS?*\n\n- Works despite high multicollinarity\n- Speed\n - OLS has $\\mathcal{O}(K^2N)$ computation time ([read more](https://math.stackexchange.com/questions/84495/computational-complexity-of-least-square-regression-operation))\n - Quadratic scaling in number of variables ($K$).\n - Stochastic gradient descent\n - Likely to converge faster with many observations ($N$)\n\n## Fitting a polynomial (1)\nPolyonomial: $f(x) = 2+8*x^4$\n\nTry models of increasing order polynomials. \n\n- Split data into train and test (50/50)\n\n\n- For polynomial order 0 to 9:\n - Iteration n: $y = \\sum_{k=0}^{n}(\\beta_k\\cdot x^k)+\\varepsilon$.\n - Estimate order n model on training data\n - Evaluate with on test data with RMSE: \n - $log RMSE = \\log (\\sqrt{MSE})$ \n\n## Fitting a polynomial (2)\nWe generate samples of data from true model.\n\n\n```python\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\n\ndef true_fct(X):\n return 2+X**4\n\nn_samples = 25\nn_degrees = 15\n\nnp.random.seed(0)\n\nX_train = np.random.normal(size=(n_samples,1))\ny_train = true_fct(X_train).reshape(-1) + np.random.randn(n_samples) \n\nX_test = np.random.normal(size=(n_samples,1))\ny_test = true_fct(X_test).reshape(-1) + np.random.randn(n_samples)\n```\n\n## Fitting a polynomial (3)\nWe estimate the polynomials\n\n\n```python\nfrom sklearn.metrics import mean_squared_error as mse\n\ntest_mse = []\ntrain_mse = []\nparameters = []\ndegrees = range(n_degrees+1)\n\nfor p in degrees:\n X_train_p = PolynomialFeatures(degree=p).fit_transform(X_train)\n X_test_p = PolynomialFeatures(degree=p).fit_transform(X_train)\n reg = LinearRegression().fit(X_train_p, y_train)\n train_mse += [mse(reg.predict(X_train_p),y_train)] \n test_mse += [mse(reg.predict(X_test_p),y_test)] \n parameters.append(reg.coef_)\n```\n\n## Fitting a polynomial (4)\n*So what happens to the model performance in- and out-of-sample?*\n\n\n```python\ndegree_index = pd.Index(degrees,name='Polynomial degree ~ model complexity')\nax = pd.DataFrame({'Train set':train_mse, 'Test set':test_mse})\\\n .set_index(degree_index)\\\n .plot(figsize=(10,4))\nax.set_ylabel('Mean squared error')\n```\n\n## Fitting a polynomial (4)\n*Why does it go wrong?*\n- more spurious parameters\n- the coefficient size increases\n\n## Fitting a polynomial (5)\n*What do you mean coefficient size increase?*\n\n\n```python\norder_idx = pd.Index(range(n_degrees+1),name='Polynomial order')\nax = pd.DataFrame(parameters,index=order_idx)\\\n.abs().mean(1)\\\n.plot(logy=True)\nax.set_ylabel('Mean parameter size')\n```\n\n## Fitting a polynomial (6)\n*How else could we visualize this problem?*\n\n\n```python\nf_bias_var['regression'][2]\n```\n\n# The curse of overfitting\n\n## Looking for a remedy\n*How might we solve the overfitting problem?*\n\nBy reducing\n- the number of variables\n- the coefficient size of variables \n\n## Regularization (1)\n\n*Why do we regularize?*\n\n- To mitigate overfitting > better model predictions\n\n*How do we regularize?*\n\n- We make models which are less complex:\n - reducing the **number** of coefficient;\n - reducing the **size** of the coefficients.\n\n## Regularization (2)\n\n*What does regularization look like?*\n\nWe add a penalty term our optimization procedure:\n \n$$ \\text{arg min}_\\beta \\, \\underset{\\text{MSE}}{\\underbrace{E[(y_0 - \\hat{f}(x_0))^2]}} + \\underset{\\text{penalty}}{\\underbrace{\\lambda \\cdot R(\\beta)}}$$\n\nIntroduction of penalties implies that increased model complexity has to be met with high increases precision of estimates.\n\n## Regularization (3)\n\n*What are some used penalty functions?*\n\nThe two most common penalty functions are L1 and L2 regularization.\n\n- L1 regularization (***Lasso***): $R(\\beta)=\\sum_{j=1}^{p}|\\beta_j|$ \n - Makes coefficients sparse, i.e. selects variables by removing some (if $\\lambda$ is high)\n \n \n- L2 regularization (***Ridge***): $R(\\beta)=\\sum_{j=1}^{p}\\beta_j^2$\n - Reduce coefficient size\n - Fast due to analytical solution\n \n*To note:* The *Elastic Net* uses a combination of L1 and L2 regularization.\n\n## Regularization (4)\n\n*How the Lasso (L1 reg.) deviates from OLS*\n\n\n\n## Regularization (5)\n\n*How the Ridge regression (L2 reg.) deviates from OLS*\n\n\n\n## Regularization (6)\n\n*How might we describe the $\\lambda$ of Lasso and Ridge?*\n\nThese are hyperparameters that we can optimize over. \n\n- More about this tomorrow.\n\n# Implementation details\n\n## The devils in the details (1)\n\n*So we just run regularization?*\n\n# NO\n\nWe need to rescale our features:\n- convert to zero mean: \n- standardize to unit std: \n\nCompute in Python:\n- option 1: `StandardScaler` in `sklearn` \n- option 2: `(X - np.mean(X)) / np.std(X)`\n\n\n\n## The devils in the details (2)\n*So we just scale our test and train?*\n\n# NO\n\nFit to the distribution in the training data first, then rescale train and test! See more [here](https://stats.stackexchange.com/questions/174823/how-to-apply-standardization-normalization-to-train-and-testset-if-prediction-i).\n\n## The devils in the details (3)\n*So we just rescale before using polynomial features?*\n\n# NO\n\nOtherwise the interacted varaibles are not gaussian distributed.\n\n## The devils in the details (4)\n*Does sklearn's `PolynomialFeatures` work for more than variable?*\n\n# YES!\n\n# The end\n[Return to agenda](#Agenda)\n", "meta": {"hexsha": "10fbbcb50b99592760753d569c430d39f8b37d55", "size": 614440, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Test_karl/material/session_12/.ipynb_checkpoints/lecture_12-checkpoint.ipynb", "max_stars_repo_name": "karlbindslev/sds_group29", "max_stars_repo_head_hexsha": "6f5263b08b35f35374b7f01b31a0e90d1cf4d53e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Test_karl/material/session_12/.ipynb_checkpoints/lecture_12-checkpoint.ipynb", "max_issues_repo_name": "karlbindslev/sds_group29", "max_issues_repo_head_hexsha": "6f5263b08b35f35374b7f01b31a0e90d1cf4d53e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test_karl/material/session_12/.ipynb_checkpoints/lecture_12-checkpoint.ipynb", "max_forks_repo_name": "karlbindslev/sds_group29", "max_forks_repo_head_hexsha": "6f5263b08b35f35374b7f01b31a0e90d1cf4d53e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 496.3166397415, "max_line_length": 82480, "alphanum_fraction": 0.9457375822, "converted": true, "num_tokens": 2517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.12252321572224491, "lm_q1q2_score": 0.060783011286740046}} {"text": "\n# Summary 2020-12-15\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.run import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\n\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 461 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.dpi : 100 ## figure dots per inch')\n\n\n## Nomenclature\n| Variable | Explain |\n|---|---|\n|$\\pi$| example |\n\nHere is a cell link: [Logbook](#logbook)\n\n# Abstract\n\nMany cost-efficient computation methods have been developed over the years to analyze various aspects of ship hydrodynamics such as: resistance, propulsion and seakeeping. Getting the best possible accuracy with the lowest possible computational cost is an important factor in a ship’s early design stage. Potential flow-based analysis partly presents such a solution for seakeeping, with good accuracy for heave and pitch, but not for roll where the roll damping contains both inviscid and viscouseffects. Roll motion is, however, often a critical degree of freedom that needs to be analyzed since large roll motions can result in cargo shifting or even capsizing. The viscous part of roll damping can be assessed with high accuracy by means of experimental model tests or URANS calculations, but these are generally too expensive in the early design stage of ships. Many semi-empirical formulas to determine viscous damping were therefore developed during the 1970s, where Ikeda’s method is one of the most widely used. The viscous damping from this method is normally combined with inviscid roll damping from strip theory.\n\nWith today’s computational power, more advanced potential flow methods can be used in the seakeeping analysis to enhance the accuracy in the predictions, but still at relatively low computational cost. This paper investigates the feasibility of combining 3D unsteady fully nonlinearpotential flow (FNPF) theory solved by means of a Boundary ElementMethod (BEM) together with the viscous contributions from Ikeda’smethod.\n\nThe approach of substituting the inviscid part from Ikeda’s method using strip theory with FNPF is investigated by conducting roll decay simulations. The results estimated by the proposed approach are compared with both the classic strip theory approach and roll decay model tests. \n**It is found that potential improvements to the modelling of roll damping can be achieved by introducing FNPF analysis in the Ikeda’s method.**\n\n# Abstract\n\n* **Important**: Good accuracy at low computational cost. \n\n(URANS or model test too expensive)\n\n* → seakeeping: Potential flow\n\n* heave/pitch good!\n\n* **NOT** roll!\n\n* **Solution**: Potential flow + semi empirical viscous roll damping\n\n* Potential flow:\n * Strip theory (milli seconds)\n * Nonlinear 3D methods (hours)\n \n\n## Background\nThe roll damping can be divided into various components :\n$$B_{44} = B_F + B_E + B_L + B_W + B_{BK}$$\n\nViscous: $ B_{visc} = B_F + B_E + B_L + B_{BK} $ (Ikeda's method, Simplified Ikeda)\n\nInviscid: $ B_{invisc} = B_W $ (Potential flow)\n\n$$B^{Ikeda} = B_{invisc}^{1D} + B_{visc}$$\n\n$$B^{Motions} = B_{invisc}^{3D} + B_{visc}$$\n\n### Problems with $B_W$ in Simplified Ikeda\n\n\n\n```python\ndata = {\n 'KVLCC2' : {\n 'type':'tanker',\n 'test data':True,\n 'B_W': 'small',\n 'bilge keel':False,\n 'publish geom':True,\n 'publish test':True,\n },\n 'DTC' : {\n 'type':'container',\n 'test data':True,\n 'B_W': '?',\n 'bilge keel':True,\n 'publish geom':True,\n 'publish test':True,\n },\n 'Wallenius' : {\n 'type':'PCTC',\n 'test data':True,\n 'B_W': 'medium',\n 'bilge keel':True,\n 'publish geom':False,\n 'publish test':True,\n },\n \n}\ntest_cases = pd.DataFrame(data=data).transpose()\n```\n\n\n```python\ndef background_colorer(val): \n return 'background-color: %s' % get_color(val)\n\ndef text_colorer(val): \n return 'color: %s' % get_color(val)\n\ndef get_color(val):\n \n color = 'none'\n if isinstance(val, bool):\n if val:\n color = 'green'\n else:\n color = 'red'\n \n return color\n\n```\n\n## Possible test cases:\n\n\n```python\ntest_cases.style.applymap(background_colorer).applymap(text_colorer)\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
    type test data B_W bilge keel publish geom publish test
    KVLCC2tankerTruesmallFalseTrueTrue
    DTCcontainerTrue??TrueTrue
    WalleniusPCTCTruemediumTrueFalseTrue
    \n\n\n\n## Test case: KVLCC2 \n[04.3_KVLCC2_Ikedas_model_tests](../../notebooks/04.3_KVLCC2_Ikedas_model_tests.ipynb)\n\n\n\n* B_W very small!\n* B_E is dominating\n\n\n\n* B_E decreased, B_L is now dominating\n* B_W is a bit larger but still minor\n\n# Abstract conclusion:\n#### \"It is found that potential improvements to the modelling of roll damping can be achieved by introducing FNPF analysis in the Ikeda’s method\"\n\n# Is this what we are aiming for?\n\n## References\n
    \n", "meta": {"hexsha": "ab41cb6151dc18e2ae29eb8d1cc1c9a463854cc3", "size": 20072, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reports/presentation_2020-12-15/summary_2020-12-15.ipynb", "max_stars_repo_name": "martinlarsalbert/Prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "cce8abde16a15a2ae45008e48b1bba9f4aeaaad4", "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": "reports/presentation_2020-12-15/summary_2020-12-15.ipynb", "max_issues_repo_name": "martinlarsalbert/Prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "cce8abde16a15a2ae45008e48b1bba9f4aeaaad4", "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": "reports/presentation_2020-12-15/summary_2020-12-15.ipynb", "max_forks_repo_name": "martinlarsalbert/Prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "cce8abde16a15a2ae45008e48b1bba9f4aeaaad4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 31.7594936709, "max_line_length": 1144, "alphanum_fraction": 0.5726385014, "converted": true, "num_tokens": 3437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.1329642436335826, "lm_q1q2_score": 0.060782837790107076}} {"text": "Programação Probabilística \n=====\ne Métodos Bayesianos para Hackers \n========\n\n##### Versão 0.1\n\n`Conteúdo original criado por Cam Davidson-Pilon`\n\n`Transferido para Python 3 e PyMC3 por Max Margenot (@clean_utensils) e Thomas Wiecki (@twiecki) em Quantopian (@quantopian)`\n__\n\n\nBem-vindo a *Métodos Bayesianos para Hackers*. O repositório Github completo está disponível em [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). Os outros capítulos podem ser encontrados em [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). Esperamos que você goste do livro e incentivamos qualquer contribuição!\n___\n\nVersão pt_BR\n\nTradução por Rodolpho Macedo dos Santos disponibilizado em [Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](http://github.com/rodolphomacedo/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers)\n\nCapítulo 1\n======\n***\n\nA filosofia da inferência bayesiana\n------\n\n> Você é um programador habilidoso, mas ainda assim existem bugs em seu código. Após uma implementação particularmente difícil de um algoritmo, você decide testar seu código em um exemplo trivial. Ele roda. Você testa o código em um problema mais difícil. Isso roda mais uma vez. E roda no próximo, *ainda mais difícil*, roda também! Você está começando a acreditar que pode não ter bugs no código ...\n\nSe você pensa assim, então parabéns, você já está pensando bayesiano! A inferência bayesiana é simplesmente atualizar suas crenças após considerar novas evidências. Um bayesiano raramente pode ter certeza sobre o resultado, mas pode estar muito confiante. Assim como no exemplo acima, nunca podemos ter 100% de certeza de que nosso código está livre de bugs, a menos que o testemos em todos os problemas possíveis; algo raramente possível na prática. Em vez disso, podemos testá-lo em um grande número de problemas e, se for bem-sucedido, podemos nos sentir mais *confiantes* sobre nosso código, mas ainda não temos certeza. A inferência bayesiana funciona de forma idêntica: atualizamos nossas crenças sobre um resultado; raramente podemos ter certeza absoluta, a menos que excluamos todas as outras alternativas.\n\n\n### O estado de espírito bayesiano\n\nA inferência bayesiana difere da inferência estatística mais tradicional por preservar a *incerteza*. A princípio, isso soa como uma técnica estatística ruim. As estatísticas não são apenas derivar *certeza* da aleatoriedade? Para reconciliar isso, precisamos começar a pensar como bayesianos.\n\nA visão de mundo bayesiana interpreta a probabilidade como uma medida de *credibilidade em um evento*, ou seja, o quão confiantes estamos na ocorrência de um evento. Na verdade, veremos em um momento que esta é a interpretação natural da probabilidade.\n\nPara que isso fique mais claro, consideramos uma interpretação alternativa da probabilidade: *Frequentista* (ou *Frequencista*), conhecida como a versão mais *clássica* da estatística, assume que a probabilidade é a frequência relativa de eventos no longo prazo (daí o título concedido). Por exemplo, a *probabilidade de acidentes de avião* sob uma filosofia frequentista é interpretada como a *frequência relativa no longo prazo de acidentes de avião*. Isso faz sentido lógico para muitas probabilidades de eventos, mas se torna mais difícil de entender quando os eventos não têm a frequência de ocorrência de longo prazo. Considere: muitas vezes atribuímos probabilidades aos resultados das eleições presidenciais, mas a eleição em si só acontece uma vez! Os frequentistas contornam isso invocando realidades alternativas e dizendo que, em todas essas realidades, a freqüência das ocorrências define a probabilidade.\n\nOs bayesianos, por outro lado, têm uma abordagem mais intuitiva. Os bayesianos interpretam uma probabilidade como uma medida de *crença*, ou a confiança, da ocorrência de um evento. Simplesmente, a probabilidade é um resumo de uma opinião. Um indivíduo que atribui uma crença de $0$ a um evento não tem confiança de que o evento ocorrerá; inversamente, atribuir uma crença de $1$ implica que o indivíduo está absolutamente certo da ocorrência de um evento. Crenças entre $0$ e $1$ permitem ponderações para outros resultados. Esta definição está de acordo com a probabilidade do exemplo do acidente de avião, por termos observado a frequência dos acidentes de avião, a crença de um indivíduo deve ser igual a essa frequência, excluindo qualquer informação externa. Da mesma forma, sob esta definição de probabilidade igualmente a crenças, é significativo dizer que a probabilidade (crença) do resultado das eleições presidenciais: o quão confiante você está, o candidato *A* irá vencer?\n\n\nObserve no parágrafo acima, atribuímos a medida de crença (probabilidade) a um *indivíduo*, não à Natureza. Isso é muito interessante, pois essa definição abre espaço para crenças conflitantes entre os indivíduos. Novamente, isso é apropriado para o que ocorre naturalmente: diferentes indivíduos têm diferentes crenças sobre os eventos que ocorrem, porque possuem diferentes *informações* sobre o mundo. A existência de diferentes crenças não significa que alguém esteja errado. Considere os seguintes exemplos que demonstram a relação entre crenças e probabilidades individuais:\n\n- Lanço uma moeda e ambos adivinhamos o resultado. Ambos concordaríamos, supondo que a moeda seja justa, que a probabilidade de cara é $\\frac{1}{2}$. Suponha, então, que eu espie a moeda. Agora eu sei com certeza qual é o resultado: eu atribuo probabilidade $1.0$ a cara ou coroa (seja qual for). Agora, qual é a *sua* crença de que a moeda é cara? Meu conhecimento do resultado não mudou os resultados da moeda. Assim, atribuímos diferentes probabilidades ao resultado.\n\n- Seu código tem um bug ou não, mas não sabemos com certeza qual afirmação é verdadeira, embora tenhamos uma crença sobre a presença ou ausência de um bug.\n\n- Um paciente médico está exibindo os sintomas $x$, $y$ e $z$. E existem várias doenças que poderiam estar causando todos esses sintomas, mas apenas uma doença está presente. Um médico tem crenças sobre qual doença, mas um segundo médico pode ter crenças ligeiramente diferentes.\n\nEssa filosofia da abordagem de crenças como probabilidade é natural para os humanos. Nós a utilizamos constantemente à medida que interagimos com o mundo e vemos apenas verdades parciais, mas reunimos evidências para formar as crenças. Alternativamente, você deve ser *treinado* para pensar como um frequentista.\n\nPara nos alinhar com a notação de probabilidade tradicional, denotamos nossa crença sobre o evento $A$ como $P(A)$. Chamamos essa quantidade de *probabilidade a priori*.\n\nJohn Maynard Keynes, um grande economista e pensador, disse: \"Quando os fatos mudam, eu mudo de ideia. O que você faz, senhor?\" Esta citação reflete a maneira como um bayesiano atualiza suas crenças depois de ver as evidências. Mesmo — especialmente — se a evidência for contrária ao que se acreditava inicialmente, a evidência não pode ser ignorada. Denotamos nossa crença atualizada como $P(A | X)$, interpretada como a probabilidade de $A$ dada a evidência $X$. Chamamos de atualização da crença da *probabilidade posteriori* para contrastá-la com a probabilidade a priori. Por exemplo, considere as probabilidades a posteriori (leia-se: crenças a posteriori) dos exemplos acima, após observar algumas evidências $X$:\n\n1\\. $P(A): \\;\\;$ a moeda tem 50 por cento de chance de ser cara. $P(A | X):\\;\\;$ Voce olha para a moeda, \nobserva que caiu Cara, denote essa informação $X$ e atribua trivialmente a probabilidade $1.0$ para Cara e $0.0$ para Coroa.\n\n2\\. $P(A): \\;\\;$ Este é um código grande e complexo, provavelmente contém um bug. $P(A | X): \\;\\;$ O código passou em todos os testes $X$; ainda pode haver um bug, mas sua presença é menos provável agora.\n\n3\\. $P(A):\\;\\;$ O paciente pode ter muitas doenças. $P(A | X):\\;\\;$ Realização de um teste de sangue gerou evidências $X$, descartando algumas das possíveis doenças de consideração.\n\nÉ claro que em cada exemplo não descartamos completamente a crença a priori depois de ver a nova evidência $X$, mas *reponderamos a priori* para incorporar a nova evidência (ou seja, colocamos mais peso ou confiança em algumas crenças versus outras).\n\nAo introduzir a incerteza a priori sobre os eventos, já estamos admitindo que qualquer suposição que fizermos é potencialmente muito errada. Depois de observar dados, evidências ou outras informações, atualizamos nossas crenças e nosso palpite de tal modo a se tornar *menos errada*. Este é o lado alternativo da previsão de uma moeda, onde normalmente tentamos estar *mais certos*.\n\n\n### Inferência Bayesiana na Prática\n\nSe a inferência frequentista e bayesiana fossem funções de programação, com as entradas sendo problemas estatísticos, então as duas seriam diferentes no que retornam ao usuário. A função de inferência frequentista retornaria um número, representando uma estimativa (normalmente uma estatística de resumo como a média da amostra etc.), enquanto a função Bayesiana retornaria as *probabilidades*.\n\n\nPor exemplo, em nosso problema de debugging acima, chamamos a função frequentista com o argumento \"Meu código passou em todos os testes $X$; meu código está livre de erros?\" retornaria um *SIM*. Por outro lado, perguntando à nossa função Bayesiana \"Muitas vezes meu código tem bugs. Meu código passou em todos os testes $X$; meu código está livre de bugs?\" retornaria algo muito diferente: probabilidades de *SIM* e de *NÃO*. A função poderia retornar:\n\n> *SIM*, com probabilidade de 0,8; *NÃO*, com probabilidade de 0,2\n\nIsso é muito diferente da resposta que a função frequentista retornou. Observe que a função Bayesiana aceita um argumento adicional: *\"Freqüentemente meu código tem bugs\" *. Este parâmetro é o *a priori*. Ao incluir o parâmetro a priori, estamos dizendo à função bayesiana para incluir nossa crença sobre a situação. Tecnicamente, este parâmetro na função bayesiana é opcional, mas veremos que excluí-lo terá suas consequências.\n\n#### Incorporando evidências\n\nÀ medida que adquirimos mais e mais exemplos de evidências, nossa crença a priori é *apagada* pelas novas evidências. Isto é o esperado. Por exemplo, se sua crença a priori é algo ridículo, como \"Espero que o sol exploda hoje\", e a cada dia que você estiver errado, você esperaria que qualquer inferência a corrigisse, ou pelo menos alinhasse melhor suas crenças. A inferência bayesiana corrigirá essa crença.\n\nDenote $N$ como o número de evidências que possuímos. À medida que reunimos uma quantidade *infinita* de evidência, digamos como $N \\rightarrow \\infty$, nossos resultados bayesianos (frequentemente) se alinham aos resultados frequentistas. Portanto, para $N$ grandes, a inferência estatística é mais ou menos objetiva. Por outro lado, para $N$ pequenos, a inferência é muito mais *instável*: as estimativas frequentistas têm mais variância e intervalos de confiança maiores. É aqui que a análise bayesiana se destaca. Ao introduzir uma probabilidade a priori e retornar (em vez de uma estimativa escalar), *preservamos a incerteza* que reflete a instabilidade da inferência estatística de um pequeno conjunto de dados $N$.\n\nPode-se pensar que para $N$ grandes, pode-se ficar indiferente entre as duas técnicas, visto que elas oferecem inferência semelhante, e pode-se inclinar para os métodos frequentistas mais simples computacionalmente. Um indivíduo nesta posição deve considerar a seguinte citação de Andrew Gelman (2005)[1], antes de tomar tal decisão:\n\n> Os tamanhos das amostras nunca são grandes. Se $N$ for muito pequeno para obter uma estimativa suficientemente precisa, você precisará obter mais dados (ou fazer mais suposições). Mas uma vez que $N$ é \"grande o suficiente\", você pode começar a subdividir os dados para aprender mais (por exemplo, em uma pesquisa de opinião pública, depois de ter uma boa estimativa para todo o país, você pode estimar entre homens e mulheres, pessoas do norte e pessoas do sul, diferentes faixas etárias, etc.). $N$ nunca será suficiente porque se fosse \"suficiente\" você já estaria próximo do problema para o qual precisa de mais dados.\n\n### Os métodos frequentistas estão incorretos então?\n\n**Não.**\n\nOs métodos freqüentistas ainda são úteis ou de última geração em muitas áreas. Ferramentas como regressão linear de mínimos quadrados, regressão LASSO e algoritmos de maximização de expectativa são poderosos e rápidos. Os métodos bayesianos complementam essas técnicas resolvendo problemas que essas abordagens não conseguem ou iluminando o sistema subjacente com uma modelagem mais flexível.\n\n\n#### Uma nota sobre *Big Data*\nParadoxalmente, os problemas analíticos preditivos de big data são resolvidos por algoritmos relativamente simples [2][4]. Assim, podemos argumentar que a dificuldade de previsão de big data não está no algoritmo usado, mas sim nas dificuldades computacionais de armazenamento e execução em grande conjuntos de dados. (Também se deve considerar a citação de Gelman acima e perguntar \"Eu realmente tenho cenário de big data?\")\n\nOs problemas analíticos muito mais difíceis envolvem *dados médios* e, especialmente problemáticos, *dados realmente pequenos*. Usando um argumento semelhante ao do Gelman citado acima, se os problemas de big data forem *grandes o suficiente* para serem prontamente resolvidos, então, deveriamos estar muito mais interessados nos conjuntos de dados *não muito grandes*.\n\n### Nossa Estrutura Bayesiana\n\nEstamos interessados em crenças, que podem ser interpretadas como probabilidades pelo pensamento bayesiano. Temos uma crença *a priori* do evento $A$, essas crenças foram formadas por informações anteriores, por exemplo, nossa crença a priori sobre os bugs encontrados em nosso código antes de realizar os testes.\n\nEm segundo lugar, observamos nossas evidências. Para continuar em nosso exemplo do código com bugs: se nosso código passar nos testes $X$, então queremos atualizar nossa crença com essa nova informação. Chamamos essa nova crença de probabilidade *a posteriori*. A atualização de nossa crença é feita por meio da seguinte equação, conhecida como Teorema de Bayes, em homenagem a seu descobridor Thomas Bayes:\n\n\\begin{align}\n P( A | X )\\;\\ =\\;\\ & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{é proporcional à })\n\\end{align}\n\nA fórmula acima não é exclusiva da inferência bayesiana: é um fato matemático com usos fora da inferência bayesiana. A inferência bayesiana apenas a utiliza para conectar as probabilidades a priori $P(A)$ com as probabilidades a posteriori atualizadas $P(A | X)$.\n\n##### Exemplo: obrigatório exemplo de cara ou coroa\n\nTodo texto de estatísticas deve conter um exemplo de cara ou coroa, vou usá-lo aqui para tirá-lo do caminho. Suponha que, ingenuamente, você não tem certeza sobre a probabilidade de cara em um cara ou coroa (alerta de spoiler: é 50%). Você acredita que existe algum índice subjacente verdadeiro, chame-o de $p$, mas não tem opinião prévia sobre o que $p$ pode ser.\n\nComeçamos a jogar uma moeda e registramos as observações: $H$ ou $T$. Estes são os nossos dados observados. Uma pergunta interessante a se fazer é como nossa inferência muda à medida que observamos mais e mais dados? Mais especificamente, como são nossas probabilidades a posteriori quando temos poucos dados, em comparação com quando temos muitos dados.\n\nAbaixo, traçamos uma seqüência de atualização das probabilidades a posteriori à medida que observamos quantidades crescentes de dados (cara ou coroa).\n\n\n```python\n\"\"\"\nO livro usa um arquivo matplotlibrc personalizado, que fornece estilos exclusivos para\ngráficos de matplotlib. Se estiver executando este livro, e você deseja usar o \nestilo do livro, são fornecidas duas opções:\n 1. Substitua seu próprio arquivo matplotlibrc com o arquivo rc fornecido no\n styles/dir do livro. Veja http://matplotlib.org/users/customizing.html\n 2. Também nos estilos está o arquivo bmh_matplotlibrc.json. Isso pode ser usado para\n atualizar os estilos apenas neste bloco de notas. Tente executar o seguinte código:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n# O código abaixo pode ser ignorado, pois atualmente não é importante, mais ele\n# usa tópicos avançados que ainda não cobrimos. OLHE A FOTO, MICHAEL!\n\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# Para os já preparados, estou usando o conjugação a priori da Binomial.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(int(len(n_trials)/2), 2, k+1)\n plt.xlabel(\"$p$, probabilidade de cara\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n if heads != 1:\n plt.plot(x, y, label=\"observando %d lançamentos,\\n %d caras\" % (N, heads))\n else:\n plt.plot(x, y, label=\"observando %d lançamentos,\\n %d cara\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Atualização bayesiana das probabilidades a posteriori\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nAs probabilidades a posteriori são representadas pelas curvas, e nossa incerteza é proporcional à largura da curva. Como mostra o gráfico acima, conforme começamos a observar os dados, nossas probabilidades a posteriori começam a se deslocar e se mover. Eventualmente, conforme observamos mais e mais dados (caras ou coroas), nossas probabilidades ficarão cada vez mais estreitas em torno do valor real de $p = 0.5$ (marcado por uma linha tracejada).\n\n\nObserve que os gráficos nem sempre têm *picos* em 0,5. Não há motivo para isso: lembre-se de que presumimos que não tínhamos uma opinião a priori sobre qual é o valor de $p$. Na verdade, se observarmos dados bastante extremos, digamos 8 lançamentos e apenas 1 cara observada, nossa distribuição pareceria muito tendenciosa *longe* de agrupar em torno de $0.5$ (sem a opinião a priori, quão confiante você se sentiria ao apostar em uma moeda justa após observar 8 coroas e 1 cara?). À medida que mais dados se acumulam, veríamos mais e mais a probabilidade sendo atribuída a $p = 0.5$, embora nunca temos toda ela.\n\nO próximo exemplo é uma demonstração simples da matemática da inferência bayesiana.\n\n##### Exemplo: Bug, ou apenas um recurso agradável e não intencional?\n\n\nSeja $A$ o evento em que nosso código **não contém bugs**. Seja $X$ o evento em que o código passa em todos os testes de depuração. Por enquanto, deixaremos a probabilidade a priori de nenhum bug como variável, ou seja, $P(A) = p$.\n\nEstamos interessados em $P(A|X)$, ou seja, a probabilidade de nenhum bug, dados nossos testes de debugging $X$. Para usar a fórmula acima, precisamos calcular algumas quantidades.\n\nO que é $P(X|A)$, ou seja, a probabilidade de que o código passe nos testes $X$ *dado* que não haja bugs? Bem, é igual a 1, pois um código sem bugs passará em todos os testes.\n\n$P(X)$ é um pouco mais complicado: o evento $X$ pode ser dividido em duas possibilidades, o evento $X$ ocorrendo mesmo que nosso código *realmente tenha* bugs (denotado $\\sim A\\;$, dito *não $A$*), ou evento $X$ sem bugs ($A$).\n\nAssim, $P(X)$ pode ser representado como:\n\n\\begin{align}\nP(X ) & = P(X \\text{ e } A) + P(X \\text{ e } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nJá calculamos $P(X|A)$ acima ( $=1$). Por outro lado, $ P(X|\\sim A)$ é subjetivo: nosso código pode passar nos testes, mas ainda tem um bug nele, embora a probabilidade de haver um bug seja reduzida. Observe que isso depende do número de testes realizados, do grau de complicação nos testes, etc. Vamos ser conservadores e atribuir $P(X|\\sim A) = 0,5$. Então:\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{p}{ p + 0.5-0.5 p } \\\\\\\\\n& = \\frac{p}{ 0.5 + 0.5 p } \\\\\\\\\n& = \\frac{p}{ 0.5 \\cdot ( 1 + p )} \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\n\nEsta é a probabilidade a posteriori. A qual se parece como a nossa função a priori, $p \\in [0,1]$?\n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Priori, $P(A) = p$\")\nplt.ylabel(\"Posteriori, $P(A|X)$, com $P(A) = p$\")\nplt.title(\"Existem bugs no meu código?\");\n```\n\nPodemos ver os maiores ganhos se observarmos os testes $X$ que passaram quando a probabilidade a priori, $p$, é baixa. Vamos definir um valor específico para a priori. Sou um programador bom (eu acho), então vou me dar uma ideia realista a priori de 0.20, ou seja, há 20% de chance de escrever um código sem bugs. Para ser mais realista, essa prioridade deve ser uma função de quão complicado e grande é o código, mas vamos fixá-lo em 0.20. Então, minha crença atualizada de que meu código está livre de bugs é de 0,33.\n\nLembre-se de que a priori é uma probabilidade: $p$ é a probabilidade a priori de *não haver bugs*, então $1-p$ é a probabilidade a priori de *ter bugs* no código.\n\nDa mesma forma, nossa posteriori também é uma probabilidade, com $P(A|X)$ a probabilidade de não haver bug *dado que vimos que todos os testes passaram*, portanto $1 - P(A|X)$ é a probabilidade de haver um bug *considerando que todos os testes passaram*. Qual é a nossa probabilidade a posteriori? Abaixo está um gráfico das probabilidades a priori e a posteriori.\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\n# posterior = [(2*0.2)/(1+0.2),1-(2*0.2)/(1+0.2)] \n\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"Distribuição a Priori\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"Distribuição a Posteriori\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Ausentes\", \"Bugs Presentes\"])\nplt.title(\"Probabilidade de bugs presentes - Priori e Posteriori\")\nplt.ylabel(\"Probabildade\")\nplt.legend(loc=\"upper left\");\n```\n\nObserve que, depois que observamos a ocorrência de $X$, a probabilidade dos bugs estarem ausentes aumentou. Aumentando o número de testes, podemos nos aproximar da confiança (probabilidade 1) de que não há bugs presentes.\n\nEste foi um exemplo muito simples de inferência bayesiana e da regra de Bayes. Infelizmente, a matemática necessária para realizar inferências bayesianas mais complicadas apenas se torna mais difícil, exceto para casos construídos artificialmente. Veremos mais tarde que esse tipo de análise matemática é realmente desnecessária. Primeiro, devemos ampliar nossas ferramentas de modelagem. A próxima seção trata das *distribuições de probabilidades*. Se você já estiver familiarizado, sinta-se à vontade para pular (ou pelo menos dar uma olhada), mas para os menos familiarizados, a próxima seção é essencial.\n\n_______\n\n##Distribuições de Probabilidades\n\n\n**Vamos lembrar rapidamente o que é uma distribuição de probabilidade:** Seja $Z$ alguma variável aleatória. Então, associada a $Z$ está uma *função de distribuição de probabilidade* que atribui probabilidades aos diferentes resultados que $Z$ pode obter. Graficamente, uma distribuição de probabilidade é uma curva em que a probabilidade de um resultado é proporcional à altura da curva. Você pode ver exemplos na primeira figura deste capítulo.\n\nPodemos dividir as variáveis aleatórias em três classificações:\n\n- **$Z$ é discreto**: Variáveis aleatórias discretas só podem assumir valores em uma lista especificada. Coisas como populações, classificações de filmes e número de votos são variáveis aleatórias discretas. Variáveis aleatórias discretas tornam-se mais claras quando as contrastamos com ...\n\n- **$Z$ é contínuo**: a variável aleatória contínua pode assumir valores exatos arbitrariamente. Por exemplo, temperatura, velocidade, tempo, cor são modelados como variáveis contínuas porque você pode tornar os valores cada vez mais precisos.\n\n- **$Z$ é misto**: as variáveis aleatórias mistas atribuem probabilidades a variáveis aleatórias discretas e contínuas, ou seja, é uma combinação das duas categorias acima.\n\n\n### Caso Discreto\n\nSe $Z$ for discreto, então sua distribuição é chamada de *função de massa de probabilidade*, que mede a probabilidade de $Z$ assumir o valor $k$, denotado $P(Z = k)$. Observe que a função de massa de probabilidade descreve completamente a variável aleatória $Z$, ou seja, se conhecemos a função de massa, sabemos como $Z$ deve se comportar. Existem funções de massa de probabilidade populares que aparecem de forma consistente: iremos apresentá-las conforme necessário, mas vamos introduzir a primeira função de massa de probabilidade muito útil. \n\nDizemos que a variável $Z$ é *Poisson*-distribuída se:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ é chamado de parâmetro da distribuição e controla a forma da distribuição. Para a distribuição de Poisson, $\\lambda$ pode ser qualquer número positivo. Aumentando $\\lambda$, estamos adicionamos mais probabilidade a valores maiores e, inversamente, diminuindo $\\lambda$, estamos adicionamos mais probabilidade a valores menores. Pode-se descrever $\\lambda$ como a *intensidade* da distribuição de Poisson.\n\nAo contrário de $\\lambda$, que pode ser qualquer número positivo, o valor $k$ na fórmula acima deve ser um número inteiro não negativo, ou seja, $k$ deve assumir os valores 0,1,2 e assim por diante. Isso é muito importante, porque se você quisesse modelar uma população, não conseguiria entender as populações com 4,25 ou 5,612 indivíduos.\n\nSe a variável aleatória $z$ tem a distribuição de massa de uma Poisson, nós denotamos isso escrevendo: \n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nUma propriedade útil da distribuição de Poisson é que seu valor esperado é igual ao seu parâmetro, ou seja:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nUsaremos essa propriedade com frequência, por isso é útil lembrar. Abaixo, traçamos a distribuição de massa de probabilidade para diferentes valores de $\\lambda$. A primeira coisa a notar é que ao aumentar $\\lambda$, adicionamos mais probabilidade de ocorrência de valores maiores. Em segundo lugar, observe que embora o gráfico termine em 15, as distribuições não. Eles atribuem probabilidade positiva a cada número inteiro não negativo.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"Probabilidade de $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"\"\"Função de massa de probabilidade de uma variável aleatória de Poisson; \n\\n Com diferentes valores para $\\lambda$!\"\"\");\n```\n\n### Caso Contínuo\n\nEm vez de uma função de massa de probabilidade, agora temos uma variável aleatória contínua que tem uma *função de densidade de probabilidade*. Isso pode parecer uma nomenclatura desnecessária, mas a função de densidade e a função de massa são criaturas muito diferentes. Um exemplo de variável aleatória contínua é uma variável aleatória com *densidade exponencial*. A função de densidade para uma variável aleatória exponencial se parece com isto:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nComo uma variável aleatória de Poisson, uma variável aleatória Exponencial pode assumir apenas valores não negativos. Mas, ao contrário de uma variável de Poisson, a Exponencial pode assumir *quaisquer* valores não negativos, incluindo valores não integrais, como 4,25 ou 5,612401. Esta propriedade a torna uma escolha ruim para dados de contagem, que devem ser um número inteiro, mas uma ótima escolha para dados de tempo, dados de temperatura (medidos em Kelvins, é claro) ou qualquer outra variável precisa *e positiva*. O gráfico abaixo mostra duas funções de densidade de probabilidade com diferentes valores $\\lambda$.\n\nQuando uma variável aleatória $Z$ tem uma distribuição Exponencial com o parâmetro $\\lambda$, dizemos *$Z$ é (distribuído conforme) Exponencial* e escrevemos:\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nDado um $\\lambda$ específico, o valor esperado de uma variável aleatória exponencial é igual ao inverso de $\\lambda$, ou seja:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"FDP de $z^{(1)}$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"\"\"Função de densidade de probabilidade de uma variável aleatória exponencial;\ndiferentes $\\lambda$\"\"\");\n```\n\n----\n$^{(1)}$ *Nota do Tradutor*:\nA nomenclatura **FDP** é o acrônimo de **F**unção **D**ensidade de **P**robabilidade. Textos em inglês são rotulados como **PDF**, ou seja, **P**robability **D**ensity **F**unction.\n\n\n### Mas o que é $\\lambda \\;$?\n\n**Esta questão é o que motiva as estatísticas**. No mundo real, $\\lambda$ está oculto para nós. Vemos apenas $Z$ e devemos retroceder para tentar determinar $\\lambda$. O problema é difícil porque não há mapeamento um-para-um de $Z$ para $\\lambda$. Muitos métodos diferentes foram criados para resolver o problema de estimar $\\lambda$, mas como $\\lambda$ nunca é realmente observado, ninguém pode dizer com certeza qual método é o melhor!\n\nA inferência bayesiana está preocupada com *crenças* sobre o que $\\lambda$ pode ser. Em vez de tentar adivinhar $\\lambda$ exatamente, só podemos falar sobre o que $\\lambda$ **provavelmente será** atribuindo, assim, uma distribuição de probabilidade à $\\lambda$.\n\nIsso pode parecer estranho à primeira vista. Afinal, $\\lambda$ é fixo; não é (necessariamente) aleatório! Como podemos atribuir probabilidades a valores de uma variável não aleatória? Ah, caímos na nossa velha maneira de pensar: frequentista. Lembre-se de que, sob a filosofia bayesiana, nós *podemos* atribuir probabilidades se as interpretarmos como crenças. E é totalmente aceitável ter *crenças* sobre o parâmetro $\\lambda$.\n\n\n##### Exemplo: inferir comportamento dos dados nas mensagens de texto recebidas\n\nVamos tentar modelar um exemplo mais interessante, que diz respeito à taxa na qual um usuário envia e recebe mensagens de texto:\n\n> Você recebe uma série de mensagens de texto diárias *(whatsapp, messenger, email, etc)* de de um usuário do seu sistema. Os dados, plotados ao longo do tempo, aparecem no gráfico abaixo. Você está curioso para saber se os hábitos de envio de mensagens de texto do usuário mudaram com o tempo, gradual ou repentinamente. Como você pode modelar isso? (Estes são, na verdade, meus próprios dados de mensagens de texto. Avalie minha popularidade como desejar.)\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Tempo (dias)\")\nplt.ylabel(\"Contagem de mensagens de texto recebidas\")\nplt.title(\"Os hábitos de envio de mensagens de texto desse usuário mudaram com o tempo?\")\nplt.xlim(0, n_count_data);\n```\n\nAntes de começarmos a modelar, veja o que você pode descobrir olhando para o gráfico acima. Você diria que houve uma mudança de comportamento durante esse período?\n\nComo podemos começar a modelar isso? Bem, como já vimos convenientemente, uma variável aleatória de Poisson é um modelo muito apropriado para este tipo de dados de *contagem*. Denotando a **$C$**ontagem de mensagens de texto do dia $i$ por $C_i$,\n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nNão temos certeza de qual é realmente o valor do parâmetro $\\lambda$. Olhando para o gráfico acima, parece que a taxa pode ficar mais alta no final do período de observação, o que equivale a dizer que $\\lambda$ aumenta em algum ponto durante as observações. (Lembre-se de que um valor mais alto de $\\lambda$ atribui mais probabilidade a resultados maiores. Ou seja, há uma probabilidade maior de muitas mensagens de texto terem sido enviadas em um determinado dia.)\n\nComo podemos representar esta observação matematicamente? Vamos supor que em algum *dia* durante o período de observação (chamaremos esse dia de $\\tau$), o parâmetro $\\lambda$ repentinamente salte para um valor mais alto. Portanto, temos realmente dois parâmetros $\\lambda$: um ($\\lambda_1$) para o período anterior a $\\tau$ e outro ($\\lambda_2$) para o resto do período de observação. Na literatura, uma transição repentina como esta seria chamada de *switchpoint* $^{(1)}$:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\nSe, na realidade, nenhuma mudança repentina ocorreu e de fato $\\lambda_1 = \\lambda_2$, então as distribuições posterioris de $\\lambda$s devem parecer iguais.\n\nEstamos interessados em inferir os desconhecidos $\\lambda$s. Para usar a inferência Bayesiana, precisamos atribuir probabilidades prioris aos diferentes valores possíveis de $\\lambda$. Quais seriam boas distribuições de probabilidade a priori para $\\lambda_1$ e $\\lambda_2$? Lembre-se de que $\\lambda$ pode ser qualquer número positivo. Como vimos anteriormente, a distribuição *exponencial* fornece uma função de densidade contínua para números positivos, portanto, pode ser uma boa escolha para modelar $\\lambda_i$. Mas lembre-se de que a distribuição exponencial tem um parâmetro próprio, portanto, precisaremos incluir esse parâmetro em nosso modelo. Vamos chamar esse parâmetro de $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ é chamado de *hiperparâmetro* ou *variável pai*. Em termos literais, é um parâmetro que influencia outros parâmetros. Nossa estimativa inicial em $\\alpha$ não influencia o modelo muito fortemente, portanto, temos alguma flexibilidade em nossa escolha. Uma boa regra prática é definir o parâmetro exponencial igual ao inverso da média dos dados de contagem. Como estamos modelando $\\lambda$ usando uma distribuição exponencial, podemos usar a identidade de valor esperada mostrada anteriormente para obter:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nUma alternativa, e algo que encorajo o leitor a tentar, seria ter duas prioris: um para cada $\\lambda_i$. A criação de duas distribuições exponenciais com valores $\\alpha$ diferentes reflete nossa crença à priori de que a taxa mudou em algum ponto durante as observações.\n\nE quanto a $\\tau$? Por causa do ruído dos dados, é difícil definir a priori quando $\\tau$ pode ter ocorrido. Em vez disso, podemos atribuir uma *crença à priori uniforme* a todos os dias possíveis. Isso é equivalente a dizer:\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nDepois de tudo isso, como nossas distribuições à priori em geral ficam para as variáveis desconhecidas? Francamente, *não importa*. O que devemos entender é que é uma bagunça feia e complicada envolvendo símbolos que apenas um matemático poderia amar. E as coisas só vão ficar mais feias quanto mais complicados nossos modelos se tornarem. Independentemente disso, tudo o que realmente importa é a distribuição *à posteriori*.\n\nEm seguida, voltamos para PyMC3, uma biblioteca Python para realizar análises bayesianas que não se intimida com o monstro matemático que criamos.\n\n\nApresentando nosso primeiro martelo: PyMC3\n-----\n\nPyMC3 é uma biblioteca Python para programação de análises Bayesianas[3]. É uma biblioteca rápida e bem mantida. A única parte lamentável é que sua documentação está faltando em certas áreas, especialmente aquelas que preenchem a lacuna entre iniciante e o hacker. Um dos principais objetivos deste livro é resolver esse problema e também demonstrar por que o PyMC3 é tão legal.\n\nVamos modelar o problema acima usando PyMC3. Esse tipo de programação é chamado de *programação probabilística*, um nome impróprio infeliz que invoca idéias de código gerado aleatoriamente e provavelmente confundiu e assustou os usuários para longe desse campo. O código não é aleatório; é probabilístico no sentido de que criamos modelos de probabilidade usando variáveis de programação como componentes do modelo. Os componentes do modelo são primitivos de primeira classe na estrutura PyMC3.\n\nB. Cronin [5] tem uma descrição muito motivadora de programação probabilística:\n\n> Outra maneira de pensar sobre isso: ao contrário de um programa tradicional, que só roda nas direções para frente, um programa probabilístico é executado tanto na direção para frente quanto para trás. Ele avança para calcular as consequências das suposições que contém sobre o mundo (ou seja, o espaço do modelo que representa), mas também avança para trás a partir dos dados para restringir as possíveis explicações. Na prática, muitos sistemas de programação probabilística habilmente intercalam essas operações de avanço e retrocesso para localizar com eficiência as melhores explicações.\n\nPor causa da confusão gerada pelo termo *programação probabilística*, vou abster-me de usá-lo. Em vez disso, direi simplesmente *programação*, pois é isso que realmente é.\n\nO código PyMC3 é fácil de ler. A única coisa nova deve ser a sintaxe. Simplesmente lembre-se de que estamos representando os componentes do modelo ($\\tau, \\lambda_1, \\lambda_2 $) como variáveis.\n\n---\n\n$^{(1)}$(*Nota do Tradutor*): *switchpoint* significa ponto de troca, nesse exemplo, indica o momento no qual o comportamento da quantidade de mensagens recebidas se alterou.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Lembre-se que count_data é a \n # variável que mantém nossas contagens de txt \n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\n WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n\n\nNo código acima, criamos as variáveis PyMC3 correspondentes a $\\lambda_1$ e $\\lambda_2$. Nós os atribuímos às *variáveis estocásticas* de PyMC3, e são chamadas assim porque são tratadas pelo backend como geradores de números aleatórios.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nEste código cria uma nova função `lambda_`, mas realmente podemos pensar nela como uma variável aleatória: a variável aleatória $\\lambda$ de cima. A função `switch ()` atribui `lambda_1` ou` lambda_2` como o valor de `lambda_`, dependendo do lado de` tau` em que estamos. Os valores de `lambda_` até` tau` são `lambda_1` e os valores posteriores são` lambda_2`.\n\nObserve que, como `lambda_1`,` lambda_2` e `tau` são aleatórios,` lambda_` será aleatório. **Não** estamos corrigindo nenhuma variável ainda.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nA variável `observation` combina nossos dados,` count_data`, com nosso esquema de geração de dados proposto, dado pela variável `lambda_`, através da palavra-chave `observation`.\n\nO código abaixo será explicado no Capítulo 3, mas eu o mostro aqui para que você possa ver de onde vêm nossos resultados. Pode-se pensar nisso como um passo de *aprendizagem*. O maquinário sendo empregado é chamado *Markov Chain Monte Carlo* (MCMC), que também retardo a explicação até o Capítulo 3. Essa técnica retorna milhares de variáveis aleatórias das distribuições posteriores de $\\lambda_1, \\lambda_2$ e $\\tau$. Podemos traçar um histograma das variáveis aleatórias para ver como as distribuições à posterioris se parecem. Abaixo, coletamos algumas amostras (chamadas *traces*$^{(1)}$ na literatura MCMC) em histogramas.\n\n\n----\n$^{(1)}$ Nota do Tradutor: *traces* podem ser entendidos como o traço, ou melhor, rastros. Significando o caminhos que o algoritmo do MCMC faz no espaço das variáveis no processo de construção da posteriori.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n Sampling 4 chains, 0 divergences: 100%|██████████| 60000/60000 [00:07<00:00, 7817.55draws/s] \n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Distribuição à posteriori das variáveis $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"Valor de $\\lambda_1$\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"Posteriori de $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"Valor de $\\lambda_2$\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"Posteriori de $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (em dias)\")\nplt.ylabel(\"probabilidade\");\n```\n\n### Interpretação\n\nLembre-se de que na metodologia bayesiana é retornado uma *distribuição*. Portanto, agora temos distribuições para descrever os desconhecidos $\\lambda$s e $\\tau$. O que ganhamos? Imediatamente, podemos ver a incerteza em nossas estimativas: quanto mais ampla a distribuição, menos certa deve ser nossa crença posterior. Também podemos ver quais são os valores plausíveis para os parâmetros: $\\lambda_1$ é cerca de 18 e $\\lambda_2$ é cerca de 23. As distribuições posteriores dos dois $\\lambda$s são claramente distintas, indicando que é de fato provável que houve uma mudança no comportamento da mensagem de texto do usuário.\n\nQue outras observações você pode fazer? Se você olhar os dados originais novamente, esses resultados parecem razoáveis?\n\nObserve também que as distribuições à posterioris para os $\\lambda$s não se parecem com distribuições exponenciais, embora nossas prioris para essas variáveis fossem exponenciais. Na verdade, as distribuições à posterioris não são realmente de qualquer forma que reconhecemos do modelo original. Mas tudo bem! Este é um dos benefícios de se adotar um ponto de vista computacional. Se, em vez disso, tivéssemos feito essa análise usando abordagens matemáticas, teríamos ficado presos a uma distribuição analiticamente intratável (e confusa). No uso de uma abordagem computacional torna-se indiferentes à tratabilidade matemática.\n\nNossa análise também retornou uma distribuição de $\\tau$. Sua distribuição à posteriori parece um pouco diferente das outras duas porque é uma variável aleatória discreta, então não atribui probabilidades a intervalos. Podemos ver que próximo ao dia 45, havia 50% de chance de que o comportamento do usuário mudasse. Se nenhuma mudança tivesse ocorrido, ou se a mudança tivesse sido gradual ao longo do tempo, a distribuição posterior de $\\tau$ teria sido mais espalhada, refletindo que muitos dias eram candidatos plausíveis para $\\tau$. Em contraste, nos resultados reais, vemos que apenas três ou quatro dias fazem algum sentido como pontos de transição potenciais.\n\n### Enfim, por que eu iria querer amostras da parte da posteriori?\n\nTrataremos dessa questão no restante do livro, e é um eufemismo dizer que nos levará a alguns resultados surpreendentes. Por enquanto, vamos encerrar este capítulo com mais um exemplo.\n\nUsaremos as amostras à posterioris para responder à seguinte pergunta: qual é o número esperado de textos no dia $t,\\; 0 \\leq t \\leq 70$? Lembre-se de que o valor esperado de uma variável Poisson é igual ao seu parâmetro $\\lambda$. Portanto, a questão é equivalente a *qual é o valor esperado de $\\lambda$ no tempo $t$*?\n\nNo código abaixo, o $i$ indexa as amostras das distribuições à posteriori. Dado um dia $t$, fazemos a média de todos os $\\lambda_i$ possíveis para esse dia $t$, usando $\\lambda_i = \\lambda_{1, i}$ se $t \\lt \\tau_i$ (ou seja, se o a mudança de comportamento ainda não ocorreu), senão usamos $\\lambda_i = \\lambda_{2, i}$.\n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contém\n# N amostras a partir da distribuição à posteriori correspondente\n\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\n\nfor day in range(0, n_count_data):\n # ix é um índice booleano de todas as amostras de tau correspondentes ao\n # switchpoint (ponto de mudança) ocorrendo antes do valor do 'dia'\n ix = day < tau_samples\n # Cada amostra à posteriori corresponde a um valor para tau.\n # para cada dia, esse valor de tau indica se estamos \"antes\"\n # (regido pelo lambda1) ou\n # \"depois\" (regido pelo lambda2), sob o ponto de switchpoint.\n # tomando a amostra à posteriori de lambda_{1/2} adequadamente, \n # podemos calcular a média\n # em todas as amostras para obter um valor esperado para lambda naquele dia.\n # Conforme explicado, a variável aleatória \"contagem de mensagens\" \n # é distribuída por Poisson,\n # e, portanto, lambda (o parâmetro da Poisson) é o valor esperado de\n # \"contagem das mensagens\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\" número esperado do número de mensagens de texto recebídas\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Dia\")\nplt.ylabel(\"Esperado # mensagens de texto\")\nplt.title(\"Esperado número de mensagens de texto recebídas\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"Observação de texto por dia\")\n\nplt.legend(loc=\"upper left\");\n```\n\nNossa análise mostra um forte suporte que nos leva a acreditar que o comportamento do usuário mudou ($\\lambda_1$ teria valor próximo a $\\lambda_2$ se isso não fosse verdade), e que a mudança foi repentina em vez de gradual (como demonstrado por $\\tau$ na posteriori fortemente pontiaguda). Podemos especular o que pode ter causado isso: uma taxa de mensagem de texto mais barata, uma assinatura recente do clima para texto ou talvez um novo relacionamento. (Na verdade, o 45º dia corresponde ao Natal, e me mudei para Toronto no mês seguinte, deixando uma namorada para trás.)\n\n##### Exercícios\n\n1\\. Usando `lambda_1_samples` e `lambda_2_samples`, qual é a média das distribuições à posterioris de $\\lambda_1$ e $\\lambda_2$?\n\n\n```python\n# Digite seu código aqui.\n```\n\n2\\. Qual é o aumento percentual esperado de aumento nas taxas de mensagens de texto? `dica:` calcule a média de `lambda_1_samples / lambda_2_samples`. Observe que esta quantidade é muito diferente de `lambda_1_samples.mean () / lambda_2_samples.mean ()`.\n\n\n```python\n# Digite seu código aqui.\n```\n\n3\\. Qual é a média de $\\lambda_1$ **dado** que sabemos que $\\tau$ é menor que 45. Ou seja, suponha que recebemos novas informações de que a mudança de comportamento ocorreu antes do dia 45. Qual é o valor esperado de $\\lambda_1$ agora? (Você não precisa refazer a parte PyMC3. Considere todas as instâncias em que `tau_samples < 45`.)\n\n\n```python\n# Digite seu código aqui.\n```\n\n### Referências\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "25b2fefde0f744c9617c909d2b0eeb98e9832cb0", "size": 321229, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3_pt_BR.ipynb", "max_stars_repo_name": "rodolphomacedo/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "c46bee14589c31d3bc11bcd6c45445cd34170d4d", "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": "Chapter1_Introduction/Ch1_Introduction_PyMC3_pt_BR.ipynb", "max_issues_repo_name": "rodolphomacedo/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "c46bee14589c31d3bc11bcd6c45445cd34170d4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3_pt_BR.ipynb", "max_forks_repo_name": "rodolphomacedo/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "c46bee14589c31d3bc11bcd6c45445cd34170d4d", "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": 286.3003565062, "max_line_length": 92884, "alphanum_fraction": 0.9019235499, "converted": true, "num_tokens": 14788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386101825929835, "lm_q2_score": 0.23934934189686402, "lm_q1q2_score": 0.06076146765363084}} {"text": "```python\n# This mounts your Google Drive to the Colab VM.\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# TODO: Enter the foldername in your Drive where you have saved the unzipped\n# assignment folder, e.g. 'cs231n/assignments/assignment1/'\nFOLDERNAME = '/Colab Notebooks/Stanford_CS231n/assignment2'\nassert FOLDERNAME is not None, \"[!] Enter the foldername.\"\n\n# Now that we've mounted your Drive, this ensures that\n# the Python interpreter of the Colab VM can load\n# python files from within it.\nimport sys\nsys.path.append('/content/drive/My Drive/{}'.format(FOLDERNAME))\n\n# This downloads the CIFAR-10 dataset to your Drive\n# if it doesn't already exist.\n%cd /content/drive/My\\ Drive/$FOLDERNAME/cs231n/datasets/\n!bash get_datasets.sh\n%cd /content/drive/My\\ Drive/$FOLDERNAME\n```\n\n Mounted at /content/drive\n /content/drive/My Drive/Colab Notebooks/Stanford_CS231n/assignment2/cs231n/datasets\n /content/drive/My Drive/Colab Notebooks/Stanford_CS231n/assignment2\n\n\n# Batch Normalization\nOne way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. One idea along these lines is batch normalization, proposed by [1] in 2015.\n\nTo understand the goal of batch normalization, it is important to first recognize that machine learning methods tend to perform better with input data consisting of uncorrelated features with zero mean and unit variance. When training a neural network, we can preprocess the data before feeding it to the network to explicitly decorrelate its features. This will ensure that the first layer of the network sees data that follows a nice distribution. However, even if we preprocess the input data, the activations at deeper layers of the network will likely no longer be decorrelated and will no longer have zero mean or unit variance, since they are output from earlier layers in the network. Even worse, during the training process the distribution of features at each layer of the network will shift as the weights of each layer are updated.\n\nThe authors of [1] hypothesize that the shifting distribution of features inside deep neural networks may make training deep networks more difficult. To overcome this problem, they propose to insert into the network layers that normalize batches. At training time, such a layer uses a minibatch of data to estimate the mean and standard deviation of each feature. These estimated means and standard deviations are then used to center and normalize the features of the minibatch. A running average of these means and standard deviations is kept during training, and at test time these running averages are used to center and normalize features.\n\nIt is possible that this normalization strategy could reduce the representational power of the network, since it may sometimes be optimal for certain layers to have features that are not zero-mean or unit variance. To this end, the batch normalization layer includes learnable shift and scale parameters for each feature dimension.\n\n[1] [Sergey Ioffe and Christian Szegedy, \"Batch Normalization: Accelerating Deep Network Training by Reducing\nInternal Covariate Shift\", ICML 2015.](https://arxiv.org/abs/1502.03167)\n\n\n```python\n# Setup cell.\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.fc_net import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array\nfrom cs231n.solver import Solver\n\n%matplotlib inline\nplt.rcParams[\"figure.figsize\"] = (10.0, 8.0) # Set default size of plots.\nplt.rcParams[\"image.interpolation\"] = \"nearest\"\nplt.rcParams[\"image.cmap\"] = \"gray\"\n\n%load_ext autoreload\n%autoreload 2\n\ndef rel_error(x, y):\n \"\"\"Returns relative error.\"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\ndef print_mean_std(x,axis=0):\n print(f\" means: {x.mean(axis=axis)}\")\n print(f\" stds: {x.std(axis=axis)}\\n\")\n```\n\n =========== You can safely ignore the message below if you are NOT working on ConvolutionalNetworks.ipynb ===========\n \tYou will need to compile a Cython extension for a portion of this assignment.\n \tThe instructions to do this will be given in a section of the notebook below.\n\n\n\n```python\n# Load the (preprocessed) CIFAR-10 data.\ndata = get_CIFAR10_data()\nfor k, v in list(data.items()):\n print(f\"{k}: {v.shape}\")\n```\n\n X_train: (49000, 3, 32, 32)\n y_train: (49000,)\n X_val: (1000, 3, 32, 32)\n y_val: (1000,)\n X_test: (1000, 3, 32, 32)\n y_test: (1000,)\n\n\n# Batch Normalization: Forward Pass\nIn the file `cs231n/layers.py`, implement the batch normalization forward pass in the function `batchnorm_forward`. Once you have done so, run the following to test your implementation.\n\nReferencing the paper linked to above in [1] may be helpful!\n\n\n```python\n# Check the training-time forward pass by checking means and variances\n# of features both before and after batch normalization \n\n# Simulate the forward pass for a two-layer network.\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before batch normalization:')\nprint_mean_std(a,axis=0)\n\ngamma = np.ones((D3,))\nbeta = np.zeros((D3,))\n\n# Means should be close to zero and stds close to one.\nprint('After batch normalization (gamma=1, beta=0)')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n\ngamma = np.asarray([1.0, 2.0, 3.0])\nbeta = np.asarray([11.0, 12.0, 13.0])\n\n# Now means should be close to beta and stds close to gamma.\nprint('After batch normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n```\n\n Before batch normalization:\n means: [ -2.3814598 -13.18038246 1.91780462]\n stds: [27.18502186 34.21455511 37.68611762]\n \n After batch normalization (gamma=1, beta=0)\n means: [5.32907052e-17 7.04991621e-17 1.85962357e-17]\n stds: [0.99999999 1. 1. ]\n \n After batch normalization (gamma= [1. 2. 3.] , beta= [11. 12. 13.] )\n means: [11. 12. 13.]\n stds: [0.99999999 1.99999999 2.99999999]\n \n\n\n\n```python\n# Check the test-time forward pass by running the training-time\n# forward pass many times to warm up the running averages, and then\n# checking the means and variances of activations after a test-time\n# forward pass.\n\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\n\nbn_param = {'mode': 'train'}\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n\nfor t in range(50):\n X = np.random.randn(N, D1)\n a = np.maximum(0, X.dot(W1)).dot(W2)\n batchnorm_forward(a, gamma, beta, bn_param)\n\nbn_param['mode'] = 'test'\nX = np.random.randn(N, D1)\na = np.maximum(0, X.dot(W1)).dot(W2)\na_norm, _ = batchnorm_forward(a, gamma, beta, bn_param)\n\n# Means should be close to zero and stds close to one, but will be\n# noisier than training-time forward passes.\nprint('After batch normalization (test-time):')\nprint_mean_std(a_norm,axis=0)\n```\n\n After batch normalization (test-time):\n means: [-0.03927354 -0.04349152 -0.10452688]\n stds: [1.01531428 1.01238373 0.97819988]\n \n\n\n# Batch Normalization: Backward Pass\nNow implement the backward pass for batch normalization in the function `batchnorm_backward`.\n\nTo derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing branches; make sure to sum gradients across these branches in the backward pass.\n\nOnce you have finished, run the following to numerically check your backward pass.\n\n\n```python\n# Gradient check batchnorm backward pass.\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nfx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]\nfg = lambda a: batchnorm_forward(x, a, beta, bn_param)[0]\nfb = lambda b: batchnorm_forward(x, gamma, b, bn_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = batchnorm_forward(x, gamma, beta, bn_param)\ndx, dgamma, dbeta = batchnorm_backward(dout, cache)\n\n# You should expect to see relative errors between 1e-13 and 1e-8.\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.7029261167605239e-09\n dgamma error: 7.420414216247087e-13\n dbeta error: 2.8795057655839487e-12\n\n\n# Batch Normalization: Alternative Backward Pass\nIn class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For example, you can derive a very simple formula for the sigmoid function's backward pass by simplifying gradients on paper.\n\nSurprisingly, it turns out that you can do a similar simplification for the batch normalization backward pass too! \n\nIn the forward pass, given a set of inputs $X=\\begin{bmatrix}x_1\\\\x_2\\\\...\\\\x_N\\end{bmatrix}$, \n\nwe first calculate the mean $\\mu$ and variance $v$.\nWith $\\mu$ and $v$ calculated, we can calculate the standard deviation $\\sigma$ and normalized data $Y$.\nThe equations and graph illustration below describe the computation ($y_i$ is the i-th element of the vector $Y$).\n\n\\begin{align}\n& \\mu=\\frac{1}{N}\\sum_{k=1}^N x_k & v=\\frac{1}{N}\\sum_{k=1}^N (x_k-\\mu)^2 \\\\\n& \\sigma=\\sqrt{v+\\epsilon} & y_i=\\frac{x_i-\\mu}{\\sigma}\n\\end{align}\n\n\n\nThe meat of our problem during backpropagation is to compute $\\frac{\\partial L}{\\partial X}$, given the upstream gradient we receive, $\\frac{\\partial L}{\\partial Y}.$ To do this, recall the chain rule in calculus gives us $\\frac{\\partial L}{\\partial X} = \\frac{\\partial L}{\\partial Y} \\cdot \\frac{\\partial Y}{\\partial X}$.\n\nThe unknown/hard part is $\\frac{\\partial Y}{\\partial X}$. We can find this by first deriving step-by-step our local gradients at \n$\\frac{\\partial v}{\\partial X}$, $\\frac{\\partial \\mu}{\\partial X}$,\n$\\frac{\\partial \\sigma}{\\partial v}$, \n$\\frac{\\partial Y}{\\partial \\sigma}$, and $\\frac{\\partial Y}{\\partial \\mu}$,\nand then use the chain rule to compose these gradients (which appear in the form of vectors!) appropriately to compute $\\frac{\\partial Y}{\\partial X}$.\n\nIf it's challenging to directly reason about the gradients over $X$ and $Y$ which require matrix multiplication, try reasoning about the gradients in terms of individual elements $x_i$ and $y_i$ first: in that case, you will need to come up with the derivations for $\\frac{\\partial L}{\\partial x_i}$, by relying on the Chain Rule to first calculate the intermediate $\\frac{\\partial \\mu}{\\partial x_i}, \\frac{\\partial v}{\\partial x_i}, \\frac{\\partial \\sigma}{\\partial x_i},$ then assemble these pieces to calculate $\\frac{\\partial y_i}{\\partial x_i}$. \n\nYou should make sure each of the intermediary gradient derivations are all as simplified as possible, for ease of implementation. \n\nAfter doing so, implement the simplified batch normalization backward pass in the function `batchnorm_backward_alt` and compare the two implementations by running the following. Your two implementations should compute nearly identical results, but the alternative implementation should be a bit faster.\n\n\n```python\nnp.random.seed(231)\nN, D = 100, 500\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nout, cache = batchnorm_forward(x, gamma, beta, bn_param)\n\nt1 = time.time()\ndx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache)\nt2 = time.time()\ndx2, dgamma2, dbeta2 = batchnorm_backward_alt(dout, cache)\nt3 = time.time()\n\nprint('dx difference: ', rel_error(dx1, dx2))\nprint('dgamma difference: ', rel_error(dgamma1, dgamma2))\nprint('dbeta difference: ', rel_error(dbeta1, dbeta2))\nprint('speedup: %.2fx' % ((t2 - t1) / (t3 - t2)))\n```\n\n dx difference: 7.49749656041581e-13\n dgamma difference: 0.0\n dbeta difference: 0.0\n speedup: 2.04x\n\n\n# Fully Connected Networks with Batch Normalization\nNow that you have a working implementation for batch normalization, go back to your `FullyConnectedNet` in the file `cs231n/classifiers/fc_net.py`. Modify your implementation to add batch normalization.\n\nConcretely, when the `normalization` flag is set to `\"batchnorm\"` in the constructor, you should insert a batch normalization layer before each ReLU nonlinearity. The outputs from the last layer of the network should not be normalized. Once you are done, run the following to gradient-check your implementation.\n\n**Hint:** You might find it useful to define an additional helper layer similar to those in the file `cs231n/layer_utils.py`.\n\n\n```python\nnp.random.seed(231)\nN, D, H1, H2, C = 2, 15, 20, 30, 10\nX = np.random.randn(N, D)\ny = np.random.randint(C, size=(N,))\n\n# You should expect losses between 1e-4~1e-10 for W, \n# losses between 1e-08~1e-10 for b,\n# and losses between 1e-08~1e-09 for beta and gammas.\nfor reg in [0, 3.14]:\n print('Running check with reg = ', reg)\n model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,\n reg=reg, weight_scale=5e-2, dtype=np.float64,\n normalization='batchnorm')\n\n loss, grads = model.loss(X, y)\n print('Initial loss: ', loss)\n\n for name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)\n print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))\n if reg == 0: print()\n```\n\n Running check with reg = 0\n Initial loss: 8.447989963075447\n W1 relative error: 1.10e-04\n W2 relative error: 7.56e-07\n W3 relative error: 8.76e-11\n b1 relative error: 2.49e-06\n b2 relative error: 1.78e-07\n b3 relative error: 2.55e-11\n beta1 relative error: 7.17e-09\n beta2 relative error: 7.31e-10\n gamma1 relative error: 7.52e-09\n gamma2 relative error: 9.68e-10\n \n Running check with reg = 3.14\n Initial loss: 11.926373672569037\n W1 relative error: 1.25e-06\n W2 relative error: 6.14e-07\n W3 relative error: 6.26e-01\n b1 relative error: 8.88e-03\n b2 relative error: 8.88e-03\n b3 relative error: 6.99e-11\n beta1 relative error: 6.25e-09\n beta2 relative error: 2.53e-09\n gamma1 relative error: 6.09e-09\n gamma2 relative error: 1.03e-09\n\n\n# Batch Normalization for Deep Networks\nRun the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization.\n\n\n```python\nnp.random.seed(231)\n\n# Try training a very deep net with batchnorm.\nhidden_dims = [100, 100, 100, 100, 100]\n\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nweight_scale = 2e-2\nbn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\nmodel = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\nprint('Solver with batch norm:')\nbn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True,print_every=20)\nbn_solver.train()\n\nprint('\\nSolver without batch norm:')\nsolver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=20)\nsolver.train()\n```\n\n Solver with batch norm:\n (Iteration 1 / 200) loss: 9.307661\n (Epoch 0 / 10) train acc: 0.106000; val_acc: 0.119000\n (Epoch 1 / 10) train acc: 0.331000; val_acc: 0.271000\n (Iteration 21 / 200) loss: 5.947877\n (Epoch 2 / 10) train acc: 0.407000; val_acc: 0.271000\n (Iteration 41 / 200) loss: 4.991967\n (Epoch 3 / 10) train acc: 0.473000; val_acc: 0.308000\n (Iteration 61 / 200) loss: 4.969000\n (Epoch 4 / 10) train acc: 0.537000; val_acc: 0.323000\n (Iteration 81 / 200) loss: 2.854577\n (Epoch 5 / 10) train acc: 0.580000; val_acc: 0.320000\n (Iteration 101 / 200) loss: 2.697992\n (Epoch 6 / 10) train acc: 0.630000; val_acc: 0.323000\n (Iteration 121 / 200) loss: 1.656204\n (Epoch 7 / 10) train acc: 0.692000; val_acc: 0.338000\n (Iteration 141 / 200) loss: 1.791152\n (Epoch 8 / 10) train acc: 0.722000; val_acc: 0.347000\n (Iteration 161 / 200) loss: 0.848149\n (Epoch 9 / 10) train acc: 0.750000; val_acc: 0.324000\n (Iteration 181 / 200) loss: 1.716791\n (Epoch 10 / 10) train acc: 0.787000; val_acc: 0.332000\n \n Solver without batch norm:\n (Iteration 1 / 200) loss: 8.997418\n (Epoch 0 / 10) train acc: 0.130000; val_acc: 0.132000\n (Epoch 1 / 10) train acc: 0.259000; val_acc: 0.209000\n (Iteration 21 / 200) loss: 6.253194\n (Epoch 2 / 10) train acc: 0.270000; val_acc: 0.222000\n (Iteration 41 / 200) loss: 5.843208\n (Epoch 3 / 10) train acc: 0.338000; val_acc: 0.286000\n (Iteration 61 / 200) loss: 4.396365\n (Epoch 4 / 10) train acc: 0.379000; val_acc: 0.310000\n (Iteration 81 / 200) loss: 4.258562\n (Epoch 5 / 10) train acc: 0.453000; val_acc: 0.314000\n (Iteration 101 / 200) loss: 4.274043\n (Epoch 6 / 10) train acc: 0.487000; val_acc: 0.314000\n (Iteration 121 / 200) loss: 2.996210\n (Epoch 7 / 10) train acc: 0.559000; val_acc: 0.343000\n (Iteration 141 / 200) loss: 2.036799\n (Epoch 8 / 10) train acc: 0.565000; val_acc: 0.311000\n (Iteration 161 / 200) loss: 1.926624\n (Epoch 9 / 10) train acc: 0.628000; val_acc: 0.318000\n (Iteration 181 / 200) loss: 1.558469\n (Epoch 10 / 10) train acc: 0.682000; val_acc: 0.339000\n\n\nRun the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster.\n\n\n```python\ndef plot_training_history(title, label, baseline, bn_solvers, plot_fn, bl_marker='.', bn_marker='.', labels=None):\n \"\"\"utility function for plotting training history\"\"\"\n plt.title(title)\n plt.xlabel(label)\n bn_plots = [plot_fn(bn_solver) for bn_solver in bn_solvers]\n bl_plot = plot_fn(baseline)\n num_bn = len(bn_plots)\n for i in range(num_bn):\n label='with_norm'\n if labels is not None:\n label += str(labels[i])\n plt.plot(bn_plots[i], bn_marker, label=label)\n label='baseline'\n if labels is not None:\n label += str(labels[0])\n plt.plot(bl_plot, bl_marker, label=label)\n plt.legend(loc='lower center', ncol=num_bn+1) \n\n \nplt.subplot(3, 1, 1)\nplot_training_history('Training loss','Iteration', solver, [bn_solver], \\\n lambda x: x.loss_history, bl_marker='o', bn_marker='o')\nplt.subplot(3, 1, 2)\nplot_training_history('Training accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.train_acc_history, bl_marker='-o', bn_marker='-o')\nplt.subplot(3, 1, 3)\nplot_training_history('Validation accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.val_acc_history, bl_marker='-o', bn_marker='-o')\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n# Batch Normalization and Initialization\nWe will now run a small experiment to study the interaction of batch normalization and weight initialization.\n\nThe first cell will train eight-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training accuracy, validation set accuracy, and training loss as a function of the weight initialization scale.\n\n\n```python\nnp.random.seed(231)\n\n# Try training a very deep net with batchnorm.\nhidden_dims = [50, 50, 50, 50, 50, 50, 50]\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nbn_solvers_ws = {}\nsolvers_ws = {}\nweight_scales = np.logspace(-4, 0, num=20)\nfor i, weight_scale in enumerate(weight_scales):\n print('Running weight scale %d / %d' % (i + 1, len(weight_scales)))\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\n bn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n bn_solver.train()\n bn_solvers_ws[weight_scale] = bn_solver\n\n solver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n solver.train()\n solvers_ws[weight_scale] = solver\n```\n\n Running weight scale 1 / 20\n Running weight scale 2 / 20\n Running weight scale 3 / 20\n Running weight scale 4 / 20\n Running weight scale 5 / 20\n Running weight scale 6 / 20\n Running weight scale 7 / 20\n Running weight scale 8 / 20\n Running weight scale 9 / 20\n Running weight scale 10 / 20\n Running weight scale 11 / 20\n Running weight scale 12 / 20\n Running weight scale 13 / 20\n Running weight scale 14 / 20\n Running weight scale 15 / 20\n Running weight scale 16 / 20\n Running weight scale 17 / 20\n Running weight scale 18 / 20\n Running weight scale 19 / 20\n Running weight scale 20 / 20\n\n\n\n```python\n# Plot results of weight scale experiment.\nbest_train_accs, bn_best_train_accs = [], []\nbest_val_accs, bn_best_val_accs = [], []\nfinal_train_loss, bn_final_train_loss = [], []\n\nfor ws in weight_scales:\n best_train_accs.append(max(solvers_ws[ws].train_acc_history))\n bn_best_train_accs.append(max(bn_solvers_ws[ws].train_acc_history))\n \n best_val_accs.append(max(solvers_ws[ws].val_acc_history))\n bn_best_val_accs.append(max(bn_solvers_ws[ws].val_acc_history))\n \n final_train_loss.append(np.mean(solvers_ws[ws].loss_history[-100:]))\n bn_final_train_loss.append(np.mean(bn_solvers_ws[ws].loss_history[-100:]))\n \nplt.subplot(3, 1, 1)\nplt.title('Best val accuracy vs. weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best val accuracy')\nplt.semilogx(weight_scales, best_val_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm')\nplt.legend(ncol=2, loc='lower right')\n\nplt.subplot(3, 1, 2)\nplt.title('Best train accuracy vs. weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best training accuracy')\nplt.semilogx(weight_scales, best_train_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm')\nplt.legend()\n\nplt.subplot(3, 1, 3)\nplt.title('Final training loss vs. weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Final training loss')\nplt.semilogx(weight_scales, final_train_loss, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_final_train_loss, '-o', label='batchnorm')\nplt.legend()\nplt.gca().set_ylim(1.0, 3.5)\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n## Inline Question 1:\nDescribe the results of this experiment. How does the weight initialization scale affect models with/without batch normalization differently, and why?\n\n## Answer:\n[FILL THIS IN]\n\n\n# Batch Normalization and Batch Size\nWe will now run a small experiment to study the interaction of batch normalization and batch size.\n\nThe first cell will train 6-layer networks both with and without batch normalization using different batch sizes. The second layer will plot training accuracy and validation set accuracy over time.\n\n\n```python\ndef run_batchsize_experiments(normalization_mode):\n np.random.seed(231)\n \n # Try training a very deep net with batchnorm.\n hidden_dims = [100, 100, 100, 100, 100]\n num_train = 1000\n small_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n }\n n_epochs=10\n weight_scale = 2e-2\n batch_sizes = [5,10,50]\n lr = 10**(-3.5)\n solver_bsize = batch_sizes[0]\n\n print('No normalization: batch size = ',solver_bsize)\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n solver = Solver(model, small_data,\n num_epochs=n_epochs, batch_size=solver_bsize,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n solver.train()\n \n bn_solvers = []\n for i in range(len(batch_sizes)):\n b_size=batch_sizes[i]\n print('Normalization: batch size = ',b_size)\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=normalization_mode)\n bn_solver = Solver(bn_model, small_data,\n num_epochs=n_epochs, batch_size=b_size,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n bn_solver.train()\n bn_solvers.append(bn_solver)\n \n return bn_solvers, solver, batch_sizes\n\nbatch_sizes = [5,10,50]\nbn_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('batchnorm')\n```\n\n No normalization: batch size = 5\n Normalization: batch size = 5\n Normalization: batch size = 10\n Normalization: batch size = 50\n\n\n\n```python\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 2:\nDescribe the results of this experiment. What does this imply about the relationship between batch normalization and batch size? Why is this relationship observed?\n\n## Answer:\n[FILL THIS IN]\n\n\n# Layer Normalization\nBatch normalization has proved to be effective in making networks easier to train, but the dependency on batch size makes it less useful in complex networks which have a cap on the input batch size due to hardware limitations. \n\nSeveral alternatives to batch normalization have been proposed to mitigate this problem; one such technique is Layer Normalization [2]. Instead of normalizing over the batch, we normalize over the features. In other words, when using Layer Normalization, each feature vector corresponding to a single datapoint is normalized based on the sum of all terms within that feature vector.\n\n[2] [Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. \"Layer Normalization.\" stat 1050 (2016): 21.](https://arxiv.org/pdf/1607.06450.pdf)\n\n## Inline Question 3:\nWhich of these data preprocessing steps is analogous to batch normalization, and which is analogous to layer normalization?\n\n1. Scaling each image in the dataset, so that the RGB channels for each row of pixels within an image sums up to 1.\n2. Scaling each image in the dataset, so that the RGB channels for all pixels within an image sums up to 1. \n3. Subtracting the mean image of the dataset from each image in the dataset.\n4. Setting all RGB values to either 0 or 1 depending on a given threshold.\n\n## Answer:\n[FILL THIS IN]\n\n\n# Layer Normalization: Implementation\n\nNow you'll implement layer normalization. This step should be relatively straightforward, as conceptually the implementation is almost identical to that of batch normalization. One significant difference though is that for layer normalization, we do not keep track of the moving moments, and the testing phase is identical to the training phase, where the mean and variance are directly calculated per datapoint.\n\nHere's what you need to do:\n\n* In `cs231n/layers.py`, implement the forward pass for layer normalization in the function `layernorm_forward`. \n\nRun the cell below to check your results.\n* In `cs231n/layers.py`, implement the backward pass for layer normalization in the function `layernorm_backward`. \n\nRun the second cell below to check your results.\n* Modify `cs231n/classifiers/fc_net.py` to add layer normalization to the `FullyConnectedNet`. When the `normalization` flag is set to `\"layernorm\"` in the constructor, you should insert a layer normalization layer before each ReLU nonlinearity. \n\nRun the third cell below to run the batch size experiment on layer normalization.\n\n\n```python\n# Check the training-time forward pass by checking means and variances\n# of features both before and after layer normalization.\n\n# Simulate the forward pass for a two-layer network.\nnp.random.seed(231)\nN, D1, D2, D3 =4, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before layer normalization:')\nprint_mean_std(a,axis=1)\n\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n\n# Means should be close to zero and stds close to one.\nprint('After layer normalization (gamma=1, beta=0)')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n\ngamma = np.asarray([3.0,3.0,3.0])\nbeta = np.asarray([5.0,5.0,5.0])\n\n# Now means should be close to beta and stds close to gamma.\nprint('After layer normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n```\n\n Before layer normalization:\n means: [-59.06673243 -47.60782686 -43.31137368 -26.40991744]\n stds: [10.07429373 28.39478981 35.28360729 4.01831507]\n \n After layer normalization (gamma=1, beta=0)\n means: [ 4.81096644e-16 -7.40148683e-17 2.22044605e-16 -5.92118946e-16]\n stds: [0.99999995 0.99999999 1. 0.99999969]\n \n After layer normalization (gamma= [3. 3. 3.] , beta= [5. 5. 5.] )\n means: [5. 5. 5. 5.]\n stds: [2.99999985 2.99999998 2.99999999 2.99999907]\n \n\n\n\n```python\n# Gradient check batchnorm backward pass.\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nln_param = {}\nfx = lambda x: layernorm_forward(x, gamma, beta, ln_param)[0]\nfg = lambda a: layernorm_forward(x, a, beta, ln_param)[0]\nfb = lambda b: layernorm_forward(x, gamma, b, ln_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = layernorm_forward(x, gamma, beta, ln_param)\ndx, dgamma, dbeta = layernorm_backward(dout, cache)\n\n# You should expect to see relative errors between 1e-12 and 1e-8.\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 0.5013824514038396\n dgamma error: 4.519489546032799e-12\n dbeta error: 2.276445013433725e-12\n\n\n# Layer Normalization and Batch Size\n\nWe will now run the previous batch size experiment with layer normalization instead of batch normalization. Compared to the previous experiment, you should see a markedly smaller influence of batch size on the training history!\n\n\n```python\nln_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('layernorm')\n\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 4:\nWhen is layer normalization likely to not work well, and why?\n\n1. Using it in a very deep network\n2. Having a very small dimension of features\n3. Having a high regularization term\n\n\n## Answer:\n[FILL THIS IN]\n\n", "meta": {"hexsha": "405f256e90b12653c21a1ff789b03517a9b87964", "size": 435229, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignment2/BatchNormalization.ipynb", "max_stars_repo_name": "zheedong/Stanford_CS231n_assignment_2017", "max_stars_repo_head_hexsha": "4b333d48aabd6192dafd3725fed55546b8871df6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-30T06:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T06:22:41.000Z", "max_issues_repo_path": "assignment2/BatchNormalization.ipynb", "max_issues_repo_name": "zheedong/Stanford_CS231n_assignment_2017", "max_issues_repo_head_hexsha": "4b333d48aabd6192dafd3725fed55546b8871df6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-08-29T14:01:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-08T13:59:30.000Z", "max_forks_repo_path": "assignment2/BatchNormalization.ipynb", "max_forks_repo_name": "zheedong/Stanford_CS231n_assignment_2017", "max_forks_repo_head_hexsha": "4b333d48aabd6192dafd3725fed55546b8871df6", "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": 435229.0, "max_line_length": 435229, "alphanum_fraction": 0.936950433, "converted": true, "num_tokens": 9236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455664065234, "lm_q2_score": 0.2018132246607271, "lm_q1q2_score": 0.06069443255891733}} {"text": "```python\nfrom IPython.core.display import HTML\nfrom IPython.display import Image\nHTML(\"\"\"\n\n\"\"\")\n```\n\n\n\n\n\n\n\n\n\n\n# *Circuitos Elétricos I - Semana 6*\n\n## Elementos armazenadores de energia\n\nComparação entre capacitores convencionais, supercapacitores e baterias de lítio. A tabela abaixo mostra as especificações necessários para cada dispositivo armazenar ∼1 megajoule (MJ) de energia (300 watts-hora). 1 MJ de energia irá alimentar um laptop com um consumo médio de 50 W por 6 horas. Observe na primeira coluna que uma bateria de íon de lítio pode conter 1000 vezes mais energia do que um capacitor convencional.\n\n$$\n\\begin{array}{|c|c|c|c|c|c|}\n\\hline \\text { Dispositivo } & \\begin{array}{c}\n\\text { Energia } \\\\\n\\text { específica } \\\\\n\\text { [Wh/kg]} \\\\\n\\end{array} & \\begin{array}{c}\n\\text { Energia } \\\\\n\\text { específica } \\\\\n\\text { [MJ/kg] }\n\\end{array} & \\begin{array}{c}\n\\text { Densidade de} \\\\\n\\text { Energia } \\\\\n\\text { [MJ / L] }\n\\end{array} & \\begin{array}{c}\n\\text { Volume } \\\\\n\\text { requerido para } \\\\\n\\text { armazenar 1 MJ } \\\\\n\\text { [L] }\n\\end{array} & \\begin{array}{c}\n\\text { Peso } \\\\\n\\text { requerido para } \\\\\n\\text { armazenar 1 MJ } \\\\\n\\text { [kg] }\n\\end{array} \\\\\n\\hline \\begin{array}{c}\n\\text { Capacitor convencional} \\\\\n\\end{array} & 0.01-0.1 & 4 \\times 10^{-5}-4 \\times 10^{-4} & 6 \\times 10^{-5}-6 \\times 10^{-4} & 17000-1700 & 25000-2500 \\\\\n\\text { Supercapacitor } & 1-10 & 0.004-0.04 & 0.006-0.06 & 166-16 & 250-25 \\\\\n\\text { Bateria de Íons de Lítio } & 100-250 & 0.36-0.9 & 1-2 & 1-0.5 & 2.8-1.1 \\\\\n\\hline\n\\end{array}\n$$\n\nFonte: Fawwaz Ulaby, Michel M. Maharbiz and Cynthia M. Furse, $\\textit{ Circuit Analysis and Design}$, Michigan Publishing Services, 2018\n\n\n## Resumo dos elementos passivos ideais de dois terminais\n\n$$\n\\begin{array}{|l|c|c|c|}\n\\hline \\text { Propriedade } & R & L & C \\\\\n\\hline \\text { Relação } i-v & i=\\frac{v}{R} & i=\\frac{1}{L} \\int_{t_{0}}^{t} v(\\tau) d \\tau+i\\left(t_{0}\\right) & i=C \\frac{d v}{d t} \\\\\n\\text { Relação } v-i & v=Ri & v=L \\frac{d i}{d t} & v=\\frac{1}{C} \\int_{t_{0}}^{t} i(\\tau) d \\tau+v\\left(t_{0}\\right) \\\\\np \\text { (potência }) & p=Ri^{2} & p=L i \\frac{d i}{d t} & p=C v \\frac{d v}{d t} \\\\\nw \\text { (energia armazenada) } & 0 & w=\\frac{1}{2} L i^{2} & w=\\frac{1}{2} C v^{2} \\\\\n\\text { Associação em série } & R_{\\mathrm{eq}}=R_{1}+R_{2} & L_{\\mathrm{eq}}=L_{1}+L_{2} & \\frac{1}{C_{\\mathrm{eq}}}=\\frac{1}{C_{1}}+\\frac{1}{C_{2}} \\\\\n\\text { Associação em paralelo } & \\frac{1}{R_{\\mathrm{eq}}}=\\frac{1}{R_{1}}+\\frac{1}{R_{2}} & \\frac{1}{L_{\\mathrm{eq}}}=\\frac{1}{R_{1}}+\\frac{1}{R_{2}} & C_{\\mathrm{eq}}=C_{1}+C_{2} \\\\\n\\text { Comportamento em regime estacionário } & \\text { sem mudanças } & \\text { curto-circuito } & \\text { circuito aberto } \\\\\n\\text { Pode } v \\text { variar instantaneamente? } & \\text { sim } & \\text { sim } & \\text { não } \\\\\n\\text { Pode } i \\text { variar instantaneamente? } & \\text { sim } & \\text { não } & \\text { sim }\\\\ \\hline\n\\end{array}\n$$\n\n### Problema 1\n \nPara o circuito abaixo, determine $v_{C1}$, $v_{C2}$ e $i_{L}$ assumindo que o circuito encontra-se em regime estacionário.\n\n\n\n```python\nImage(\"./figures/J9C1.png\", width=600)\n```\n\n### Problema 2\n \nNo circuito abaixo, sabe-se que $i_0(t)= 50e^{-8000t}[\\cos(6000t)+2\\mathrm{sen}(6000t)]$ mA, para $t\\geq 0^+$. Determine $v_{C}(0^+)$, $v_{L}(0^+)$ e $v_{R}(0^+)$.\n\n\n\n```python\nImage(\"./figures/J9C2.png\", width=600)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sympy import *\n\ntmax = 1e-3\nt = np.linspace(0, tmax, num = 1000)\ni0 = 50*np.exp(-8000*t)*(np.cos(6000*t)+2*np.sin(6000*t))*1e-3\n\nplt.plot(t, i0)\nplt.xlim(0, tmax)\nplt.grid()\nplt.xlabel('t [s]')\nplt.ylabel('i0(t) [A]')\nplt.show()\n```\n\n\n```python\n# valores\nR = 320\nL = 20e-3\nC = 0.5e-6\n```\n\n\n```python\n# define variáveis \nt, τ = symbols('t, τ')\n\n# define i0(t)\ni0 = 50*exp(-8000*t)*(cos(6000*t)+2*sin(6000*t))*1e-3\ni0\n```\n\n\n```python\n# calcula tensão no indutor\nvL = L*diff(i0, t)\nvL = simplify(vL)\n\nprint('Tensão no indutor:')\nprint('vL(t) = ', vL , ' V')\n```\n\n\n```python\nprint('vL(0+) = %.2f V' %vL.evalf(subs={t:0}))\n```\n\n\n```python\n# calcula tensão no resistor\nvR = R*i0\n#vR = simplify(vR)\n\nprint('Tensão no resistor:')\nprint('vR(t) = ', vR , ' V')\n```\n\n\n```python\nprint('vR(0+) = %.2f V' %vR.evalf(subs={t:0}))\n```\n\n\n```python\n# calcula tensão no capacitor (LKT)\nvC = vR + vL\nvC = simplify(vC)\n\nprint('Tensão no capacitor:')\nprint('vC(t) = ', vC , ' V')\n```\n\n\n```python\nprint('vC(0+) = %.2f V' %vC.evalf(subs={t:0}))\n```\n\n\n```python\n# checagem de vC(t) via integração de i0\n\ni0 = 50*exp(-8000*τ)*(cos(6000*τ)+2*sin(6000*τ))*1e-3\n\nvC = -(1/C)*integrate(i0, (τ, 0, t)) + 20\nvC = simplify(vC)\n\nprint('vC(t) = ', vC , ' V')\n```\n\n\n```python\np = plot(vC, vR, vL, (t,0,6e-4), ylim = (-20,20), show=False, legend=True)\np[0].line_color = 'red'\np[1].line_color = 'blue'\np[2].line_color = 'black'\np[0].label = 'vC'\np[1].label = 'vR'\np[2].label = 'vL'\np.show()\n```\n", "meta": {"hexsha": "61e453c591529fd7706b7437ce134d58c55e334f", "size": 228310, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 6.2.ipynb", "max_stars_repo_name": "Willh-AM/ElectricCircuits", "max_stars_repo_head_hexsha": "32dc2cd79498f2819967b747a792b7db2822f8bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-05-19T18:36:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T16:30:17.000Z", "max_issues_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 6.2.ipynb", "max_issues_repo_name": "Willh-AM/ElectricCircuits", "max_issues_repo_head_hexsha": "32dc2cd79498f2819967b747a792b7db2822f8bc", "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": "Jupyter notebooks/Circuitos Eletricos I - Semana 6.2.ipynb", "max_forks_repo_name": "Willh-AM/ElectricCircuits", "max_forks_repo_head_hexsha": "32dc2cd79498f2819967b747a792b7db2822f8bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-06-25T12:52:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T14:25:48.000Z", "avg_line_length": 610.4545454545, "max_line_length": 150280, "alphanum_fraction": 0.9432438351, "converted": true, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.18713268896245422, "lm_q1q2_score": 0.060675044512032206}} {"text": "```python\n{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"id\": \"1e51ab9a\",\n \"metadata\": {},\n \"source\": [\n \"# Kerja Gaya Gesek\\n\",\n \"\\n\",\n \"Sparisoma Viridi1, Raden Roro Zahra Auliya S2
    \\n\",\n \"Program Studi Sarjana Fisika, Institut Teknologi Bandung
    \\n\",\n \"Jalan Gensha 10, Bandung 40132, Indonesia
    \\n\",\n \"1dudung@gmail.com, https://github.com/dudung
    \\n\",\n \"2rzahraauliya@gmail.com, https://github.com/RRZahra\\n\",\n \"\\n\",\n \"Kerja yang dilakukan oleh gaya gesek merupakan bentuk kerja yang tidak diharapkan karena energi yang dikeluarkan, biasanya dalam bentuk panas atau bunyi yang dilepas ke lingkungan, tidak dapat dimanfaatkan lagi oleh sistem sehingga energi sistem berkurang.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"aed2f31a\",\n \"metadata\": {},\n \"source\": [\n \"## Gerak benda di atas lantai mendatar kasar\\n\",\n \"Sistem yang ditinjau adalah suatu benda yang bergerak di atas lantai mendatar kasar. Benda diberi kecepatan awal tertentu dan bergerak melambat sampai berhenti karena adanya gaya gesek kinetis antara benda dan lantai kasar.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"dc4acf61\",\n \"metadata\": {},\n \"source\": [\n \"## Parameter\\n\",\n \"Beberapa parameter yang digunakan adalah seperti pada tabel berikut ini.\\n\",\n \"\\n\",\n \"Tabel 1. Simbol beserta satuan dan artinya.\\n\",\n \"\\n\",\n \"Simbol | Satuan | Arti\\n\",\n \":- | :- | :-\\n\",\n \"$t$ | s | waktu\\n\",\n \"$v_0$ | m/s | kecepatan awal\\n\",\n \"$x_0$ | m | posisi awal\\n\",\n \"$v$ | m/s | kecepatan saat $t$\\n\",\n \"$x$ | m | waktu saat $t$\\n\",\n \"$a$ | m/s2 | percepatan\\n\",\n \"$\\\\mu_k$ | - | koefisien gesek kinetis\\n\",\n \"$f_k$ | N | gaya gesek kinetis\\n\",\n \"$m$ | kg | massa benda\\n\",\n \"$F$ | N | total gaya yang bekerja\\n\",\n \"$N$ | N | gaya normal\\n\",\n \"$w$ | N | gaya gravitasi\\n\",\n \"\\n\",\n \"Simbol-simbol pada Tabel [1](#tab1) akan diberi nilai kemudian saat diimplementasikan dalam program.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"12457da3\",\n \"metadata\": {},\n \"source\": [\n \"## Persamaan\\n\",\n \"Persamaan-persamaan yang akan digunakan adalah seperti dicantumkan pada bagian ini.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"fb54dc5c\",\n \"metadata\": {},\n \"source\": [\n \"### Kinematika\\n\",\n \"Hubungan antara antara kecepatan $v$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ diberikan oleh\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:kinematics-v-a-t}\\\\tag{1}\\n\",\n \"v = v_0 + at.\\n\",\n \"\\\\end{equation}\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"0e52be88\",\n \"metadata\": {},\n \"source\": [\n \"Posisi benda $x$ bergantung pada posisi awal $x_0$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ melalui hubungan\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:kinematics-x-v-a-t}\\\\tag{2}\\n\",\n \"x = x_0 + v_0 t + \\\\tfrac12 at^2.\\n\",\n \"\\\\end{equation}\\n\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"3c8a08fa\",\n \"metadata\": {},\n \"source\": [\n \"Selain kedua persamaan sebelumnya, terdapat pula persamaan berikut\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:kinematics-v-x-a}\\\\tag{3}\\n\",\n \"v^2 = v_0^2 + 2a(x - x_0),\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"yang menghubungkan kecepatan $v$ dengan kecepatan awal $v_0$, percepatan $a$, dan jarak yang ditempuh $x - x_0$.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"4fbcd3b6\",\n \"metadata\": {},\n \"source\": [\n \"### Dinamika\\n\",\n \"Hukum Newton I menyatakan bahwa benda yang semula diam akan tetap diam dan yang semula bergerak dengan kecepatan tetap akan tetap bergerak dengan kecepatan tetap bila tidak ada gaya yang bekerja pada benda atau jumlah gaya-gaya yang bekerja sama dengan nol\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:newtons-law-1}\\\\tag{4}\\n\",\n \"\\\\sum F = 0.\\n\",\n \"\\\\end{equation}\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"c237c502\",\n \"metadata\": {},\n \"source\": [\n \"Bila ada gaya yang bekerj pada benda bermassa $m$ atau jumlah gaya-gaya tidak nol\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:newtons-law-2}\\\\tag{5}\\n\",\n \"\\\\sum F = ma,\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"maka keadaan gerak benda akan berubah melalui percepatan $a$, dengan $m > 0$ dan $a \\\\ne 0$.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"79c05418\",\n \"metadata\": {},\n \"source\": [\n \"### Usaha\\n\",\n \"Usaha oleh suatu gaya $F$ dengan posisi awal $x_0$ dan posisi akhir $x_0$ dapat diperoleh melalui\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:work-1}\\\\tag{6}\\n\",\n \"W = \\\\int_{x_0}^x F dx\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"atau dengan\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:work-2}\\\\tag{7}\\n\",\n \"W = \\\\Delta K\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"dengan $K$ adalah energi kinetik. Persamaan ([7](#eqn7)) akan memberikan gaya oleh semua gaya. Dengan demikian bila $F$ adalah satu-satunya gaya yang bekerja pada benda, maka persamaan ini akan menjadi Persamaan ([6](#eqn6)).\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"44901d75\",\n \"metadata\": {},\n \"source\": [\n \"## Sistem\\n\",\n \"Ilustrasi sistem perlu diberikan agar dapat terbayangan dan memudahkan penyelesaian masalah. Selain itu juga perlu disajikan diagram gaya-gaya yang bekerja pada benda.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"8060fbca\",\n \"metadata\": {},\n \"source\": [\n \"### Ilustrasi\\n\",\n \"Sistem yang benda bermassa $m$ bergerak di atas lantai kasar dapat digambarkan\\n\",\n \"seperti berikut ini.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": 1,\n \"id\": \"479756b2\",\n \"metadata\": {\n \"tags\": [\n \"hide_input\"\n ]\n },\n \"outputs\": [\n {\n \"data\": {\n \"text/html\": [\n \"\\n\",\n \"\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\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 \" image/svg+xml\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" v0\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" v = 0\\n\",\n \" μk > 0\\n\",\n \" m\\n\",\n \" \\n\",\n \" g\\n\",\n \" x0\\n\",\n \" x\\n\",\n \" \\n\",\n \"\\n\",\n \"\\n\",\n \"
    \\n\",\n \"\\n\",\n \"Gambar 1. Sistem benda bermassa $m$ begerak di atas lantai\\n\",\n \"mendatar kasar dengan koefisien gesek kinetis $\\\\mu_k$.\\n\"\n ],\n \"text/plain\": [\n \"\"\n ]\n },\n \"metadata\": {},\n \"output_type\": \"display_data\"\n }\n ],\n \"source\": [\n \"%%html\\n\",\n \"\\n\",\n \"\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\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 \" image/svg+xml\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" v0\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" v = 0\\n\",\n \" μk > 0\\n\",\n \" m\\n\",\n \" \\n\",\n \" g\\n\",\n \" x0\\n\",\n \" x\\n\",\n \" \\n\",\n \"\\n\",\n \"\\n\",\n \"
    \\n\",\n \"\\n\",\n \"Gambar 1. Sistem benda bermassa $m$ begerak di atas lantai\\n\",\n \"mendatar kasar dengan koefisien gesek kinetis $\\\\mu_k$.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"7018f95c\",\n \"metadata\": {},\n \"source\": [\n \"Keadaan akhir benda, yaitu saat kecepatan $v = 0$ diberikan pada bagian kanan Gambar [1](#fig1) dengan warna abu-abu.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"fb277d2b\",\n \"metadata\": {},\n \"source\": [\n \"### Diagram gaya\\n\",\n \"Diagram gaya-gaya yang berja pada benda perlu dibuat berdasarkan informasi dari Gambar [1](#fig1) dan Tabel [1](#tab1), yang diberikan berikut ini.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": 8,\n \"id\": \"1d265114\",\n \"metadata\": {},\n \"outputs\": [\n {\n \"data\": {\n \"text/html\": [\n \"\\n\",\n \"\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\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 \" image/svg+xml\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" N\\n\",\n \" v\\n\",\n \" \\n\",\n \" w\\n\",\n \" \\n\",\n \" g\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" fk\\n\",\n \" \\n\",\n \"\\n\",\n \"\\n\",\n \"
    \\n\",\n \"\\n\",\n \"Gambar 2. Diagram gaya-gaya yang bekerja pada benda\\n\",\n \"bermassa $m$.\\n\"\n ],\n \"text/plain\": [\n \"\"\n ]\n },\n \"metadata\": {},\n \"output_type\": \"display_data\"\n }\n ],\n \"source\": [\n \"%%html\\n\",\n \"\\n\",\n \"\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\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 \" image/svg+xml\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" N\\n\",\n \" v\\n\",\n \" \\n\",\n \" w\\n\",\n \" \\n\",\n \" g\\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" \\n\",\n \" fk\\n\",\n \" \\n\",\n \"\\n\",\n \"\\n\",\n \"
    \\n\",\n \"\\n\",\n \"Gambar 2. Diagram gaya-gaya yang bekerja pada benda\\n\",\n \"bermassa $m$.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"a8ac2b2c\",\n \"metadata\": {},\n \"source\": [\n \"Terlihat bahwa pada arah $y$ terdapat gaya normal $N$ dan gaya gravitasi $w$, sedangkan pada arah $x$ hanya terdapat gaya gesek kinetis $f_k$ yang melawan arah gerak benda. Arah gerak benda diberikan oleh arah kecepatan $v$.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"23119498\",\n \"metadata\": {},\n \"source\": [\n \"## Metode numerik\\n\",\n \"Interasi suatu fungsi $f(x)$ berbentuk\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:integral-1}\\\\tag{8}\\n\",\n \"A = \\\\int_a^b f(x) dx\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"dapat didekati dengan\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:integral-2}\\\\tag{9}\\n\",\n \"A \\\\approx \\\\sum_{i = 0}^N f\\\\left[ \\\\tfrac12(x_i + x_{i+1}) \\\\right] \\\\Delta x\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"yang dikenal sebagai metode persegi titik tengah, di mana\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:integral-3}\\\\tag{10}\\n\",\n \"\\\\Delta x = \\\\frac{b - a}{N}\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"dengan $N$ adalah jumlah partisi. Variabel $x_i$ pada Persamaan ([9](#eqn9)) diberikan oleh\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:integral-4}\\\\tag{11}\\n\",\n \"x_i = a + i\\\\Delta x\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"dengan $i = 0, \\\\dots, N$.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"d82ae009\",\n \"metadata\": {},\n \"source\": [\n \"## Penyelesaian\\n\",\n \"Penerapan Persamaan ([1](#eqn1)), ([2](#eqn2)), ([3](#eqn3)), ([4](#eqn4)), dan ([5](#eqn5)) pada Gambar [2](#fig2) akan menghasilkan\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:friction}\\\\tag{10}\\n\",\n \"f_k = \\\\mu_k mg\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"dan usahanya adalah\\n\",\n \"\\n\",\n \"\\n\",\n \"\\\\begin{equation}\\\\label{eqn:friction-work}\\\\tag{11}\\n\",\n \"\\\\begin{array}{rcl}\\n\",\n \"W & = & \\\\displaystyle \\\\int_{x_0}^x f_k dx \\\\newline\\n\",\n \"& = & \\\\displaystyle \\\\int_{x_0}^x \\\\mu_k m g dx \\\\newline\\n\",\n \"& = & \\\\displaystyle m g \\\\int_{x_0}^x \\\\mu_k dx\\n\",\n \"\\\\end{array}\\n\",\n \"\\\\end{equation}\\n\",\n \"\\n\",\n \"dengan koefisien gesek statisnya dapat merupakan fungsi dari posisi $\\\\mu_k = \\\\mu_k(x)$.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": 17,\n \"id\": \"33c63a26\",\n \"metadata\": {},\n \"outputs\": [\n {\n \"data\": {\n \"text/html\": [\n \"\\n\",\n \"
    \\n\",\n \"Gambar 3. Kurva antara usaha $W$ dan jarak tempuh $x - x_0$.\\n\",\n \"
    \\n\"\n ],\n \"text/plain\": [\n \"\"\n ]\n },\n \"execution_count\": 17,\n \"metadata\": {},\n \"output_type\": \"execute_result\"\n },\n {\n \"data\": {\n \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAXgAAAEKCAYAAAAYd05sAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAP60lEQVR4nO3df2xd91nH8c9njlnv2moexHSNUwhCyBI0bA5WVdSpKh2du7XqrNA/irSNDkEETKMTkysCiIqBiISlabAJpqgdbKxlqzLXlGqtV9SWaRILOHWZu2Zm1dRqdTrFLXJ/wNWWuA9/3JM0cZ3YN7nfe+zH75dk9frck/t9dBq/c33u8bUjQgCAfN5U9wAAgDIIPAAkReABICkCDwBJEXgASIrAA0BSW+oe4FRbt26NHTt21D0GAGwYhw4deiEi+le6b10FfseOHZqenq57DADYMGw/e6b7OEUDAEkReABIisADQFIEHgCSKvoiq+0+SXdKulxSSPrNiPj3kmsCwEYxOTOv8ak5HVlsaltfQ2MjgxodGujY45e+iuavJT0UETfb/jFJbym8HgBsCJMz89o7MavmsSVJ0vxiU3snZiWpY5EvdorG9lslXS3pLkmKiB9FxGKp9QBgIxmfmjsZ9xOax5Y0PjXXsTVKnoP/GUkLkv7e9oztO21fuHwn23tsT9ueXlhYKDgOAKwfRxabbW0/FyUDv0XSLkl/FxFDkv5X0h8u3yki9kfEcEQM9/ev+MNYAJDOtr5GW9vPRcnAPyfpuYg4WH1+QK3gA8CmNzYyqEZvz2nbGr09GhsZ7NgaxQIfET+Q9H3bJ6Z9t6SnSq0HABvJ6NCA9u3eqYG+hixpoK+hfbt3bqiraD4q6e7qCprvSfpw4fUAYMMYHRroaNCXKxr4iHhC0nDJNQAAK+MnWQEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CktpR8cNvPSHpF0pKk4xExXHI9APWanJnX+NScjiw2ta2vobGRQY0ODdQ91qZVNPCVX4mIF7qwDoAaTc7Ma+/ErJrHliRJ84tN7Z2YlSQiXxNO0QDoiPGpuZNxP6F5bEnjU3M1TYTSgQ9JX7N9yPaelXawvcf2tO3phYWFwuMAKOXIYrOt7SivdODfFRG7JL1X0kdsX718h4jYHxHDETHc399feBwApWzra7S1HeUVDXxEzFf/PSrpPklXlFwPQH3GRgbV6O05bVujt0djI4M1TYRigbd9oe2LT9yW9B5JT5ZaD0C9RocGtG/3Tg30NWRJA30N7du9kxdYa1TyKppLJN1n+8Q690TEQwXXA1Cz0aEBgr6OFAt8RHxP0jtKPT4A4Oy4TBIAkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkVD7ztHtszth8ovRYA4HXdeAZ/m6TDXVgHAHCKooG3vV3SDZLuLLkOAOCNSj+D/5Sk2yW9VngdAMAyxQJv+0ZJRyPi0Cr77bE9bXt6YWGh1DgAsOmUfAZ/laSbbD8j6UuSrrX9xeU7RcT+iBiOiOH+/v6C4wDA5lIs8BGxNyK2R8QOSbdIeiQiPlBqPQDA6bgOHgCS2tKNRSLiMUmPdWMtAEALz+ABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSWjXwtj9q+23dGAYA0DlreQZ/iaT/tH2v7ettu/RQAIDzt2rgI+JPJP2cpLsk3Srpu7b/0vbPFp4NAHAe1nQOPiJC0g+qj+OS3ibpgO2/KjgbAOA8rPobnWzfJulDkl6QdKeksYg4ZvtNkr4r6fayIwIAzsVafmXfj0vaHRHPnroxIl6zfWOZsQAA52vVwEfEHWe573BnxwEAdArXwQNAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJDUWt5s7JzYvkDS1yW9uVrnwNne1wZYjyZn5jU+Nacji01t62tobGRQo0MDdY8FrEmxwEv6oaRrI+JV272SvmH7wYj4ZsE1gY6ZnJnX3olZNY8tSZLmF5vaOzErSUQeG0KxUzTR8mr1aW/1EaXWAzptfGruZNxPaB5b0vjUXE0TAe0peg7edo/tJyQdlfRwRBxcYZ89tqdtTy8sLJQcB2jLkcVmW9uB9aZo4CNiKSLeKWm7pCtsX77CPvsjYjgihvv7+0uOA7RlW1+jre3AetOVq2giYlHSo5Ku78Z6QCeMjQyq0dtz2rZGb4/GRgZrmghoT7HA2+633Vfdbki6TtJ3Sq0HdNro0ID27d6pgb6GLGmgr6F9u3fyAis2jJJX0Vwq6fO2e9T6h+TeiHig4HpAx40ODRB0bFjFAh8R35I0VOrxAQBnx0+yAkBSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgqWKBt32Z7UdtP2X727ZvK7UWAOCNthR87OOSPh4Rj9u+WNIh2w9HxFMF18QqJmfmNT41pyOLTW3ra2hsZFCjQwN1jwWggGKBj4jnJT1f3X7F9mFJA5IIfE0mZ+a1d2JWzWNLkqT5xab2TsxKEpEHEurKOXjbOyQNSTrYjfWwsvGpuZNxP6F5bEnjU3M1TQSgpOKBt32RpK9I+lhEvLzC/XtsT9ueXlhYKD3OpnZksdnWdgAbW9HA2+5VK+53R8TESvtExP6IGI6I4f7+/pLjbHrb+hptbQewsZW8isaS7pJ0OCI+WWodrN3YyKAavT2nbWv09mhsZLCmiQCUVPIZ/FWSPijpWttPVB/vK7geVjE6NKB9u3dqoK8hSxroa2jf7p28wAokVfIqmm9IcqnHx7kZHRog6MAmwU+yAkBSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEltKfXAtj8n6UZJRyPi8lLrTM7Ma3xqTkcWm9rW19DYyKBGhwZKLQcAG0bJZ/D/IOn6go+vyZl57Z2Y1fxiUyFpfrGpvROzmpyZL7ksAGwIxQIfEV+X9D+lHl+Sxqfm1Dy2dNq25rEljU/NlVwWADaE2s/B295je9r29MLCQlt/9shis63tALCZ1B74iNgfEcMRMdzf39/Wn93W12hrOwBsJrUH/nyMjQyq0dtz2rZGb4/GRgZrmggA1o9iV9F0w4mrZbiKBgDeqORlkv8k6RpJW20/J+mOiLir0+uMDg0QdABYQbHAR8Svl3psAMDqNvQ5eADAmRF4AEiKwANAUgQeAJJyRNQ9w0m2FyQ9e45/fKukFzo4TqcwV3uYqz3M1Z6Mc/10RKz4U6LrKvDnw/Z0RAzXPcdyzNUe5moPc7Vns83FKRoASIrAA0BSmQK/v+4BzoC52sNc7WGu9myqudKcgwcAnC7TM3gAwCkIPAAktaECb/tzto/afvIM99v239h+2va3bO9aJ3NdY/sl209UH3/apbkus/2o7adsf9v2bSvs0/Vjtsa5un7MbF9g+z9s/1c115+tsM+bbX+5Ol4Hbe9YJ3PdanvhlOP1W6XnOmXtHtszth9Y4b6uH681zlXL8bL9jO3Zas3pFe7v7NdjRGyYD0lXS9ol6ckz3P8+SQ9KsqQrJR1cJ3NdI+mBGo7XpZJ2VbcvlvTfkn6+7mO2xrm6fsyqY3BRdbtX0kFJVy7b5/ckfba6fYukL6+TuW6V9Jlu/x2r1v4DSfes9P+rjuO1xrlqOV6SnpG09Sz3d/TrcUM9g4/Vf5H3+yV9IVq+KanP9qXrYK5aRMTzEfF4dfsVSYclLX/z/K4fszXO1XXVMXi1+rS3+lh+FcL7JX2+un1A0rttex3MVQvb2yXdIOnOM+zS9eO1xrnWq45+PW6owK/BgKTvn/L5c1oH4aj8cvUt9oO2f6Hbi1ffGg+p9ezvVLUes7PMJdVwzKpv65+QdFTSwxFxxuMVEcclvSTpJ9bBXJL0a9W39QdsX1Z6psqnJN0u6bUz3F/L8VrDXFI9xyskfc32Idt7Vri/o1+P2QK/Xj2u1vtFvEPSpyVNdnNx2xdJ+oqkj0XEy91c+2xWmauWYxYRSxHxTknbJV1h+/JurLuaNcz1L5J2RMQvSnpYrz9rLsb2jZKORsSh0mu1Y41zdf14Vd4VEbskvVfSR2xfXXKxbIGfl3Tqv8Tbq221ioiXT3yLHRFfldRre2s31rbdq1ZE746IiRV2qeWYrTZXncesWnNR0qOSrl9218njZXuLpLdKerHuuSLixYj4YfXpnZJ+qQvjXCXpJtvPSPqSpGttf3HZPnUcr1Xnqul4KSLmq/8elXSfpCuW7dLRr8dsgb9f0oeqV6KvlPRSRDxf91C2337ivKPtK9Q67sWjUK15l6TDEfHJM+zW9WO2lrnqOGa2+233Vbcbkq6T9J1lu90v6Teq2zdLeiSqV8fqnGvZedqb1Hpdo6iI2BsR2yNih1ovoD4SER9YtlvXj9da5qrjeNm+0PbFJ25Leo+k5VfedfTrsdjvZC3BK/wib7VecFJEfFbSV9V6FfppSf8n6cPrZK6bJf2u7eOSmpJuKf2XvHKVpA9Kmq3O30rSH0n6qVNmq+OYrWWuOo7ZpZI+b7tHrX9Q7o2IB2x/QtJ0RNyv1j9M/2j7abVeWL+l8Exrnev3bd8k6Xg1161dmGtF6+B4rWWuOo7XJZLuq563bJF0T0Q8ZPt3pDJfj7xVAQAkle0UDQCgQuABICkCDwBJEXgASIrAA0BSBB4AktpQ18ED6131Ayx/K+lHkh6LiLtrHgmbGM/ggc7aLelARPy2Wj8hCdSGwAOdtV2vvxvgUp2DAAQem45bv03quur2X9j+dAcf5zm1Ii/x9YWacQ4em9Edkj5h+yfVei/6cz2VstLjXCDpM7ZvUOstaYHa8F402JRs/5ukiyRdU/1WqVPv+1dJb1/hj/1xRPzzWh8HqBvP4LHp2N6p1js0vrhSlCPiVzvxOEDdOEeITaV6H/C71frdl6/aXv4LPbr6OEBJBB6bhu23SJqQ9PGIOCzpz9U6j17L4wClcQ4eAJLiGTwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAk9f92i6o+KZldAgAAAABJRU5ErkJggg==\\n\",\n \"text/plain\": [\n \"
    \"\n ]\n },\n \"metadata\": {\n \"needs_background\": \"light\"\n },\n \"output_type\": \"display_data\"\n }\n ],\n \"source\": [\n \"import numpy as np\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"plt.ion()\\n\",\n \"\\n\",\n \"# set integral lower and upper bounds\\n\",\n \"a = 0\\n\",\n \"b = 1\\n\",\n \"\\n\",\n \"# generate x\\n\",\n \"x = [1, 2, 3, 4, 5]\\n\",\n \"\\n\",\n \"# generate y from numerical integration\\n\",\n \"y = [1, 2, 3, 5, 6]\\n\",\n \"\\n\",\n \"## plot results\\n\",\n \"fig, ax = plt.subplots()\\n\",\n \"ax.scatter(x, y)\\n\",\n \"ax.set_xlabel(\\\"$x - x^0$\\\")\\n\",\n \"ax.set_ylabel(\\\"y\\\")\\n\",\n \"\\n\",\n \"from IPython import display\\n\",\n \"from IPython.core.display import HTML\\n\",\n \"HTML('''\\n\",\n \"
    \\n\",\n \"Gambar 3. Kurva antara usaha $W$ dan jarak tempuh $x - x_0$.\\n\",\n \"
    \\n\",\n \"''')\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"6f0ceb31\",\n \"metadata\": {},\n \"source\": [\n \"## Diskusi\\n\",\n \"Berdasarkan Gambar [3](#fig3) dapat dijelaskan bahwa dengan $\\\\mu_k = \\\\mu_k(x)$ maka kurva $W(x)$ tidak lagi linier karena dipengaruhi oleh sejauh mana perhitungan kerja dilakukan.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"67fba2fe\",\n \"metadata\": {},\n \"source\": [\n \"## Kesimpulan\\n\",\n \"Perhitungan kerja dengan $\\\\mu_k = \\\\mu_k(x)$ telah dapat dilakukan.\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"44995bd5\",\n \"metadata\": {},\n \"source\": [\n \"## Referensi\\n\",\n \"1. J. A. C. Martins, J. T. Oden, F. M. F. Simões, \\\"A study of static and kinetic friction\\\", International Journal of Engineerting Science, vol 28, no 1, p 29-92, 1990, url . \\n\",\n \"1. Carl Rod Nave, \\\"Friction\\\", HyperPhysics, 2017, url [20220419].\\n\",\n \"2. Wikipedia contributors, \\\"Friction\\\", Wikipedia, The Free Encyclopedia, 12 April 2022, 00:33 UTC, url [20220419].\\n\",\n \"3. Tia Ghose, Ailsa Harvey, \\\"What is friction?\\\", Live Science, 8 Feb 2022, url [20220419].\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": [],\n \"id\": \"a7da2b33\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"Python 3 (ipykernel)\",\n \"language\": \"python\",\n \"name\": \"python3\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.4\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n\n```\n\n\n\n\n {'cells': [{'cell_type': 'markdown',\n 'id': '1e51ab9a',\n 'metadata': {},\n 'source': ['# Kerja Gaya Gesek\\n',\n '\\n',\n 'Sparisoma Viridi1, Raden Roro Zahra Auliya S2
    \\n',\n 'Program Studi Sarjana Fisika, Institut Teknologi Bandung
    \\n',\n 'Jalan Gensha 10, Bandung 40132, Indonesia
    \\n',\n '1dudung@gmail.com, https://github.com/dudung
    \\n',\n '2rzahraauliya@gmail.com, https://github.com/RRZahra\\n',\n '\\n',\n 'Kerja yang dilakukan oleh gaya gesek merupakan bentuk kerja yang tidak diharapkan karena energi yang dikeluarkan, biasanya dalam bentuk panas atau bunyi yang dilepas ke lingkungan, tidak dapat dimanfaatkan lagi oleh sistem sehingga energi sistem berkurang.']},\n {'cell_type': 'markdown',\n 'id': 'aed2f31a',\n 'metadata': {},\n 'source': ['## Gerak benda di atas lantai mendatar kasar\\n',\n 'Sistem yang ditinjau adalah suatu benda yang bergerak di atas lantai mendatar kasar. Benda diberi kecepatan awal tertentu dan bergerak melambat sampai berhenti karena adanya gaya gesek kinetis antara benda dan lantai kasar.']},\n {'cell_type': 'markdown',\n 'id': 'dc4acf61',\n 'metadata': {},\n 'source': ['## Parameter\\n',\n 'Beberapa parameter yang digunakan adalah seperti pada tabel berikut ini.\\n',\n '\\n',\n \"Tabel 1. Simbol beserta satuan dan artinya.\\n\",\n '\\n',\n 'Simbol | Satuan | Arti\\n',\n ':- | :- | :-\\n',\n '$t$ | s | waktu\\n',\n '$v_0$ | m/s | kecepatan awal\\n',\n '$x_0$ | m | posisi awal\\n',\n '$v$ | m/s | kecepatan saat $t$\\n',\n '$x$ | m | waktu saat $t$\\n',\n '$a$ | m/s2 | percepatan\\n',\n '$\\\\mu_k$ | - | koefisien gesek kinetis\\n',\n '$f_k$ | N | gaya gesek kinetis\\n',\n '$m$ | kg | massa benda\\n',\n '$F$ | N | total gaya yang bekerja\\n',\n '$N$ | N | gaya normal\\n',\n '$w$ | N | gaya gravitasi\\n',\n '\\n',\n 'Simbol-simbol pada Tabel [1](#tab1) akan diberi nilai kemudian saat diimplementasikan dalam program.']},\n {'cell_type': 'markdown',\n 'id': '12457da3',\n 'metadata': {},\n 'source': ['## Persamaan\\n',\n 'Persamaan-persamaan yang akan digunakan adalah seperti dicantumkan pada bagian ini.']},\n {'cell_type': 'markdown',\n 'id': 'fb54dc5c',\n 'metadata': {},\n 'source': ['### Kinematika\\n',\n 'Hubungan antara antara kecepatan $v$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ diberikan oleh\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:kinematics-v-a-t}\\\\tag{1}\\n',\n 'v = v_0 + at.\\n',\n '\\\\end{equation}']},\n {'cell_type': 'markdown',\n 'id': '0e52be88',\n 'metadata': {},\n 'source': ['Posisi benda $x$ bergantung pada posisi awal $x_0$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ melalui hubungan\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:kinematics-x-v-a-t}\\\\tag{2}\\n',\n 'x = x_0 + v_0 t + \\\\tfrac12 at^2.\\n',\n '\\\\end{equation}\\n']},\n {'cell_type': 'markdown',\n 'id': '3c8a08fa',\n 'metadata': {},\n 'source': ['Selain kedua persamaan sebelumnya, terdapat pula persamaan berikut\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:kinematics-v-x-a}\\\\tag{3}\\n',\n 'v^2 = v_0^2 + 2a(x - x_0),\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'yang menghubungkan kecepatan $v$ dengan kecepatan awal $v_0$, percepatan $a$, dan jarak yang ditempuh $x - x_0$.']},\n {'cell_type': 'markdown',\n 'id': '4fbcd3b6',\n 'metadata': {},\n 'source': ['### Dinamika\\n',\n 'Hukum Newton I menyatakan bahwa benda yang semula diam akan tetap diam dan yang semula bergerak dengan kecepatan tetap akan tetap bergerak dengan kecepatan tetap bila tidak ada gaya yang bekerja pada benda atau jumlah gaya-gaya yang bekerja sama dengan nol\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:newtons-law-1}\\\\tag{4}\\n',\n '\\\\sum F = 0.\\n',\n '\\\\end{equation}']},\n {'cell_type': 'markdown',\n 'id': 'c237c502',\n 'metadata': {},\n 'source': ['Bila ada gaya yang bekerj pada benda bermassa $m$ atau jumlah gaya-gaya tidak nol\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:newtons-law-2}\\\\tag{5}\\n',\n '\\\\sum F = ma,\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'maka keadaan gerak benda akan berubah melalui percepatan $a$, dengan $m > 0$ dan $a \\\\ne 0$.']},\n {'cell_type': 'markdown',\n 'id': '79c05418',\n 'metadata': {},\n 'source': ['### Usaha\\n',\n 'Usaha oleh suatu gaya $F$ dengan posisi awal $x_0$ dan posisi akhir $x_0$ dapat diperoleh melalui\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:work-1}\\\\tag{6}\\n',\n 'W = \\\\int_{x_0}^x F dx\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'atau dengan\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:work-2}\\\\tag{7}\\n',\n 'W = \\\\Delta K\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'dengan $K$ adalah energi kinetik. Persamaan ([7](#eqn7)) akan memberikan gaya oleh semua gaya. Dengan demikian bila $F$ adalah satu-satunya gaya yang bekerja pada benda, maka persamaan ini akan menjadi Persamaan ([6](#eqn6)).']},\n {'cell_type': 'markdown',\n 'id': '44901d75',\n 'metadata': {},\n 'source': ['## Sistem\\n',\n 'Ilustrasi sistem perlu diberikan agar dapat terbayangan dan memudahkan penyelesaian masalah. Selain itu juga perlu disajikan diagram gaya-gaya yang bekerja pada benda.']},\n {'cell_type': 'markdown',\n 'id': '8060fbca',\n 'metadata': {},\n 'source': ['### Ilustrasi\\n',\n 'Sistem yang benda bermassa $m$ bergerak di atas lantai kasar dapat digambarkan\\n',\n 'seperti berikut ini.']},\n {'cell_type': 'code',\n 'execution_count': 1,\n 'id': '479756b2',\n 'metadata': {'tags': ['hide_input']},\n 'outputs': [{'data': {'text/html': ['\\n',\n '\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\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 ' image/svg+xml\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' v0\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' v = 0\\n',\n ' μk > 0\\n',\n ' m\\n',\n ' \\n',\n ' g\\n',\n ' x0\\n',\n ' x\\n',\n ' \\n',\n '\\n',\n '\\n',\n '
    \\n',\n '\\n',\n \"Gambar 1. Sistem benda bermassa $m$ begerak di atas lantai\\n\",\n 'mendatar kasar dengan koefisien gesek kinetis $\\\\mu_k$.\\n'],\n 'text/plain': ['']},\n 'metadata': {},\n 'output_type': 'display_data'}],\n 'source': ['%%html\\n',\n '\\n',\n '\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\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 ' image/svg+xml\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' v0\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' v = 0\\n',\n ' μk > 0\\n',\n ' m\\n',\n ' \\n',\n ' g\\n',\n ' x0\\n',\n ' x\\n',\n ' \\n',\n '\\n',\n '\\n',\n '
    \\n',\n '\\n',\n \"Gambar 1. Sistem benda bermassa $m$ begerak di atas lantai\\n\",\n 'mendatar kasar dengan koefisien gesek kinetis $\\\\mu_k$.']},\n {'cell_type': 'markdown',\n 'id': '7018f95c',\n 'metadata': {},\n 'source': ['Keadaan akhir benda, yaitu saat kecepatan $v = 0$ diberikan pada bagian kanan Gambar [1](#fig1) dengan warna abu-abu.']},\n {'cell_type': 'markdown',\n 'id': 'fb277d2b',\n 'metadata': {},\n 'source': ['### Diagram gaya\\n',\n 'Diagram gaya-gaya yang berja pada benda perlu dibuat berdasarkan informasi dari Gambar [1](#fig1) dan Tabel [1](#tab1), yang diberikan berikut ini.']},\n {'cell_type': 'code',\n 'execution_count': 8,\n 'id': '1d265114',\n 'metadata': {},\n 'outputs': [{'data': {'text/html': ['\\n',\n '\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\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 ' image/svg+xml\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' N\\n',\n ' v\\n',\n ' \\n',\n ' w\\n',\n ' \\n',\n ' g\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' fk\\n',\n ' \\n',\n '\\n',\n '\\n',\n '
    \\n',\n '\\n',\n \"Gambar 2. Diagram gaya-gaya yang bekerja pada benda\\n\",\n 'bermassa $m$.\\n'],\n 'text/plain': ['']},\n 'metadata': {},\n 'output_type': 'display_data'}],\n 'source': ['%%html\\n',\n '\\n',\n '\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\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 ' image/svg+xml\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' N\\n',\n ' v\\n',\n ' \\n',\n ' w\\n',\n ' \\n',\n ' g\\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' \\n',\n ' fk\\n',\n ' \\n',\n '\\n',\n '\\n',\n '
    \\n',\n '\\n',\n \"Gambar 2. Diagram gaya-gaya yang bekerja pada benda\\n\",\n 'bermassa $m$.']},\n {'cell_type': 'markdown',\n 'id': 'a8ac2b2c',\n 'metadata': {},\n 'source': ['Terlihat bahwa pada arah $y$ terdapat gaya normal $N$ dan gaya gravitasi $w$, sedangkan pada arah $x$ hanya terdapat gaya gesek kinetis $f_k$ yang melawan arah gerak benda. Arah gerak benda diberikan oleh arah kecepatan $v$.']},\n {'cell_type': 'markdown',\n 'id': '23119498',\n 'metadata': {},\n 'source': ['## Metode numerik\\n',\n 'Interasi suatu fungsi $f(x)$ berbentuk\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:integral-1}\\\\tag{8}\\n',\n 'A = \\\\int_a^b f(x) dx\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'dapat didekati dengan\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:integral-2}\\\\tag{9}\\n',\n 'A \\\\approx \\\\sum_{i = 0}^N f\\\\left[ \\\\tfrac12(x_i + x_{i+1}) \\\\right] \\\\Delta x\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'yang dikenal sebagai metode persegi titik tengah, di mana\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:integral-3}\\\\tag{10}\\n',\n '\\\\Delta x = \\\\frac{b - a}{N}\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'dengan $N$ adalah jumlah partisi. Variabel $x_i$ pada Persamaan ([9](#eqn9)) diberikan oleh\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:integral-4}\\\\tag{11}\\n',\n 'x_i = a + i\\\\Delta x\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'dengan $i = 0, \\\\dots, N$.']},\n {'cell_type': 'markdown',\n 'id': 'd82ae009',\n 'metadata': {},\n 'source': ['## Penyelesaian\\n',\n 'Penerapan Persamaan ([1](#eqn1)), ([2](#eqn2)), ([3](#eqn3)), ([4](#eqn4)), dan ([5](#eqn5)) pada Gambar [2](#fig2) akan menghasilkan\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:friction}\\\\tag{10}\\n',\n 'f_k = \\\\mu_k mg\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'dan usahanya adalah\\n',\n '\\n',\n \"\\n\",\n '\\\\begin{equation}\\\\label{eqn:friction-work}\\\\tag{11}\\n',\n '\\\\begin{array}{rcl}\\n',\n 'W & = & \\\\displaystyle \\\\int_{x_0}^x f_k dx \\\\newline\\n',\n '& = & \\\\displaystyle \\\\int_{x_0}^x \\\\mu_k m g dx \\\\newline\\n',\n '& = & \\\\displaystyle m g \\\\int_{x_0}^x \\\\mu_k dx\\n',\n '\\\\end{array}\\n',\n '\\\\end{equation}\\n',\n '\\n',\n 'dengan koefisien gesek statisnya dapat merupakan fungsi dari posisi $\\\\mu_k = \\\\mu_k(x)$.']},\n {'cell_type': 'code',\n 'execution_count': 17,\n 'id': '33c63a26',\n 'metadata': {},\n 'outputs': [{'data': {'text/html': ['\\n',\n '
    \\n',\n \"Gambar 3. Kurva antara usaha $W$ dan jarak tempuh $x - x_0$.\\n\",\n '
    \\n'],\n 'text/plain': ['']},\n 'execution_count': 17,\n 'metadata': {},\n 'output_type': 'execute_result'},\n {'data': {'image/png': 'iVBORw0KGgoAAAANSUhEUgAAAXgAAAEKCAYAAAAYd05sAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAP60lEQVR4nO3df2xd91nH8c9njlnv2moexHSNUwhCyBI0bA5WVdSpKh2du7XqrNA/irSNDkEETKMTkysCiIqBiISlabAJpqgdbKxlqzLXlGqtV9SWaRILOHWZu2Zm1dRqdTrFLXJ/wNWWuA9/3JM0cZ3YN7nfe+zH75dk9frck/t9dBq/c33u8bUjQgCAfN5U9wAAgDIIPAAkReABICkCDwBJEXgASIrAA0BSW+oe4FRbt26NHTt21D0GAGwYhw4deiEi+le6b10FfseOHZqenq57DADYMGw/e6b7OEUDAEkReABIisADQFIEHgCSKvoiq+0+SXdKulxSSPrNiPj3kmsCwEYxOTOv8ak5HVlsaltfQ2MjgxodGujY45e+iuavJT0UETfb/jFJbym8HgBsCJMz89o7MavmsSVJ0vxiU3snZiWpY5EvdorG9lslXS3pLkmKiB9FxGKp9QBgIxmfmjsZ9xOax5Y0PjXXsTVKnoP/GUkLkv7e9oztO21fuHwn23tsT9ueXlhYKDgOAKwfRxabbW0/FyUDv0XSLkl/FxFDkv5X0h8u3yki9kfEcEQM9/ev+MNYAJDOtr5GW9vPRcnAPyfpuYg4WH1+QK3gA8CmNzYyqEZvz2nbGr09GhsZ7NgaxQIfET+Q9H3bJ6Z9t6SnSq0HABvJ6NCA9u3eqYG+hixpoK+hfbt3bqiraD4q6e7qCprvSfpw4fUAYMMYHRroaNCXKxr4iHhC0nDJNQAAK+MnWQEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CktpR8cNvPSHpF0pKk4xExXHI9APWanJnX+NScjiw2ta2vobGRQY0ODdQ91qZVNPCVX4mIF7qwDoAaTc7Ma+/ErJrHliRJ84tN7Z2YlSQiXxNO0QDoiPGpuZNxP6F5bEnjU3M1TYTSgQ9JX7N9yPaelXawvcf2tO3phYWFwuMAKOXIYrOt7SivdODfFRG7JL1X0kdsX718h4jYHxHDETHc399feBwApWzra7S1HeUVDXxEzFf/PSrpPklXlFwPQH3GRgbV6O05bVujt0djI4M1TYRigbd9oe2LT9yW9B5JT5ZaD0C9RocGtG/3Tg30NWRJA30N7du9kxdYa1TyKppLJN1n+8Q690TEQwXXA1Cz0aEBgr6OFAt8RHxP0jtKPT4A4Oy4TBIAkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkVD7ztHtszth8ovRYA4HXdeAZ/m6TDXVgHAHCKooG3vV3SDZLuLLkOAOCNSj+D/5Sk2yW9VngdAMAyxQJv+0ZJRyPi0Cr77bE9bXt6YWGh1DgAsOmUfAZ/laSbbD8j6UuSrrX9xeU7RcT+iBiOiOH+/v6C4wDA5lIs8BGxNyK2R8QOSbdIeiQiPlBqPQDA6bgOHgCS2tKNRSLiMUmPdWMtAEALz+ABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSWjXwtj9q+23dGAYA0DlreQZ/iaT/tH2v7ettu/RQAIDzt2rgI+JPJP2cpLsk3Srpu7b/0vbPFp4NAHAe1nQOPiJC0g+qj+OS3ibpgO2/KjgbAOA8rPobnWzfJulDkl6QdKeksYg4ZvtNkr4r6fayIwIAzsVafmXfj0vaHRHPnroxIl6zfWOZsQAA52vVwEfEHWe573BnxwEAdArXwQNAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJDUWt5s7JzYvkDS1yW9uVrnwNne1wZYjyZn5jU+Nacji01t62tobGRQo0MDdY8FrEmxwEv6oaRrI+JV272SvmH7wYj4ZsE1gY6ZnJnX3olZNY8tSZLmF5vaOzErSUQeG0KxUzTR8mr1aW/1EaXWAzptfGruZNxPaB5b0vjUXE0TAe0peg7edo/tJyQdlfRwRBxcYZ89tqdtTy8sLJQcB2jLkcVmW9uB9aZo4CNiKSLeKWm7pCtsX77CPvsjYjgihvv7+0uOA7RlW1+jre3AetOVq2giYlHSo5Ku78Z6QCeMjQyq0dtz2rZGb4/GRgZrmghoT7HA2+633Vfdbki6TtJ3Sq0HdNro0ID27d6pgb6GLGmgr6F9u3fyAis2jJJX0Vwq6fO2e9T6h+TeiHig4HpAx40ODRB0bFjFAh8R35I0VOrxAQBnx0+yAkBSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgqWKBt32Z7UdtP2X727ZvK7UWAOCNthR87OOSPh4Rj9u+WNIh2w9HxFMF18QqJmfmNT41pyOLTW3ra2hsZFCjQwN1jwWggGKBj4jnJT1f3X7F9mFJA5IIfE0mZ+a1d2JWzWNLkqT5xab2TsxKEpEHEurKOXjbOyQNSTrYjfWwsvGpuZNxP6F5bEnjU3M1TQSgpOKBt32RpK9I+lhEvLzC/XtsT9ueXlhYKD3OpnZksdnWdgAbW9HA2+5VK+53R8TESvtExP6IGI6I4f7+/pLjbHrb+hptbQewsZW8isaS7pJ0OCI+WWodrN3YyKAavT2nbWv09mhsZLCmiQCUVPIZ/FWSPijpWttPVB/vK7geVjE6NKB9u3dqoK8hSxroa2jf7p28wAokVfIqmm9IcqnHx7kZHRog6MAmwU+yAkBSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEkReABIisADQFIEHgCSIvAAkBSBB4CkCDwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAkReABICkCDwBJEXgASIrAA0BSBB4AkiLwAJAUgQeApAg8ACRF4AEgKQIPAEltKfXAtj8n6UZJRyPi8lLrTM7Ma3xqTkcWm9rW19DYyKBGhwZKLQcAG0bJZ/D/IOn6go+vyZl57Z2Y1fxiUyFpfrGpvROzmpyZL7ksAGwIxQIfEV+X9D+lHl+Sxqfm1Dy2dNq25rEljU/NlVwWADaE2s/B295je9r29MLCQlt/9shis63tALCZ1B74iNgfEcMRMdzf39/Wn93W12hrOwBsJrUH/nyMjQyq0dtz2rZGb4/GRgZrmggA1o9iV9F0w4mrZbiKBgDeqORlkv8k6RpJW20/J+mOiLir0+uMDg0QdABYQbHAR8Svl3psAMDqNvQ5eADAmRF4AEiKwANAUgQeAJJyRNQ9w0m2FyQ9e45/fKukFzo4TqcwV3uYqz3M1Z6Mc/10RKz4U6LrKvDnw/Z0RAzXPcdyzNUe5moPc7Vns83FKRoASIrAA0BSmQK/v+4BzoC52sNc7WGu9myqudKcgwcAnC7TM3gAwCkIPAAktaECb/tzto/afvIM99v239h+2va3bO9aJ3NdY/sl209UH3/apbkus/2o7adsf9v2bSvs0/Vjtsa5un7MbF9g+z9s/1c115+tsM+bbX+5Ol4Hbe9YJ3PdanvhlOP1W6XnOmXtHtszth9Y4b6uH681zlXL8bL9jO3Zas3pFe7v7NdjRGyYD0lXS9ol6ckz3P8+SQ9KsqQrJR1cJ3NdI+mBGo7XpZJ2VbcvlvTfkn6+7mO2xrm6fsyqY3BRdbtX0kFJVy7b5/ckfba6fYukL6+TuW6V9Jlu/x2r1v4DSfes9P+rjuO1xrlqOV6SnpG09Sz3d/TrcUM9g4/Vf5H3+yV9IVq+KanP9qXrYK5aRMTzEfF4dfsVSYclLX/z/K4fszXO1XXVMXi1+rS3+lh+FcL7JX2+un1A0rttex3MVQvb2yXdIOnOM+zS9eO1xrnWq45+PW6owK/BgKTvn/L5c1oH4aj8cvUt9oO2f6Hbi1ffGg+p9ezvVLUes7PMJdVwzKpv65+QdFTSwxFxxuMVEcclvSTpJ9bBXJL0a9W39QdsX1Z6psqnJN0u6bUz3F/L8VrDXFI9xyskfc32Idt7Vri/o1+P2QK/Xj2u1vtFvEPSpyVNdnNx2xdJ+oqkj0XEy91c+2xWmauWYxYRSxHxTknbJV1h+/JurLuaNcz1L5J2RMQvSnpYrz9rLsb2jZKORsSh0mu1Y41zdf14Vd4VEbskvVfSR2xfXXKxbIGfl3Tqv8Tbq221ioiXT3yLHRFfldRre2s31rbdq1ZE746IiRV2qeWYrTZXncesWnNR0qOSrl9218njZXuLpLdKerHuuSLixYj4YfXpnZJ+qQvjXCXpJtvPSPqSpGttf3HZPnUcr1Xnqul4KSLmq/8elXSfpCuW7dLRr8dsgb9f0oeqV6KvlPRSRDxf91C2337ivKPtK9Q67sWjUK15l6TDEfHJM+zW9WO2lrnqOGa2+233Vbcbkq6T9J1lu90v6Teq2zdLeiSqV8fqnGvZedqb1Hpdo6iI2BsR2yNih1ovoD4SER9YtlvXj9da5qrjeNm+0PbFJ25Leo+k5VfedfTrsdjvZC3BK/wib7VecFJEfFbSV9V6FfppSf8n6cPrZK6bJf2u7eOSmpJuKf2XvHKVpA9Kmq3O30rSH0n6qVNmq+OYrWWuOo7ZpZI+b7tHrX9Q7o2IB2x/QtJ0RNyv1j9M/2j7abVeWL+l8Exrnev3bd8k6Xg1161dmGtF6+B4rWWuOo7XJZLuq563bJF0T0Q8ZPt3pDJfj7xVAQAkle0UDQCgQuABICkCDwBJEXgASIrAA0BSBB4AktpQ18ED6131Ayx/K+lHkh6LiLtrHgmbGM/ggc7aLelARPy2Wj8hCdSGwAOdtV2vvxvgUp2DAAQem45bv03quur2X9j+dAcf5zm1Ii/x9YWacQ4em9Edkj5h+yfVei/6cz2VstLjXCDpM7ZvUOstaYHa8F402JRs/5ukiyRdU/1WqVPv+1dJb1/hj/1xRPzzWh8HqBvP4LHp2N6p1js0vrhSlCPiVzvxOEDdOEeITaV6H/C71frdl6/aXv4LPbr6OEBJBB6bhu23SJqQ9PGIOCzpz9U6j17L4wClcQ4eAJLiGTwAJEXgASApAg8ASRF4AEiKwANAUgQeAJIi8ACQFIEHgKQIPAAk9f92i6o+KZldAgAAAABJRU5ErkJggg==\\n',\n 'text/plain': ['
    ']},\n 'metadata': {'needs_background': 'light'},\n 'output_type': 'display_data'}],\n 'source': ['import numpy as np\\n',\n 'import matplotlib.pyplot as plt\\n',\n 'plt.ion()\\n',\n '\\n',\n '# set integral lower and upper bounds\\n',\n 'a = 0\\n',\n 'b = 1\\n',\n '\\n',\n '# generate x\\n',\n 'x = [1, 2, 3, 4, 5]\\n',\n '\\n',\n '# generate y from numerical integration\\n',\n 'y = [1, 2, 3, 5, 6]\\n',\n '\\n',\n '## plot results\\n',\n 'fig, ax = plt.subplots()\\n',\n 'ax.scatter(x, y)\\n',\n 'ax.set_xlabel(\"$x - x^0$\")\\n',\n 'ax.set_ylabel(\"y\")\\n',\n '\\n',\n 'from IPython import display\\n',\n 'from IPython.core.display import HTML\\n',\n \"HTML('''\\n\",\n '
    \\n',\n \"Gambar 3. Kurva antara usaha $W$ dan jarak tempuh $x - x_0$.\\n\",\n '
    \\n',\n \"''')\"]},\n {'cell_type': 'markdown',\n 'id': '6f0ceb31',\n 'metadata': {},\n 'source': ['## Diskusi\\n',\n 'Berdasarkan Gambar [3](#fig3) dapat dijelaskan bahwa dengan $\\\\mu_k = \\\\mu_k(x)$ maka kurva $W(x)$ tidak lagi linier karena dipengaruhi oleh sejauh mana perhitungan kerja dilakukan.']},\n {'cell_type': 'markdown',\n 'id': '67fba2fe',\n 'metadata': {},\n 'source': ['## Kesimpulan\\n',\n 'Perhitungan kerja dengan $\\\\mu_k = \\\\mu_k(x)$ telah dapat dilakukan.']},\n {'cell_type': 'markdown',\n 'id': '44995bd5',\n 'metadata': {},\n 'source': ['## Referensi\\n',\n '1. J. A. C. Martins, J. T. Oden, F. M. F. Simões, \"A study of static and kinetic friction\", International Journal of Engineerting Science, vol 28, no 1, p 29-92, 1990, url . \\n',\n '1. Carl Rod Nave, \"Friction\", HyperPhysics, 2017, url [20220419].\\n',\n '2. Wikipedia contributors, \"Friction\", Wikipedia, The Free Encyclopedia, 12 April 2022, 00:33 UTC, url [20220419].\\n',\n '3. Tia Ghose, Ailsa Harvey, \"What is friction?\", Live Science, 8 Feb 2022, url [20220419].']},\n {'cell_type': 'code',\n 'execution_count': [],\n 'id': 'a7da2b33',\n 'metadata': {},\n 'outputs': [],\n 'source': []}],\n 'metadata': {'kernelspec': {'display_name': 'Python 3 (ipykernel)',\n 'language': 'python',\n 'name': 'python3'},\n 'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3},\n 'file_extension': '.py',\n 'mimetype': 'text/x-python',\n 'name': 'python',\n 'nbconvert_exporter': 'python',\n 'pygments_lexer': 'ipython3',\n 'version': '3.10.4'}},\n 'nbformat': 4,\n 'nbformat_minor': 5}\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "86d7917b0081972a1aaac648707a37c103a9b2e4", "size": 198764, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "work_of_friction (10219069_Rr Zahra).ipynb", "max_stars_repo_name": "RRZahra/fi3201-01-2021-2", "max_stars_repo_head_hexsha": "c5bf0c1bd879e48e72cbc5025c32c2625f067ad1", "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": "work_of_friction (10219069_Rr Zahra).ipynb", "max_issues_repo_name": "RRZahra/fi3201-01-2021-2", "max_issues_repo_head_hexsha": "c5bf0c1bd879e48e72cbc5025c32c2625f067ad1", "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": "work_of_friction (10219069_Rr Zahra).ipynb", "max_forks_repo_name": "RRZahra/fi3201-01-2021-2", "max_forks_repo_head_hexsha": "c5bf0c1bd879e48e72cbc5025c32c2625f067ad1", "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": 62.5044025157, "max_line_length": 5677, "alphanum_fraction": 0.4334939929, "converted": true, "num_tokens": 56006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.1294027450214798, "lm_q1q2_score": 0.06066279392577555}} {"text": "# **Monitoring and Optimizing Quantum Circuits**\n\n\n```python\nimport numpy as np\n\n# Importing standard Qiskit libraries\nfrom qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\nfrom ibm_quantum_widgets import *\nfrom qiskit.providers.aer import QasmSimulator\n\n# Loading your IBM Quantum account(s)\nprovider = IBMQ.load_account()\n```\n\n## **Monitoring and Tracking Jobs**\n\n\n```python\n# Import the Qiskit Jupyter tools \nfrom qiskit.tools import jupyter\n```\n\n\n```python\n# Initialize the job tracker to automatically track all jobs\n%qiskit_job_watcher\n```\n\n\n Accordion(children=(VBox(layout=Layout(max_width='710px', min_width='710px')),), layout=Layout(max_height='500…\n\n\n\n \n\n\n\n```python\n# Let's run a simple circuit on the least busy quantum device \n# and check the job watcher widget.\nfrom qiskit.providers.ibmq import least_busy\n\nbackend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (2) and \n not x.configuration().simulator \n and x.status().operational==True))\n\n#Create a simple circuit\nqc = QuantumCircuit(1)\nqc.h(0)\nqc.measure_all()\n#Execute the circuit on the backend\njob = execute(qc, backend)\n```\n\n\n```python\n#Disable the job watcher\n%qiskit_disable_job_watcher\n```\n\n\n```python\n#Display the list of all available backends and provide \n#a brief overview of each \n%qiskit_backend_overview\n```\n\n\n VBox(children=(HTML(value=\"

    \n\n\n\n\n```python\n# Get the backend device: ibmq_lima\nbackend_lima = provider.get_backend('ibmq_lima')\n# Launch backend viewer of ibmq_lima\nbackend_lima\n```\n\n\n VBox(children=(HTML(value=\"

    \n\n\n\n\n```python\n# Visualize the coupling directional map between the qubits \nplot_gate_map(backend_santiago, plot_directed=True)\n```\n\n\n```python\n# Visualize the coupling directional map between the qubits \nplot_gate_map(backend_lima, plot_directed=True)\n```\n\n\n```python\n# Quantum circuit with a single and multi-qubit gates\nqc = QuantumCircuit(4)\nqc.h(0)\nqc.cx(0,1)\nqc.cx(0,2)\nqc.cx(0,3)\nqc.draw()\n```\n\n\n```python\n# Transpile the circuit with an optimization level = 0\nqc_santiago_0 = transpile(qc, backend_santiago, \nseed_transpiler=10258, optimization_level=0)\n# Print out the depth of the circuit\nprint('Depth:', qc_santiago_0.depth())\n# Plot the resulting layout of the quantum circuit after Layout\nplot_circuit_layout(qc_santiago_0, backend_santiago)\n```\n\n\n```python\n# Draw the transpiled circuit pertaining to Santiago\nqc_santiago_0.draw()\n```\n\n\n```python\n# View the transpiled circuit with an optimization level = 0\nqc_lima_0 = transpile(qc, backend_lima, seed_transpiler=10258, optimization_level=0)\nprint('Depth:', qc_lima_0.depth())\nplot_circuit_layout(qc_lima_0, backend_lima)\n```\n\n\n```python\n# Draw the transpiled circuit pertaining to Lima\nqc_lima_0.draw()\n```\n\n\n```python\n# Transpile the circuit with the optimization level = 3\nqc_transpiled_santiago = transpile(qc, backend_santiago, optimization_level=3)\n# Print the depth of the transpiled circuit\nprint('Depth:', qc_transpiled_santiago.depth())\n# Print the number of operations of the transpiled circuit\nprint('Ops count: ', qc_transpiled_santiago.count_ops())\n# Plot the layout mapping of the transpiled circuit\nplot_circuit_layout(qc_transpiled_santiago, backend_santiago)\n```\n\n\n```python\n# Redraw the transpiled circuit at new level\nqc_transpiled_santiago.draw()\n```\n\n\n```python\n# Transpile the quantum circuit with the optimization level = 3\nqc_transpiled_lima = transpile(qc, backend_lima, optimization_level=3)\n# Get the depth and operation count of the transpiled circuit. \nprint('Depth:', qc_transpiled_lima.depth())\nprint('Ops count: ', qc_transpiled_lima.count_ops())\n# Print the circuit layout\nplot_circuit_layout(qc_transpiled_lima, backend_lima)\n```\n\n\n```python\n# View the ibmq_quito backend device configuration and properties\nbackend = provider.get_backend('ibmq_quito')\nbackend\n```\n\n\n VBox(children=(HTML(value=\"

    \n\n\n\n\n```python\n# View the backend coupling map, displayed as CNOTs (Control-Target)\nbackend = provider.get_backend('ibmq_quito')\n# Extract the coupling map from the backend\nibmqquito_coupling_map = backend.configuration().coupling_map\n# List out the extracted coupling map\nibmqquito_coupling_map\n```\n\n\n\n\n [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]]\n\n\n\n\n```python\n# Transpile a custom circuit using only the coupling map. \n# Set the backend to ‘None’ so it will force using the coupling map provided.\nqc_custom = transpile(qc, backend=None, \ncoupling_map=ibmqquito_coupling_map)\n# Draw the resulting custom topology circuit.\nqc_custom.draw()\n```\n\n\n```python\n# Create our own coupling map (custom topology)\ncustom_linear_topology = [[0,1],[1,2],[2,3],[3,4]]\n# Set the coupling map to our custom linear topology\nqc_custom = transpile(qc, backend=None, coupling_map=custom_linear_topology)\n# Draw the resulting circuit.\nqc_custom.draw()\n```\n\n\n```python\n# Import the PassManager and a few Passes\nfrom qiskit.transpiler import PassManager, CouplingMap\nfrom qiskit.transpiler.passes import TrivialLayout, BasicSwap\n# Create a TrivialLayout based on the ibmqx2 coupling map\ntrivial = TrivialLayout(CouplingMap(ibmqquito_coupling_map))\n\npm = PassManager()\n# Append the TrivialLayout to the PassManager\npm.append(trivial)\n# Run the PassManager and draw the resulting circuit\ntv_qc = pm.run(qc)\ntv_qc.draw()\n```\n\n\n```python\n# Create a BasicSwap based on the ibmq_quito coupling map we used earlier\nbasic_swap = BasicSwap(CouplingMap(ibmqquito_coupling_map))\n#Add the BasicSwap to the PassManager\npm = PassManager(basic_swap)\n# Run the PassManager and draw the results\nnew_qc = pm.run(qc)\nnew_qc.draw()\n```\n\n\n```python\n# Sample quantum circuit \nqc = QuantumCircuit(4)\nqc.h(0)\nqc.cx(0,1)\nqc.barrier()\nqc.cx(0,2)\nqc.cx(0,3)\nqc.barrier()\nqc.cz(3,0)\nqc.h(0)\nqc.measure_all()\n# Draw the circuit using the default renderer\nqc.draw()\n```\n\n\n```python\nqc.draw('latex')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "f0efb5aea550fcf19383c2cbd59506461292c4ef", "size": 550772, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "QC with IBM QE/Monitoring and Optimizing Quantum Circuits.ipynb", "max_stars_repo_name": "thirasit/Quantum-Computing", "max_stars_repo_head_hexsha": "32be3646e3af14e2868d9325660996927efe30d2", "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": "QC with IBM QE/Monitoring and Optimizing Quantum Circuits.ipynb", "max_issues_repo_name": "thirasit/Quantum-Computing", "max_issues_repo_head_hexsha": "32be3646e3af14e2868d9325660996927efe30d2", "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": "QC with IBM QE/Monitoring and Optimizing Quantum Circuits.ipynb", "max_forks_repo_name": "thirasit/Quantum-Computing", "max_forks_repo_head_hexsha": "32be3646e3af14e2868d9325660996927efe30d2", "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": 99.7775362319, "max_line_length": 27264, "alphanum_fraction": 0.8273986332, "converted": true, "num_tokens": 2638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.12940272151925927, "lm_q1q2_score": 0.060662782908154876}} {"text": "```python\n!pip install econml\n```\n\n Collecting econml\r\n Downloading econml-0.12.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (3.1 MB)\r\n |████████████████████████████████| 3.1 MB 241 kB/s \r\n \u001b[?25hCollecting shap<0.40.0,>=0.38.1\r\n Downloading shap-0.39.0.tar.gz (356 kB)\r\n |████████████████████████████████| 356 kB 49.0 MB/s \r\n \u001b[?25h Preparing metadata (setup.py) ... \u001b[?25l-\b \b\\\b \bdone\r\n \u001b[?25hRequirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from econml) (1.19.5)\r\n Requirement already satisfied: statsmodels>=0.10 in /opt/conda/lib/python3.7/site-packages (from econml) (0.12.2)\r\n Requirement already satisfied: scikit-learn>0.22.0 in /opt/conda/lib/python3.7/site-packages (from econml) (0.23.2)\r\n Requirement already satisfied: lightgbm in /opt/conda/lib/python3.7/site-packages (from econml) (3.3.1)\r\n Collecting sparse\r\n Downloading sparse-0.13.0-py2.py3-none-any.whl (77 kB)\r\n |████████████████████████████████| 77 kB 4.5 MB/s \r\n \u001b[?25hRequirement already satisfied: scipy>1.4.0 in /opt/conda/lib/python3.7/site-packages (from econml) (1.7.2)\r\n Requirement already satisfied: pandas in /opt/conda/lib/python3.7/site-packages (from econml) (1.3.4)\r\n Collecting dowhy\r\n Downloading dowhy-0.7-py3-none-any.whl (152 kB)\r\n |████████████████████████████████| 152 kB 47.9 MB/s \r\n \u001b[?25hRequirement already satisfied: numba!=0.42.1 in /opt/conda/lib/python3.7/site-packages (from econml) (0.54.1)\r\n Requirement already satisfied: joblib>=0.13.0 in /opt/conda/lib/python3.7/site-packages (from econml) (1.1.0)\r\n Requirement already satisfied: llvmlite<0.38,>=0.37.0rc1 in /opt/conda/lib/python3.7/site-packages (from numba!=0.42.1->econml) (0.37.0)\r\n Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from numba!=0.42.1->econml) (59.1.1)\r\n Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from scikit-learn>0.22.0->econml) (3.0.0)\r\n Requirement already satisfied: tqdm>4.25.0 in /opt/conda/lib/python3.7/site-packages (from shap<0.40.0,>=0.38.1->econml) (4.62.3)\r\n Requirement already satisfied: slicer==0.0.7 in /opt/conda/lib/python3.7/site-packages (from shap<0.40.0,>=0.38.1->econml) (0.0.7)\r\n Requirement already satisfied: cloudpickle in /opt/conda/lib/python3.7/site-packages (from shap<0.40.0,>=0.38.1->econml) (2.0.0)\r\n Requirement already satisfied: patsy>=0.5 in /opt/conda/lib/python3.7/site-packages (from statsmodels>=0.10->econml) (0.5.2)\r\n Requirement already satisfied: python-dateutil>=2.7.3 in /opt/conda/lib/python3.7/site-packages (from pandas->econml) (2.8.0)\r\n Requirement already satisfied: pytz>=2017.3 in /opt/conda/lib/python3.7/site-packages (from pandas->econml) (2021.3)\r\n Requirement already satisfied: pydot>=1.4 in /opt/conda/lib/python3.7/site-packages (from dowhy->econml) (1.4.2)\r\n Requirement already satisfied: networkx>=2.0 in /opt/conda/lib/python3.7/site-packages (from dowhy->econml) (2.6.3)\r\n Requirement already satisfied: sympy>=1.4 in /opt/conda/lib/python3.7/site-packages (from dowhy->econml) (1.9)\r\n Requirement already satisfied: wheel in /opt/conda/lib/python3.7/site-packages (from lightgbm->econml) (0.37.0)\r\n Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from patsy>=0.5->statsmodels>=0.10->econml) (1.16.0)\r\n Requirement already satisfied: pyparsing>=2.1.4 in /opt/conda/lib/python3.7/site-packages (from pydot>=1.4->dowhy->econml) (3.0.6)\r\n Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.7/site-packages (from sympy>=1.4->dowhy->econml) (1.2.1)\r\n Building wheels for collected packages: shap\r\n Building wheel for shap (setup.py) ... \u001b[?25l-\b \b\\\b \b|\b \b/\b \b-\b \b\\\b \b|\b \bdone\r\n \u001b[?25h Created wheel for shap: filename=shap-0.39.0-cp37-cp37m-linux_x86_64.whl size=544687 sha256=445ef5154401c3539d7f5e36cd9a367244536c5f3536b77d40b93faca179bc5a\r\n Stored in directory: /root/.cache/pip/wheels/ca/25/8f/6ae5df62c32651cd719e972e738a8aaa4a87414c4d2b14c9c0\r\n Successfully built shap\r\n Installing collected packages: sparse, shap, dowhy, econml\r\n Attempting uninstall: shap\r\n Found existing installation: shap 0.40.0\r\n Uninstalling shap-0.40.0:\r\n Successfully uninstalled shap-0.40.0\r\n Successfully installed dowhy-0.7 econml-0.12.0 shap-0.39.0 sparse-0.13.0\r\n \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\r\n\n\n\n```python\n# Some imports to get us started\nimport warnings\nwarnings.simplefilter('ignore')\n\n# Utilities\nimport os\nimport urllib.request\nimport numpy as np\nimport pandas as pd\nfrom networkx.drawing.nx_pydot import to_pydot\nfrom IPython.display import Image, display\n\n# Generic ML imports\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.ensemble import GradientBoostingRegressor\n\n# EconML imports\nfrom econml.dml import LinearDML, CausalForestDML\nfrom econml.cate_interpreter import SingleTreeCateInterpreter, SingleTreePolicyInterpreter\n\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n```\n\n\n```python\n# Import the sample pricing data\nfile_url = \"https://msalicedatapublic.blob.core.windows.net/datasets/Pricing/pricing_sample.csv\"\ntrain_data = pd.read_csv(file_url)\n```\n\n\n```python\ntrain_data.head()\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    account_ageageavg_hoursdays_visitedfriends_counthas_membershipis_USsongs_purchasedincomepricedemand
    03531.83423428114.9032370.9608631.03.917117
    15547.17141179013.3301610.7324871.011.585706
    23335.35192069013.0362031.1309371.024.675960
    32346.72355108017.9119260.9291971.06.361776
    44302.44824758107.1489670.5335270.812.624123
    \n
    \n\n\n\n\n```python\n#estimator inputs\ntrain_data[\"log_demand\"] = np.log(train_data[\"demand\"])\ntrain_data[\"log_price\"] = np.log(train_data[\"price\"])\n\nY = train_data[\"log_demand\"].values\nT = train_data[\"log_price\"].values\nX = train_data[[\"income\"]].values # features\nconfounder_names = [\"account_age\", \"age\", \"avg_hours\", \"days_visited\", \"friends_count\", \"has_membership\", \"is_US\", \"songs_purchased\"]\nW = train_data[confounder_names].values\n```\n\n\n```python\n# Get test data\nX_test = np.linspace(0, 5, 100).reshape(-1, 1)\nX_test_data = pd.DataFrame(X_test, columns=[\"income\"])\n```\n\n## Create Causal Model \n\n\n```python\n# initiate an EconML cate estimator\nest = LinearDML(model_y=GradientBoostingRegressor(), model_t=GradientBoostingRegressor(),\n featurizer=PolynomialFeatures(degree=2, include_bias=False))\n```\n\n\n```python\n# fit through dowhy\nest_dw = est.dowhy.fit(Y, T, X=X, W=W, outcome_names=[\"log_demand\"], treatment_names=[\"log_price\"], feature_names=[\"income\"],\n confounder_names=confounder_names, inference=\"statsmodels\")\n```\n\n\n```python\n# Visualize causal graph\ntry:\n # Try pretty printing the graph. Requires pydot and pygraphviz\n display(\n Image(to_pydot(est_dw._graph._graph).create_png())\n )\nexcept:\n # Fall back on default graph view\n est_dw.view_model() \n```\n\n\n```python\nidentified_estimand = est_dw.identified_estimand_\nprint(identified_estimand)\n```\n\n Estimand type: nonparametric-ate\n \n ### Estimand : 1\n Estimand name: backdoor\n Estimand expression:\n d \n ────────────(Expectation(log_demand|is_US,avg_hours,age,songs_purchased,income\n d[log_price] \n \n \n ,friends_count,has_membership,account_age,days_visited))\n \n Estimand assumption 1, Unconfoundedness: If U→{log_price} and U→log_demand then P(log_demand|log_price,is_US,avg_hours,age,songs_purchased,income,friends_count,has_membership,account_age,days_visited,U) = P(log_demand|log_price,is_US,avg_hours,age,songs_purchased,income,friends_count,has_membership,account_age,days_visited)\n \n ### Estimand : 2\n Estimand name: iv\n No such variable(s) found!\n \n ### Estimand : 3\n Estimand name: frontdoor\n No such variable(s) found!\n \n\n\n\n```python\n# initiate an EconML cate estimator\nest_nonparam = CausalForestDML(model_y=GradientBoostingRegressor(), model_t=GradientBoostingRegressor())\n# fit through dowhy\nest_nonparam_dw = est_nonparam.dowhy.fit(Y, T, X=X, W=W, outcome_names=[\"log_demand\"], treatment_names=[\"log_price\"],\n feature_names=[\"income\"], confounder_names=confounder_names, inference=\"blb\")\n```\n\n# Test Estimate Robustness with DoWhy\n\n## Add Random Common Cause\n\nHow robust are our estimates to adding another confounder?\n\n\n\n\n```python\nres_random = est_nonparam_dw.refute_estimate(method_name=\"random_common_cause\")\nprint(res_random)\n```\n\n Refute: Add a random common cause\n Estimated effect:-0.9573995973779295\n New effect:-0.95832930881448\n p value:0.37\n \n\n\nHow robust are our estimates to unobserved confounders\n\n\n```python\nres_unobserved = est_nonparam_dw.refute_estimate(\n method_name=\"add_unobserved_common_cause\",\n confounders_effect_on_treatment=\"linear\",\n confounders_effect_on_outcome=\"linear\",\n effect_strength_on_treatment=0.1,\n effect_strength_on_outcome=0.1,\n)\nprint(res_unobserved)\n```\n\n Refute: Add an Unobserved Common Cause\n Estimated effect:-0.9573995973779295\n New effect:-1.010149368734301\n \n\n\n## Replace Treatment with a Random (Placebo) Variable\n\n\nWhat happens our estimates if we replace the treatment variable with noise?\n\n\n```python\nres_placebo = est_nonparam_dw.refute_estimate(\n method_name=\"placebo_treatment_refuter\", placebo_type=\"permute\", \n num_simulations=3\n)\nprint(res_placebo)\n```\n\n Refute: Use a Placebo Treatment\n Estimated effect:-0.9573995973779295\n New effect:-0.009779517229192933\n p value:0.15574829607146912\n \n\n\n## Remove a Random Subset of the Data\n\nDo we recover similar estimates on subsets of the data?\n\n\n```python\nres_subset = est_nonparam_dw.refute_estimate(\n method_name=\"data_subset_refuter\", subset_fraction=0.8, \n num_simulations=3)\nprint(res_subset)\n```\n\n Refute: Use a subset of data\n Estimated effect:-0.9573995973779295\n New effect:-0.9517490711399156\n p value:0.31210482684964586\n \n\n\n\n```python\n\n```\n", "meta": {"hexsha": "4a23b194023e3824d909c7fdc40ce22599b086e2", "size": 154481, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "causal-inference-tutorial.ipynb", "max_stars_repo_name": "ssameermah/Causal-Inference-examples", "max_stars_repo_head_hexsha": "c25c39f93b0047bee83b9291efd53843966ae137", "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": "causal-inference-tutorial.ipynb", "max_issues_repo_name": "ssameermah/Causal-Inference-examples", "max_issues_repo_head_hexsha": "c25c39f93b0047bee83b9291efd53843966ae137", "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": "causal-inference-tutorial.ipynb", "max_forks_repo_name": "ssameermah/Causal-Inference-examples", "max_forks_repo_head_hexsha": "c25c39f93b0047bee83b9291efd53843966ae137", "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": 161.929769392, "max_line_length": 123264, "alphanum_fraction": 0.882684602, "converted": true, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.12421299700498413, "lm_q1q2_score": 0.06065114391746499}} {"text": "```python\n# %load /Users/facai/Study/book_notes/preconfig.py\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\n#sns.set(font='SimHei')\nplt.rcParams['axes.grid'] = False\n\n#from IPython.display import SVG\ndef show_image(filename, figsize=None, res_dir=True):\n if figsize:\n plt.figure(figsize=figsize)\n\n if res_dir:\n filename = './res/{}'.format(filename)\n\n plt.imshow(plt.imread(filename))\n```\n\nChapter 8 Optimization for Training Deep Models\n=========\n\noptimization: finding the parameters $\\theta$ of a neural network that significantly reduce a cost function $J(\\theta)$.\n\n### 8.1 How Learning Differs from Pure Optimization\n\nexpectation is taken across **the data generating distribution** $p_{data}$ rather than just over the finite training set:\n\n\\begin{equation}\n J^*(\\theta) = \\mathcal{E}_{(x, y) \\sim p_{data}} L(f(x; \\theta), y)\n\\end{equation}\n\n\n#### 8.1.1 Empirical Risk Minimization\n\nRather than optimizing the risk direcly, we optimize the empirical risk, and hope that the risk decreases significantly as well.\n\n\n#### 8.1.2 Surrogate Loss Functions and Early Stopping\n\n\n#### 8.1.3 Batch and Minibatch Algorithms\n\nSmall batches can offer a regularing effect.\n\ngradient can handle smaller batch size like 100, while second-order methods typically require much large batch sizes like 10,000.\n\nminibatches must be selected randomly. For very large datasets, it is usually sufficient to shuffle the order of the dataset once and then store it in shuffled fashion.\n\nOn the second pass, the estimator becomes biased because it is formed by re-sampling values used before.\n\n### 8.2 Challenges in Neural Network Optimization\n\n\n#### 8.2.1 Ill-Conditioning\n\nTo determin whether ill-conditioning, one can monitor the squared gradient norm $g^T g$ and the $g^T H g$ term. In many cases, the gradient norm does not shrink significantly throughout learning, but the $g^T H g$ term grows by more than order of magnitude.\n\n\n#### 8.2.2 Local Minima\n\nmodel identifiability problem: models with latent variables are often not identifiable <= weight space symmetry.\n\n\n#### 8.2.3 Plateaus, Saddle Points and Other Flat Regions\n\n+ saddle point: local minimum along one cross-section, and local maximum along another another cross-section.\n - in higher dimensional spaces, local minima are rare and saddle points are more common.\n - difficult for newton's method, while easy for gradient descent.\n\n+ maxima\n+ wide, flat regions of constant value \n\n\n#### 8.2.4 Cliffs and Exploding Gradients\n\n\n```python\nshow_image(\"fig8_3.png\")\n```\n\ncan be avoided using the *gradient clipping* heuristic\n\n\n#### 8.2.5 Long-Term Dependencies\n\nwhen graph becomes extremely deep => vanishing and exploding gradient problem\n\nVanishing gradients make it difficult to know which direction the parameters should move to improve to the cost function, while exploding gradients can make learning unstable.\n\n\n#### 8.2.6 Inexact Gradients\n\n\n#### 8.2.7 Poor Correspondence between Local and Global Structure\n\nMany existing research directions are aimed at finding good initial points, rather than developing algorithms that use non-local moves.\n\n\n#### 8.2.8 Theoretical Limits of Optimization\n\n### 8.3 Basic Algorithms\n\n\n#### 8.3.1 Stochastic Gradient Descent\n\nIn practice, it is necessary to gradually decrease the learning rate over time.\n\nIn practice, it is common to decay the learning rate linearly until iteration $\\tau$:\n\n\\begin{equation}\n \\epsilon_k = (1 - \\alpha) \\epsilon_0 + \\alpha \\epsilon_{\\tau}\n\\end{equation}\n\n+ $\\tau$: a few hundred passes through the training set\n+ $\\epsilon_\\tau \\approx 1\\% \\, \\epsilon_0$\n+ $\\epsilon_0$: monitor the first several iterations and use a learning rate that is higher than the best-performing learning rate at this time, but not so high that it causes severe instability.\n\nTo study the convergence rate of an optimization algorithm, it is common to measure the *excess error* $J(\\theta) - \\min_\\theta J(\\theta)$.\n+ SGD is applied to a convex problem: $O(\\frac{1}{\\sqrt{k}}$\n+ in the stronly convex case it is $O(\\frac{1}{k})$.\n\n\n#### 8.3.2 Momentum\n\nThe momentum algorithm accumulates an exponentially decaying moving average of past gradients and continues to move in their direction.\n\n\\begin{align}\n v &\\gets \\alpha v - \\epsilon \\Delta_\\theta \\left ( \\frac1{m} \\displaystyle \\sum^m_{i = 1} L \\left ( f(x^{(i)}; \\theta), y^{(i)} \\right ) \\right ) \\\\\n \\theta &\\gets \\theta + v\n\\end{align}\n\nThe larger $\\alpha$ is relative to $\\epsilon$, the more previous gradients affect the current direction.\n\n\n```python\nshow_image(\"fig8_5.png\")\n```\n\nthe size of each step is $\\frac{\\epsilon \\| g \\|}{1 - \\alpha} \\implies$ it is thus helpful to think of the momentum hyperparameter in terms of $\\frac1{1 - \\alpha}$.\n\n+ Common values of $\\alpha$ used in practice include 0.5, 0.9 and 0.99.\n+ Typically it begins with a small value and is later raised. \n+ It is less important to adapt $\\alpha$ over time than to shrink $\\epsilon$ over time.\n\n\n#### 8.3.3 Nesterov Momentum\n\nNesterov momentum: the gradient is evaluated after the current velocity is applied.\n\n\\begin{align}\n v &\\gets \\alpha v - \\epsilon \\Delta_\\theta \\left ( \\frac1{m} \\displaystyle \\sum^m_{i = 1} L \\left ( f(x^{(i)}; \\theta + \\color{blue}{\\alpha v}), y^{(i)} \\right ) \\right ) \\\\\n \\theta &\\gets \\theta + v\n\\end{align}\n\n考虑了提前量\n\n### 8.4 Parameter Initialization Strategies\n\nDesigning improved initialization strategies is a difficult task because neural network optimization is not yet well understood.\n\nA further difficulty is that some initial points may be benefical from the viewpoint of optimization but detrimental from the viewpoint of generalization.\n\ncomplete certainty: break symmetry between different units\n\n+ initialize each unit to compute a different function from all of the other units.\n+ random initialization of the parameters.\n - Typically, set biases for each unit to heuristically chosen constants, and initilize only the weights randomly.\n\n##### weight\n\nWe can think of initializing the parameters $\\theta$ to $\\theta_0$ as being similar to imposing a Gaussian prior $p(\\theta)$ with mean $\\theta_0$. \n$\\implies$ choose $\\theta_0$ to be near 0 = more likely that units do not interact with each other than that they do interact.\n\n1. normalized initialization: $W_{i, j} \\sim U \\left ( - \\frac{6}{\\sqrt{m + n}}, \\frac{6}{\\sqrt{m + n}} \\right )$\n2. initializing to random orthogonal matrices\n3. perserve norms\n4. sparse initialization\n\nA good rule of thumb for choosing the initial scales is to look at the range or standard deviation of activations or gradients on a single minibatch of data.\n\n##### biase\n\n1. Setting the biases to zero is compatible with most weight initialization schemes.\n2. a few situations where we may set some biases to non-zero values:\n + for an output unit, often feneficial to initialize the bias to obtain the right marginal statistics of the output.\n + choose the bias to avoid causing too much saturation at initialization. \n eg: set the bias of ReLU hidden unit to 0.1 rather than 0\n + Sometimes a unit controls whether other units are able to participate in a function => all units have a chance to learn.\n \n##### initialize model parameters using machine learning\n\neg: to initialize a supervised model with the parameters learned by an unsupervised model trained on the same inputs.\n\n### 8.5 Algorithms with Adaptive Learning Rates\n\nthe cost is often highly sensitive to some directions in parameter space and insensitive to others. => adapt the learning rates of model parameters.\n\n\n#### 8.5.1 AdaGrad\n\ngradient accumulation\n\n$\\text{rate} = \\frac1{\\sum \\text{squared gradients}}$\n\n\n#### 8.5.2 RMSProp\n\nchanging the gradient accumulation into an exponentially weighted moving average.\n\n\n#### 8.5.3 Adam\n\nadaptive moments: combination of RMSProp and momentum\n\nCurrently, the most popular optimization algorithms actively in use include \n+ SGD, \n+ SGD with momentum, \n+ RMSProp, \n+ RMSProp with momentum, \n+ AdaDelta and Adam.\n\nThe choice of which algorithm to use, at this point, seems to depend largely on the user’s familiarity with the algorithm (for ease of hyperparameter tuning).\n\n### 8.6 Approximate Second-Order Methods\n\n#### 8.6.1 Newton's Method\n\na two-step iterative procedure:\n\n+ update or compute the inverse Hessian\n+ update the parameters: $\\theta^* = \\theta_0 - \\mathbf{H}^{-1} \\Delta_\\theta J(\\theta_0)$\n\n\n#### 8.6.2 Conjugate Gradients\n\n\n#### 8.6.3 BFGS\n\nL-BFGS\n\n### 8.7 Optimization Strategies and Meta-Algorithms\n\n#### 8.7.1 Batch Normalization\n\nadaptive reparametrization => training very deep models\n\n\n#### 8.7.2 Coordinate Descent\n\nbad: variables are dependent.\n\n\n#### 8.7.3 Polyak Averaging\n\naveraging points.\n\n\n#### 8.7.4 Supervised Pretraining\n\ntraining sample models on simple tasks => then make the model more complex.\n\n\n#### 8.7.5 Designing Models to Aid Optimization\n\nIn practice, it is more important to choose a model family that is easy to optimize than to use a powerful optimization algorithm.\n\n\n#### 8.7.6 Continuous Methods and Curriculumn Learning\n\n\n```python\n\n```\n", "meta": {"hexsha": "8d2e90d42a4d557f6ed163b8c1ebf2ab009f598f", "size": 147999, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "deep_learning/Optimization_for_Training_Deep_Models/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "deep_learning/Optimization_for_Training_Deep_Models/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "deep_learning/Optimization_for_Training_Deep_Models/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 371.8567839196, "max_line_length": 71270, "alphanum_fraction": 0.9216683897, "converted": true, "num_tokens": 2242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961697, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.0603652661324424}} {"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## Diagonalne matrike: Divergentne modalne oblike\n\nTa interaktivni primer vključuje prednastavljeno diagonalno matriko z vsaj eno divergetno modalno obliko. Primer omogoča, da prosto spreminjate elemente te matrike in ob tem spremljate ali ima nova matrika divergentene modalne oblike (in je s tem nestabilna) ali ne.\n\nRazišči naslednje možnosti:\n* diagonalna matrika z divergentnimi (nestabilnimi) modalnimi oblikami,\n* diagonalna matrika s stabilnimi modalnimi oblikami,\n* diagonalna matrika s stabilnimi in divergetnimi (nestabilnimi) modalnimi oblikami.\n\nAli lahko enostavno ugotoviš če ima matrika divergentno modalno obliko, kadar je izražena v diagonalni obliki?\n\n[//]: # \"This example shows a diagonal matrix with at least one divergent mode. It is possible to change any element of the matrix and analyze if the new matrix has divergent modes (unstable matrix) or not. \n\nExplore the various possibilities:\n* diagonal matrices with divergent (unstable) modes,\n* diagonal matrices with stable modes,\n* diagonal matrices with both stable and divergent (unstable) modes.\n\nCan you easily tell if a matrix has divergent modes when it is in diagonal form?\"\n\n\n```python\n%matplotlib notebook\nimport control\nimport numpy\nimport sympy\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\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\nA=matrixWidget(4,4)\nA.setM(numpy.matrix('1,0,0,0;0,-2,0,0;0,0,-3,0;0,0,0,-4'))\n\ndef main_callback(matA,DW):\n (r,c) = numpy.shape(matA)\n sol = numpy.linalg.eig(matA)[0]\n print('Lastne vrednosti matrike so: %s' %str(sol))\n \n matAs = sympy.Matrix(matA)\n eig = matAs.eigenvals()\n eigvals = list(eig.keys())\n Amul = list(eig.values())\n \n diag = True\n for i in range(r):\n for j in range(c):\n if i != j:\n if matA[i,j] != 0:\n diag = False\n \n if diag:\n for i in range(len(eigvals)):\n if numpy.real(eigvals[i]) > 0:\n print('Ok! Matrika je nestabilna.')\n return\n elif numpy.real(eigvals[i]) == 0:\n if Amul[i] > 1:\n if len((matAs-eigvals[i]*sympy.eye(4)).nullspace()) < Amul[i]:\n print('Ok! Matrika je nestabilna.')\n return\n print('Matrika ni nestabilna.')\n else:\n for i in range(len(eigvals)):\n if numpy.real(eigvals[i]) > 0:\n print('Matrika je nestabilna, a ni diagonalna.')\n return\n elif numpy.real(eigvals[i]) == 0:\n if Amul[i] > 1:\n if len((matAs-eigvals[i]*sympy.eye(4)).nullspace()) < Amul[i]:\n print('Matrika je nestabilna, a ni diagonalna.')\n return\n print('Matrika ni nestabilna in ni diagonalna.')\n \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\nout = widgets.interactive_output(main_callback,{'matA':A,'DW':DW})\ndisplay(A,START,out)\n```\n\n\n matrixWidget(children=(HBox(children=(FloatText(value=1.0, layout=Layout(width='90px')), FloatText(value=0.0, …\n\n\n\n Button(description='Test', icon='check', style=ButtonStyle(), tooltip='Test')\n\n\n\n Output()\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "fef8d88dd61912a8d6fff3c0e017fe63fddb8329", "size": 12397, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/.ipynb_checkpoints/SS-04-Diagonalne_matrike_divergentna_oblika-checkpoint.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/.ipynb_checkpoints/SS-04-Diagonalne_matrike_divergentna_oblika-checkpoint.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/.ipynb_checkpoints/SS-04-Diagonalne_matrike_divergentna_oblika-checkpoint.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": 35.9333333333, "max_line_length": 275, "alphanum_fraction": 0.5011696378, "converted": true, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.20434189266867248, "lm_q1q2_score": 0.06012044426324592}} {"text": "# KVLCC2 geometry analysis\n\n# Purpose\nAnalyse the geometry section by section\n\n# Methodology\nLoad offset points from Rhino\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n#%matplotlib inline\n%matplotlib notebook\n%load_ext autoreload\n%autoreload 2\n\n#from jupyterthemes import jtplot\n#jtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.run import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\nimport shipflowmotionshelpers.shipflowmotionshelpers as helpers\nimport src.visualization.visualize as visualize\n\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 461 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.dpi : 100 ## figure dots per inch')\n\n\n\n```python\nfrom reports.paper_writing import save_fig\n```\n\n\n```python\ndb = database.get_db()\n\nsql = \"\"\"\nSELECT * from run\nINNER JOIN loading_conditions\nON (run.loading_condition_id = loading_conditions.id)\nINNER JOIN models\nON (run.model_number = models.model_number)\nINNER JOIN ships\nON (run.ship_name = ships.name)\nWHERE run.model_number='M5057-01-A' and run.test_type='roll decay' and run.project_number=40178362;\n\"\"\"\ndf_rolldecays = pd.read_sql(sql=sql, con=db.engine)\ndf_rolldecays['rho']=1000\ndf_rolldecays['g']=9.81\ndf_rolldecays=df_rolldecays.loc[:,~df_rolldecays.columns.duplicated()]\ndf_rolldecays.set_index('id', inplace=True)\n```\n\n\n```python\ndf_rolldecays.head()\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 \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 \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 \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 \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 \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 \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
    project_numberseries_numberrun_numbertest_numbermodel_numbership_nameloading_condition_idascii_nameship_speedcommentfile_path_asciifile_path_ascii_tempfile_path_logfile_path_hdf5datetest_typefacilityangle1angle2KörfallstypnamelcgkggmCWTFTABWLKXXKZZBTT1CPVolumeA0RHscale_factorlppbeamABULBBKXTWINDCLRVDESRHBLASKEGPDARHCFPAIXPDTDESRTYPESFPBKLBKBPROTDLSKEGRRXSKEGNDESARBRBRAIRUDPTYPEXRUDAIHSKEGRSKEGLOAship_type_idrhog
    id
    21337401783621941M5057-01-AM5057-01-A16694.0NaNRoll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone10009.81
    21338401783621951M5057-01-AM5057-01-A16695.0NaNRoll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone10009.81
    21339401783621961M5057-01-AM5057-01-A16696.0NaNRoll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-11-28roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone10009.81
    21340401783621971M5057-01-AM5057-01-A16697.015.5Roll decay, 15.5 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-04roll decayMDLNoneNoneNone20.811.267218.65.73None20.820.8None23.280.0NoneNone312653.00.99538None68.0320.058.0NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone10009.81
    \n
    \n\n\n\n\n```python\nloading_condition = df_rolldecays.loc[21340]\n#print(loading_condition.project_path)\n```\n\n\n```python\nloading_condition.TA\n```\n\n\n\n\n 20.8\n\n\n\n\n```python\nloading_condition.TF\n```\n\n\n\n\n 20.8\n\n\n\n\n```python\nloading_condition.lpp\n```\n\n\n\n\n 320.0\n\n\n\n\n```python\ndraught = (loading_condition.TA + loading_condition.TF)/2\n```\n\n\n```python\nfile_path = r'S:/2020/40209514-DEMOPS/03_Project/020_PROJECT_MANAGEMENT/arbetsmapp/ISOPE/KVLCC2_points.txt'\npoints = pd.read_csv(file_path, sep=';', header=None)\npoints.columns = ['x','y','z']\npoints.describe()\n```\n\n\n\n\n
    \n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    xyz
    count7140.0000007140.0000007.140000e+03
    mean157.45489317.7502997.740190e+00
    std110.63326310.8849879.114148e+00
    min-5.495000-0.000173-2.220446e-16
    25%48.1790546.4518138.789816e-01
    50%153.29074022.2573203.160564e+00
    75%264.42932027.8895031.273352e+01
    max327.99500029.0000044.000111e+01
    \n
    \n\n\n\n\n```python\nns = np.arange(10)\nn_sections = []\nfor n in ns:\n n_sections.append( len(points['x'].round(decimals=n).unique()))\n\nfig,ax=plt.subplots()\nax.plot(ns,n_sections)\n```\n\n\n \n\n\n\n
    \n\n\n\n\n\n []\n\n\n\n\n```python\npoints['x'] = points['x'].round(decimals=6)\npoints['z'] = points['z'].round(decimals=2)\nx = points['x'].unique()\nx_groups = points.groupby(by='x')\npoints2 = x_groups.filter(lambda x:x['x'].count() > 2)\nx = points2['x'].unique()\nx_groups = points2.groupby(by='x')\n```\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nax.plot(points['x'], points['y'], points['z'], '.')\n```\n\n\n \n\n\n\n
    \n\n\n\n\n\n []\n\n\n\n\n```python\n\nN = 100\nz_ = np.linspace(0,1,N)**-1.1\nz_ = z_/z_[1]\nz = draught*z_[1:]\nz = np.concatenate((z,[0]))\nz = np.flipud(z)\n\n\nsection = x_groups.get_group(x[int(len(x)/2)])\nsection.sort_values(by='z', inplace=True)\ny = np.interp(z, section['z'], section['y'])\n \n\nfig,ax=plt.subplots()\nsection.plot(x='y', y='z', ax=ax)\nax.plot(y,z,'.:')\n```\n\n c:\\dev\\prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-ikedas-method\\venv\\lib\\site-packages\\ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in power\n \n c:\\dev\\prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-ikedas-method\\venv\\lib\\site-packages\\ipykernel_launcher.py:10: SettingWithCopyWarning: \n A value is trying to be set on a copy of a slice from a DataFrame\n \n See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n # Remove the CWD from sys.path while we load stuff.\n\n\n\n \n\n\n\n
    \n\n\n\n\n\n []\n\n\n\n\n```python\ndata = {\n 'y':[3,2,1],\n 'z':[5,3,2],\n}\nsection = pd.DataFrame(data=data)\n\nfig,ax=plt.subplots()\nsection.plot(x='y', y='z', style = 'ko-', label='original', ax=ax)\n\nxy = section[['y','z']].values.tolist()\n\n\nif xy[-1][0] > 0:\n centre_end_point = [0,xy[-1][1]]\n xy.append(centre_end_point) # Adding missing centre end point\n\nif xy[0][1] < draught:\n water_line_point_1 = [xy[0][0],draught]\n xy.insert(0,water_line_point_1) # Adding missing water line point\n\ntop_centre_point = [0,xy[0][1]]\nxy.insert(0,top_centre_point)\n\nclose_point = xy[-1]\nxy.insert(0,close_point)\nxy = np.array(xy)\n\nax.plot(xy[:,0], xy[:,1],'--')\nax.plot(*centre_end_point, 'ro', label='centre end point')\nax.plot(*water_line_point_1, 'bo', label='water_line_point_1')\nax.plot(*top_centre_point, 'yo', label='top_centre_point')\nax.plot(*close_point, 'ro', label='close_point')\n\nax.legend()\n\n\n```\n\n\n \n\n\n\n
    \n\n\n\n\n\n \n\n\n\n\n```python\ndef close_section(section):\n \n \"\"\"\n The sections are defined as:\n (y,z):\n 0\n 1\n 2\n 3\n 4\n 5\n \"\"\"\n xy = section[['y','z']].values.tolist()\n\n if xy[-1][0] > 0:\n centre_end_point = [0,xy[-1][1]]\n xy.append(centre_end_point) # Adding missing centre end point\n \n if xy[0][1] < draught:\n water_line_point_1 = [xy[0][0],draught]\n xy.insert(0,water_line_point_1) # Adding missing water line point\n \n top_centre_point = [0,xy[0][1]]\n xy.insert(0,top_centre_point)\n \n close_point = xy[-1]\n xy.insert(0,close_point)\n xy = np.array(xy)\n \n closed_section = pd.DataFrame()\n closed_section['y'] = xy[:,0]\n closed_section['z'] = xy[:,1]\n closed_section['x'] = section.iloc[0].x\n \n return closed_section\n \n```\n\n\n```python\nx_groups = points.groupby(by='x')\nN = 100\nz_ = np.linspace(0,1,N)**-1.1\nz_ = z_/z_[1]\nz = draught*z_[1:]\nz = np.concatenate((z,[0]))\nz = np.flipud(z)\n\ndf_sections = pd.DataFrame()\n\nfor i,(x_, section) in enumerate(x_groups):\n #section.sort_values(by='z', inplace=True)\n mask = section['z'] <= draught \n section = section.loc[mask]\n if len(section)==0:\n continue\n \n new_section = pd.DataFrame()\n new_section['y']=section['y']\n new_section['x']=x_\n new_section['z']=section['z']\n new_closed_section = close_section(new_section)\n new_closed_section['no']=i\n df_sections = df_sections.append(new_closed_section)\n \n```\n\n c:\\dev\\prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-ikedas-method\\venv\\lib\\site-packages\\ipykernel_launcher.py:3: RuntimeWarning: divide by zero encountered in power\n This is separate from the ipykernel package so we can avoid doing imports until\n\n\n\n```python\ndf_sections.head()\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
    yzxno
    0-9.001914e-1518.80-5.4950
    10.000000e+0020.80-5.4950
    25.819288e+0020.80-5.4950
    35.819288e+0020.75-5.4950
    45.198539e+0020.43-5.4950
    \n
    \n\n\n\n\n```python\ndef poly_area(xy):\n \"\"\" \n Calculates polygon area using Greens formula.\n x = xy[:,0], y = xy[:,1]\n \"\"\"\n xy1 = np.roll(xy,-1,axis = 0) # shift by -1\n return -0.5*np.inner(xy1[:,0] - xy[:,0],xy1[:,1] + xy[:,1])\n\ndef section_area(section):\n xy = section[['y','z']].values\n return np.abs(poly_area(xy=xy))\n```\n\n\n```python\ndf_sections['x'].unique()\n```\n\n\n\n\n array([ -5.495 , -3.258581, -1.022162, 1.214257, 3.450676,\n 5.687095, 7.923513, 10.159932, 12.396351, 14.63277 ,\n 16.869189, 19.105608, 21.342027, 23.578446, 25.814865,\n 28.051284, 30.287703, 32.524122, 34.760541, 36.996959,\n 39.233378, 41.469797, 43.706216, 45.942635, 48.179054,\n 50.415473, 52.651892, 54.888311, 57.12473 , 59.361149,\n 61.597568, 63.833986, 66.070405, 68.306824, 70.543243,\n 72.779662, 75.016081, 77.2525 , 79.488919, 81.725338,\n 83.961757, 86.198176, 88.434595, 90.671014, 92.907432,\n 95.143851, 97.38027 , 99.616689, 101.85311 , 104.08953 ,\n 106.32595 , 108.56236 , 110.79878 , 113.0352 , 115.27162 ,\n 117.50804 , 119.74446 , 121.98088 , 124.2173 , 126.45372 ,\n 128.69014 , 130.92655 , 133.16297 , 135.39939 , 137.63581 ,\n 139.87223 , 142.10865 , 144.34507 , 146.58149 , 148.81791 ,\n 151.05432 , 153.29074 , 155.52716 , 157.76358 , 160. ,\n 162.2702 , 164.54041 , 166.81061 , 169.08081 , 171.35101 ,\n 173.62122 , 175.89142 , 178.16162 , 180.43182 , 182.70203 ,\n 184.97223 , 187.24243 , 189.51264 , 191.78284 , 194.05304 ,\n 196.32324 , 198.59345 , 200.86365 , 203.13385 , 205.40405 ,\n 207.67426 , 209.94446 , 212.21466 , 214.48486 , 216.75507 ,\n 219.02527 , 221.29547 , 223.56568 , 225.83588 , 228.10608 ,\n 230.37628 , 232.64649 , 234.91669 , 237.18689 , 239.45709 ,\n 241.7273 , 243.9975 , 246.2677 , 248.53791 , 250.80811 ,\n 253.07831 , 255.34851 , 257.61872 , 259.88892 , 262.15912 ,\n 264.42932 , 266.69953 , 268.96973 , 271.23993 , 273.51014 ,\n 275.78034 , 278.05054 , 280.32074 , 282.59095 , 284.86115 ,\n 287.13135 , 289.40155 , 291.67176 , 293.94196 , 296.21216 ,\n 298.48236 , 300.75257 , 303.02277 , 305.29297 , 307.56318 ,\n 309.83338 , 312.10358 , 314.37378 , 316.64399 , 318.91419 ,\n 321.18439 , 323.45459 , 325.7248 , 327.995 ])\n\n\n\n\n```python\nsections = df_sections.groupby(by='x')\nareas = sections.apply(func=section_area)\nfig,ax=plt.subplots()\nareas.plot(ax=ax)\n```\n\n\n \n\n\n\n
    \n\n\n\n\n\n \n\n\n\n\n```python\nmin_area = 1\ndf_sections2 = sections.filter(func=lambda x : section_area(x) > min_area)\nsections = df_sections2.groupby(by='x')\n```\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nfor no,section, in sections:\n \n ax.plot(section['x'], section['y'], section['z'])\n```\n\n\n \n\n\n\n
    \n\n\n\n```python\nx_interps = np.linspace(df_sections2['x'].min(), df_sections2['x'].max(),21)\nxs = df_sections2['x'].unique()\nx_ = []\nfor x_interp in x_interps:\n i = np.argmin(np.abs(x_interp - xs))\n x_.append(xs[i])\n \ndf_sections3 = pd.DataFrame()\nfor i,x in enumerate(x_):\n section = sections.get_group(x)\n section['no'] = i\n df_sections3 = df_sections3.append(section)\n```\n\n c:\\dev\\prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-ikedas-method\\venv\\lib\\site-packages\\ipykernel_launcher.py:11: SettingWithCopyWarning: \n A value is trying to be set on a copy of a slice from a DataFrame.\n Try using .loc[row_indexer,col_indexer] = value instead\n \n See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n # This is added back by InteractiveShellApp.init_path()\n\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nsections2 = df_sections3.groupby(by='no')\nfor no, section in sections2:\n \n ax.plot(section['x'], section['y'], section['z'], label=no)\n \nax.legend()\n```\n\n\n \n\n\n\n
    \n\n\n\n\n\n \n\n\n\n\n```python\nareas2 = sections2.apply(section_area)\nfig,ax=plt.subplots()\nareas2.plot(ax=ax)\nfor no,a in areas2.items():\n ax.annotate(no,xy=(no,a))\n```\n\n\n \n\n\n\n
    \n\n\n\n```python\ndef estimate_bilge_radius(section):\n b = section['b'] \n t = section['t']\n A = section['area'] \n \n r = np.sqrt((b*t-A)/(1-np.pi/4))\n \n return r\n\ndef section_data(section):\n \n s = pd.Series()\n s.name=section.name\n s['area'] = 2*section_area(section) # two sides\n s['x'] = section.iloc[0].x\n s['t'] = section.z.max() - section.z.min()\n s['b'] = 2*section.y.max() # two sides\n s['r_b'] = estimate_bilge_radius(s)\n \n return s\n \n```\n\n\n```python\ndf_section_properties = sections2.apply(func=section_data)\n```\n\n c:\\dev\\prediction-of-roll-damping-using-fully-nonlinear-potential-flow-and-ikedas-method\\venv\\lib\\site-packages\\ipykernel_launcher.py:12: DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.\n if sys.path[0] == '':\n\n\n\n```python\ndf_section_properties.to_csv('../data/interim/kvlcc_areas.csv', sep=';')\n```\n\n\n```python\ndf_section_properties\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 \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 \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
    areaxtbr_b
    no
    013.826612-5.4950002.0011.6385776.636080
    1123.85130610.15993218.2527.89352242.367175
    2428.21140928.05128420.8041.82428445.369454
    3683.70916543.70621620.8050.28251441.080696
    4917.89506661.59756820.8056.15923234.146143
    51056.86093377.25250020.8057.87049826.158540
    61139.50355292.90743220.8058.00000817.655717
    71186.852794110.79878020.8058.0000089.543935
    81203.217372126.45372020.8058.0000083.851125
    91203.929931144.34507020.8058.0000083.392755
    101203.929195160.00000020.8058.0000083.393260
    111203.928607175.89142020.8058.0000083.393664
    121203.929195194.05304020.8058.0000083.393260
    131203.929195209.94446020.8058.0000083.393260
    141203.906161225.83588020.8058.0000083.409039
    151195.569763243.99750020.8057.9873767.017342
    161159.988460259.88892020.8057.48779212.908255
    171077.577243275.78034020.8055.36131018.561674
    18899.155097291.67176020.8048.13089621.797880
    19502.526691309.83338020.8028.20370819.797403
    2043.489245325.72480016.185.70953515.093775
    \n
    \n\n\n\n\n\n\n```python\nfig,ax = plt.subplots()\n\nzmax = sections2['z'].max().max()\nfor no,section, in sections2:\n \n section = section.iloc[2:] # Removing close\n \n y = section['z']\n \n if no < 10:\n n = no\n x = -section['y']\n y_text = zmax - n*(zmax/9) \n else:\n n = 20 - no\n x = section['y']\n y_text = zmax - n*(zmax/10) \n\n x_text = np.interp(y_text,np.flipud(y),np.flipud(x))\n \n ax.plot(x, y)\n ax.annotate(no,xy=(x_text,y_text))\n\nymax = sections2['y'].max().max()\nax.plot(1.03*np.array([-ymax,ymax]),[zmax,zmax],'b-', lw=2)\nax.set_xlabel('y [m]')\nax.set_ylabel('z [m]')\nax.grid(True)\nsave_fig(fig, name='KVLCC2_body_plan')\n```\n\n\n \n\n\n\n
    \n\n\n\n```python\nsection = sections2.get_group(4)\nsection = section.iloc[2:]\ny = section['z']\nn = 20 - no\nx = section['y'] \n\nfig,ax=plt.subplots()\nax.plot(y,x)\n\nnp.interp(y_text,np.flipud(y),np.flipud(x))\n```\n\n\n \n\n\n\n
    \n\n\n\n\n\n 28.079615999999998\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6ae39308e2a2f0988a6c587e7af4de44e73686ba", "size": 509456, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/11.1_KVLCC2_geometry.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "notebooks/11.1_KVLCC2_geometry.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "notebooks/11.1_KVLCC2_geometry.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 43.9641007939, "max_line_length": 2020, "alphanum_fraction": 0.4647153042, "converted": true, "num_tokens": 11460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12592276975547592, "lm_q1q2_score": 0.060012229671036324}} {"text": "# **Turma de Pós-Graduação de Ciência de Dados**\n\n**Disciplina: Linguagem de Programação Python**\n\n**prof: Sérgio Assunção Monteiro, DSc**\n\n**Aula 09**\n\n# **Introdução à Computação Quântica**\n\n**Fontes:** \n\n> https://qiskit.org/documentation/intro_tutorial1.html\n\n> https://qiskit.org/textbook/ch-states/introduction.html\n\n\n```python\npip install qiskit\n```\n\n Collecting qiskit\n Downloading qiskit-0.34.1.tar.gz (13 kB)\n Collecting qiskit-terra==0.19.1\n Downloading qiskit_terra-0.19.1-cp37-cp37m-manylinux2010_x86_64.whl (6.4 MB)\n \u001b[K |████████████████████████████████| 6.4 MB 4.3 MB/s \n \u001b[?25hCollecting qiskit-aer==0.10.2\n Downloading qiskit_aer-0.10.2-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (18.0 MB)\n \u001b[K |████████████████████████████████| 18.0 MB 350 kB/s \n \u001b[?25hCollecting qiskit-ibmq-provider==0.18.3\n Downloading qiskit_ibmq_provider-0.18.3-py3-none-any.whl (238 kB)\n \u001b[K |████████████████████████████████| 238 kB 70.1 MB/s \n \u001b[?25hCollecting qiskit-ignis==0.7.0\n Downloading qiskit_ignis-0.7.0-py3-none-any.whl (200 kB)\n \u001b[K |████████████████████████████████| 200 kB 72.1 MB/s \n \u001b[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.2->qiskit) (1.4.1)\n Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.2->qiskit) (1.19.5)\n Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.23.0)\n Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.8.2)\n Collecting requests-ntlm>=1.1.0\n Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n Collecting websocket-client>=1.0.1\n Downloading websocket_client-1.2.3-py3-none-any.whl (53 kB)\n \u001b[K |████████████████████████████████| 53 kB 1.6 MB/s \n \u001b[?25hRequirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.24.3)\n Collecting retworkx>=0.8.0\n Downloading retworkx-0.11.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.6 MB)\n \u001b[K |████████████████████████████████| 1.6 MB 58.7 MB/s \n \u001b[?25hRequirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)\n Collecting scipy>=1.0\n Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)\n \u001b[K |████████████████████████████████| 38.1 MB 1.3 MB/s \n \u001b[?25hCollecting symengine>=0.8\n Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n \u001b[K |████████████████████████████████| 38.2 MB 1.1 MB/s \n \u001b[?25hCollecting ply>=3.10\n Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n \u001b[K |████████████████████████████████| 49 kB 4.1 MB/s \n \u001b[?25hCollecting stevedore>=3.0.0\n Downloading stevedore-3.5.0-py3-none-any.whl (49 kB)\n \u001b[K |████████████████████████████████| 49 kB 219 kB/s \n \u001b[?25hCollecting python-constraint>=1.4\n Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit) (5.4.8)\n Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit) (1.7.1)\n Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit) (0.3.4)\n Collecting tweedledum<2.0,>=1.1\n Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n \u001b[K |████████████████████████████████| 943 kB 65.2 MB/s \n \u001b[?25hRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2.10)\n Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (3.0.4)\n Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2021.10.8)\n Collecting cryptography>=1.3\n Downloading cryptography-36.0.1-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n \u001b[K |████████████████████████████████| 3.6 MB 58.1 MB/s \n \u001b[?25hCollecting ntlm-auth>=1.0.2\n Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (2.21)\n Collecting pbr!=2.1.0,>=2.0.0\n Downloading pbr-5.8.0-py2.py3-none-any.whl (112 kB)\n \u001b[K |████████████████████████████████| 112 kB 58.0 MB/s \n \u001b[?25hRequirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit) (4.10.0)\n Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit) (3.10.0.2)\n Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit) (3.7.0)\n Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.1->qiskit) (1.2.1)\n Building wheels for collected packages: qiskit, python-constraint\n Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for qiskit: filename=qiskit-0.34.1-py3-none-any.whl size=11771 sha256=86db6f0858d82a18d20e81db5bfa58720eb18dbf6d6d27471a63e5ba617490c2\n Stored in directory: /root/.cache/pip/wheels/79/b1/3f/8cdfd5543a84705e4bd16e081f2362b9b3bfd9898d2e2d4150\n Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=b209c85fb81681840b73f43a3a02a35b1db5b502382c51a8acbef98ce8ed72e8\n Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n Successfully built qiskit python-constraint\n Installing collected packages: pbr, tweedledum, symengine, stevedore, scipy, retworkx, python-constraint, ply, ntlm-auth, cryptography, websocket-client, requests-ntlm, qiskit-terra, qiskit-ignis, qiskit-ibmq-provider, qiskit-aer, qiskit\n Attempting uninstall: scipy\n Found existing installation: scipy 1.4.1\n Uninstalling scipy-1.4.1:\n Successfully uninstalled scipy-1.4.1\n \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n Successfully installed cryptography-36.0.1 ntlm-auth-1.5.0 pbr-5.8.0 ply-3.11 python-constraint-1.4.0 qiskit-0.34.1 qiskit-aer-0.10.2 qiskit-ibmq-provider-0.18.3 qiskit-ignis-0.7.0 qiskit-terra-0.19.1 requests-ntlm-1.1.0 retworkx-0.11.0 scipy-1.7.3 stevedore-3.5.0 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.3\n\n\n\n```python\nimport numpy as np\nfrom qiskit import QuantumCircuit, transpile\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.visualization import plot_histogram\n```\n\n\n```python\n# Usar o Aer's qasm_simulator \nsimulator = QasmSimulator()\n```\n\n\n```python\n# Criar um circuito quântico para atuar no registro q\ncircuit = QuantumCircuit(2, 2)\n```\n\n\n```python\n# Adiciona uma porta H no qubit 0\ncircuit.h(0)\n```\n\n\n\n\n \n\n\n\n\n```python\n# Adiciona uma porta CX (CNOT) o qubit 0 de controle e o qubit 1 alvo\ncircuit.cx(0, 1)\n```\n\n\n\n\n \n\n\n\n\n```python\n# Mapear a medição quântica para os bits clássicos\ncircuit.measure([0,1], [0,1])\n```\n\n\n```python\n# compilar o circuito para instruções QASM \n# suportado pelo back-end \ncompiled_circuit = transpile(circuit, simulator)\n```\n\n\n```python\n# Execute o circuito no simulador qasm\njob = simulator.run(compiled_circuit, shots=1000)\n```\n\n\n```python\n# Obtenha os resultados do trabalho\nresult = job.result()\n```\n\n\n```python\n# Returna o contador\ncounts = result.get_counts(compiled_circuit)\nprint(\"\\nTotal de contagens para 00 e 11 é:\",counts)\n```\n\n\n```python\n# Desenha o circuito\ncircuit.draw()\n```\n\n\n```python\n# Denhar o histograma\nplot_histogram(counts)\n```\n", "meta": {"hexsha": "ad4eb637e17f3bbdafc06f8c1debd1fbfa73fb15", "size": 14687, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Aula_09_Pos_Ciencia_De_Dados.ipynb", "max_stars_repo_name": "rodrigosilvaluz/python_aulas_2022.1", "max_stars_repo_head_hexsha": "f6cccf3b19f44ffb08e4f57a92ac2dfe01c759ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-22T13:52:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T23:41:08.000Z", "max_issues_repo_path": "Aula_09_Pos_Ciencia_De_Dados.ipynb", "max_issues_repo_name": "sergiomonteiro76/python-aulas", "max_issues_repo_head_hexsha": "f6cccf3b19f44ffb08e4f57a92ac2dfe01c759ea", "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": "Aula_09_Pos_Ciencia_De_Dados.ipynb", "max_forks_repo_name": "sergiomonteiro76/python-aulas", "max_forks_repo_head_hexsha": "f6cccf3b19f44ffb08e4f57a92ac2dfe01c759ea", "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": 43.4526627219, "max_line_length": 336, "alphanum_fraction": 0.5443589569, "converted": true, "num_tokens": 3412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.12085322615761268, "lm_q1q2_score": 0.05995453976844517}} {"text": "

    Unit 6

    \n

    Assessing model accuracy

    \n

    (Notebook: regression_model_comparison.ipynb)

    \n
    \n
    \n
    \n

    IST 718 – Big Data Analytics

    \n

    Daniel E. Acuna

    \n

    http://acuna.io

    \n\n\n# From previous unit\n- We took a **statistical approach to learning** which acknowledges our uncertainty and noise in the data science process. \n\n- We defined a **model** of the data. \n\n- We estimated the parameters using **training data**. \n\n- We used the model to **predict** and **interpret** the results. \n\n- We could use **supervised** or **unsupervised** learning to find relationships between variables. \n\n- If variables are not quantitative, we used classification models.\n\n# In this unit\n- Generalization performance\n- Estimating generalization performance: cross-validation\n- Bias-variance decomposition\n- Performance of classifiers: confusion matrix, ROC curve, AUC\n- Bayes rule\n\n
    \n\n
    \n\n# Generalization performance\n- Generalization is the performance of a learning method on independent **test data**. \n\n- Generalization performance guides the choice of learning method or model. \n- **Why don't we teach the *best method*?**\n - *Because there is no free lunch in statistics*: David Wolpert, \"The Lack of A Priori Distinctions Between Learning Algorithms\", 1996.\n
    \n No one method dominates all others over all possible data sets.\n
    \n\n# Generalization performance (2)\n- The no free lunch theorem implies that we need to: \n\n 1. Learn about the **particular dataset** we are working on (data science!) \n \n 2. **Select the best method** using generalization performance (data science!)\n\n\n# Measuring generalization performance: theory\n- We need to define a loss function:\n\n$$l(Y,\\hat{f}(X))$$ \n\n- For example, the Squared Error for regression:\n\n$$l(Y,\\hat{f}(X)) = (Y - \\hat{f}(X))^2$$ \n\n
    (which is the same as the negative likelihood with Gaussian noise.)
    \n\n- Or zero-one loss for classification:\n\n$$l(Y,\\hat{f}(X)) = \\text{I}(Y \\neq \\hat{f}(X))$$ \n\n
    where $\\text{I}(a,b)$ is 1 if $a = b$, and 0 otherwise.
    \n\n# Measuring generalization performance: test error and expected prediction error\n- Test error is the prediction error over an *independent* test sample:\n\n$$Err_T = E[l(Y,\\hat{f}(X)) \\mid T]$$ \n\n
    where both $Y$ and $X$ are randomly sampled with a fixed training set $T$.
    \n\n- A related quantity is the expected prediction error:\n\n$$Err = E[l(Y,\\hat{f}(X))] = E[Err_T]$$ \n\n
    where everything is random including the training dataset.
    \n\n- Most methods effectively estimate $Err$ instead of $Err_T$.\n\n# Measuring generalization performance: model comparison\n\n- Typically, we must compare several models\n- We split the data into **three datasets** and compute the following over a **testing dataset**\n$$Err_{V,T}=E[l(Y,\\hat{f}(X))\\mid V,T ]$$\nwhere $V$ is a **validation dataset**, and $T$ is a **training dataset**. \n- We further restrict the previous quantity to the best model on **validation** performance, and therefore we end up estimating\n$$Err = E[E_T[Err_{V^*,T}]]$$\n\n# Estimating test error in practice: cross validation\n
    \n\n
    \n
    \n
    \n
      \n
    • Often, models have differing degrees of complexity controlled by a parameter $\\alpha$ (e.g., $\\;\\hat{f}_\\alpha(X)$)
    • \n
    • Training split is used to **fit** one model.
    • \n
    • Validation split is used to select **complexity**.
    • \n
    • Test split is used to estimate **expected test error**.
    • \n
    \n
    \n
    \n
      \n
      \n
    \n
    \n\n# Estimating test error in practice: cross validation (2)\n- The previous approach is known as **training, validation, and testing split**\n- If no alternative models are compared, there are only two splits and the method is known as training and testing\n- Typical data splits are 60%-30%-10% for training, validation, and testing\n- Or 80%-20% for training and testing splits\n\n# Estimating the expected test error: $k$-fold cross validation\n
    \n
    \n
    \n
    \n
      \n
    • The problem with the previous procedure is that we \"throw away\" the validation and test splits during training.
    • \n
      \n
    • $k$-fold cross validation (partially) fixes this by running cross validation multiple times.
    • \n
    \n
    \n
    \n
    \n
    \n\n# Estimating the expected test error: training data splits\n- The **test split** should **only** be used at the end of the data science.\n- (Demo) We will compare two models in diabetes dataset: linear regression using BMI (M1) and linear regression using BMI and age (M2). \n \n 1. Model fit: \n M1 MSE (training) = 3723, **M2 MSE (training) = 3680**\n \n 2. Model selection: \n **M1 MSE (validation) = 4582**, M2 MSE (validation) = 4618\n \n 3. Model assessment: \n **M1 MSE (test) = 3925**\n \n\n# Estimating the expected test error: variable selection\n- This procedure can be generalized to answer the question:\n - Which variables should be included in the model? \n \n- One of the simplest such procedures is the null-to-full model variable selection:\n
      \n
    1. For $k$ variables from 0 to $p$:
    2. \n
        \n
      1. Fit $p – k$ models which add one variable to the current model.
      2. \n
      3. If none of the models has lower validation error than current model, then break.
      4. \n
      5. Set the current model to the one with lowest validation error.
      6. \n
      \n
    3. Return current model.
    4. \n
    \n\n\n- This procedure selects age, bmi, map, tc, ltg, and glu as the most important variables with estimated test error of **3324**.\n\n# More on expected test error\n- The loss function used to cross validation **does not** necessarily match the loss function used during model fitting.\n- For example, you can fit models with gradient descent to minimize MSE (because it is easy and fast) but you might choose models based on the Mean Absolute Deviation (MAD)\n$$\\text{MAD} = \\frac{1}{n} \\sum_{i=1}^n | \\hat{y}_i - y |$$\n\n# The Bias-Variance decomposition: Math\n- Mathematically: \n\n$$\\begin{align}\nErr(x_0) &= E[(Y-\\hat{f}(x_0))^2\\mid x_0] \\\\\nErr(x_0) &= \\sigma_{\\epsilon}^2 + (E[\\hat{f}(x_0)]-f(x_0))^2 + E[\\hat{f}(x_0)-E[\\hat{f}(x_0)]]^2 \\\\\nErr(x_0) &= \\text{Irreducible error} + \\text{Bias}^2 + \\text{Variance}\n\\end{align}$$ \n\n# The Bias-Variance decomposition of test error\n- In general, more complex models have low bias and high variance. \n\n- Vice versa, simple models have high bias and low variance. \n\n- This is a **fundamental tradeoff**. \n\n- **High variance** means that the estimation has high \"error bars.\" \n\n- **High bias** means that the estimation will not change much even if more data is seen.\n\n# The Bias-Variance decomposition: Nearest neighbor regression\n- Take the $k$ closest points and compute the average $y$ of those points\n$$\\hat{f}(x_0) = \\frac{1}{k}\\sum_{i=1}^k f(x_{\\text{nn}_i(x_0)})$$\nwhere $\\text{nn}_i(x)$ is the index of $i$-th closest neighbor to $x$\n- The Bias-variance decomposition then becomes\n$$Err(x_0) = \\sigma_\\epsilon^2 + [f(x_0) - \\frac{1}{k}\\sum_{i=1}^k f(x_{\\text{nn}_i(x_0)})]^2 + \\frac{\\sigma_\\epsilon^2}{k}$$\nwhere $\\frac{\\sigma_\\epsilon^2}{k}$ is the variance of $\\hat{f}$\n- Bias increases with $k$ and variance decreases with $k$\n\n# The Bias-Variance decomposition: Linear regression\n- The argument is more complex: $\\hat{f}(x_0) = x_0^T b$ with vector $b$ having $p$ components\n- On average\n$$Err(x_0) \\approx \\sigma_\\epsilon^2 + \\text{Bias}^2 + p \\sigma_\\epsilon^2$$\n- Variance is proportional to the number of parameters and therefore Bias decreases with number of parameters\n\n# The Bias-Variance decomposition: in practice\n- It is many times impossible to know the irreducible error, bias, and variance decomposition\n- There are several heuristics for trying to understand whether we need to increase the bias or the variance, or whether we have simply hit the irreducible error\n- We will want to **search over many models to find the one which minimizes bias and variance**\n\n# The Bias-Variance decomposition (2)\nAn example with the diabetes dataset:\n- We add a polynomial expansion to the variables:\n - bmi, age, bmi*age, bmi$^2$, age$^2$, etc. \n \n- We will have a new set of features of size:\n\n$$p_\\text{new} = 2p + p(p-1)/2$$\n\n- We run the following procedure:\n Repeat many times:\n 1. Randomly split the data into training and testing\n 2. For $k=1$ to $p_\\text{new}$\n 1. Fit model with $k$ randomly selected features and predict.\n 2. Estimate training and testing MSEs.\n\n# The Bias-Variance decomposition (3)\n
    \n
    \n\n# The Bias-Variance decomposition: the learning curve\n
    \n
    \n
    \n
    \n
      \n
    • Simple model doesn’t learn much after 50 examples.
    • \n
    • Complex model keeps learning.
    • \n
    • Simple model has better performance with small datasets.
    • \n
    • Complex model has better performance with big datasets.
    • \n
    \n
    \n
    \n
    \n
    \n\n# Measuring generalization performance: classification\n- A typical method for measuring classification performance is *accuracy*: \n\n $$\\text{Accuracy} = \\frac{1}{n} \\sum_{i=1}^{n} \\text{I}(y_i,\\hat{f}(x_i))$$\n
    where $\\text{I}(a, b)$ is 1 if $a = b$, and 0 otherwise.
    \n\n\n- What might be the problem with using accuracy? (hint: What is the accuracy of an algorithm that predicts that every email received is not a spam?)\n\n# Measuring generalization performance: confusion matrix\n- **Activity**: Predict spam. Given one normal email (True Normal: TN) and one spam email (True Spam: TS), Gmail can classify as spam (Predict Spam: PS) or not spam (Predict Normal: PN). Where would you put all these cases in a confusion matrix?\n\n\n# Measuring generalization performance: confusion matrix (2)\n- **Activity**: Predict spam. Given one normal email (True Normal: TN) and one spam email (True Spam: TS), Gmail can classify as spam (Predict Spam: PS) or not spam (Predict Normal: PN). Where would you put all these cases in a confusion matrix?\n\n\n# Measuring generalization performance: confusion matrix (3)\n- This matrix is called a **confusion matrix**: summary of true vs predicted cases\n
    \n\n# Measuring generalization performance: Common statistics from confusion matrix\n- **Prevalence**: (TP+FN) / everything\n- **Precision**: TP / (TP + FP)\n- **Sensitivity**, **Recall**, or **True positive rate**: TP / true condition positive\n- **Specificity**: TN / true condition negative\n- **F1**: $\\frac{2*precision*recall}{precision + recall}$\n\n# Measuring generalization performance: ROC curve\n- In general, no single algorithm has the best sensitivity and specificity simultaneously.\n- Some algorithms offer a range of sensitivity/specificity points. ROC curve displays this\n\n
    \n\n# Measuring generalization performance: ROC curve (2)\n- We will classify as spam if classifier thinks with more than 50% probability. \n\n
    \n
    \n\n# Measuring generalization performance: ROC curve (3)\n- **Less stringent, we will classify as spam if P(spam) > 0.1**\n\n
    \n
    \n\n# Measuring generalization performance: ROC curve (4)\n- We can put the two thresholds $\\theta = 0.5$ and $\\theta = 0.1$ in a plot.\n\n
    \n
    \n\n# Measuring generalization performance: ROC curve (5)\n- We can do this for every threshold value and plot the result as a curve. \n
    \n
    \n
    \n**Activity**: can you guess the curve of a random classifier?\n\n# Measuring generalization performance: ROC curve (6)\n- We can do this for every threshold value and plot the result as follows: \n\n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n

    A measure that combines all thresholds is the **Area Under the ROC Curve (AUC)**

    \n
    \n\n# Area under the ROC curve (AUC)\n\n- It is hard to interpret but:\n - It can be thought as how good is the model to rank the probabilities with the real labels\n- The **AUC** is 1/2 if the classifier is *random* or *constant*\n- **Activity: show that the AUC is in fact 1/2 for a random predictor**\n\n# AUC for random prediction\n\n- AP, AN, PP, PN mean actual positive, actual negative, predicted positive, and predictived negative, respectively\n- There are $n$ cases in total\n\n| . | PP|PN |\n|---|---|---|\n| AP| TP|FN |\n| AN| FP|TN |\n\n- Cases are gonna randomly fall on PP and PN. \n- For a given threshold $\\theta$, FP = $(1-\\theta)$AN and TN=$\\theta$AN, and similarly TP=$(1-\\theta)$AP and FN=$\\theta$AP\n- FPR = $(1-\\theta)$AN/($(1-\\theta)$AN + $\\theta$AN) = $1-\\theta$\n- Therefore, AUC = $\\frac{1}{2}$\n\n# AUC for constant prediction\n- As we move the threshold there will be a change between all points being in PP to PN, or viceverse.\n- There two points will have FPR=TPR=0 and FPR=TPR=1 respectively\n- By interpolation, AUC = $\\frac{1}{2}$\n\n# The Bayesian classifier\n- Many values from confusion matrix are misleading because we are not using *prevalence rates*. \n\n- Maximum likelihood estimators estimate the most likely classification of the data given a hypothesis (actual class) without consideration of the *prevalance rate*\n\n- The optimal decision however is achieved by Bayes' theorem\n\n$$p(\\text{hypothesis} \\mid \\text{data}) = \\frac{p(\\text{data} \\mid \\text{hypothesis})\\;p(\\text{hypothesis})}{p(\\text{data})}$$\n\n# The Bayesian classifier (2)\n- Sometimes classification performance in terms of metrics that do not consider prevalance.\n- For example, a classifier for cancer (C) given positive results (R) or might be reported with:\n - Specificity: 95%\n - Sensitivity: 60% \n- But cancer prevalance is low (0.2%)\n$$p(\\text{C}\\mid \\text{R}) = \\frac{p(\\text{R}\\mid\\text{C})p(\\text{C})}{p(\\text{R})}$$\nwith\n$$p(\\text{R}) = p(\\text{R}\\mid\\text{C})p(\\text{C}) + p(\\text{R}\\mid\\neg\\text{C})p(\\neg\\text{C})$$\n\n\n# Take home message\n- Always keep the testing dataset in vault until the end of your analysis. \n\n- Use model selection to choose from models of different complexity. \n\n- Stick to a loss function throughout your analysis. \n\n- For classification problems, think carefully about the requirements of your problem. \n\n- Be careful about the prevalence values.\n", "meta": {"hexsha": "5cd6a89ba6a7446aeaf807df7f3986ef1e8afdd7", "size": 140773, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "slides/unit-06-1_assessing_model_performance.ipynb", "max_stars_repo_name": "daniel-acuna/ist718", "max_stars_repo_head_hexsha": "0a83f373aa00dc9cd1ff2e8da74d0255f04c9728", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-09-17T14:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T19:08:07.000Z", "max_issues_repo_path": "slides/unit-06-1_assessing_model_performance.ipynb", "max_issues_repo_name": "wozhouwozhou/ist718", "max_issues_repo_head_hexsha": "565e9767f6f35f77f9c14f2a94b2d75a0a6e2c02", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-03-24T15:51:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T19:48:14.000Z", "max_forks_repo_path": "slides/unit-06-1_assessing_model_performance.ipynb", "max_forks_repo_name": "wozhouwozhou/ist718", "max_forks_repo_head_hexsha": "565e9767f6f35f77f9c14f2a94b2d75a0a6e2c02", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-09-25T13:35:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T15:29:42.000Z", "avg_line_length": 180.2471190781, "max_line_length": 58764, "alphanum_fraction": 0.892337309, "converted": true, "num_tokens": 4004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.15817434878009673, "lm_q1q2_score": 0.059717251640746434}} {"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n \n\n \n\n\n\n[Python for Probability, Statistics, and Machine Learning](https://www.springer.com/fr/book/9783319307152)\n\n# Moment Generating Functions\n\nGenerating moments usually involves integrals that are extremely\ndifficult to compute. Moment generating functions make this much, much\neasier. The moment generating function is defined as,\n\n$$\nM(t) = \\mathbb{E}(\\exp(t X))\n$$\n\n The first moment is the mean, which we can easily compute from \n$M(t)$ as,\n\n$$\n\\begin{align*}\n\\frac{dM(t)}{dt} &= \\frac{d}{dt}\\mathbb{E}(\\exp(t X)) = \\mathbb{E}\\frac{d}{dt}(\\exp(t X))\\\\\\\n &= \\mathbb{E}(X \\exp(t X)) \\\\\\\n\\end{align*}\n$$\n\n Now, we have to set $t=0$ and we have the mean,\n\n$$\nM^{(1)}(0) = \\mathbb{E}(X)\n$$\n\n continuing this derivative process again, we obtain the second moment as,\n\n$$\n\\begin{align*}\nM^{(2)}(t) &= \\mathbb{E}(X^2\\exp(t X)) \\\\\\\nM^{(2)}(0) &= \\mathbb{E}(X^2)\n\\end{align*}\n$$\n\n With this in hand, we can easily compute the variance as,\n\n$$\n\\mathbb{V}(X) = \\mathbb{E}(X^2) -\\mathbb{E}(X)^2=M^{(2)}(0)-M^{(1)}(0)^2\n$$\n\n**Example.** Returning to our favorite binomial distribution, let's compute\nsome moments using Sympy.\n\n\n```python\nimport sympy as S\nfrom sympy import stats\np,t = S.symbols('p t',positive=True)\nx=stats.Binomial('x',10,p)\nmgf = stats.E(S.exp(t*x))\n```\n\n Now, let's compute the first moment (aka, mean) using\nthe usual integration method and using moment generating functions,\n\n\n```python\nprint S.simplify(stats.E(x))\nprint S.simplify(S.diff(mgf,t).subs(t,0))\n```\n\n 10*p\n 10*p\n\n\n Otherwise, we can compute this directly as follows,\n\n\n```python\nprint S.simplify(stats.moment(x,1)) # mean\nprint S.simplify(stats.moment(x,2)) # 2nd moment\n```\n\n 10*p\n 10*p*(9*p + 1)\n\n\n In general, the moment generating function for the binomial\ndistribution is the following,\n\n$$\nM_X(t) = \\left(p\\left(e^t-1\\right)+1\\right) ^n\n$$\n\nA key aspect of moment generating functions is that they are unique identifiers\nof probability distributions. By the uniqueness theorem, given two random\nvariables $X$ and $Y$, if their respective moment generating functions are\nequal, then the corresponding probability distribution functions are equal.\n\n**Example.** Let's use the uniqueness theorem to consider the following\nproblem. Suppose we know that the probability distribution of $X$ given $U=p$\nis binomial with parameters $n$ and $p$. For example, suppose $X$ represents the\nnumber of heads in $n$ coin flips, given the probability of heads is $p$. We \nwant to find the unconditional distribution of $X$. Writing out the\nmoment generating function as the following,\n\n$$\n\\mathbb{E}(e^{t X}\\vert U=p) = (p e^t + 1-p)^n\n$$\n\n Because $U$ is uniform over the unit interval, we can \nintegrate this part out\n\n$$\n\\begin{align*}\n\\mathbb{E}(e^{t X}) &=\\int_0^1 (p e^t + 1-p)^n dp \\\\\\\n &= \\frac{1}{n+1} \\frac{e^{t(n+1)-1}}{e^t-1} \\\\\\\n &= \\frac{1}{n+1} (1+e^t+e^{2t}+e^{3t}+\\ldots+e^{n t}) \\\\\\\n\\end{align*}\n$$\n\n Thus, the moment generating function of $X$ corresponds to that of a\nrandom variable that is equally likely to be any of the values $0,1,\\ldots,n$.\nThis is another way of saying that the distribution of $X$ is discrete uniform\nover $\\lbrace 0,1,\\ldots,n \\rbrace$. Concretely, suppose we have a box of coins\nwhose individual probability of heads is unknown and that we dump the box on\nthe floor, spilling all of the coins. If we then count the number of coins facing\nheads-up, that distribution is uniform.\n\nMoment generating functions are useful for deriving distributions of\nsums of independent random variables. Suppose $X_1$ and $X_2$ are independent\nand $Y=X_1+X_2$. Then, the moment generating function of $Y$ follows\nfrom the properties of the expectation,\n\n$$\n\\begin{align*}\nM_Y(t) &= \\mathbb{E}(e^{t Y}) = \\mathbb{E}(e^{t X_1 + t X_2}) \\\\\\\n &= \\mathbb{E}(e^{t X_1} e^{ t X_2 }) =\\mathbb{E}(e^{t X_1})\\mathbb{E}(e^{t X_2}) \\\\\\\n &= M_{X_1}(t)M_{X_2}(t)\n\\end{align*}\n$$\n\n**Example.** Suppose we have two normally distributed random variables, \n$X_1\\sim \\mathcal{N}(\\mu_1,\\sigma_1)$ and $ X_2\\sim \\mathcal{N}(\\mu_2,\\sigma_2)$.\nWe can save some tedium by exploring this in Sympy,\n\n\n```python\nS.var('x:2',real=True)\nS.var('mu:2',real=True)\nS.var('sigma:2',positive=True)\nS.var('t',positive=True)\nx0=stats.Normal(x0,mu0,sigma0)\nx1=stats.Normal(x1,mu1,sigma1)\n```\n\n**Programming Tip.**\n\nThe `S.var` function defines the variable and injects it into the global\nnamespace. This is sheer laziness. It is more expressive to define variables\nexplicitly as in `x = S.symbols('x')`. Also notice that we used the Greek names\nfor the `mu` and `sigma` variables. This will come in handy later when we want\nto render the equations in the Jupyter/IPython notebook which understands\nhow to typeset these symbols in \\LaTeX{}. The `var('x:2')` creates two\nsymbols, `x0` and `x1`. Using the colon this way makes it easy to generate\narray-like sequences of symbols.\n\n\n\n In the next block we compute the moment generating functions\n\n\n```python\nmgf0=S.simplify(stats.E(S.exp(t*x0)))\nmgf1=S.simplify(stats.E(S.exp(t*x1)))\nmgfY=S.simplify(mgf0*mgf1)\n```\n\n The moment generating functions an individual normally distributed\nrandom variable is the following,\n\n$$\ne^{\\mu_{0} t + \\frac{\\sigma_{0}^{2} t^{2}}{2}}\n$$\n\n Note the coefficients of $t$. To show that $Y$ is normally\ndistributed, we want to match the moment generating function of $Y$ to this\nformat. The following is the form of the moment generating function of $Y$,\n\n$$\nM_Y(t)=e^{\\frac{t}{2} \\left(2 \\mu_{0} + 2 \\mu_{1} + \\sigma_{0}^{2} t + \\sigma_{1}^{2} t\\right)}\n$$\n\n We can extract the exponent using Sympy and collect on the $t$\nvariable using the following code,\n\n\n```python\nS.collect(S.expand(S.log(mgfY)),t)\n```\n\n\n\n\n t**2*(sigma0**2/2 + sigma1**2/2) + t*(mu0 + mu1)\n\n\n\n Thus, by the uniqueness theorem, $Y$ is normally distributed with\n$\\mu_Y=\\mu_0+\\mu_1$ and $\\sigma_Y^2=\\sigma_0^2+\\sigma_1^2$.\n\n**Programming Tip.**\n\nWhen using the Jupyter/IPython notebook, you can do `S.init_printing` to get\nthe mathematical typesetting to work in the browser. Otherwise, if you want to\nkeep the raw expression and to selectively render to \\LaTeX{}, then you can\n`from IPython.display import Math`, and then use `Math(S.latex(expr))` to see\nthe typeset version of the expression.\n", "meta": {"hexsha": "fc23d4cbf41520956eacfdaf2e8fe7a4a01fdf4d", "size": 126560, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/probability/notebooks/moment_generating.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/moment_generating.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/moment_generating.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": 273.9393939394, "max_line_length": 114721, "alphanum_fraction": 0.9212547408, "converted": true, "num_tokens": 1980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.15203224738527765, "lm_q1q2_score": 0.05964785218273963}} {"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\n\nToggle cell visibility here.\n\n\n## State feedback control\n\nThis example shows the effect of full state feedback.\n\nGiven the linear time invariant system:\n\n\\begin{cases}\n\\dot{\\textbf{x}}=A\\textbf{x}+B\\textbf{u} \\\\\n\\textbf{y}=C\\textbf{x},\n\\end{cases}\n\nand the control law:\n\n$\\textbf{u}=-K\\textbf{x}+\\textbf{v},$\n\nthis example shows the free and forced responses of the close loop system: \n\n\n$$\n\\dot{\\textbf{x}}=A\\textbf{x}-BK\\textbf{x}+B\\textbf{v} = (A-BK)\\textbf{x}+B\\textbf{v}.\n$$\n\n### How to use this notebook?\nTry to change the values of $K$ or directly set the eigenvalues of $(A-BK)$ and get the corresponding controller gains:\n- Create an unstable system and make it stable with full state feedback.\n- Create a system with a slow response and make it faster with full state feedback.\n- Create a system that is not fully controllable try to change all its eigenvalues in closed loop. Is it possible to achieve that? \n- Create a system that is not fully controllable and unstable and try to make it stable with full state feedback. Can you tell in which cases it is possible to stabilize it with closed-loop control?\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 1 0; 0 0 1; 0 2 -3')\nB = numpy.matrix('0; 0; 1')\nC = numpy.matrix('1 0 0; 0 1 0; 0 0 1')\nX0 = numpy.matrix('2; 2; 2')\nK = numpy.matrix([8,14,3])\nsol1 = numpy.linalg.eig(A)\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(3,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([-2])) \neig2c.setM(numpy.matrix([[-2],[0]]))\neig3c.setM(numpy.matrix([-2]))\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= ['Set K', 'Set the eigenvalues'],\n value= 'Set K',\n description='',\n disabled=False\n)\n\n# Define the number of complex eigenvalues for the observer\nselc = widgets.Dropdown(\n options= ['0 complex eigenvalues', '2 complex eigenvalues'],\n value= '0 complex eigenvalues',\n description='Eigenvalues:',\n disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n options=['impulse', 'step', 'sinusoid', 'square wave'],\n value='impulse',\n description='Type of input:',\n disabled=False\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='input u:',\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.05,\n max=1,\n step=0.05,\n description='Period: ',\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 == '0 complex eigenvalues':\n eig1c.children[0].children[0].disabled = False\n eig2c.children[1].children[0].disabled = True\n eigc = 0\n if selc == '2 complex eigenvalues':\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 == 'Set K':\n method = 1\n selc.disabled = True\n if selm == 'Set the eigenvalues':\n method = 2\n selc.disabled = False\n return method\n```\n\n\n```python\ndef main_callback(Aw, Bw, X0w, K, eig1c, eig2c, eig3c, u, period, selm, selc, selu, DW):\n A, B = Aw, Bw\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('The system\\'s eigenvalues are:',round(sols[0][0],4),',',round(sols[0][1],4),'and',round(sols[0][2],4))\n print('The controlled system\\'s eigenvalues are:',round(sol[0][0],4),',',round(sol[0][1],4),'and',round(sol[0][2],4))\n \n sys = sss(A,B,C,sym.zeros(3,1))\n sysc = sss(A-B*K, B, numpy.eye(3), numpy.zeros(3).reshape((3,1)))\n T = numpy.linspace(0, 6, 1000)\n \n if selu == 'impulse': #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 T, youtc, xoutc = control.forced_response(sysc,T,U,X0w)\n if selu == 'step':\n U = [u for t in range(0,len(T))]\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n T, youtc, xoutc = control.forced_response(sysc,T,U,X0w)\n if selu == 'sinusoid':\n U = u*numpy.sin(2*numpy.pi/period*T)\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n T, youtc, xoutc = control.forced_response(sysc,T,U,X0w)\n if selu == 'square wave':\n U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n T, yout, xout = control.forced_response(sys,T,U,X0w)\n T, youtc, xoutc = control.forced_response(sysc,T,U,X0w)\n \n fig = plt.figure(num='Simulation', figsize=(16,10))\n \n fig.add_subplot(311)\n plt.ylabel('$X_1$ vs $X_{1f}$')\n plt.plot(T,xout[0])\n plt.plot(T,xoutc[0])\n plt.xlabel('time [s]')\n plt.legend(['Open Loop','State Feedback'])\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(312)\n plt.ylabel('$X_2$ vs $X_{2f}$')\n plt.plot(T,xout[1])\n plt.plot(T,xoutc[1])\n plt.xlabel('time [s]')\n plt.legend(['Open Loop','State Feedback'])\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(313)\n plt.ylabel('$X_3$ vs $X_{3f}$')\n plt.plot(T,xout[2])\n plt.plot(T,xoutc[2])\n plt.xlabel('time [s]')\n plt.legend(['Open Loop','State Feedback'])\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('Eigenvalues:',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('Dynamics matrix A:',border=3),\n Aw,\n widgets.Label('Input matrix B:',border=3),\n Bw])])\nout = widgets.interactive_output(main_callback, {'Aw':Aw, 'Bw':Bw, '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 = '680px'\ndisplay(out, alltogether)\n```\n\n\n Output(layout=Layout(height='680px'))\n\n\n\n VBox(children=(HBox(children=(Dropdown(options=('Set K', 'Set the eigenvalues'), value='Set K'), Dropdown(desc…\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "e6d102e3aea16a6f51d4baa96231c8ef99253aaf", "size": 19060, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/.ipynb_checkpoints/SS-30-State_feedback_control-checkpoint.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/ENG/examples/04/SS-30-State_feedback_control.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "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/ENG/examples/04/SS-30-State_feedback_control.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "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": 36.8665377176, "max_line_length": 204, "alphanum_fraction": 0.4726128017, "converted": true, "num_tokens": 3600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.19193278875832634, "lm_q1q2_score": 0.05963244187196497}} {"text": "# Let's start!\nOPEN the jupyter notebook **Tutorial1-Part1** downloaded from the **indico timetable: https://indico.cern.ch/event/1088622/timetable/#20220111** to work locally or from the following link: **https://github.com/fusterma/JUAS2022** to work online.\n\n\n# Tutorials summary\n\nThe goal of these workshops is to do numerical exercices using MAD-X to visualize transverse dynamics concepts from a different point of view.\n\n**Friday 14th of January**\n- **Tutorial 1 - Part 1**: Introduction to the tools, small numerical exercises (all together).\n- **Tutorial 1 - Part 2**: My first circular accelerator: FODO cell – optics and first matching (groups of 3/4 students).\n- **Tutorial 1 - Part 3**: Adding dipoles to the FODO cell – MAD-X matching block (groups of 3/4 students).\n\n$\\color{red}{\\text{WEEKEND: homework exercice}}$\n\n**Monday 17th of January**\n- **Tutorial 2 - Part 1**: Natural chromaticity – MAD-X tracking module (groups of 3/4 students).\n- **Tutorial 2 - Part 2**: Chromaticity correction – impact of non-linearities (groups of 3/4 students).\n- **Tutorial 2 - Part 3**: Design of a transfer line - optics and matching (groups of 3/4 students).\n\n$\\color{red}{\\text{Homework + Tutorial 1 and Tutorial 2 jupyter-notebooks}}$ (to be delivered as late on Wednesday 18th to nuria.fuster@ific.uv.es). This will be considered as a BONUS to pass the accelerator design workshop oral exam. \n\n$\\color{red}{\\text{VERY IMPORTANT}}$: Save your jupyter-notebooks and download them to your computer after finishing the tutorials!! Otherwise your work will be lost!\n\n\n- The tutorials solutions will be uploaded on the indico timetable on Wednesday 19th.\n\n$\\color{blue}{\\text{Notes}}$: \n\n- For most of the tutorials we will split in groups of 3/4 students. These groups will be kept also for the accelerator design workshops on the third and fourth weeks of the JUAS course. \n\n\n- The timing of the tutorials (except Tutorial 1 - Part 1) will be:\n - 5 minutes for the introduction to the problem.\n - 25 minutes to work within your team and with your tutor on the problem.\n - 15 minutes for going through the solutions and discussion.\n\n\n- Tutors (Axel, Guido, Tessa, Davide and Nuria) will go around to help you and answer questions!\n\n\n- You can work as a team in the groups or by yourself but when you need help please ask your team mates or the tutor and use the screen share option.\n\n
    \n\n
    \n\n- The problems are long with many questions, we don't expect you to solve all of them. Some BONUS questions are there for discussion or homework.\n\n\n- We encourage you to use the Slack MAD-X channel during the workshops for the discussion part, during the weekend and all JUAS to post questions.\n\n\n# Tutorial 1: Part 1\n\nObjectives:\n\n- [Get familiar with the jupyter-notebooks.](#introjupyter)\n\n- [Get familiar with the basic python commands that we will use during the tutorials.](#intropython)\n\n- [How do we compute the optics of a lattice?](#firstexercice)\n\n- [Get familiar with python commands to send the information to the MAD-X code and review the main MADX blocks for optics calculations.](#intromadx)\n \n\n# Jupyter notebook \n\n- **OPEN** a jupyter notebook go to **FILE -> OPEN**.\n\n\n- **EDIT/INSERT/DELATE** a cell.\n\n\n- **RUN** (press bottom on the top command line or press CAPS+ENTER).\n\n\n- If working online **SAVE and DOWNLOAD**: after we finish one tutorial you need to SAVE and DOWNLOAD the jupyter-notebook into your PC. Otherwise your progres will be lost! \n\n\n- **SAVE TO BROWSER STORAGE** using the \"cloud\" icon (for those working on BINDER).\n\n# Basic python commands \n\nThe python universe has a huge number of libraries that extend the capabilities of python. \nNearly all of these are open source. For this workshop we will use the following:\n\n\n```python\n############################\n# Import special libraries #\n############################\n#For plotting\nfrom matplotlib import pyplot as plt \n# For numerical calulations (np.max(), np.min(), np.mean()...)\nimport numpy as np \n# For symbolic computation (solving algebra problems)\nimport sympy as sp\n# For structuring the data, visualization of tables and data manipultion\nimport pandas as pd \n# Library that allows us to use the MAD-X models \nfrom cpymad.madx import Madx \n# Plot display\n%matplotlib notebook\n```\n\nIf you want to learn more about **python**: \n\nhttps://www.youtube.com/watch?v=kqtD5dpn9C8 \n\nhttps://www.kaggle.com/learn/python\n\nMore about the **cpymad** library: http://hibtc.github.io/cpymad/getting-started\n\n# Scalars, arrays and matrices in Python\n\n\n```python\n# Scalar\na=20\nb=30\nprint(a*b)\nc=a+b\nprint(c)\n```\n\n 600\n 50\n\n\n\n```python\n# Arrays and matrices\nsp.Matrix([1,2,3,4]) # 1D array\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1\\\\2\\\\3\\\\4\\end{matrix}\\right]$\n\n\n\n\n```python\nsp.Matrix([[1,2],[3,4]]) # 2x2 matrix\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]$\n\n\n\n\n```python\nA=sp.Matrix([[1,2],[3,4]])\nB=sp.Matrix([[1,2],[3,4]])\nA+B\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 & 4\\\\6 & 8\\end{matrix}\\right]$\n\n\n\n\n```python\nA*B\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}7 & 10\\\\15 & 22\\end{matrix}\\right]$\n\n\n\n# Plots in Python\n\n\n```python\n# Plot\n%matplotlib notebook\nplt.rcParams['savefig.dpi'] = 90\nplt.rcParams['figure.dpi'] = 90\n\nx=[0,1,2,3,4,5,6,7,8,9,10]\ny=[0,1,2,3,4,5,6,7,8,9,10]\nplt.plot(x,y,'.-b',label='test')\nplt.legend()\nplt.grid()\nplt.xlabel('s [m]')\nplt.ylabel('x[m]') \n```\n\n\n \n\n\n\n\n\n\n\n\n\n Text(0, 0.5, 'x[m]')\n\n\n\n# How do we compute the optics of a lattice? \n\n \n- I want to motivate the use of optics codes such as MAD-X and at the same time illustrate the basic numerical approach behind some of the methods.\n \n\n- The TWISS method is based on matrix multiplications where first and second order transport matrices are used to get the optics of the machine.\n\n\n# FODO cell\n- Compute the linear optics functions of a FODO cell, which is the simplier combination of quadrupoles required to focuse the beam in both, vertical and horizontal planes.\n\n\n\n# Thin lens approximation (f >> $l_q$)\n\n- To do some first estimations analytically one uses the thin lens approximation.\n\n
    \n\n
    \n\n\n\n```python\n# Symbolic computation\n\n# Symbols defintion\nK = sp.Symbol(\"K\", positive = True)\nLq = sp.Symbol(\"Lq\", positive = True)\nLd = sp.Symbol(\"Ld\", positive = True)\n```\n\n\n```python\n# Could you try to program the matrices and compute the FODO transfer matrix?\n# HINT: A=sp.Matrix[[1,0],[1,0]]\n```\n\n\n```python\n#Matrices definition\n\nMfoc=sp.Matrix([[1,0],[-K*Lq,1]])\n\nMdefoc=sp.Matrix([[1,0],[K*Lq,1]])\n\nMdrift=sp.Matrix([[1,Ld],[0,1]])\n```\n\n\n```python\n#################################################\n# Transport matrix of a focusing quadrupople #\n#################################################\nMfoc\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\- K Lq & 1\\end{matrix}\\right]$\n\n\n\n\n```python\n#################################################\n# Transport matrix of a defocusing quadrupople #\n#################################################\nMdefoc\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\K Lq & 1\\end{matrix}\\right]$\n\n\n\n\n```python\n##############################################\n# Transport matrix of a drift #\n##############################################\nMdrift\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & Ld\\\\0 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\n#Matrix multiplication\nM=Mdrift*Mdefoc*Mdrift*Mfoc\n#Matrix simplification\nM=sp.simplify(M)\n#Print of the matrix\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- K^{2} Ld^{2} Lq^{2} - K Ld Lq + 1 & Ld \\left(K Ld Lq + 2\\right)\\\\- K^{2} Ld Lq^{2} & K Ld Lq + 1\\end{matrix}\\right]$\n\n\n\n\n```python\n# Matrix elements computation\n# f=200 m, lq=1 m, ld= 30 m\nM_thin = M.subs(K, 1/(200*1)).subs(Lq, 1).subs(Ld,30) # units K in m-2, Lq and Ld in m\nM_thin\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0.8275 & 64.5\\\\-0.00075 & 1.15\\end{matrix}\\right]$\n\n\n\n\n```python\n#And for 3 FODO cells?\nM3=M*M*M\nM3=sp.simplify(M3)\nM3\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- K^{6} Ld^{6} Lq^{6} - K^{5} Ld^{5} Lq^{5} + 5 K^{4} Ld^{4} Lq^{4} + 4 K^{3} Ld^{3} Lq^{3} - 6 K^{2} Ld^{2} Lq^{2} - 3 K Ld Lq + 1 & Ld \\left(K^{5} Ld^{5} Lq^{5} + 2 K^{4} Ld^{4} Lq^{4} - 4 K^{3} Ld^{3} Lq^{3} - 8 K^{2} Ld^{2} Lq^{2} + 3 K Ld Lq + 6\\right)\\\\K^{2} Ld Lq^{2} \\left(- K^{4} Ld^{4} Lq^{4} + 4 K^{2} Ld^{2} Lq^{2} - 3\\right) & K^{5} Ld^{5} Lq^{5} + K^{4} Ld^{4} Lq^{4} - 4 K^{3} Ld^{3} Lq^{3} - 3 K^{2} Ld^{2} Lq^{2} + 3 K Ld Lq + 1\\end{matrix}\\right]$\n\n\n\n\n```python\nM_test = M3.subs(K, 1/(200*1)).subs(Lq, 1).subs(Ld,30) # units K in m-2, Lq and Ld in m\nM_test\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0.430943921875 & 187.727653125\\\\-0.0021828796875 & 1.3695821875\\end{matrix}\\right]$\n\n\n\n# What can we do with the transfer matrix?\nThis matrix describes the optical properties of the lattice and defines the beam parameters.\n\n - We can propagate the phase space coordinates of a particle with a given set of initial coordinates.\n\n\n```python\n# Try with paralel particle going through the center of the first quadrupole or with a certain amplitude\nx=sp.Matrix([[1],[0]])\nx\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1\\\\0\\end{matrix}\\right]$\n\n\n\n\n```python\nx2=M_thin*x\nx2\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0.8275\\\\-0.00075\\end{matrix}\\right]$\n\n\n\n- We can compute the periodic solution TWISS functions.\n\n\n```python\n# Transfer matrix\nR11, R12, R21, R22 = sp.symbols('R11,R12,R21,R22')\n\nMt=sp.Matrix([[R11,R12],[R21,R22]])\n\nMt\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}R_{11} & R_{12}\\\\R_{21} & R_{22}\\end{matrix}\\right]$\n\n\n\n\n```python\n# In case of periodic conditions in the accelerator there is another way to describe the particles trajectories.\n# Periodic solution one-turn-transfer matrix in terms of twiss functions:\n\na, b, g, m = sp.symbols(r'\\alpha,\\beta, \\gamma,\\mu')\n\nM=sp.Matrix([[sp.cos(m)+a*sp.sin(m),b*sp.sin(m)],[-g*sp.sin(m),sp.cos(m)-a*sp.sin(m)]])\n\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\alpha \\sin{\\left(\\mu \\right)} + \\cos{\\left(\\mu \\right)} & \\beta \\sin{\\left(\\mu \\right)}\\\\- \\gamma \\sin{\\left(\\mu \\right)} & - \\alpha \\sin{\\left(\\mu \\right)} + \\cos{\\left(\\mu \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n#For the phase advance we use the trace of the matrix\nsp.Eq(sp.cos(m),(R11+R22)/2)\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(\\mu \\right)} = \\frac{R_{11}}{2} + \\frac{R_{22}}{2}$\n\n\n\n\n```python\n#For the beta function we use the R12 matrix element\nsp.Eq(b,R12/sp.sin(m))\n```\n\n\n\n\n$\\displaystyle \\beta = \\frac{R_{12}}{\\sin{\\left(\\mu \\right)}}$\n\n\n\n\n```python\n#For the alfa function we use the trace of the matrix also\nsp.Eq(a,(R11-R22)/(2*sp.sin(m)))\n```\n\n\n\n\n$\\displaystyle \\alpha = \\frac{R_{11} - R_{22}}{2 \\sin{\\left(\\mu \\right)}}$\n\n\n\n\n```python\n#For the gamma we use the R21 element\nsp.Eq(g,-(R21/sp.sin(m)))\n```\n\n\n\n\n$\\displaystyle \\gamma = - \\frac{R_{21}}{\\sin{\\left(\\mu \\right)}}$\n\n\n\nOnce you have computed the periodic TWISS functions you can propagate them to any point in the machine using the transfer matrix of the TWISS functions from Transverse dynamics course.\n\n\n```python\nsp.Matrix([[R11**2, -2*R12*R11, R12**2],[-R11*R21,R12*R21+R22*R11, -R12*R22],[R21**2,-2*R22*R21, R22**2]])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}R_{11}^{2} & - 2 R_{11} R_{12} & R_{12}^{2}\\\\- R_{11} R_{21} & R_{11} R_{22} + R_{12} R_{21} & - R_{12} R_{22}\\\\R_{21}^{2} & - 2 R_{21} R_{22} & R_{22}^{2}\\end{matrix}\\right]$\n\n\n\n**Using the periodic one-turn-matrix and the stability condition of a FODO cell, one can define some interesting relations between the TWISS parameters and the magnetic properties of the lattice.**\n\n# Figure 1: Relation between $\\Delta \\mu$, K, $L_{cell}$, $L_q$\n\n\n```python\n# Relation between the phase advance of the cell and K, Lcell, Lq (from periodic solution an stbility condition)\na, b, g, m, d, Lq, Lc, K, pi = sp.symbols(r'\\alpha,\\beta, \\gamma,\\mu, \\Delta, L_{q}, L_{cell} K \\pi')\nsp.Eq(d*m/pi,2/pi*sp.asin(K*Lq*Lc/4))\n```\n\n\n\n\n$\\displaystyle \\frac{\\Delta \\mu}{\\pi} = \\frac{2 \\operatorname{asin}{\\left(\\frac{K L_{cell} L_{q}}{4} \\right)}}{\\pi}$\n\n\n\n\n```python\n# Parametric plots\n%matplotlib notebook\nplt.rcParams['savefig.dpi'] = 90\nplt.rcParams['figure.dpi'] = 90\n\nx=np.arange(0,4.01,0.01)\ny=2*np.arcsin(x/4)/np.pi\nfig, ax1 = plt.subplots()\nax1.plot(x,y,'-')\nax1.set_ylabel(\"$\\Delta \\mu / \\pi [rad]$\", fontsize=16)\nax1.set_xlabel(\"$K*L_{quad}*L_{cell}$ [-]\", fontsize=16)\nax1.grid()\nax1.tick_params(axis='both', labelsize=16)\nplt.tight_layout() \n```\n\n\n \n\n\n\n\n\n\n# Exercice:\n- What is the quadrupole strenght to match a FODO cell phase advance of 45$^\\circ$ if the $L_{quad}$=5 m and $L_{cell}$=100 m?\n\n- And for a FODO cell phase advance of 90$^\\circ$?\n\n- What is the maximum phase advance in a FODO cell?\n\n\n```python\n#for 45 degrees K*Lcell*lq=1.528\n#K[m^(-2)]=\n1.528/100/5\n```\n\n\n\n\n 0.003056\n\n\n\n\n```python\n#for 90 degrees K*Lcell*lq=2.842\n#K[m^(-2)]=\n2.842/100/5\n\n#For a larger phase advance one needs to increase the strength of the quads\n```\n\n\n\n\n 0.005684\n\n\n\n\n```python\n#The function goes assimptotically to 1 corresponding to a phase advance of 180 degrees.\n```\n\n# Figure 2: Relation between $\\beta_{max}$ and $\\beta_{min}$ with K, $L_{cell}$, $L_q$\n\n\n```python\n# Relation between the beta of the cell and K, Lcell, Lq\na, bmin, bmax, g, m, d, Lq, Lc, K, pi = sp.symbols(r'\\alpha,\\beta_{min}, \\beta_{max}, \\gamma,\\mu, \\Delta, L_{q}, L_{cell} K \\pi')\nsp.Eq(bmin/Lc,(1-(K*Lq*Lc/4))/(sp.sin(2*sp.asin(K*Lq*Lc/4))))\n```\n\n\n\n\n$\\displaystyle \\frac{\\beta_{min}}{L_{cell}} = \\frac{- \\frac{K L_{cell} L_{q}}{4} + 1}{\\sin{\\left(2 \\operatorname{asin}{\\left(\\frac{K L_{cell} L_{q}}{4} \\right)} \\right)}}$\n\n\n\n\n```python\nsp.Eq(bmax/Lc,(1+(K*Lq*Lc/4))/(sp.sin(2*sp.asin(K*Lq*Lc/4))))\n```\n\n\n\n\n$\\displaystyle \\frac{\\beta_{max}}{L_{cell}} = \\frac{\\frac{K L_{cell} L_{q}}{4} + 1}{\\sin{\\left(2 \\operatorname{asin}{\\left(\\frac{K L_{cell} L_{q}}{4} \\right)} \\right)}}$\n\n\n\n\n```python\n%matplotlib notebook\nplt.rcParams['savefig.dpi'] = 90\nplt.rcParams['figure.dpi'] = 90\n\nx=np.arange(0.5,3.90,0.01)\nbetamax=(1+(x/4))/(np.sin(2*np.arcsin(x/4)))\nbetamin=(1-(x/4))/(np.sin(2*np.arcsin(x/4)))\nfig, ax1 = plt.subplots()\nax1.plot(x,betamax,'-',label=r\"$\\beta_{max}/L_{cell}$\")\nax1.plot(x,betamin,'-',label=r\"$\\beta_{min}/L_{cell}$\")\nax1.set_ylabel(\"[-]\", fontsize=16)\nax1.set_xlabel(\"$K*L_{quad}*L_{cell}$ [-]\", fontsize=16)\nplt.grid()\nplt.legend()\nplt.tick_params(axis='both', labelsize=16)\nplt.tight_layout() \n```\n\n\n \n\n\n\n\n\n\n# Exercice:\n- What is K and $L_{cell}$ to match a FODO cell with a phase advance of 90$^\\circ$ and a $\\beta_{max}$ of 200 m? The $L_{quad}$=2 m.\n\nHINT: You may need to combine the data from both plots.\n\n\n```python\n# From Figure 1 we get that for 90 degrees K*Lcell*Lq=2.842, for this value in Figure 2 we get that bmax/Lcell=1.960\n# Lcell=\n200/1.69\n```\n\n\n\n\n 118.34319526627219\n\n\n\n\n```python\n#And replacing in K*Lcell*Lq=1.528 from Figure 1.\n# K=\n2.842/118/2\n```\n\n\n\n\n 0.012042372881355932\n\n\n\nThe exact solution of the particle motion has to be calculted in full detail but using some approximations we can make the first steps easier and estimate the order of magnitud of some magnetic properties of our lattice.\n\n# Thick lens computation\n\n\n```python\nK = sp.Symbol(\"K\")\nLq = sp.Symbol(\"Lq\")\nLd= sp.Symbol(\"Ld\")\n\nMfoc=sp.Matrix([[sp.cos(sp.sqrt(K)*Lq),1/(sp.sqrt(K))*sp.sin(sp.sqrt(K)*Lq)],[-(sp.sqrt(K))*sp.sin(sp.sqrt(K)*Lq),sp.cos(sp.sqrt(K)*Lq)]])\n\nMdefoc=sp.Matrix([[sp.cosh(sp.sqrt(K)*Lq),1/(sp.sqrt(K))*sp.sinh(sp.sqrt(K)*Lq)],[(sp.sqrt(K))*sp.sinh(sp.sqrt(K)*Lq),sp.cosh(sp.sqrt(K)*Lq)]])\n\nMdrift=sp.Matrix([[1,Ld],[0,1]])\n```\n\n\n```python\n#################################################\n# Transport matrix of a focusing quadrupople #\n#################################################\nMfoc\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\cos{\\left(\\sqrt{K} Lq \\right)} & \\frac{\\sin{\\left(\\sqrt{K} Lq \\right)}}{\\sqrt{K}}\\\\- \\sqrt{K} \\sin{\\left(\\sqrt{K} Lq \\right)} & \\cos{\\left(\\sqrt{K} Lq \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n################################################\n# Transport matrix of a defocusing quadrupople #\n################################################\nMdefoc\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\cosh{\\left(\\sqrt{K} Lq \\right)} & \\frac{\\sinh{\\left(\\sqrt{K} Lq \\right)}}{\\sqrt{K}}\\\\\\sqrt{K} \\sinh{\\left(\\sqrt{K} Lq \\right)} & \\cosh{\\left(\\sqrt{K} Lq \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n##############################################\n# Transport matrix of a dipole #\n##############################################\nMdrift\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & Ld\\\\0 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nM=Mdrift*Mdefoc*Mdrift*Mfoc\nM=sp.simplify(M)\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\cos{\\left(\\sqrt{K} Lq \\right)} - \\left(2 \\sqrt{K} Ld \\cosh{\\left(\\sqrt{K} Lq \\right)} + K Ld^{2} \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\sinh{\\left(\\sqrt{K} Lq \\right)}\\right) \\sin{\\left(\\sqrt{K} Lq \\right)} & \\frac{\\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\sin{\\left(\\sqrt{K} Lq \\right)} + \\left(2 \\sqrt{K} Ld \\cosh{\\left(\\sqrt{K} Lq \\right)} + K Ld^{2} \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\sinh{\\left(\\sqrt{K} Lq \\right)}\\right) \\cos{\\left(\\sqrt{K} Lq \\right)}}{\\sqrt{K}}\\\\- \\sqrt{K} \\left(\\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\sin{\\left(\\sqrt{K} Lq \\right)} - \\cos{\\left(\\sqrt{K} Lq \\right)} \\sinh{\\left(\\sqrt{K} Lq \\right)}\\right) & \\left(\\sqrt{K} Ld \\sinh{\\left(\\sqrt{K} Lq \\right)} + \\cosh{\\left(\\sqrt{K} Lq \\right)}\\right) \\cos{\\left(\\sqrt{K} Lq \\right)} + \\sin{\\left(\\sqrt{K} Lq \\right)} \\sinh{\\left(\\sqrt{K} Lq \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n# Matrix elements computation\n# f=200 m, lq=1 m, ld= 30 m\nM_thick = M.subs(K, 1/(200*1)).subs(Lq, 1).subs(Ld,30) # units K in m-2, Lq and Ld in m\nM_thick\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0.821745966061752 & 66.6422445425746\\\\-0.000766666456349212 & 1.15474570697446\\end{matrix}\\right]$\n\n\n\n\n```python\nM_thin\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0.8275 & 64.5\\\\-0.00075 & 1.15\\end{matrix}\\right]$\n\n\n\n\n```python\n#And for 3 FODO cells?\nM3=M*M*M\n```\n\nIn real world applications, lattices (including FODO) are not designed by hand but\ndedicated software is used to do the design and simulation as for example MAD-X.\n\nThe TWISS in MADX it is based in matrix multiplications similar to what has been shown here but accounting also for second order matrices. \n\n# Wha is next?\n\n- Now we are going to do optics calculations using the MAD-X TWISS command (handle thousands of elements).\n\n\n- We will use the MATCHING MAD-X tool to compute the required magnetic properties for a desired TWISS functions.\n\n\n- We will use MAD-X to visulize the impact of some properties of the lattice on the TWISS and single particle DYNAMICS.\n\n# An introduction to MAD-X using the python interface
    \n\nIn this first part we are going to get familiar with MAD-X syntax.\n\nFor more information please refer to the [MAD-X online manual](http://cern.ch/madx/releases/last-rel/madxuguide.pdf).\n\n**Basic steps:**\n\n - Load the cpymad library.\n - Instantiate the MAD-X class (we create an object of the class).\n - Access the methods in the class.\n - From the methods available we will be mainly using the method \"input\" to send to MAD-X the commands.\n\n\n```python\n#Load the cpymad library\nfrom cpymad.madx import Madx \n```\n\n\n```python\n#Launching MAD-X\nmyMad = Madx(stdout=True)\n```\n\n\n```python\n#String that will be interpreted by MAD-X\nmyString='''\nstop;\n'''\n```\n\n\n```python\n#Using the \"input\" method to send the commandas to the MAD-X class\nmyMad.input(myString);\n```\n\nWith the 'stop;' instruction we exit from MAD-X, so, as done in the following cell we need to re-instantiate our MAD-X object with the \n**myMad = Madx()** instruction.\n\n---\nIt is a good practice to make header, please use '!' to comment the single line.\n\n\n```python\nmyMad = Madx(stdout=True)\n```\n\n\n```python\n# Define and print a value\nmyString='''\n\n!***************************************\n! It is a good practice to make a header\n!*************************************** \n\na= 20;\nvalue a;\n\n'''\nmyMad.input(myString);\n```\n\n--- \nUse the **help** keyword (very rudimental help)\n\n\n```python\n# To get information about the MAD-X methods (twiss, beam,match... ) use the commnd \"help\"\nmyString='''\nhelp, twiss;\n'''\nmyMad.input(myString);\n```\n\n\n```python\nmyString='''\nhelp, drift;\n'''\nmyMad.input(myString);\n```\n\n# Let's define the main ingredients to get some results from MAD-X!\n\n-Definition of machine parameters\n\n-Magnets definition\n\n-Sequence definition\n\n-Beam definition\n\n-Activate the sequence\n\n-Actions\n\n\n\n```python\nmyString='''\n\n! *********************************************************************\n! Definition of some parameters\n! ********************************************************************* \n\nl_cell=60;\nquadrupoleLenght=1;\nmyK:=0.005;// m^-2\n\n\n! *********************************************************************\n! Definition of magnets\n! ********************************************************************* \nQF: quadrupole, L=quadrupoleLenght, K1:=myK;\nQD: quadrupole, L=quadrupoleLenght, K1:=-myK;\n\n! *********************************************************************\n! Definition of sequence\n! *********************************************************************\nmyCell:sequence, refer=entry, L=L_CELL;\nquadrupole1: QF, at=0;\nmarker1: marker, at=15;\nquadrupole2: QD, at=30;\nendsequence;\n\n! *********************************************************************\n! Definition of beam\n! *********************************************************************\nbeam, particle=proton, energy=1;\n\n! *********************************************************************\n! Use of the sequence\n! *********************************************************************\nuse, sequence=myCell;\n\n! *********************************************************************\n! TWISS\n! *********************************************************************\n\nselect, flag=TWISS, column=keyword, name, s, betx, bety,alfx, alfy, x, y, dx, dy;\n\ntwiss, file=Test_Nuria.madx;\n\nplot, haxis=s, vaxis=betx,bety,dx,colour=100,file=Test_Nuria;\n\n'''\nmyMad.input(myString);\n```\n\nThe OUTPUT generated by MADX can be found by accessing the jupyter-notebook files-view.\n- For accessing: CLIC on the jupyter-logo on the top of the page using the right buttom of your mouse and use the option \"Open Link in a New Tab\".\n\n**Output:**\n\n- SUMM table\n\n- TWISS table\n\n- TWISS .txt file\n\n- TWISS .ps plot\n\n# Accessing the data\n\n- Open the files generated by MAD-X.\n- Use python and output the required data on the jupyter-notebook.\n - Using MAD-X commands and the **input()** method.\n - Using **cpymad** methods:\n - **myMad.table.twiss.dframe()**\n - **myMad.table.summ.dframe()**\n\n\n```python\n#######################\n#Using MAD-X commands #\n#######################\n\nmyString='''\nvalue, table(SUMM,Q1);\nvalue, table(SUMM,betxmax);\n'''\nmyMad.input(myString);\n```\n\nAnd for the vertical plane?\n\n\n```python\n#######################\n#Using MAD-X commands #\n#######################\n\nmyString='''\nvalue, table(SUMM,Q2);\nvalue, table(SUMM,betymax);\n'''\nmyMad.input(myString);\n```\n\n\n```python\nmyString='''\nvalue, table(TWISS,MYCELL$END,betx);\nvalue, table(TWISS,MYCELL$END,bety);\n'''\nmyMad.input(myString);\n```\n\n# Using python pandas library\n\nPandas dataframe are very convenient, have a look in https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf.\n\n\n```python\n# Using another method from cpymad \"table.twiss.dframe()\"\nmyDF=myMad.table.twiss.dframe()\n```\n\n\n```python\nmyDF\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 \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 \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 \n \n \n \n \n \n \n
    namekeywordsbetxalfxmuxbetyalfymuyx...sig54sig55sig56sig61sig62sig63sig64sig65sig66n1
    #smycell$start:1marker0.0434.996645-1.0867960.000000376.1793270.9413870.0000000.0...0.00.00.00.00.00.00.00.00.00.0
    quadrupole1quadrupole1:1quadrupole1.0434.9966451.0867960.000366376.179327-0.9413870.0004230.0...0.00.00.00.00.00.00.00.00.00.0
    drift_0[0]drift_0:0drift15.0405.5491121.0165990.005672403.520929-1.0115850.0061440.0...0.00.00.00.00.00.00.00.00.00.0
    marker1marker1:1marker15.0405.5491121.0165990.005672403.520929-1.0115850.0061440.0...0.00.00.00.00.00.00.00.00.00.0
    drift_1[0]drift_1:0drift30.0376.1793270.9413870.011785434.996645-1.0867960.0118430.0...0.00.00.00.00.00.00.00.00.00.0
    quadrupole2quadrupole2:1quadrupole31.0376.179327-0.9413870.012209434.9966451.0867960.0122090.0...0.00.00.00.00.00.00.00.00.00.0
    drift_2[0]drift_2:0drift60.0434.996645-1.0867960.023628376.1793270.9413870.0236280.0...0.00.00.00.00.00.00.00.00.00.0
    #emycell$end:1marker60.0434.996645-1.0867960.023628376.1793270.9413870.0236280.0...0.00.00.00.00.00.00.00.00.00.0
    \n

    8 rows × 256 columns

    \n
    \n\n\n\n\n```python\nmyDF[['name','s','betx','bety','alfx','alfy']]\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    namesbetxbetyalfxalfy
    #smycell$start:10.0434.996645376.179327-1.0867960.941387
    quadrupole1quadrupole1:11.0434.996645376.1793271.086796-0.941387
    drift_0[0]drift_0:015.0405.549112403.5209291.016599-1.011585
    marker1marker1:115.0405.549112403.5209291.016599-1.011585
    drift_1[0]drift_1:030.0376.179327434.9966450.941387-1.086796
    quadrupole2quadrupole2:131.0376.179327434.996645-0.9413871.086796
    drift_2[0]drift_2:060.0434.996645376.179327-1.0867960.941387
    #emycell$end:160.0434.996645376.179327-1.0867960.941387
    \n
    \n\n\n\n\n```python\nmyDF[\"s\"]\n```\n\n\n\n\n #s 0.0\n quadrupole1 1.0\n drift_0[0] 15.0\n marker1 15.0\n drift_1[0] 30.0\n quadrupole2 31.0\n drift_2[0] 60.0\n #e 60.0\n Name: s, dtype: float64\n\n\n\n\n```python\nmyDF[\"betx\"]\n```\n\n\n\n\n #s 434.996645\n quadrupole1 434.996645\n drift_0[0] 405.549112\n marker1 405.549112\n drift_1[0] 376.179327\n quadrupole2 376.179327\n drift_2[0] 434.996645\n #e 434.996645\n Name: betx, dtype: float64\n\n\n\n\n```python\nmyDF2=myMad.table.summ.dframe()\n```\n\n\n```python\nmyDF2\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
    lengthorbit5alfagammatrq1dq1betxmaxdxmaxdxrmsxcomax...ycormsdeltapsynch_1synch_2synch_3synch_4synch_5synch_6synch_8nflips
    #e60.0-0.01.110223e-169.490627e+070.023628-0.068435434.9966450.00.00.0...0.00.00.00.00.00.00.00.00.00.0
    \n

    1 rows × 27 columns

    \n
    \n\n\n\n\n```python\nmyDF2[\"q1\"]\n```\n\n\n\n\n #e 0.023628\n Name: q1, dtype: float64\n\n\n\n# Basic plot\n\n\n```python\n#Plot\n%matplotlib notebook\nplt.rcParams['savefig.dpi'] = 90\nplt.rcParams['figure.dpi'] = 90\n\nplt.plot(myDF['s'],myDF['betx'],'.-b',label='$\\\\beta_x$')\nplt.plot(myDF['s'],myDF['bety'],'.-r',label='$\\\\beta_y$')\n#Labels of the plot\nplt.xlabel('s [m]')\nplt.ylabel('[m]')\n#Legend and grid\nplt.legend(loc='best')\nplt.grid()\n```\n\n\n \n\n\n\n\n\n\n# For reference...\n\n---\nThis is an example to get familiar with the use of the physical constants and the formatting of the output. Have a look on the difference.\n\n\n```python\nmyString='''\na=pi;\nvalue a; \nset, format=\"22.20e\";\nvalue a; \n'''\nmyMad.input(myString);\n```\n\n# \nThis is an example to get familiar with if and deferred expression. Please note the after the block delimited with {...} the ; can be omitted. Pay attention to circular call!\n\n\n\n```python\nmyString='''\nif (1==1){\noption, echo=false, info=true;\na=pi;\nb:=a;\nc=a;\nvalue a; \nvalue b;\nvalue c;\na=CLIGHT*cos(a);\nvalue a;\nvalue b;\nvalue c;}\n! BEWARE of circular call!\n!a:=a+1;\n! When evaluating you will get a fatal error\n! value a; \noption, echo=true, info=true;\n'''\nmyMad.input(myString);\n```\n\n# ---\nThis is an example to get familiar with **while** and **macros** loops.\n\n\n```python\nmyString='''\na(myvariable1,myvariable2): macro = {\nvalue, myvariable1;\nvalue, myvariable1*myvariable2;\n}\n\nN=1;\nwhile (N<10){\nexec, a(N,N);\nN=N+1;\n}\n'''\nmyMad.input(myString);\n```\n\n---\n### List of functions\nIn MAD-X the following functions are available\n\n- SQRT(x) square root,\n- LOG(x) natural logarithm,\n- LOG10(x) logarithm base 10,\n- EXP(x) exponential,\n- SIN(x) trigonometric sine,\n- COS(x) trigonometric cosine,\n- TAN(x) trigonometric tangent,\n- ASIN(x) arc sine,\n- ACOS(x) arc cosine,\n- ATAN(x) arc tangent,\n- SINH(x) hyperbolic sine,\n- COSH(x) hyperbolic cosine,\n- TANH(x) hyperbolic tangent,\n- SINC(x) cardinal sine function,\n- ABS(x) absolute value,\n- ERF(x) Gauss error,\n- ERFC(x) complementary error,\n- FLOOR(x) floor, largest previous integer,\n- CEIL(x) ceiling, smallest next integer,\n- ROUND(x) round, closest integer,\n- FRAC(x) fractional part of number,\n- RANF() random number, uniformly distributed in [0,1],\n- GAUSS() random number, gaussian distribution with unit standard deviation,\n- TGAUSS(x) random number, gaussian distribution with unit standard deviation, truncated at x standard deviations;\n\n---\n### List of physical constant\n\n| MAD-X name | symbol | value |unit|\n|:-:|:-:|:-:|:-:|\n|PI| π |4 * atan(1)| 1|\n|TWOPI|2π| 2 * PI| 1|\n|DEGRAD| 180/π |180 / PI| deg/rad|\n|RADDEG| π/180 |PI / 180 |rad/deg|\n|E| e |exp(1) |1|\n|EMASS| me |0.510998928e−3| GeV|\n|PMASS| mp |0.938272046| GeV|\n|NMASS| u |0.931494061| GeV|\n|MUMASS| mµ| 0.1056583715 |GeV|\n|CLIGHT| c| 299792458| m/s|\n|QELECT| e| 1.602176565e−19| A.s|\n|HBAR| ¯h| 6.58211928e−25| MeV.s|\n|ERAD| re| 2.8179403267e−15| m|\n|PRAD| re(me/mp)| ERAD*EMASS/PMASS| m|\n", "meta": {"hexsha": "2991c5fb0bd4c7db51994da9e4676f740e226a37", "size": 629688, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorial1_Part1_solutions.ipynb", "max_stars_repo_name": "fusterma/JUAS2022_Solutions", "max_stars_repo_head_hexsha": "7071e7a4aa82e5a746139d68c08afbd0360c5287", "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": "Tutorial1_Part1_solutions.ipynb", "max_issues_repo_name": "fusterma/JUAS2022_Solutions", "max_issues_repo_head_hexsha": "7071e7a4aa82e5a746139d68c08afbd0360c5287", "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": "Tutorial1_Part1_solutions.ipynb", "max_forks_repo_name": "fusterma/JUAS2022_Solutions", "max_forks_repo_head_hexsha": "7071e7a4aa82e5a746139d68c08afbd0360c5287", "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": 96.7114114575, "max_line_length": 111380, "alphanum_fraction": 0.7647755714, "converted": true, "num_tokens": 12166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418489200747, "lm_q2_score": 0.2254166262422842, "lm_q1q2_score": 0.059248922818847416}} {"text": "```javascript\n%%javascript\n$('#appmode-leave').hide();\n$('#copy-binder-link').hide();\n$('#visit-repo-link').hide();\n```\n\n# Water anomalies\nDespite its simple molecular structure, water is an exceptionally complicated fluid.\nMany of its properties do not follow the trends obeyed by other liquids and are often referred to as water anomalies.\nScientists often report more than 50 _anomalous_ properties of water, and some of the most well-known examples are\n1. Water has an unusually high melting point for a molecule of such a low molecular weight.\n2. Water has an unusually high boiling point for a molecule of such a low molecular weight.\n3. A liquid-liquid transition occurs at about 330 K.\n4. Pressure reduces ice's melting point.\n5. Cold liquid water has a high density that increases on warming (up to 3.984 °C).\n\nMost of these anomalous behaviours have been explained and there is ample scientific (and non-scientific) literature discussing them. As an example, this website [https://water.lsbu.ac.uk/water/water_anomalies.html](https://water.lsbu.ac.uk/water/water_anomalies.html) will provide a good overview, and plenty of references, on the topic.\n\nIn this numerical workshop you will use a computational technique called Molecular Dynamics (MD) to study the how the water density changes with temperature.\nMD is one of the most widely used type of atomistic simulations, and it is now routinely used in many research groups to complement experimental studies.\n\n## Molecular dynamics\nMolecular dynamics is conceptually very simple, an iterative solution of Newton's equations of motions at the atomic level, but subtly complicated to use for direct quantitative comparison with experiments.\nAlthough a detailed description of MD is beyond the scope of this laboratory, it is worth discussing some basic ideas for you to start appreciating the power and limitations of this technique. There are plenty of webpage and tutorials that describe the working principles of MD; Wikipedia has a fairly good an general overview of this topic [https://en.wikipedia.org/wiki/Molecular_dynamics]( https://en.wikipedia.org/wiki/Molecular_dynamics).\nAnother very good reference, albeit a bit dated, is this collection of notes from the 1997 ICTP Spring Colleges in Computational Physics[Molecular Dynamics primer](https://web.mst.edu/~vojtat/class_5403/ercolessi.pdf).\n\nIn MD the atoms are treated as point particles with a mass and a partial charge. Their interactions are described by simple empirical equations, such as the Coulomb and the van der Waals (dispersion) forces, supplemented with two-, three- or four-body interactions to better capture the covalent nature of the intramolecular bonds.\nFor example, in classical molecular dynamics the interaction *energy* between two non-bonded atoms separated by a distance, $r$, can be written as\n\n\\begin{equation}\nU_{ij} = \\frac{1}{4\\pi\\varepsilon_0}\\frac{q_i q_j}{r} + \\frac{A}{r^{12}} - \\frac{B}{r^6} \\tag{1}\n\\end{equation}\n\nWhere the first term is the Coulomb interaction and the last two the repulsive and attractive parts of the van der Waals interactions.\nOn the other hand the bonded two-, three- and four-body interactions between covalently bonded atoms are typically described by *harmonic* potentials\n\n\\begin{eqnarray}\nU_{ij}^b &=& K_b(b_{ij}-b_0)^2 \\tag{2} \\\\\nU_{ijk}^a &=& K_\\theta(\\theta_{ijk}-\\theta_0)^2 \\tag{3} \\\\\nU_{ijkl}^t &=& K_\\phi[1+\\cos(n\\phi_{jikl}-\\phi_0)]^2 \\tag{3} \\\\\n\\end{eqnarray}\n\nwhere $b_{ij}$, $\\theta_{ijk}$ and $\\phi_{jikl}$ are the bond lengths, angle and torsional angle between the atoms and the other quantities are fitting parameters, which are key to determine the accuracy of the simulations.\n\nOnce the interaction energy is known we can then compute the forces on the atoms as the sum of all pair-wise interactions\n\n\\begin{equation}\nF_i = -\\nabla_i U = \\sum_{j\\neq i} F_{ij} = -\\Bigg[\n \\sum \\frac{\\partial U_{ij}}{\\partial x_i} +\n \\sum \\frac{\\partial U_{ij}^a}{\\partial x_i} +\n \\sum \\frac{\\partial U_{ijk}^b}{\\partial x_i} +\n \\sum \\frac{\\partial U_{ijkl}^t}{\\partial x_i} \\Bigg] \\tag{5} \n\\end{equation}\n\nThen, by knowing the positions, velocities and forces for all the atoms at a certain time $t$, we can use the Newton's equations of motions to *predict* the positions and velocities of the particles after a certain (short) amount of time as passed\n\n\\begin{eqnarray}\na_i(t) &=& \\frac{F_i(t)}{m_i} \\tag{6} \\\\\nv_i(t+\\delta t) &=& v_i(t) + a_i(t)\\delta t \\tag{7} \\\\\nx_i(t+\\delta t) &=& x_i(t) + v_i(t)\\delta t + \\frac{1}{2}a_i(t)\\delta t^2 \\tag{8} \\\\\n\\end{eqnarray}\n\nwhere $a_i$, $v_i$ and $x_i$ are the acceleration, velocity and position of particle $i$, and $\\delta t$ is called the time step.\nThese three equations (or some variants of them) are usually called **equations of motions**.\nNow that we have the new atomic positions we can compute the new forces on the atoms, and use again the Newton's equations of motions to *propagate* the atoms' positions further. \nThis iterative procedure will generate a **trajectory** for the atoms, and by using energies and velocities collected along the way we will also get information about the temperature, pressure and other thermodynamic quantities of the system.\n\n\n### Importance of the time step\nThe time step is one of the most important quantities in MD, and it is key to understand the potentials and limitations of atomistic molecular dynamics simulations.\nIn fact, for the above equations of motions to be valid, the time step has to be short enough to describe the fastest **atomic** motion in the system, which in the case of water is the O-H stretching mode.\nThe O-H stretching has a vibrational frequency of approximately $1\\times10^{14}$Hz, *i.e* it takes about $1\\times10^{-14}$s to complete one oscillation. Therefore, if we want to describe this very fast atomic motion using discrete points in time we would need 10-20 snapshots. Hence the time step has to be of the order of 1~fs ($1\\times10^{-15}$s) or less.\n\nNow, let’s imagine running a simulation with a 1 fs time step and that the computer take 10 ms to calculate energies, forces and do one cycle of the equations of motions.\nIn the table below you can see how long it would you take to simulate a chemical or physical process depending on the time scale it experimentally occurs\n\n| Experimental time scale | Phenomenon | Simulation time \n| :-----: | :--------: |:---------\n| 10 fs | O-H vibration | 0.1 s\n| 1 ps | H-bond persistence | 10 s\n| 1 ns | Ion permeation through a membrane | 3 hours\n| 1$\\mu$s | Conformational rearrangement | 115 days \n| 1 ms | Protein folding (fast) | 317 days\n| 1 s | Protein folding (typical) | 317,000 days\n\nObviously, the time required to do one MD cycle depends on the number of operations the computer has to perform, hence it increases with the system size.\nAlthough computational power has increased exponentially since MD was first introduced in the 1940s and we can now afford to study systems of millions of atoms or of hundreds of nm in size, there are still strong limitations to what can be reliably simulated due to the finite (small) number of atoms is included in the system (compared to Avogadro's number) and the short time scale that the simulation can span.\n\n### Ensemble\nMD codes are more complicated that a simple iterative solution of Newton's equations of motions and they include algorithms to control the temperature, pressure and other thermodynamics quantities of the system.\nOf particular relevance for this experience is the need to use **thermostats** and **barostats** to fix the boundary conditions of the simulations.\nFor this laboratory is not important to know the working details of these algorithms, but is key that you are aware that the variables relating to the temperature and pressure of the simulations are input parameters that may need to be changed.\n\n## Scope of the laboratory\nThe scope of this virtual experiment is to introduce you to atomistic molecular dynamics simulations and to compute the variations of the water density as a function of temperature, and to compare it with experimental values. As briefly mentioned above, the accuracy of the simulation depends on the parameters that are used to compute the intermolecular interactions. \nThe water models available for this laboratory are\n* SPC/E\n* TIP3P\n* TIP4P/ew\n* TIP5P\n\nwhich is a very small selections of the available models for water.\nThe models are listed in increasing level of complexity and one would reasonably expect that the more complex model gives more accurate results.\n\nIn this laboratory, you will choose one water model and run a series of simulations to compute the water density at various temperatures and determine the volumetric thermal expansion coefficient of water $\\alpha$, which is defined as\n\n\\begin{equation*}\n\\alpha(T) = \\frac{1}{V}\\bigg(\\frac{\\mathrm{d}V}{\\mathrm{d}T}\\bigg)_P = \\bigg(\\frac{\\mathrm{d}\\ln V}{\\mathrm{d}T}\\bigg)_P \\tag{9}\n\\end{equation*}\n\nwhere the subscript _P_ means that the simulations are performed at constant pressure, and we have explicitly indicated the the volumetric thermal expansion coefficient depends on the temperature. In this laboratory we will assume that the temperature dependence of $\\alpha(T)$ can be described with a simple polynomial expansion, which means that $\\ln V(T)$ can also be described with a polynomial expansion\n\n\\begin{eqnarray*}\n\\ln V(T) &=& a + bT + cT^2 + \\dots \\\\\n\\frac{\\mathrm{d}\\ln V}{\\mathrm{d}T} = \\alpha(T) &=& b + 2cT + \\dots\n\\end{eqnarray*}\n\nFrom each simulation you will compute the average volume of the simulation cell, discarding the initial portion of the simulation, where the system is out of equilibrium. \n\nYou will then fit the logarithm of the average volumes _vs_ temperature with a polynomial function, and compute the value of its derivative, $\\alpha$, at a few selected temperatures.\n\n## Your first MD simulation\n\nYou will now run your first MD simulation.\nIn the next Jupyter Notebook we will go under the hood of a molecular dynamics code in written python to see how the ensemble parameters are passed to the code, how to modify them and what outputs the code produces.\n\nThis first simulation will also give you an indication of how long a typical run takes. Please note that the timing depends on the load of the machine, so the more users are working on this laboratory to slower the calculations might get. This could be the \"worst case scenario\" given that all the class would be accessing the VM.\n\n[Run Molecular Dynamics](templateMD.ipynb)\n\n## Section 3 - Molecular dynamics simulations of water\n\n### Section 3.1 - Introduction\n\n**Task 1** - Describe the scope of the laboratory\n\n**Task 2** - Describe the water model that you have chosen\n\n**Task 3** - Describe The set of temperatures that you have chosen\n\n**Task 4** - Detail the length of the simulations you chose.\n\n### Section 3.1 - Results\n\n**Task 5** - How you computed the average, standard error and standard deviation of the volume/density\n\n**Task 6** - A table with the average (molar) volumes and densities\n\n**Task 7** - A plot of $\\ln V$ _vs_ T and the polynomial fitting function\n\n**Task 8** - The volumetric thermal expansion coefficient of water at 20$^\\circ$C and 50$^\\circ$C\n\n### Section 3.1 - Discussion\n\n**Task 9** - A comparison between your values for the density and the thermal expansion coefficient with literature values for \"real\" water and obtained from other simulations with the same water model.\n\n\n```python\n\n```\n", "meta": {"hexsha": "9d0be864f8f0731d7349266dd16d59a7b56243db", "size": 14039, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week_11_molecularMechanics2/waterDensity.ipynb", "max_stars_repo_name": "praiteri/TeachingNotebook", "max_stars_repo_head_hexsha": "75ee8baf8ef81154dffcac556d4739bf73eba712", "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": "week_11_molecularMechanics2/waterDensity.ipynb", "max_issues_repo_name": "praiteri/TeachingNotebook", "max_issues_repo_head_hexsha": "75ee8baf8ef81154dffcac556d4739bf73eba712", "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": "week_11_molecularMechanics2/waterDensity.ipynb", "max_forks_repo_name": "praiteri/TeachingNotebook", "max_forks_repo_head_hexsha": "75ee8baf8ef81154dffcac556d4739bf73eba712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-23T11:36:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T11:36:12.000Z", "avg_line_length": 64.1050228311, "max_line_length": 452, "alphanum_fraction": 0.6728399459, "converted": true, "num_tokens": 2773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776782797747225, "lm_q2_score": 0.20434190720501938, "lm_q1q2_score": 0.05880302680116262}} {"text": "##### Copyright 2020 The TensorFlow Authors.\n\n\n```python\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# Quantum data\n\n\n \n \n \n \n
    \n View on TensorFlow.org\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
    \n\nBuilding off of the comparisons made in the [MNIST](https://www.tensorflow.org/quantum/tutorials/mnist) tutorial, this tutorial explores the recent work of [Huang et al.](https://arxiv.org/abs/2011.01938) that shows how different datasets affect performance comparisons. In the work, the authors seek to understand how and when classical machine learning models can learn as well as (or better than) quantum models. The work also showcases an empirical performance separation between classical and quantum machine learning model via a carefully crafted dataset. You will:\n\n1. Prepare a reduced dimension Fashion-MNIST dataset.\n2. Use quantum circuits to re-label the dataset and compute Projected Quantum Kernel features (PQK).\n3. Train a classical neural network on the re-labeled dataset and compare the performance with a model that has access to the PQK features.\n\n## Setup\n\n\n```python\n!pip -q install tensorflow==2.3.1 tensorflow-quantum\n```\n\n WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.\r\n Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.\r\n To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.\r\n\n\n\n```python\nimport cirq\nimport sympy\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_quantum as tfq\n\n# visualization tools\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom cirq.contrib.svg import SVGCircuit\nnp.random.seed(1234)\n```\n\n## 1. Data preparation\n\nYou will begin by preparing the fashion-MNIST dataset for running on a quantum computer.\n\n### 1.1 Download fashion-MNIST\n\nThe first step is to get the traditional fashion-mnist dataset. This can be done using the `tf.keras.datasets` module.\n\n\n```python\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()\n\n# Rescale the images from [0,255] to the [0.0,1.0] range.\nx_train, x_test = x_train/255.0, x_test/255.0\n\nprint(\"Number of original training examples:\", len(x_train))\nprint(\"Number of original test examples:\", len(x_test))\n```\n\n Number of original training examples: 60000\n Number of original test examples: 10000\n\n\nFilter the dataset to keep just the T-shirts/tops and dresses, remove the other classes. At the same time convert the label, `y`, to boolean: True for 0 and False for 3.\n\n\n```python\ndef filter_03(x, y):\n keep = (y == 0) | (y == 3)\n x, y = x[keep], y[keep]\n y = y == 0\n return x,y\n```\n\n\n```python\nx_train, y_train = filter_03(x_train, y_train)\nx_test, y_test = filter_03(x_test, y_test)\n\nprint(\"Number of filtered training examples:\", len(x_train))\nprint(\"Number of filtered test examples:\", len(x_test))\n```\n\n Number of filtered training examples: 12000\n Number of filtered test examples: 2000\n\n\n\n```python\nprint(y_train[0])\n\nplt.imshow(x_train[0, :, :])\nplt.colorbar()\n```\n\n### 1.2 Downscale the images\n\nJust like the MNIST example, you will need to downscale these images in order to be within the boundaries for current quantum computers. This time however you will use a PCA transformation to reduce the dimensions instead of a `tf.image.resize` operation.\n\n\n```python\ndef truncate_x(x_train, x_test, n_components=10):\n \"\"\"Perform PCA on image dataset keeping the top `n_components` components.\"\"\"\n n_points_train = tf.gather(tf.shape(x_train), 0)\n n_points_test = tf.gather(tf.shape(x_test), 0)\n\n # Flatten to 1D\n x_train = tf.reshape(x_train, [n_points_train, -1])\n x_test = tf.reshape(x_test, [n_points_test, -1])\n\n # Normalize.\n feature_mean = tf.reduce_mean(x_train, axis=0)\n x_train_normalized = x_train - feature_mean\n x_test_normalized = x_test - feature_mean\n\n # Truncate.\n e_values, e_vectors = tf.linalg.eigh(\n tf.einsum('ji,jk->ik', x_train_normalized, x_train_normalized))\n return tf.einsum('ij,jk->ik', x_train_normalized, e_vectors[:,-n_components:]), \\\n tf.einsum('ij,jk->ik', x_test_normalized, e_vectors[:, -n_components:])\n```\n\n\n```python\nDATASET_DIM = 10\nx_train, x_test = truncate_x(x_train, x_test, n_components=DATASET_DIM)\nprint(f'New datapoint dimension:', len(x_train[0]))\n```\n\n New datapoint dimension: 10\n\n\nThe last step is to reduce the size of the dataset to just 1000 training datapoints and 200 testing datapoints.\n\n\n```python\nN_TRAIN = 1000\nN_TEST = 200\nx_train, x_test = x_train[:N_TRAIN], x_test[:N_TEST]\ny_train, y_test = y_train[:N_TRAIN], y_test[:N_TEST]\n```\n\n\n```python\nprint(\"New number of training examples:\", len(x_train))\nprint(\"New number of test examples:\", len(x_test))\n```\n\n New number of training examples: 1000\n New number of test examples: 200\n\n\n## 2. Relabeling and computing PQK features\n\nYou will now prepare a \"stilted\" quantum dataset by incorporating quantum components and re-labeling the truncated fashion-MNIST dataset you've created above. In order to get the most seperation between quantum and classical methods, you will first prepare the PQK features and then relabel outputs based on their values. \n\n### 2.1 Quantum encoding and PQK features\nYou will create a new set of features, based on `x_train`, `y_train`, `x_test` and `y_test` that is defined to be the 1-RDM on all qubits of: \n\n$V(x_{\\text{train}} / n_{\\text{trotter}}) ^ {n_{\\text{trotter}}} U_{\\text{1qb}} | 0 \\rangle$\n\nWhere $U_\\text{1qb}$ is a wall of single qubit rotations and $V(\\hat{\\theta}) = e^{-i\\sum_i \\hat{\\theta_i} (X_i X_{i+1} + Y_i Y_{i+1} + Z_i Z_{i+1})}$\n\nFirst, you can generate the wall of single qubit rotations:\n\n\n```python\ndef single_qubit_wall(qubits, rotations):\n \"\"\"Prepare a single qubit X,Y,Z rotation wall on `qubits`.\"\"\"\n wall_circuit = cirq.Circuit()\n for i, qubit in enumerate(qubits):\n for j, gate in enumerate([cirq.X, cirq.Y, cirq.Z]):\n wall_circuit.append(gate(qubit) ** rotations[i][j])\n\n return wall_circuit\n```\n\nYou can quickly verify this works by looking at the circuit:\n\n\n```python\nSVGCircuit(single_qubit_wall(\n cirq.GridQubit.rect(1,4), np.random.uniform(size=(4, 3))))\n```\n\n\n\n\n \n\n \n\n\n\nNext you can prepare $V(\\hat{\\theta})$ with the help of `tfq.util.exponential` which can exponentiate any commuting `cirq.PauliSum` objects:\n\n\n```python\ndef v_theta(qubits):\n \"\"\"Prepares a circuit that generates V(\\theta).\"\"\"\n ref_paulis = [\n cirq.X(q0) * cirq.X(q1) + \\\n cirq.Y(q0) * cirq.Y(q1) + \\\n cirq.Z(q0) * cirq.Z(q1) for q0, q1 in zip(qubits, qubits[1:])\n ]\n exp_symbols = list(sympy.symbols('ref_0:'+str(len(ref_paulis))))\n return tfq.util.exponential(ref_paulis, exp_symbols), exp_symbols\n```\n\nThis circuit might be a little bit harder to verify by looking at, but you can still examine a two qubit case to see what is happening:\n\n\n```python\ntest_circuit, test_symbols = v_theta(cirq.GridQubit.rect(1, 2))\nprint(f'Symbols found in circuit:{test_symbols}')\nSVGCircuit(test_circuit)\n```\n\n Symbols found in circuit:[ref_0]\n\n\n\n\n\n \n\n \n\n\n\nNow you have all the building blocks you need to put your full encoding circuits together:\n\n\n```python\ndef prepare_pqk_circuits(qubits, classical_source, n_trotter=10):\n \"\"\"Prepare the pqk feature circuits around a dataset.\"\"\"\n n_qubits = len(qubits)\n n_points = len(classical_source)\n\n # Prepare random single qubit rotation wall.\n random_rots = np.random.uniform(-2, 2, size=(n_qubits, 3))\n initial_U = single_qubit_wall(qubits, random_rots)\n\n # Prepare parametrized V\n V_circuit, symbols = v_theta(qubits)\n exp_circuit = cirq.Circuit(V_circuit for t in range(n_trotter))\n \n # Convert to `tf.Tensor`\n initial_U_tensor = tfq.convert_to_tensor([initial_U])\n initial_U_splat = tf.tile(initial_U_tensor, [n_points])\n\n full_circuits = tfq.layers.AddCircuit()(\n initial_U_splat, append=exp_circuit)\n # Replace placeholders in circuits with values from `classical_source`.\n return tfq.resolve_parameters(\n full_circuits, tf.convert_to_tensor([str(x) for x in symbols]),\n tf.convert_to_tensor(classical_source*(n_qubits/3)/n_trotter))\n```\n\nChoose some qubits and prepare the data encoding circuits:\n\n\n```python\nqubits = cirq.GridQubit.rect(1, DATASET_DIM + 1)\nq_x_train_circuits = prepare_pqk_circuits(qubits, x_train)\nq_x_test_circuits = prepare_pqk_circuits(qubits, x_test)\n```\n\nNext, compute the PQK features based on the 1-RDM of the dataset circuits above and store the results in `rdm`, a `tf.Tensor` with shape `[n_points, n_qubits, 3]`. The entries in `rdm[i][j][k]` = $\\langle \\psi_i | OP^k_j | \\psi_i \\rangle$ where `i` indexes over datapoints, `j` indexes over qubits and `k` indexes over $\\lbrace \\hat{X}, \\hat{Y}, \\hat{Z} \\rbrace$ .\n\n\n```python\ndef get_pqk_features(qubits, data_batch):\n \"\"\"Get PQK features based on above construction.\"\"\"\n ops = [[cirq.X(q), cirq.Y(q), cirq.Z(q)] for q in qubits]\n ops_tensor = tf.expand_dims(tf.reshape(tfq.convert_to_tensor(ops), -1), 0)\n batch_dim = tf.gather(tf.shape(data_batch), 0)\n ops_splat = tf.tile(ops_tensor, [batch_dim, 1])\n exp_vals = tfq.layers.Expectation()(data_batch, operators=ops_splat)\n rdm = tf.reshape(exp_vals, [batch_dim, len(qubits), -1])\n return rdm\n```\n\n\n```python\nx_train_pqk = get_pqk_features(qubits, q_x_train_circuits)\nx_test_pqk = get_pqk_features(qubits, q_x_test_circuits)\nprint('New PQK training dataset has shape:', x_train_pqk.shape)\nprint('New PQK testing dataset has shape:', x_test_pqk.shape)\n```\n\n New PQK training dataset has shape: (1000, 11, 3)\n New PQK testing dataset has shape: (200, 11, 3)\n\n\n### 2.2 Re-labeling based on PQK features\nNow that you have these quantum generated features in `x_train_pqk` and `x_test_pqk`, it is time to re-label the dataset. To achieve maximum seperation between quantum and classical performance you can re-label the dataset based on the spectrum information found in `x_train_pqk` and `x_test_pqk`.\n\nNote: This preparation of your dataset to explicitly maximize the seperation in performance between the classical and quantum models might feel like cheating, but it provides a **very** important proof of existance for datasets that are hard for classical computers and easy for quantum computers to model. There would be no point in searching for quantum advantage in QML if you couldn't first create something like this to demonstrate advantage.\n\n\n```python\ndef compute_kernel_matrix(vecs, gamma):\n \"\"\"Computes d[i][j] = e^ -gamma * (vecs[i] - vecs[j]) ** 2 \"\"\"\n scaled_gamma = gamma / (\n tf.cast(tf.gather(tf.shape(vecs), 1), tf.float32) * tf.math.reduce_std(vecs))\n return scaled_gamma * tf.einsum('ijk->ij',(vecs[:,None,:] - vecs) ** 2)\n\ndef get_spectrum(datapoints, gamma=1.0):\n \"\"\"Compute the eigenvalues and eigenvectors of the kernel of datapoints.\"\"\"\n KC_qs = compute_kernel_matrix(datapoints, gamma)\n S, V = tf.linalg.eigh(KC_qs)\n S = tf.math.abs(S)\n return S, V\n```\n\n\n```python\nS_pqk, V_pqk = get_spectrum(\n tf.reshape(tf.concat([x_train_pqk, x_test_pqk], 0), [-1, len(qubits) * 3]))\n\nS_original, V_original = get_spectrum(\n tf.cast(tf.concat([x_train, x_test], 0), tf.float32), gamma=0.005)\n\nprint('Eigenvectors of pqk kernel matrix:', V_pqk)\nprint('Eigenvectors of original kernel matrix:', V_original)\n```\n\n Eigenvectors of pqk kernel matrix: tf.Tensor(\n [[-2.09569391e-02 1.05973557e-02 2.16634180e-02 ... 2.80352887e-02\n 1.55521873e-02 2.82677952e-02]\n [-2.29303762e-02 4.66355234e-02 7.91163836e-03 ... -6.14174758e-04\n -7.07804322e-01 2.85902526e-02]\n [-1.77853629e-02 -3.00758495e-03 -2.55225878e-02 ... -2.40783971e-02\n 2.11018627e-03 2.69009806e-02]\n ...\n [ 6.05797209e-02 1.32483775e-02 2.69536003e-02 ... -1.38843581e-02\n 3.05043962e-02 3.85345481e-02]\n [ 6.33309558e-02 -3.04112374e-03 9.77444276e-03 ... 7.48321265e-02\n 3.42793856e-03 3.67484428e-02]\n [ 5.86028099e-02 5.84433973e-03 2.64811981e-03 ... 2.82612257e-02\n -3.80136147e-02 3.29943895e-02]], shape=(1200, 1200), dtype=float32)\n Eigenvectors of original kernel matrix: tf.Tensor(\n [[ 0.03835681 0.0283473 -0.01169789 ... 0.02343717 0.0211248\n 0.03206972]\n [-0.04018159 0.00888097 -0.01388255 ... 0.00582427 0.717551\n 0.02881948]\n [-0.0166719 0.01350376 -0.03663862 ... 0.02467175 -0.00415936\n 0.02195409]\n ...\n [-0.03015648 -0.01671632 -0.01603392 ... 0.00100583 -0.00261221\n 0.02365689]\n [ 0.0039777 -0.04998879 -0.00528336 ... 0.01560401 -0.04330755\n 0.02782002]\n [-0.01665728 -0.00818616 -0.0432341 ... 0.00088256 0.00927396\n 0.01875088]], shape=(1200, 1200), dtype=float32)\n\n\nNow you have everything you need to re-label the dataset! Now you can consult with the flowchart to better understand how to maximize performance seperation when re-labeling the dataset:\n\n\n\nIn order to maximize the seperation between quantum and classical models, you will attempt to maximize the geometric difference between the original dataset and the PQK features kernel matrices $g(K_1 || K_2) = \\sqrt{ || \\sqrt{K_2} K_1^{-1} \\sqrt{K_2} || _\\infty}$ using `S_pqk, V_pqk` and `S_original, V_original`. A large value of $g$ ensures that you initially move to the right in the flowchart down towards a prediction advantage in the quantum case.\n\nNote: Computing quantities for $s$ and $d$ are also very useful when looking to better understand performance seperations. In this case ensuring a large $g$ value is enough to see performance seperation.\n\n\n```python\ndef get_stilted_dataset(S, V, S_2, V_2, lambdav=1.1):\n \"\"\"Prepare new labels that maximize geometric distance between kernels.\"\"\"\n S_diag = tf.linalg.diag(S ** 0.5)\n S_2_diag = tf.linalg.diag(S_2 / (S_2 + lambdav) ** 2)\n scaling = S_diag @ tf.transpose(V) @ \\\n V_2 @ S_2_diag @ tf.transpose(V_2) @ \\\n V @ S_diag\n\n # Generate new lables using the largest eigenvector.\n _, vecs = tf.linalg.eig(scaling)\n new_labels = tf.math.real(\n tf.einsum('ij,j->i', tf.cast(V @ S_diag, tf.complex64), vecs[-1])).numpy()\n # Create new labels and add some small amount of noise.\n final_y = new_labels > np.median(new_labels)\n noisy_y = (final_y ^ (np.random.uniform(size=final_y.shape) > 0.95))\n return noisy_y\n```\n\n\n```python\ny_relabel = get_stilted_dataset(S_pqk, V_pqk, S_original, V_original)\ny_train_new, y_test_new = y_relabel[:N_TRAIN], y_relabel[N_TRAIN:]\n```\n\n## 3. Comparing models\nNow that you have prepared your dataset it is time to compare model performance. You will create two small feedforward neural networks and compare performance when they are given access to the PQK features found in `x_train_pqk`.\n\n### 3.1 Create PQK enhanced model\nUsing standard `tf.keras` library features you can now create and a train a model on the `x_train_pqk` and `y_train_new` datapoints:\n\n\n```python\n#docs_infra: no_execute\ndef create_pqk_model():\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Dense(32, activation='sigmoid', input_shape=[len(qubits) * 3,]))\n model.add(tf.keras.layers.Dense(16, activation='sigmoid'))\n model.add(tf.keras.layers.Dense(1))\n return model\n\npqk_model = create_pqk_model()\npqk_model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n optimizer=tf.keras.optimizers.Adam(learning_rate=0.003),\n metrics=['accuracy'])\n\npqk_model.summary()\n```\n\n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n dense (Dense) (None, 32) 1088 \n _________________________________________________________________\n dense_1 (Dense) (None, 16) 528 \n _________________________________________________________________\n dense_2 (Dense) (None, 1) 17 \n =================================================================\n Total params: 1,633\n Trainable params: 1,633\n Non-trainable params: 0\n _________________________________________________________________\n\n\n\n```python\n#docs_infra: no_execute\npqk_history = pqk_model.fit(tf.reshape(x_train_pqk, [N_TRAIN, -1]),\n y_train_new,\n batch_size=32,\n epochs=1000,\n verbose=0,\n validation_data=(tf.reshape(x_test_pqk, [N_TEST, -1]), y_test_new))\n```\n\n### 3.2 Create a classical model\nSimilar to the code above you can now also create a classical model that doesn't have access to the PQK features in your stilted dataset. This model can be trained using `x_train` and `y_label_new`.\n\n\n```python\n#docs_infra: no_execute\ndef create_fair_classical_model():\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Dense(32, activation='sigmoid', input_shape=[DATASET_DIM,]))\n model.add(tf.keras.layers.Dense(16, activation='sigmoid'))\n model.add(tf.keras.layers.Dense(1))\n return model\n\nmodel = create_fair_classical_model()\nmodel.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n optimizer=tf.keras.optimizers.Adam(learning_rate=0.03),\n metrics=['accuracy'])\n\nmodel.summary()\n```\n\n Model: \"sequential_1\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n dense_3 (Dense) (None, 32) 352 \n _________________________________________________________________\n dense_4 (Dense) (None, 16) 528 \n _________________________________________________________________\n dense_5 (Dense) (None, 1) 17 \n =================================================================\n Total params: 897\n Trainable params: 897\n Non-trainable params: 0\n _________________________________________________________________\n\n\n\n```python\n#docs_infra: no_execute\nclassical_history = model.fit(x_train,\n y_train_new,\n batch_size=32,\n epochs=1000,\n verbose=0,\n validation_data=(x_test, y_test_new))\n```\n\n### 3.3 Compare performance\nNow that you have trained the two models you can quickly plot the performance gaps in the validation data between the two. Typically both models will achieve > 0.9 accuaracy on the training data. However on the validation data it becomes clear that only the information found in the PQK features is enough to make the model generalize well to unseen instances.\n\n\n```python\n#docs_infra: no_execute\nplt.figure(figsize=(10,5))\nplt.plot(classical_history.history['accuracy'], label='accuracy_classical')\nplt.plot(classical_history.history['val_accuracy'], label='val_accuracy_classical')\nplt.plot(pqk_history.history['accuracy'], label='accuracy_quantum')\nplt.plot(pqk_history.history['val_accuracy'], label='val_accuracy_quantum')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\n```\n\nSuccess: You have engineered a stilted quantum dataset that can intentionally defeat classical models in a fair (but contrived) setting. Try comparing results using other types of classical models. The next step is to try and see if you can find new and interesting datasets that can defeat classical models without needing to engineer them yourself!\n\n## 4. Important conclusions\n\nThere are several important conclusions you can draw from this and the [MNIST](https://www.tensorflow.org/quantum/tutorials/mnist) experiments:\n\n1. It's very unlikely that the quantum models of today will beat classical model performance on classical data. Especially on today's classical datasets that can have upwards of a million datapoints.\n\n2. Just because the data might come from a hard to classically simulate quantum circuit, doesn't necessarily make the data hard to learn for a classical model.\n\n3. Datasets (ultimately quantum in nature) that are easy for quantum models to learn and hard for classical models to learn do exist, regardless of model architecture or training algorithms used.\n", "meta": {"hexsha": "80a67b8abf98ef69e036652476c016e195a2d258", "size": 119603, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/quantum_data.ipynb", "max_stars_repo_name": "kyle-w-brown/quantum", "max_stars_repo_head_hexsha": "14320539ec4657a95e55e995bf069b0f76b3de2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-02T23:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T23:38:47.000Z", "max_issues_repo_path": "docs/tutorials/quantum_data.ipynb", "max_issues_repo_name": "Saiprasad16/quantum", "max_issues_repo_head_hexsha": "40e3c253006eb78488896eb9d7f9699536dd7343", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-15T04:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T04:47:04.000Z", "max_forks_repo_path": "docs/tutorials/quantum_data.ipynb", "max_forks_repo_name": "Saiprasad16/quantum", "max_forks_repo_head_hexsha": "40e3c253006eb78488896eb9d7f9699536dd7343", "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": 107.6534653465, "max_line_length": 62768, "alphanum_fraction": 0.8176801585, "converted": true, "num_tokens": 5800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11757212736159103, "lm_q1q2_score": 0.05878606368079552}} {"text": "##### Copyright 2020 The OpenFermion Developers\n\n\n```python\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# The Jordan-Wigner and Bravyi-Kitaev Transforms\n\n\n \n \n \n \n
    \n View on QuantumLib\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
    \n\n## Setup\n\nInstall the OpenFermion package:\n\n\n```python\ntry:\n import openfermion\nexcept ImportError:\n !pip install git+https://github.com/quantumlib/OpenFermion.git@master#egg=openfermion\n```\n\n## Ladder operators and the canonical anticommutation relations\n\nA system of $N$ fermionic modes is\ndescribed by a set of fermionic *annihilation operators*\n$\\{a_p\\}_{p=0}^{N-1}$ satisfying the *canonical anticommutation relations*\n$$\\begin{align}\n \\{a_p, a_q\\} &= 0, \\label{eq:car1} \\\\\n \\{a_p, a^\\dagger_q\\} &= \\delta_{pq}, \\label{eq:car2}\n \\end{align}$$ where $\\{A, B\\} := AB + BA$. The adjoint\n$a^\\dagger_p$ of an annihilation operator $a_p$ is called a *creation\noperator*, and we refer to creation and annihilation operators as\nfermionic *ladder operators*.\nIn a finite-dimensional vector space the anticommutation relations have the following consequences:\n\n- The operators $\\{a^\\dagger_p a_p\\}_{p=0}^{N-1}$ commute with each\n other and have eigenvalues 0 and 1. These are called the *occupation\n number operators*.\n\n- There is a normalized vector $\\lvert{\\text{vac}}\\rangle$, called the *vacuum\n state*, which is a mutual 0-eigenvector of all\n the $a^\\dagger_p a_p$.\n\n- If $\\lvert{\\psi}\\rangle$ is a 0-eigenvector of $a_p^\\dagger a_p$, then\n $a_p^\\dagger\\lvert{\\psi}\\rangle$ is a 1-eigenvector of $a_p^\\dagger a_p$.\n This explains why we say that $a_p^\\dagger$ creates a fermion in\n mode $p$.\n\n- If $\\lvert{\\psi}\\rangle$ is a 1-eigenvector of $a_p^\\dagger a_p$, then\n $a_p\\lvert{\\psi}\\rangle$ is a 0-eigenvector of $a_p^\\dagger a_p$. This\n explains why we say that $a_p$ annihilates a fermion in mode $p$.\n\n- $a_p^2 = 0$ for all $p$. One cannot create or annihilate a fermion\n in the same mode twice.\n \n- The set of $2^N$ vectors\n $$\\lvert n_0, \\ldots, n_{N-1} \\rangle :=\n (a^\\dagger_0)^{n_0} \\cdots (a^\\dagger_{N-1})^{n_{N-1}} \\lvert{\\text{vac}}\\rangle,\n \\qquad n_0, \\ldots, n_{N-1} \\in \\{0, 1\\}$$\n are orthonormal. We can assume they form a basis for the entire vector space.\n \n- The annihilation operators $a_p$ act on this basis as follows:\n $$\\begin{aligned} a_p \\lvert n_0, \\ldots, n_{p-1}, 1, n_{p+1}, \\ldots, n_{N-1} \\rangle &= (-1)^{\\sum_{q=0}^{p-1} n_q} \\lvert n_0, \\ldots, n_{p-1}, 0, n_{p+1}, \\ldots, n_{N-1} \\rangle \\,, \\\\ a_p \\lvert n_0, \\ldots, n_{p-1}, 0, n_{p+1}, \\ldots, n_{N-1} \\rangle &= 0 \\,.\\end{aligned}$$\n \nSee [here](http://michaelnielsen.org/blog/archive/notes/fermions_and_jordan_wigner.pdf) for a derivation and discussion of these\nconsequences.\n\n## Mapping fermions to qubits with transforms\n\nTo simulate a system of fermions on a quantum computer, we must choose a representation of the ladder operators on the Hilbert space of the qubits. In other words, we must designate a set of qubit operators (matrices) which satisfy the canonical anticommutation relations. Qubit operators are written in terms of the Pauli matrices $X$, $Y$, and $Z$. In OpenFermion a representation is specified by a transform function which maps fermionic operators (typically instances of FermionOperator) to qubit operators (instances of QubitOperator). In this demo we will discuss the Jordan-Wigner and Bravyi-Kitaev transforms, which are implemented by the functions `jordan_wigner` and `bravyi_kitaev`.\n\n### The Jordan-Wigner Transform\nUnder the Jordan-Wigner Transform (JWT), the annihilation operators are mapped to qubit operators as follows:\n$$\\begin{aligned}\n a_p &\\mapsto \\frac{1}{2} (X_p + \\mathrm{i}Y_p) Z_1 \\cdots Z_{p - 1} \\\\\n &= (\\lvert{0}\\rangle\\langle{1}\\rvert)_p Z_1 \\cdots Z_{p - 1} \\\\\n &=: \\tilde{a}_p.\n\\end{aligned}$$\n\nThis operator has the following action on a computational basis vector\n$\\lvert z_0, \\ldots, z_{N-1} \\rangle$:\n$$\\begin{aligned}\n \\tilde{a}_p \\lvert z_0 \\ldots, z_{p-1}, 1, z_{p+1}, \\ldots, z_{N-1} \\rangle &=\n (-1)^{\\sum_{q=0}^{p-1} z_q} \\lvert z_0 \\ldots, z_{p-1}, 0, z_{p+1}, \\ldots, z_{N-1} \\rangle \\\\\n \\tilde{a}_p \\lvert z_0 \\ldots, z_{p-1}, 0, z_{p+1}, \\ldots, z_{N-1} \\rangle &= 0.\n \\end{aligned}$$\n\nNote that $\\lvert n_0, \\ldots, n_{N-1} \\rangle$ is a basis vector in the Hilbert space of fermions, while $\\lvert z_0, \\ldots, z_{N-1} \\rangle$ is a basis vector in the Hilbert space of qubits. Similarly, in OpenFermion $a_p$ is a FermionOperator while $\\tilde{a}_p$ is a QubitOperator.\n\nLet's instantiate some FermionOperators, map them to QubitOperators using the JWT, and check that the resulting operators satisfy the expected relations.\n\n\n```python\nfrom openfermion import *\n\n# Create some ladder operators\nannihilate_2 = FermionOperator('2')\ncreate_2 = FermionOperator('2^')\nannihilate_5 = FermionOperator('5')\ncreate_5 = FermionOperator('5^')\n\n# Construct occupation number operators\nnum_2 = create_2 * annihilate_2\nnum_5 = create_5 * annihilate_5\n\n# Map FermionOperators to QubitOperators using the JWT\nannihilate_2_jw = jordan_wigner(annihilate_2)\ncreate_2_jw = jordan_wigner(create_2)\nannihilate_5_jw = jordan_wigner(annihilate_5)\ncreate_5_jw = jordan_wigner(create_5)\nnum_2_jw = jordan_wigner(num_2)\nnum_5_jw = jordan_wigner(num_5)\n\n# Create QubitOperator versions of zero and identity\nzero = QubitOperator()\nidentity = QubitOperator(())\n\n# Check the canonical anticommutation relations\nassert anticommutator(annihilate_5_jw, annihilate_2_jw) == zero\nassert anticommutator(annihilate_5_jw, annihilate_5_jw) == zero\nassert anticommutator(annihilate_5_jw, create_2_jw) == zero\nassert anticommutator(annihilate_5_jw, create_5_jw) == identity\n\n# Check that the occupation number operators commute\nassert commutator(num_2_jw, num_5_jw) == zero\n\n# Print some output\nprint(\"annihilate_2_jw = \\n{}\".format(annihilate_2_jw))\nprint('')\nprint(\"create_2_jw = \\n{}\".format(create_2_jw))\nprint('')\nprint(\"annihilate_5_jw = \\n{}\".format(annihilate_5_jw))\nprint('')\nprint(\"create_5_jw = \\n{}\".format(create_5_jw))\nprint('')\nprint(\"num_2_jw = \\n{}\".format(num_2_jw))\nprint('')\nprint(\"num_5_jw = \\n{}\".format(num_5_jw))\n```\n\n### The parity transform\n\nBy comparing the action of $\\tilde{a}_p$ on $\\lvert z_0, \\ldots, z_{N-1} \\rangle$ in the JWT with the action of $a_p$ on $\\lvert n_0, \\ldots, n_{N-1} \\rangle$ (described in the first section of this demo), we can see that the JWT is associated with a particular mapping of bitstrings $e: \\{0, 1\\}^N \\to \\{0, 1\\}^N$, namely, the identity map $e(x) = x$. In other words, under the JWT, the fermionic basis vector $\\lvert n_0, \\ldots, n_{N-1} \\rangle$ is represented by the computational basis vector $\\lvert z_0, \\ldots, z_{N-1} \\rangle$, where $z_p = n_p$ for all $p$. We can write this as\n$$\\lvert x \\rangle \\mapsto \\lvert e(x) \\rangle,$$\nwhere the vector on the left is fermionic and the vector on the right is qubit. We call the mapping $e$ an *encoder*.\n\nThere are other transforms which are associated with different encoders. To see why we might be interested in these other transforms, observe that under the JWT, $\\tilde{a}_p$ acts not only on qubit $p$ but also on qubits $0, \\ldots, p-1$. This means that fermionic operators with low weight can get mapped to qubit operators with high weight, where by weight we mean the number of modes or qubits an operators acts on. There are some disadvantages to having high-weight operators; for instance, they may require more gates to simulate and are more expensive to measure on some near-term hardware platforms. In the worst case, the annihilation operator on the last mode will map to an operator which acts on all the qubits. To emphasize this point let's apply the JWT to the annihilation operator on mode 99:\n\n\n```python\nprint(jordan_wigner(FermionOperator('99')))\n```\n\nThe purpose of the string of Pauli $Z$'s is to introduce the phase factor $(-1)^{\\sum_{q=0}^{p-1} n_q}$ when acting on a computational basis state; when $e$ is the identity encoder, the modulo-2 sum $\\sum_{q=0}^{p-1} n_q$ is computed as $\\sum_{q=0}^{p-1} z_q$, which requires reading $p$ bits and leads to a Pauli $Z$ string with weight $p$. A simple solution to this problem is to consider instead the encoder defined by\n$$e(x)_p = \\sum_{q=0}^p x_q \\quad (\\text{mod 2}),$$\nwhich is associated with the mapping of basis vectors\n$\\lvert n_0, \\ldots, n_{N-1} \\rangle \\mapsto \\lvert z_0, \\ldots, z_{N-1} \\rangle,$\nwhere $z_p = \\sum_{q=0}^p n_q$ (again addition is modulo 2). With this encoding, we can compute the sum $\\sum_{q=0}^{p-1} n_q$ by reading just one bit because this is the value stored by $z_{p-1}$. The associated transform is called the parity transform because the $p$-th qubit is storing the parity (modulo-2 sum) of modes $0, \\ldots, p$. Under the parity transform, annihilation operators are mapped as follows:\n$$\\begin{aligned}\n a_p &\\mapsto \\frac{1}{2} (X_p Z_{p - 1} + \\mathrm{i}Y_p) X_{p + 1} \\cdots X_{N} \\\\\n &= \\frac{1}{4} [(X_p + \\mathrm{i} Y_p) (I + Z_{p - 1}) -\n (X_p - \\mathrm{i} Y_p) (I - Z_{p - 1})]\n X_{p + 1} \\cdots X_{N} \\\\\n &= [(\\lvert{0}\\rangle\\langle{1}\\rvert)_p (\\lvert{0}\\rangle\\langle{0}\\rvert)_{p - 1} -\n (\\lvert{0}\\rangle\\langle{1}\\rvert)_p (\\lvert{1}\\rangle\\langle{1}\\rvert)_{p - 1}]\n X_{p + 1} \\cdots X_{N} \\\\\n\\end{aligned}$$\n\nThe term in brackets in the last line means \"if $z_p = n_p$ then annihilate in mode $p$; otherwise, create in mode $p$ and attach a minus sign\". The value stored by $z_{p-1}$ contains the information needed to determine whether a minus sign should be attached or not. However, now there is a string of Pauli $X$'s acting on modes $p+1, \\ldots, N-1$ and hence using the parity transform also yields operators with high weight. These Pauli $X$'s perform the necessary update to $z_{p+1}, \\ldots, z_{N-1}$ which is needed if the value of $n_{p}$ changes. In the worst case, the annihilation operator on the first mode will map to an operator which acts on all the qubits.\n\nSince the parity transform does not offer any advantages over the JWT, OpenFermion does not include a standalone function to perform it. However, there is functionality for defining new transforms by specifying an encoder and decoder pair, also known as a binary code (in our examples the decoder is simply the inverse mapping), and the binary code which defines the parity transform is included in the library as an example. See [Lowering qubit requirements using binary codes](./binary_code_transforms_demo.ipynb) for a demonstration of this functionality and how it can be used to reduce the qubit resources required for certain applications.\n\nLet's use this functionality to map our previously instantiated FermionOperators to QubitOperators using the parity transform with 10 total modes and check that the resulting operators satisfy the expected relations.\n\n\n```python\n# Set the number of modes in the system\nn_modes = 10\n\n# Define a function to perform the parity transform\ndef parity(fermion_operator, n_modes):\n return binary_code_transform(fermion_operator, parity_code(n_modes))\n\n# Map FermionOperators to QubitOperators using the parity transform\nannihilate_2_parity = parity(annihilate_2, n_modes)\ncreate_2_parity = parity(create_2, n_modes)\nannihilate_5_parity = parity(annihilate_5, n_modes)\ncreate_5_parity = parity(create_5, n_modes)\nnum_2_parity = parity(num_2, n_modes)\nnum_5_parity = parity(num_5, n_modes)\n\n# Check the canonical anticommutation relations\nassert anticommutator(annihilate_5_parity, annihilate_2_parity) == zero\nassert anticommutator(annihilate_5_parity, annihilate_5_parity) == zero\nassert anticommutator(annihilate_5_parity, create_2_parity) == zero\nassert anticommutator(annihilate_5_parity, create_5_parity) == identity\n\n# Check that the occupation number operators commute\nassert commutator(num_2_parity, num_5_parity) == zero\n\n# Print some output\nprint(\"annihilate_2_parity = \\n{}\".format(annihilate_2_parity))\nprint('')\nprint(\"create_2_parity = \\n{}\".format(create_2_parity))\nprint('')\nprint(\"annihilate_5_parity = \\n{}\".format(annihilate_5_parity))\nprint('')\nprint(\"create_5_parity = \\n{}\".format(create_5_parity))\nprint('')\nprint(\"num_2_parity = \\n{}\".format(num_2_parity))\nprint('')\nprint(\"num_5_parity = \\n{}\".format(num_5_parity))\n```\n\nNow let's map one of the FermionOperators again but with the total number of modes set to 100.\n\n\n```python\nprint(parity(annihilate_2, 100))\n```\n\nNote that with the JWT, it is not necessary to specify the total number of modes in the system because $\\tilde{a}_p$ only acts on qubits $0, \\ldots, p$ and not any higher ones.\n\n### The Bravyi-Kitaev transform\n\nThe discussion above suggests that we can think of the action of a transformed annihilation operator $\\tilde{a}_p$ on a computational basis vector $\\lvert z \\rangle$ as a 4-step classical algorithm:\n1. Check if $n_p = 0$. If so, then output the zero vector. Otherwise,\n2. Update the bit stored by $z_p$.\n3. Update the rest of the bits $z_q$, $q \\neq p$.\n4. Multiply by the parity $\\sum_{q=0}^{p-1} n_p$.\n\nUnder the JWT, Steps 1, 2, and 3 are represented by the operator $(\\lvert{0}\\rangle\\langle{1}\\rvert)_p$ and Step 4 is accomplished by the operator $Z_{0} \\cdots Z_{p-1}$ (Step 3 actually requires no action).\nUnder the parity transform, Steps 1, 2, and 4 are represented by the operator\n$(\\lvert{0}\\rangle\\langle{1}\\rvert)_p (\\lvert{0}\\rangle\\langle{0}\\rvert)_{p - 1} -\n(\\lvert{0}\\rangle\\langle{1}\\rvert)_p (\\lvert{1}\\rangle\\langle{1}\\rvert)_{p - 1}$ and Step 3 is accomplished by the operator $X_{p+1} \\cdots X_{N-1}$.\n\nTo obtain a simpler description of these and other transforms (with an aim at generalizing), it is better to put aside the ladder operators and work with an alternative set of $2N$ operators defined by\n$$c_p = a_p + a_p^\\dagger\\,, \\qquad d_p = -\\mathrm{i} (a_p - a_p^\\dagger)\\,.$$\nThese operators are known as Majorana operators. Note that if we describe how Majorana operators should be transformed, then we also know how the annihilation operators should be transformed, since\n$$a_p = \\frac{1}{2} (c_p + \\mathrm{i} d_p).$$\n\nFor simplicity, let's consider just the $c_p$; the $d_p$ are treated similarly. The action of $c_p$ on a fermionic basis vector is given by\n$$c_p \\lvert n_0, \\ldots, n_{p-1}, n_p, n_{p+1}, \\ldots, n_{N-1} \\rangle =\n(-1)^{\\sum_{q=0}^{p-1} n_q} \\lvert n_0, \\ldots, n_{p-1}, 1 - n_p, n_{p+1}, \\ldots, n_{N-1} \\rangle$$\n\nIn words, $c_p$ flips the occupation of mode $p$ and multiplies by the ever-present parity factor. If we transform $c_p$ to a qubit operator $\\tilde{c}_p$, we should be able to describe the action of $\\tilde{c}_p$ on a computational basis vector $\\lvert z \\rangle$ with a 2-step classical algorithm:\n1. Update the string $z$ to a new string $z'$.\n2. Multiply by the parity $\\sum_{q=0}^{p-1} n_q$.\n\nStep 1 amounts to flipping some bits, so it will be performed by some Pauli $X$'s, and Step 2 will be performed by some Pauli $Z$'s. So $\\tilde{c}_p$ should take the form\n$$\\tilde{c}_p = X_{U(p)} Z_{P(p - 1)},$$\nwhere $U(j)$ is the set of bits that need to be updated upon flipping $n_j$, and $P(j)$ is a set of bits that stores the sum $\\sum_{q=0}^{j} n_q$ (let's define $P(-1)$ to be the empty set). Let's see how this looks under the JWT and parity transforms.\n\n\n```python\n# Create a Majorana operator from our existing operators\nc_5 = annihilate_5 + create_5\n\n# Set the number of modes (required for the parity transform)\nn_modes = 10\n\n# Transform the Majorana operator to a QubitOperator in two different ways\nc_5_jw = jordan_wigner(c_5)\nc_5_parity = parity(c_5, n_modes)\n\n# Print some output\nprint(\"c_5_jw = \\n{}\".format(c_5_jw))\nprint('')\nprint(\"c_5_parity = \\n{}\".format(c_5_parity))\n```\n\nFor the JWT, $U(j) = \\{j\\}$ and $P(j) = \\{0, \\ldots, j\\}$, whereas for the parity transform, $U(j) = \\{j, \\ldots, N-1\\}$ and $P(j) = \\{j\\}$. The size of these sets can be as large as $N$, the total number of modes. These sets are determined by the encoding function $e$.\n\nIt is possible to pick a clever encoder with the property that these sets have size $O(\\log N)$. The corresponding transform will map annihilation operators to qubit operators with weight $O(\\log N)$, which is much smaller than the $\\Omega(N)$ weight associated with the JWT and parity transforms. This fact was noticed by [Bravyi and Kitaev](https://arxiv.org/abs/quant-ph/0003137), and later [Havlíček and others](https://arxiv.org/abs/1701.07072) pointed out that the encoder which achieves this is implemented by a classical data structure called a Fenwick tree. The transforms described in these two papers actually correspond to different variants of the Fenwick tree data structure and give different results when the total number of modes is not a power of 2. OpenFermion implements the one from the first paper as `bravyi_kitaev` and the one from the second paper as `bravyi_kitaev_tree`. Generally, the first one (`bravyi_kitaev`) is preferred because it results in operators with lower weight and is faster to compute.\n\nLet's transform our previously instantiated Majorana operator using the Bravyi-Kitaev transform.\n\n\n```python\nc_5_bk = bravyi_kitaev(c_5, n_modes)\nprint(\"c_5_bk = \\n{}\".format(c_5_bk))\n```\n\nThe advantage of the Bravyi-Kitaev transform is not apparent in a system with so few modes. Let's look at a system with 100 modes.\n\n\n```python\nn_modes = 100\n\n# Initialize some Majorana operators\nc_17 = FermionOperator('[17] + [17^]')\nc_50 = FermionOperator('[50] + [50^]')\nc_73 = FermionOperator('[73] + [73^]')\n\n# Map to QubitOperators\nc_17_jw = jordan_wigner(c_17)\nc_50_jw = jordan_wigner(c_50)\nc_73_jw = jordan_wigner(c_73)\nc_17_parity = parity(c_17, n_modes)\nc_50_parity = parity(c_50, n_modes)\nc_73_parity = parity(c_73, n_modes)\nc_17_bk = bravyi_kitaev(c_17, n_modes)\nc_50_bk = bravyi_kitaev(c_50, n_modes)\nc_73_bk = bravyi_kitaev(c_73, n_modes)\n\n# Print some output\nprint(\"Jordan-Wigner\\n\"\n \"-------------\")\nprint(\"c_17_jw = \\n{}\".format(c_17_jw))\nprint('')\nprint(\"c_50_jw = \\n{}\".format(c_50_jw))\nprint('')\nprint(\"c_73_jw = \\n{}\".format(c_73_jw))\nprint('')\nprint(\"Parity\\n\"\n \"------\")\nprint(\"c_17_parity = \\n{}\".format(c_17_parity))\nprint('')\nprint(\"c_50_parity = \\n{}\".format(c_50_parity))\nprint('')\nprint(\"c_73_parity = \\n{}\".format(c_73_parity))\nprint('')\nprint(\"Bravyi-Kitaev\\n\"\n \"-------------\")\nprint(\"c_17_bk = \\n{}\".format(c_17_bk))\nprint('')\nprint(\"c_50_bk = \\n{}\".format(c_50_bk))\nprint('')\nprint(\"c_73_bk = \\n{}\".format(c_73_bk))\n```\n\nNow let's go back to a system with 10 modes and check that the Bravyi-Kitaev transformed operators satisfy the expected relations.\n\n\n```python\n# Set the number of modes in the system\nn_modes = 10\n\n# Map FermionOperators to QubitOperators using the Bravyi-Kitaev transform\nannihilate_2_bk = bravyi_kitaev(annihilate_2, n_modes)\ncreate_2_bk = bravyi_kitaev(create_2, n_modes)\nannihilate_5_bk = bravyi_kitaev(annihilate_5, n_modes)\ncreate_5_bk = bravyi_kitaev(create_5, n_modes)\nnum_2_bk = bravyi_kitaev(num_2, n_modes)\nnum_5_bk = bravyi_kitaev(num_5, n_modes)\n\n# Check the canonical anticommutation relations\nassert anticommutator(annihilate_5_bk, annihilate_2_bk) == zero\nassert anticommutator(annihilate_5_bk, annihilate_5_bk) == zero\nassert anticommutator(annihilate_5_bk, create_2_bk) == zero\nassert anticommutator(annihilate_5_bk, create_5_bk) == identity\n\n# Check that the occupation number operators commute\nassert commutator(num_2_bk, num_5_bk) == zero\n\n# Print some output\nprint(\"annihilate_2_bk = \\n{}\".format(annihilate_2_bk))\nprint('')\nprint(\"create_2_bk = \\n{}\".format(create_2_bk))\nprint('')\nprint(\"annihilate_5_bk = \\n{}\".format(annihilate_5_bk))\nprint('')\nprint(\"create_5_bk = \\n{}\".format(create_5_bk))\nprint('')\nprint(\"num_2_bk = \\n{}\".format(num_2_bk))\nprint('')\nprint(\"num_5_bk = \\n{}\".format(num_5_bk))\n```\n", "meta": {"hexsha": "822f011f15e1ffba772f61a7e9db4daa392d075d", "size": 27964, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/jordan_wigner_and_bravyi_kitaev_transforms.ipynb", "max_stars_repo_name": "Emieeel/OpenFermion", "max_stars_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "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/tutorials/jordan_wigner_and_bravyi_kitaev_transforms.ipynb", "max_issues_repo_name": "Emieeel/OpenFermion", "max_issues_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "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/jordan_wigner_and_bravyi_kitaev_transforms.ipynb", "max_forks_repo_name": "Emieeel/OpenFermion", "max_forks_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-13T04:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T04:41:01.000Z", "avg_line_length": 48.5486111111, "max_line_length": 1041, "alphanum_fraction": 0.622550422, "converted": true, "num_tokens": 6626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.1968262107100778, "lm_q1q2_score": 0.058549884054767035}} {"text": "# [2.1]() Pairwise sequence alignment
    [edit]\n\n**Table of Contents**\n0. [What is a sequence alignment?](#1)\n0. [A simple procedure for aligning a pair of sequences](#2)\n 0. [Step 1: Create a blank matrix where the rows and columns represent the positions in the sequences.](#2.1)\n 0. [Step 2: Add values to the cells in the matrix.](#2.2)\n 0. [Step 3: Identify the longest diagonals.](#2.3)\n 0. [Step 4: Transcribe some of the possible alignments that arise from this process.](#2.4)\n 0. [Why this simple procedure is too simplistic](#2.5)\n0. [Differential scoring of matches and mismatches](#3)\n0. [A better approach for global pairwise alignment using the Needleman-Wunsch algorithm](#4)\n 0. [Stepwise Needleman-Wunsch alignment](#4.1)\n 0. [Step 1: Create blank matrices.](#4.1.1)\n 0. [Step 2: Compute $F$ and $T$.](#4.1.2)\n 0. [Step 3: Transcribe the alignment.](#4.1.3)\n 0. [Automating Needleman-Wunsch alignment with Python](#4.2)\n 0. [A note on computing $F$ and $T$](#4.3)\n0. [Global versus local alignment](#5)\n0. [Smith-Waterman local sequence alignment](#6)\n 0. [Step 1: Create blank matrices.](#6.1)\n 0. [Step 2: Compute $F$ and $T$.](#6.2)\n 0. [Step 3: Transcribe the alignment.](#6.3)\n 0. [Automating Smith-Waterman alignment with Python](#6.4)\n0. [Differential scoring of gaps](#7)\n0. [How long does pairwise sequence alignment take?](#8)\n 0. [Comparing implementations of Smith-Waterman](#8.1)\n 0. [Analyzing Smith-Waterman run time as a function of sequence length](#8.2)\n 0. [Conclusions on the scalability of pairwise sequence alignment with Smith-Waterman](#8.3)\n\n\nOne of the most fundamental problems in bioinformatics is determining how \"similar\" a pair of biological sequences are. There are many applications for this, including inferring the function or source organism of an unknown gene sequence, developing hypotheses about the relatedness of organisms, or grouping sequences from closely related organisms. On the surface this seems like a pretty straight-forward problem, not one that would have been at the center of decades of research and the subject of [one of the most cited papers](http://scholar.google.com/citations?view_op=view_citation&hl=en&user=VRccPlQAAAAJ&citation_for_view=VRccPlQAAAAJ:u-x6o8ySG0sC) in modern biology. In this chapter we'll explore why determining sequence similarity is harder than it might initially seem, and learn about *pairwise sequence alignment*, the standard approach for determining sequence similarity.\n\nImagine you have three sequences - call them ``r1``and ``r2`` (*r* is for *reference*) and ``q1`` (*q* is for *query*) - and you want to know whether ``q1`` is more similar to ``r1`` or ``r2``. On the surface, it seems like you could just count the number of positions where they differ (i.e., compute the [Hamming distance](http://en.wikipedia.org/wiki/Hamming_distance) between them) to figure this out. Here's what this would look like.\n\n\n```\n%pylab inline\nfrom __future__ import division, print_function\n\nimport numpy as np\nfrom IPython.core.display import HTML\nfrom IPython.core import page\npage.page = print\n```\n\n\n```\nfrom scipy.spatial.distance import hamming\nfrom skbio import DNA\n\nr1 = DNA(\"ACCCAGGTTAACGGTGACCAGGTACCAGAAGGGTACCAGGTAGGACACACGGGGATTAA\")\nr2 = DNA(\"ACCGAGGTTAACGGTGACCAGGTACCAGAAGGGTACCAGGTAGGAGACACGGCGATTAA\")\nq1 = DNA(\"TTCCAGGTAAACGGTGACCAGGTACCAGTTGCGTTTGTTGTAGGAGACACGGGGACCCA\")\n\n%psource hamming\n```\n\n\n```\nprint(hamming(r1, q1))\nprint(hamming(r2, q1))\n```\n\nIn this case, ``q1`` has a smaller distance to ``r1`` than it does to ``r2``, so ``q1`` is more similar to ``r1`` than ``r2``. But it's not always that simple.\n\nHere we've assumed that only *substitution events* have occurred, meaning one DNA base was substituted with another. Let's define ``q2``, which is the same as ``q1`` except that a single base has been deleted at the beginning of the sequence, and a single base has been inserted at the end of the sequence.\n\n\n```\nq2 = DNA(\"TCCAGGTAAACGGTGACCAGGTACCAGTTGCGTTTGTTGTAGGAGACACGGGGACCCAT\")\nprint(hamming(r1, q2))\n```\n\nThis change had a big effect on the distance between the two sequences. In this case, the deletion event at the beginning of ``q2`` has shifted that sequence relative to ``r1``, which resulted in many of the bases \"downstream\" of the deleted base being different. However the sequences do still seem fairly similar, so perhaps this relatively large distance isn't biologically justified.\n\nWhat we'd really want to do is have a way to indicate that a deletion seems to have occurred in ``q2``. Let's define ``q3``, where we use a ``-`` character to indicate a deletion with respect to ``r1``. This results in what seems like a more reasonable distance between the two sequences:\n\n\n```\nq3 = DNA(\"-TCCAGGTAAACGGTGACCAGGTACCAGTTGCGTTTGTTGTAGGAGACACGGGGACCCA\")\nprint(hamming(r1, q3))\n```\n\nWhat we've done here is create a pairwise alignment of ``r1`` and ``q3``. In other words, we've **aligned** positions to maximize the similarity of the two sequences, using the ``-`` to fill in spaces where one character is missing with respect to the other sequence. We refer to ``-`` characters in aligned sequences as **gap characters**, or gaps.\n\nThe *alignment* of these two sequences is clear if we print them out, one on top of the other:\n\n\n```\nprint(r1)\nprint(q3)\n```\n\nScanning through these two sequences, we can see that they are largely identical, with the exception of one ``-`` character, and about 25% *substitutions* of one base for another.\n\n## [2.1.1](#1) What is a sequence alignment? [edit]\n\n\nLet's take a minute to think about sequence evolution and what a biological sequence alignment actually is. Over the course of biological evolution, a DNA sequence changes, most frequently due to random errors in replication (or the copying of a DNA sequence). These replications errors are referred to as **mutations**. Some types of mutation events that can occur are:\n\n* **substitutions**, where one base (or amino acid, in protein sequences) is replaced with another;\n* **insertions**, where one or more contiguous bases are inserted into a sequence;\n* and **deletions**, where one or more contiguous bases are deleted from a sequence.\n\n(Other types of mutation events can occur, but we're going to focus on these for now.)\n\nFigure 1 illustrates how one ancestral DNA sequence (Figure 1a), over time, might evolve into two derived sequences (Figure 1b). When two or more sequences are derived from a single ancestral sequence, as is the case in this example, those sequences are said to be **homologs** of one another, or homologous sequences. On a piece of paper, make a hypothesis about which of these types of mutation events occurred where over our hypothetical evolution of these sequences.\n\n
    \n \n
    Figure 1: Sequence evolution and pairwise sequence alignment. Abbreviation key: *indel*: insertion or deletion event has occurred since the last common ancestor; *sub*: substitution event has occurred since the last common ancestor; *nc*: no change has occurred since the last common ancestor.
    \n
    \n

    \n\n**The goal of pairwise sequence alignment is, given two sequences, to generate a hypothesis about which sequence positions derived from a common ancestral sequence position.** In practice, we develop this hypothesis by aligning the sequences to one another inserting gaps as necessary, in a way that maximizes their similarity. This is a **maximum parsimony** approach (an application of [Occam's razor](https://en.wikipedia.org/wiki/Occam%27s_razor)), where we assume that the simplest explanation (the one involving the fewest or least extreme mutation events) is the most likely.\n\nIn nearly all cases, the only sequences we have to work with are the modern (derived) sequences, as illustrated in Figure 1c. The ancestral sequence is not something we have access to (for example, because the organism whose genome it was present in went extinct 100 million years ago).\n\nFigure 1d-f illustrates three possible alignments of these two sequences. Just as the notes you made about which types of mutation events may have happened at which positions represents your *hypothesis* about the evolutionary events that took place, a sequence alignment that you might get from a computer program such as BLAST is also only a hypothesis. Which do you think is the most likely alignment of these sequences (note that there may not be a single best answer)?\n\nYou can think of an alignment as a table (Figure 1g), where the rows are sequences and the columns are positions in those sequences. When you have two or more aligned sequences, there will, by definition, always be the same number of columns in each row. Each column in your alignment represents a hypothesis about the evolutionary events that occurred at that position since the last ancestor of the aligned sequences (the sequence in Figure 1a in our example). The specific hypotheses represented by each column in the Figure 1d alignment are explicitly annotated in Figure 1g.\n\nOne thing that's worth pointing out at this point is that because we don't know what the ancestral sequence was, when we encounter a gap in a pairwise alignment, we generally won't know whether a deletion occurred in one sequence, or an insertion occurred in the other. For that reason, you will often see the term **indel** used to refer to these either an insertion or deletion events.\n\nIn the next section we'll work through our first bioinformatics algorithm, in this case a very simple (and also simplistic) method for aligning a pair of sequences. As you work through this exercise, think about why it might be too simple given what you know about biological sequences.\n\n## [2.1.2](#2) A simple procedure for aligning a pair of sequences [edit]\n\n**Table of Contents**\n0. [Step 1: Create a blank matrix where the rows and columns represent the positions in the sequences.](#2.1)\n0. [Step 2: Add values to the cells in the matrix.](#2.2)\n0. [Step 3: Identify the longest diagonals.](#2.3)\n0. [Step 4: Transcribe some of the possible alignments that arise from this process.](#2.4)\n0. [Why this simple procedure is too simplistic](#2.5)\n\n\nLet's define two sequences, ``seq1`` and ``seq2``, and develop an approach for aligning them.\n\n\n```\nseq1 = DNA(\"ACCGGTGGAACCGGTAACACCCAC\")\nseq2 = DNA(\"ACCGGTAACCGGTTAACACCCAC\")\n```\n\nI'm going to use a function in the following cells called ``show_table`` to display a table that we're going to use to develop our alignment. Once a function has been imported, you can view the source code for that function. This will be useful as we begin to explore some of the algorithms that are in use throughout these notebooks. You should spend time reading the source code examples in this book until you're sure that you understand what's happening, especially if your goal is to develop bioinformatics software. Reading other people's code is a good way to improve your own.\n\nHere's how you'd import a function and then view its source code:\n\n\n```\nfrom iab.algorithms import show_F\n```\n\n\n```\n%psource show_F\n```\n\nNow let's look at how to align these sequences.\n\n### [2.1.2.1](#2.1) Step 1: Create a blank matrix where the rows and columns represent the positions in the sequences. [edit]\n\n\nWe'll create this matrix and initialize it with all zeros as follows:\n\n\n```\nnum_rows = len(seq2)\nnum_cols = len(seq1)\ndata = np.zeros(shape=(num_rows, num_cols), dtype=np.int)\n\nHTML(show_F(seq1, seq2, data))\n```\n\n### [2.1.2.2](#2.2) Step 2: Add values to the cells in the matrix. [edit]\n\n\nNext we'll add initial values to the cells so that if the characters at the corresponding row and column are the same, the value of the cell is changed from zero to one. We can then review the resulting matrix. For clarity, we'll have ``show_table`` hide the zero values.\n\n\n```\nfor row_number, row_character in enumerate(seq2):\n for col_number, col_character in enumerate(seq1):\n if row_character == col_character:\n data[row_number, col_number] = 1\n\nHTML(show_F(seq1, seq2, data, hide_zeros=True))\n```\n\n### [2.1.2.3](#2.3) Step 3: Identify the longest diagonals. [edit]\n\n\nNext we'll identify the longest stretches of non-zero characters, which we'll refer to here as the *diagonals*. Diagonals indicate segments of the two sequences that are identical and uninterrupted by mismatched characters (substitution events) or indel events.\n\nWe can identify the longest diagonals as follows:\n\n\n```\n# create a copy of our data matrix to work with, so we\n# leave the original untouched.\nsummed_data = data.copy()\n# iterate over the cells in our data matrix, starting in\n# the second row and second column\nfor i in range(1, summed_data.shape[0]):\n for j in range(1, summed_data.shape[1]):\n # if the value in the current cell is greater than zero\n # (i.e., the characters at the corresponding pair of\n # sequence positions are the same), add the value from the\n # cell that is diagonally up and to the left.\n if summed_data[i, j] > 0:\n summed_data[i, j] += summed_data[i-1][j-1]\n\n# Identify the longest diagonal\nprint(\"The longest diagonal is %d characters long.\" % summed_data.max())\nHTML(show_F(seq1, seq2, summed_data, hide_zeros=True))\n```\n\n### [2.1.2.4](#2.4) Step 4: Transcribe some of the possible alignments that arise from this process. [edit]\n\n\nWe're going to gloss over how to do this algorithmically for the moment, as we'll come back to that in a lot of detail later in this chapter. Briefly, what we want to do is start with the longest diagonal and trace it backwards to transcribe the alignment by writing down the characters from each of the two sequences at every row and column corresponding to the diagonal that you're following. When we encounter a break in the diagonal, we find the next longest diagonal that starts in a cell that is up and/or to the left of the cell when the previous diagonal you were following ends. For every cell that you move straight upwards (non-diagonally), you'd insert a gap in the sequence on the horizontal axis of your matrix. For every cell that you move straight leftwards, you'd insert a gap in the sequence on the vertical axis of your matrix.\n\nWe'd also generally compute a score for an alignment to help us figure out which alignments are better than others. For now, let's add one for every match, and subtract one for every mismatch.\n\nIf this step is confusing, don't worry about it for now. We'll be back to this in a lot more detail soon.\n\nHere are two possible alignments:\n\nAlignment 1 (score: 19)\n```\nACCGGTGGAACCGG-TAACACCCAC\nACCGGT--AACCGGTTAACACCCAC\n```\n\nAlignment 2 (score: 8)\n```\nACCGGTGGAACCGGTAACACCCAC\nACCGGT--------TAACACCCAC\n```\n\nWhy might the first alignment be the more biologically relevant one (meaning the one that is more likely to represent that true evolutionary history of this pair of molecules)? Why might the second be the more biologically relevant one?\n\n**As an exercise**, go back to where we defined `seq1` and `seq2` and re-define one or both of those as other sequences. Execute the code through here and see how the matrices change.\n\n### [2.1.2.5](#2.5) Why this simple procedure is too simplistic [edit]\n\n\nI suggested above that you keep a list of assumptions that are made by this approach. Here are a couple of the very problematic ones.\n\n1. We're scoring all matches as 1 and all mismatches as 0. This suggests that all matches are equally likely, and all mismatches are equally unlikely. What's a more biologically meaningful way to do this (think about protein sequences here)?\n2. Similarly, every gap that is introduced results in the same penalty being incurred. Based on what we know about how insertion/deletion events occur, what do you think is a more biologically meaningful way to do this?\n\nAll scoring schemes have limitations, and you should remember that when you're working with software that generates alignments for you (e.g., systems such as [BLAST](http://blast.ncbi.nlm.nih.gov/Blast.cgi)). Especially as you're getting started in bioinformatics, it's easy to forget that and just accept the result from computer software as \"the right answer\". You'll need to determine if you agree with the result that a computational system gives you, which will involve examining the result in the context of what you know about the biology of the systems your studying. Algorithms such as the one we just explored are there to help you do your work, but they won't do your work for you. Their answers are based on models (for example, how we model matches, mismatches and gaps here) and as you're learning here, the models are not perfect. Be skeptical!\n\nAnother important consideration as we think about algorithms for aligning pairs of sequences is how long an algorithm will take to run as a function of the input it's provided (or in technical terminology, the [computational complexity](http://bigocheatsheet.com/) of the algorithm). When searching a sequence against a database (for example, to get an idea of what its function is), you may have billions of bases to search against, which would correspond to billions of columns in one of the matrices we just computed. Computers are fast, but the data sets you're going to be working with are very large and in many cases growing exponentially in size over time. Working in bioinformatics, it's inevitable that you're going to begin to discover the limitations of the algorithms and software you use. Runtime and memory requirements are the usual culprits. Because the data sets are getting bigger more quickly than computers are getting faster (at least as of this writing), just waiting for computers to get faster won't work. We need smart people who understand some computer science and some biology to design clever algorithms, software, and analytic techniques to enable the next generation of advances that technologies like high-throughput DNA sequencing are promising. (And there are a lot of people who want to spend good money to pay people who can do these things, so keep reading!)\n\nOver the next several sections we'll explore ways of addressing the two issues noted above. We'll introduce the problem of the computational complexity of pairwise sequence alignment at the end of this chapter, and explore approaches for addressing that (i.e., making database searching faster) in the next chapter.\n\n## [2.1.3](#3) Differential scoring of matches and mismatches [edit]\n\n\nWhen aligning nucleotide sequences, using a simple two-value scoring scheme (where all matches are scored with one value and all mismatches with another value) is common, but this approach is overly simplistic for protein sequences. In this section, we're going to switch gears to talking about protein alignment. The most commonly used algorithms are the same for nucleotides and proteins, so most of the ideas that we'll discuss here are general to both. With protein sequences, we're aligning amino acid residues (or *residues*, for short) to one another, instead of nucleotides.\n\nFirst, let's talk about why two-value scoring schemes are too simplistic for protein alignment. In a protein, each amino acid residue is contributing to the structure and/or function of the protein. A given amino acid residue may contribute a charge to an enzyme that helps it to bind its substrate, it may introduce structural stability or instability in a protein, or provide spacing between different functional domains of the protein. Substitutions between amino acids that have similar chemical or physical properties tend to be better tolerated (i.e., less detrimental to the function of the protein) than substitutions between amino acids with different chemical or physical properties. It therefore makes sense to account for the chemical and physical properties of the amino acids being aligned when scoring matches and mismatches.\n\nLet's take the sodium-potassium pump as an example. This molecule is described in the Protein Data Bank's (PDB) *Molecule of the Month* series. Spend a couple of minutes reading about it [here](http://pdb101.rcsb.org/motm/118).\n\n

    \n \n
    Figure 2: Structure of a sodium-potassium pump, as illustrated in the PDB Molecule of the Month series. To learn more about protein structure, a good place to start is the PDB Educational Portal.
    \n
    \n

    \n\nBecause the sodium-potassium pump is a membrane-bound protein, it has regions that are composed of long stretches of polar or charged residues, which facilitate being positioned inside or outside of the cell, and regions that are composed of long stretches of non-polar residues, which facilitate being positioned within the cell membrane. If a mutation occurs in a gene encoding a sodium-potassium pump that substitutes a non-polar residue for another non-polar residue, that will likely be less disruptive to the protein's function than if a polar residue is substituted for a non-polar residue. This is because the non-polar residue is likely to be in the membrane-bound region of the protein (since that's where most of the non-polar residues are in this protein), and polar residues destabilize membrane-bound proteins when they are present within the membrane (a highly non-polar environment). Given this knowledge of amino acids and proteins, when aligning a pair of protein sequences, we probably want to score the alignment of a non-polar residue with a polar residue as less likely than with another non-polar residue.\n\nTo score matches and mismatches differently based on which pair of amino acid residues are being aligned, our alignment algorithm is redefined to incorporate a **substitution matrix**, which defines the score associated with substitution of one amino acid for another. A widely used substitution matrix is referred to as BLOSUM 50. Let's take a look at this matrix:\n\n\n```\nfrom iab.algorithms import blosum50, show_substitution_matrix\naas = list(blosum50.keys())\naas.sort()\ndata = []\nfor aa1 in aas:\n row = []\n for aa2 in aas:\n row.append(blosum50[aa1][aa2])\n data.append(row)\n\naa_labels = ''.join(aas)\nHTML(show_substitution_matrix(aa_labels, data))\n```\n\nLook at the scores in this matrix in the context of details about the biochemistry of the amino acids (see the molecular structures [on Wikipedia](http://en.wikipedia.org/wiki/Amino_acid) or in any general microbiology or biochemistry text). Does a positive score represent a more or less favorable substitution? Confirm that the scores match your intuition for some similar and dissimilar amino acids.\n\nYou can look up individual substitution scores as follows:\n\n\n```\nprint(blosum50['A']['G'])\nprint(blosum50['G']['A'])\n\nprint(blosum50['W']['K'])\n\nprint(blosum50['A']['A'])\nprint(blosum50['W']['W'])\n```\n\nEarly work on defining protein substitution matrices was performed by Margaret Dayhoff in the 1970s (Dayhoff, Schwartz, Orcutt (1978) A Model of Evolutionary Change in Proteins. Atlas of Protein Sequence and Structure) and by [Henikoff and Henikoff](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC50453/) in the early 1990s. Briefly, these matrices are often defined empirically, by aligning sequences manually or through automated systems, and counting how frequent certain substitutions are. [This](https://www.ncbi.nlm.nih.gov/pubmed/15286655) is a good article on the source of the widely used substitution matrices by Sean Eddy. We'll work with BLOSUM 50 here for the remainder of this chapter.\n\n\n## [2.1.4](#4) A better approach for global pairwise alignment using the Needleman-Wunsch algorithm [edit]\n\n**Table of Contents**\n0. [Stepwise Needleman-Wunsch alignment](#4.1)\n 0. [Step 1: Create blank matrices.](#4.1.1)\n 0. [Step 2: Compute $F$ and $T$.](#4.1.2)\n 0. [Step 3: Transcribe the alignment.](#4.1.3)\n0. [Automating Needleman-Wunsch alignment with Python](#4.2)\n0. [A note on computing $F$ and $T$](#4.3)\n\n\nWe're next going to work through the standard algorithm for aligning a pair of biological sequences. This algorithm was originally published by [Saul B. Needleman and Christian D. Wunsch in 1970](https://www.ncbi.nlm.nih.gov/pubmed/5420325), and is therefore referred to as *Needleman-Wunsch alignment*. This performs what is known as *global alignment*, meaning that both sequences are aligned from their first residue (or base) through their last residue (or base). We'll contrast this later in this chapter with local alignment.\n\n### [2.1.4.1](#4.1) Stepwise Needleman-Wunsch alignment [edit]\n\n**Table of Contents**\n0. [Step 1: Create blank matrices.](#4.1.1)\n0. [Step 2: Compute $F$ and $T$.](#4.1.2)\n0. [Step 3: Transcribe the alignment.](#4.1.3)\n\n\nNeedleman-Wunsch alignment is similar to the approach that we explored above. We'll work through the steps of the algorithm first, and then automate the process by defining Python functions that perform the steps for us given a pair of sequences.\n\nWe'll define two protein sequences to work with in this section. After working through this section, come back to this cell and change these protein sequences to explore how it changes the process. Make some small changes and some large changes to the protein sequences. The sequences that we're starting with are the same that are used in Chapter 2 of [Biological Sequence Analysis](http://amzn.to/1IYUEz2).\n\n\n```\nfrom skbio import Protein\nseq1 = Protein(\"HEAGAWGHEE\")\nseq2 = Protein(\"PAWHEAE\")\n```\n\n#### [2.1.4.1.1](#4.1.1) Step 1: Create blank matrices. [edit]\n\n\nAs we discussed earlier in this chapter, a pair of sequences can be aligned in different ways. Needleman-Wunsch provides the best alignment, as defined by its score. Here we'll compute two new matrices that together allow us to determine the highest alignment score given the sequences and the substitution matrix, and to transcribe the aligned sequences. These matrices are\n * the *dynamic programming matrix*, or $F$\n * and the *traceback matrix*, or $T$.\n\n$F$ and $T$ are defined at the same time.\n\n$F$ looks a lot like the matrix we defined in our simplistic example above, but it has one extra row and column, corresponding to the start of each of the sequences (a *state* that is independent of the first residue of the sequences that is important for our algorithm). $F$ keeps track of the best score of the alignment through the corresponding pair of positions, if the alignment were to terminate at that pair of positions.\n\nBecause there are multiple possible alignments that a score in $F$ can be derived from, we use our second matrix, $T$, to track which single alignment led to each score in $F$. $T$ has the same shape (i.e., numbers of rows and columns) as $F$, and its values encode information about how the sequences were aligned to result in the score in the corresponding cell in $F$.\n\nPrior to initialization, $F$ and $T$ would look like the following.\n\n\n```\nnum_rows = len(seq2) + 1\nnum_cols = len(seq1) + 1\nF = np.zeros(shape=(num_rows, num_cols), dtype=np.int)\nHTML(show_F(seq1, seq2, F))\n```\n\n\n```\nfrom iab.algorithms import show_T\n\nT = np.full(shape=(num_rows, num_cols), fill_value=\" \", dtype=np.str)\nHTML(show_T(seq1, seq2, T))\n```\n\n#### [2.1.4.1.2](#4.1.2) Step 2: Compute $F$ and $T$. [edit]\n\n\nThe first row and column of $F$ are initialized using the following formulas. $d$ in these formulas is a value referred to as the *gap penalty*. This is a constant value that is subtracted from the score of the alignment every time a gap character has to be introduced to align the sequences. We'll use a constant value of $d=8$ (it's positive because we subtract it) for now, and explore its use more shortly. $i$ is the row number in $F$, and $j$ is the column number in $F$.\n\n$$\n\\begin{align}\n& F(0, 0) = 0\\\\\n& F(i, 0) = F(i-1, 0) - d\\\\\n& F(0, j) = F(0, j-1) - d\\\\\n\\end{align}\n$$\n\nAs an exercise, try computing the values for the cells in the first four rows in column zero and the first four columns in row zero of $F$. What you'll notice is that the score that you compute for most of the cells (all of them except for $F(0, 0)$) depends on the score at another position in $F$. In a second matrix, $T$, draw an arrow from the cell that you're currently defining the score for in $F$ to the cell whose score it depends on. If the score depends on the cell above, you'd draw an up arrow (↑). If the score depends on the cell to the left, you'd draw a left arrow (←). If the score doesn't depend on any other cell (you should have only one of these), indicate that with a bullet (•).\n\nInitializing $F$ would result in the following.\n\n\n```\nd = 8\nF[0][0] = 0\nfor i in range(1, num_rows):\n F[i][0] = F[i-1][0] - d\n\nfor j in range(1, num_cols):\n F[0][j] = F[0][j-1] - d\n\nHTML(show_F(seq1, seq2, F))\n```\n\nInitializing $T$ would result in the following.\n\n\n```\nT[0][0] = \"•\"\nfor i in range(1, num_rows):\n T[i][0] = \"↑\"\n\nfor j in range(1, num_cols):\n T[0][j] = \"←\"\n\nHTML(show_T(seq1, seq2, T))\n```\n\nNext, we'll compute the scores for all of the other cells in $F$, starting at position $(1, 1)$. In Needleman-Wunsch alignment, the score $F$ for cell $(i, j)$ (when $i > 0$ and $j > 0$) is computed as the maximum of three possible values. $s$ refers to the substitution matrix, and $c_i$ and $c_j$ refer to characters in `seq1` and `seq2`.\n\n$$\nF(i, j) = max \\left(\\begin{align}\n& F(i-1, j-1) + s(c_i, c_j)\\\\\n& F(i-1, j) - d\\\\\n& F(i, j-1) - d\n\\end{align}\\right)\n$$\n\n Describing the scoring function in English, we score a cell with the maximum of three values: either the value of the cell up and to the left plus the score for the substitution taking place in the current cell (which you find by looking up the substitution in the substitution matrix); the value of the cell above minus the gap penalty; or the value of the cell to the left minus the gap penalty. In this way, you're determining whether the best (highest) score is obtained by inserting a gap in sequence 1 (corresponding to $F(i-1, j) - d$), inserting a gap in sequence 2 (corresponding to $F(i, j-1) - d$), or aligning the characters in sequence 1 and sequence 2 (corresponding to $F(i-1, j-1) + s(c_i, c_j)$).\n\nAs an exercise, fill in the values of cells $(1, 1)$, $(1, 2)$, and $(2, 1)$ in $F$ and $T$. Remember to insert arrows in $T$ indicating which cell each score was derived from as you fill in the matrix. If you're deriving the score for a given cell in $F$ from the cell diagonally up and to the left, you should put a diagonal arrow in $T$ (↖).\n\nNotice the situation that you encounter when computing the value for $F(2, 1)$. Which arrow do you draw there? Keep this question in mind, and think about how it might impact your final result.\n\nThe function in the next cell generates the dynamic programming and traceback matrices for us. You should review this code to understand exactly how it's working.\n\n\n```\nfrom iab.algorithms import format_dynamic_programming_matrix, format_traceback_matrix\nfrom skbio.alignment._pairwise import _compute_score_and_traceback_matrices\n\n%psource _compute_score_and_traceback_matrices\n```\n\nYou can now apply this function to `seq1` and `seq2` to compute the dynamic programming and traceback matrices.\n\n\n```\nfrom skbio.sequence import Protein\nfrom skbio.alignment import TabularMSA\n\nseq1 = TabularMSA([seq1])\nseq2 = TabularMSA([seq2])\n\nnw_matrix, traceback_matrix = _compute_score_and_traceback_matrices(\n seq1, seq2, 8, 8, blosum50)\n\nHTML(show_F(seq1[0], seq2[0], nw_matrix))\n```\n\n\n```\nHTML(show_T(seq1[0], seq2[0], traceback_matrix))\n```\n\n#### [2.1.4.1.3](#4.1.3) Step 3: Transcribe the alignment. [edit]\n\n\nWe can now use $F$ and $T$ to transcribe and score the alignment of sequences 1 and 2. To do this, we start at the bottom-right of the matrices and follow the arrows to cell $(0, 0)$.\n\n* Every time we encounter a vertical arrow, we consume a character from sequence 2 (the vertical sequence) and add a gap to sequence 1.\n* Every time we encounter a horizontal arrow, we consume a character from sequence 1 (the horizontal sequence) and add a gap to sequence 2.\n* Every time we encounter a diagonal arrow, we consume a character from sequence 1 and sequence 2.\n* When we encounter a bullet, we've reached the end of the alignment so we're done.\n\nAs you transcribe the alignment, write sequence 1 on top of sequence 2, and work from right to left (since you are working backwards through the matrix).\n\nThe score in the cell that you started in (the bottom-right in this case) is the score for the alignment.\n\nWork through this process on paper, and then review the function in the next cell to see how this looks in Python.\n\n\n```\nfrom skbio.alignment._pairwise import _traceback\n%psource _traceback\n```\n\nYou can then execute this as follows, and print out the resulting alignment. Compare the result that you obtained with the result of calling this function.\n\n\n```\naln1, aln2, score, _, _ = _traceback(traceback_matrix,nw_matrix,seq1,seq2, nw_matrix.shape[0]-1, nw_matrix.shape[1]-1)\n\nprint(aln1[0])\nprint(aln2[0])\nprint(score)\n```\n\n### [2.1.4.2](#4.2) Automating Needleman-Wunsch alignment with Python [edit]\n\n\nCalling the steps we just described is labor-intensive, and they don't change regardless of the protein sequences that we want to align. So, as a bioinformatics software developer, you'd want to make this functionality more easily accessible to users. To do that, you'd define a function that takes all of the necessary input and provides the aligned sequences and the score as output, without requiring the user to make several function calls.\n\nThink for a minute about how you'd define this function. What are the required inputs? What would the function provide as output? What would be a good name for the function? (Naming functions is hard: you want the name to be self-documenting, so users know what the function does, but you also want it to be concise because you and your users will be typing it often.) Write your answers to these questions down. What you're doing here is sketching an *Application Programmer Interface*, or *API* for a function. Defining APIs is a bit of an art and a bit of a science, and there are great APIs and horrible APIs. API definition is hard, and it's something that you get better at with practice. Spending time thinking about APIs is important for developers, as it's how your users will interact with your code. There is a lot of good code out there that no one uses because it has a bad API.\n\nHere's the scikit-bio implementation of Needleman-Wunsch alignment. How is its API different from the interface you sketched out above?\n\n\n```\nfrom skbio.alignment import global_pairwise_align\n%psource global_pairwise_align\n```\n\n\n```\naln, score, _ = global_pairwise_align(Protein(\"HEAGAWGHEE\"), Protein(\"PAWHEAE\"), 8, 8, blosum50, penalize_terminal_gaps=True)\n\nprint(aln)\nprint(score)\n```\n\n### [2.1.4.3](#4.3) A note on computing $F$ and $T$ [edit]\n\n\nSome applications of global alignment use both the alignment score and the aligned sequences, and some only use one or the other. As a result, some applications optimize this process by only keeping track of the information they need. For example, if you're working on a database search algorithm, you might only care about the score of the alignment. In this case you might not need to keep track of $T$, and could reduce the amount of memory that your software requires by not keeping track of it.\n\n## [2.1.5](#5) Global versus local alignment [edit]\n\n\nThe alignment we just constructed is a *global alignment*, meaning we align both sequences from their beginning through their end. This has some important specific applications: for example, if we have two full-length protein sequences, and we have a crystal structure for one of them, we can use global alignment to give us a direct mapping between all positions in both sequences.\n\nThis is in contrast to local alignment, where we have a pair of sequences that we suspect may partially overlap each other, and we want to know what the best possible alignment of all or part of one sequence is with all or part of the other sequences. Perhaps the most widely used application of this is in sequence database searching (e.g., [the BLAST web server](http://blast.ncbi.nlm.nih.gov/Blast.cgi)), where we have a query sequence and we want to find the closest match (or matches) in a reference database containing many different gene sequences. In this case, the whole reference database could be represented as a single sequence, as we could perform a local alignment against it to find the region that contains the highest scoring match.\n\nGlobal and local alignment are both used for different applications. We'll next look at an algorithm for computing local alignments. You'll see that this is very similar to Needleman-Wunsch alignment.\n\n## [2.1.6](#6) Smith-Waterman local sequence alignment [edit]\n\n**Table of Contents**\n0. [Step 1: Create blank matrices.](#6.1)\n0. [Step 2: Compute $F$ and $T$.](#6.2)\n0. [Step 3: Transcribe the alignment.](#6.3)\n0. [Automating Smith-Waterman alignment with Python](#6.4)\n\n\nThe algorithm that is most commonly used for performing local alignment was originally published by [Temple F. Smith and Michael S. Waterman in 1981](https://www.ncbi.nlm.nih.gov/pubmed/7265238), and is therefore referred to as Smith-Waterman alignment. In terms of the resulting alignment, the difference between Smith-Waterman and Needleman-Wunsch is that the aligned sequences in Smith-Waterman can be a subsequence of one or both of the unaligned (input) sequences. In Needleman-Wunsch alignment, the aligned sequences will be full-length with respect to the unaligned sequences.\n\nAlgorithmically, Smith-Waterman is nearly identical to Needleman-Wunsch, with three small important differences. We'll now work through Smith-Waterman alignment following the same steps that we followed for Needleman-Wunsch, and look at the differences as we go. We'll redefine our two sequences to align here. As you did for Needleman-Wunsch, after working through this example with these sequences, come back here and experiment with different sequences.\n\n\n```\nfrom skbio import Protein\nseq1 = Protein(\"HEAGAWGHEE\")\nseq2 = Protein(\"PAWHEAE\")\n```\n\n### [2.1.6.1](#6.1) Step 1: Create blank matrices. [edit]\n\n\n$F$ and $T$ are created in the same way for Smith-Waterman as for Needleman-Wunsch so prior to initialization, $F$ and $T$ would again look like the following.\n\n\n```\nnum_rows = len(seq2) + 1\nnum_cols = len(seq1) + 1\nF = np.zeros(shape=(num_rows, num_cols), dtype=np.int)\nHTML(show_F(seq1, seq2, F))\n```\n\n\n```\nfrom iab.algorithms import show_T\n\nT = np.full(shape=(num_rows, num_cols), fill_value=\" \", dtype=np.str)\nHTML(show_T(seq1, seq2, T))\n```\n\n### [2.1.6.2](#6.2) Step 2: Compute $F$ and $T$. [edit]\n\n\nComputing $F$ and $T$ is slightly different for Smith-Waterman than for Needleman-Wunsch. First, initialization is easier. The following formulas are used for computing the first row and column of $F$.\n\n$$\n\\begin{align}\n& F(0, 0) = 0\\\\\n& F(i, 0) = 0\\\\\n& F(0, j) = 0\n\\end{align}\n$$\n\nInitializing $F$ would therefore result in the following.\n\n\n```\nd = 8\nF[0][0] = 0\nfor i in range(1, num_rows):\n F[i][0] = 0\n\nfor j in range(1, num_cols):\n F[0][j] = 0\n\nHTML(show_F(seq1, seq2, F))\n```\n\nBecause none of the values that were just added to $F$ depend on any other cells in $F$, initializing $T$ would result in the following.\n\n\n```\nT[0][0] = \"•\"\nfor i in range(1, num_rows):\n T[i][0] = \"•\"\n\nfor j in range(1, num_cols):\n T[0][j] = \"•\"\n\nHTML(show_T(seq1, seq2, T))\n```\n\nWe'd next want to compute the remaining cells in $F$ and $T$. This proceeds exactly the same as for Needleman-Wunsch, except that there is one additional term in the scoring function:\n\n$$\nF(i, j) = max \\left(\\begin{align}\n& 0\\\\\n& F(i-1, j-1) + s(c_i, c_j)\\\\\n& F(i-1, j) - d\\\\\n& F(i, j-1) - d)\n\\end{align}\\right)\n$$\n\nGo back to the final $F$ matrix that you computed with Needleman-Wunsch earlier in the chapter. How would this new scoring term change that matrix? As you did before, compute the values for the first few cells of $F$ and $T$, this time using the Smith-Waterman scoring function. Remember that when you add a score to $F$ that does not depend on other cells in $F$ (which in this case corresponds to $0$ being the max value from the scoring function), you should add a bullet (•) to the corresponding cell in $T$.\n\nWe'll use the same function that we used above to compute the full $F$ and $T$ matrices. To indicate that we now want to compute this using Smith-Waterman, we pass some additional parameters.\n\n\n```\nfrom skbio.alignment._pairwise import _init_matrices_sw\nseq1 = TabularMSA([seq1])\nseq2 = TabularMSA([seq2])\n\nsw_matrix, traceback_matrix = _compute_score_and_traceback_matrices(\n seq1, seq2, 8, 8, blosum50, new_alignment_score=0.0,\n init_matrices_f=_init_matrices_sw)\n\nHTML(show_F(seq1[0], seq2[0], sw_matrix))\n```\n\n\n```\nHTML(show_T(seq1[0], seq2[0], traceback_matrix))\n```\n\n### [2.1.6.3](#6.3) Step 3: Transcribe the alignment. [edit]\n\n\nThere is one small difference in the traceback step between Smith-Waterman and Needleman-Wunsch. You should now begin tracing back from the cell with the highest value in $F$, rather than the bottom right cell of the matrix. We find this cell directly in the code below. As before, the alignment terminates when we hit a bullet (•) character, but in contrast to Needleman-Wunsch alignment, this can happen anywhere in the matrix, not only in $F(0, 0)$.\n\n\n```\nmax_value = 0.0\nmax_i = 0\nmax_j = 0\nfor i in range(sw_matrix.shape[0]):\n for j in range(sw_matrix.shape[1]):\n if sw_matrix[i, j] > max_value:\n max_i, max_j = i, j\n max_value = sw_matrix[i, j]\n\naln1, aln2, score, start_a1, start_a2 = _traceback(traceback_matrix, sw_matrix, seq1, seq2, max_i, max_j)\nprint(aln1[0])\nprint(aln2[0])\nprint(score)\n```\n\n### [2.1.6.4](#6.4) Automating Smith-Waterman alignment with Python [edit]\n\n\nAgain, we can define a *convenience function*, which will allow us to provide the required input and just get our aligned sequences back.\n\n\n```\nfrom skbio.alignment import local_pairwise_align\n\n%psource local_pairwise_align\n```\n\nAnd we can take the *convenience function* one step further, and wrap `local_pairwise_align` and `global_pairwise_align` up in a more general `align` function, which takes a boolean parameter (i.e., `True` or `False`) indicating where we want a local or global alignment.\n\n\n```\ndef align(sequence1, sequence2, gap_penalty, substitution_matrix, local):\n if local:\n return local_pairwise_align(sequence1, sequence2, gap_penalty, gap_penalty, substitution_matrix)\n else:\n return global_pairwise_align(sequence1, sequence2, gap_penalty, gap_penalty, substitution_matrix)\n```\n\n\n```\naln, score, _ = align(Protein('HEAGAWGHEE'), Protein('PAWHEAE'), 8, blosum50, True)\n\nprint(aln)\nprint(score)\n```\n\n\n```\naln, score, _ = align(Protein('HEAGAWGHEE'), Protein('PAWHEAE'), 8, blosum50, False)\n\nprint(aln)\nprint(score)\n```\n\nThis was a lot of complicated material, so congratulations on making it this far. If you feel comfortable with everything we just went through, you now understand the basics of pairwise alignment, which is easily the most fundamental algorithm in bioinformatics. If you're not feeling totally comfortable with all of this, go back and re-read it. This time spend more time working out the individual steps with a pencil and paper by computing more cells in $F$ and $T$ as you go, and performing the traceback step manually. And don't get discouraged: we can describe the steps that need to be carried out to a computer with just a few lines of code, so it's nothing magical. Computing a pairwise alignment just involves the systematic application of a few well defined steps. You *will* be able to carry out those steps (a metric of your understanding of the algorithm) as long as you put a bit of effort into performing those steps.\n\n## [2.1.7](#7) Differential scoring of gaps [edit]\n\n\nThe second limitation of the our simple alignment algorithm (which we discussed [way back at the beginning of this chapter](#2.5)), and one that is also present in the versions of Needleman-Wunsch and Smith-Waterman implemented above, is that all gaps are scored equally whether they represent the opening of a new insertion/deletion, or the extension of an existing insertion/deletion. This isn't ideal based on what we know about how insertion/deletion events occur (see [this discussion of replication slippage](http://www.ncbi.nlm.nih.gov/books/NBK21114/) if you're not familiar with the biological process that is thought to lead to small insertions as deletions). Instead, we might want to incur a large penalty for opening a gap, but a smaller penalty for extending an existing gap. This is referred to as *affine gap scoring*.\n\nTo score gap extensions differently from gap creations (or gap opens), we need to modify the terms corresponding to the addition of gaps in our scoring function. When we compute the score corresponding to a gap in our alignment (i.e., where we'd insert either a ↑ or a ← in $T$), we should incur a *gap extension penalty* if the value in $T$ that the new arrow will point to is the same type of arrow. Otherwise, we should incur the *gap open penalty*. If we represent our gap open penalty as $d^0$, and our gap extend penalty as $d^e$, our scoring scheme would look now like the following:\n\n$$\nF(i, j) = max \\left(\\begin{align}\n& 0\\\\\n& F(i-1, j-1) + s(c_i, c_j)\\\\\n& \\left\\{\\begin{array}{l l} F(i-1, j) - d^e \\quad \\text{if $T(i-1, j)$ is ↑}\\\\ F(i-1, j) - d^o \\quad \\text{if $T(i-1, j)$ is not ↑} \\end{array} \\right\\} \\\\\n& \\left\\{\\begin{array}{l l} F(i, j-1) - d^e \\quad \\text{if $T(i, j-1)$ is ←}\\\\ F(i, j-1) - d^o \\quad \\text{if $T(i, j-1)$ is not ←} \\end{array} \\right\\}\n \\end{align}\\right)\n$$\n\nNotice how we only use the gap extend penalty if the previous max score resulted from a gap in the same sequence because it represents the continuation of an existing gap in that sequence. We know which sequence a gap is being introduced in by the characters in the traceback matrix: ↑ always implies a gap in the sequence on the horizontal axis of $F$ and $T$, and ← always implies a gap in the sequence on the vertical axis of $F$ and $T$.\n\nAnd here's a quick quiz: is this a Smith-Waterman or Needleman-Wunsch scoring function? How do you know?\n\nTake a look at how the scores differ with these additions.\n\n\n```\nseq1 = TabularMSA([Protein(\"HEAGAWGHEE\")])\nseq2 = TabularMSA([Protein(\"PAWHEAE\")])\n\nsw_matrix, traceback_matrix = _compute_score_and_traceback_matrices(seq1, seq2, 8, 1, blosum50)\n\nHTML(show_F(seq1[0], seq2[0], sw_matrix))\n```\n\n\n```\nHTML(show_T(seq1[0], seq2[0], traceback_matrix))\n```\n\nWhile we just looked at Smith-Waterman alignment with affine gap scoring, Needleman-Wunsch is adapted in the same way for affine gap scoring.\n\nThe convenience functions we worked with above all take ``gap_open_penalty`` and ``gap_extend_penalty``, which we can see by calling ``help`` on the function. So, we can use those functions to explore sequence alignment with affine gap scoring.\n\n\n```\nhelp(global_pairwise_align)\n```\n\nHere I define `seq1` to be slightly different than what I have above. Notice how we get different alignments when we use affine gap penalties (i.e., ``gap_extend_penalty`` is not equal to ``gap_open_penalty``) versus equal gap open and gap extend penalties.\n\n\n```\nseq1 = TabularMSA([Protein(\"HEAGAWGFHEE\")])\nseq2 = TabularMSA([Protein(\"PAWHEAE\")])\n```\n\n\n```\naln, score, _ = global_pairwise_align(seq1, seq2, 8, 8, blosum50)\nprint(aln)\nprint(score)\n```\n\n\n```\naln, score, _ = global_pairwise_align(seq1, seq2, 8, 1, blosum50)\nprint(aln)\nprint(score)\n```\n\nAs a final exercise in this section, try to adapt the commands above to compute local alignments with affine gap scoring. You won't need to write any code to do this, but rather you can adapt some of the commands that we've already used above. Don't forget about the ``help`` function - that's essential for learning how to use a function.\n\n## [2.1.8](#8) How long does pairwise sequence alignment take? [edit]\n\n**Table of Contents**\n0. [Comparing implementations of Smith-Waterman](#8.1)\n0. [Analyzing Smith-Waterman run time as a function of sequence length](#8.2)\n0. [Conclusions on the scalability of pairwise sequence alignment with Smith-Waterman](#8.3)\n\n\nThe focus of this book is *applied* bioinformatics, and two of the practical considerations we need to think about when developing algorithms and applications is how long they'll take to run, and how much system memory (or RAM) they'll require. Both of these can be limiting factors for applications that require sequence alignments, so a lot of effort is spent understanding how to optimize sequence alignment.\n\nWe just worked through a few algorithms for pairwise sequence alignment, and ran some toy examples based on short sequences. What if we wanted to scale this up to align much longer sequences, or to align relatively short sequences against a large database? In this section we'll explore the runtime of sequence alignment.\n\n### [2.1.8.1](#8.1) Comparing implementations of Smith-Waterman [edit]\n\n\nTo explore runtime, let's use the IPython [magic function](http://ipython.org/ipython-doc/dev/interactive/tutorial.html#magic-functions) called ``timeit``. This allows us to conveniently run a given command many times and reports the average time it takes to run. We'll use this to see how long local alignment takes to run. Note that we don't care about getting the actual alignment back for the moment. We just want the runtime in seconds.\n\nFirst, let's *benchmark* the runtime of the scikit-bio ``local_pairwise_align_nucleotide`` function. This specifically performs nucleotide alignment, and is implemented in Python.\n\n\n```\nfrom skbio.alignment import local_pairwise_align_nucleotide\n\nseq1 = DNA(\"GGTCTTCGCTAGGCTTTCATCGGGTTCGGCATCTACTCTGAGTTACTACG\")\nseq2 = DNA(\"GGTCTTCAGGCTTTCATCGGGAACGGCATCTCTGAGTTACTACC\")\n\n%timeit local_pairwise_align_nucleotide(seq1, seq2, gap_open_penalty=8, gap_extend_penalty=1)\n```\n\nFrom interpreting these results, it looks like this is taking a few seconds to compute the alignment. When executing this, you may see a red warning box pop up. Read that warning message (a good practice, in general!). This is telling us that there is a faster implementation of Smith-Waterman alignment available in scikit-bio, so let's benchmark that one for comparison. We'll use the same two sequences for a direct comparison, of course.\n\n\n```\nfrom skbio.alignment import local_pairwise_align_ssw\n\n%timeit local_pairwise_align_ssw(seq1, seq2)\n```\n\nWe clearly see here that the ``local_pairwise_align_ssw`` function is much faster for performing alignment than ``local_pairwise_align_nucleotide`` (be sure to compare the units of each run time!). This is because ``local_pairwise_align_ssw`` is a much more efficient implementation of Smith-Waterman alignment, and it additionally applies some cool tricks that allow it to not compute all of the values in $F$ and $T$, but still get the right answer most of the time. This is referred to as a *heuristic* approach to optimizing an algorithm. We'll spend some time defining and comparing heuristics in the Database Searching chapter, but to get you to start thinking about it, what you care about is how much a heuristic reduces the run time of an algorithm, and how often it gives you the same answer as the full algorithm. Take a minute to compare the results of the two functions we just ran:\n\n\n```\nmsa, _, _ = local_pairwise_align_nucleotide(seq1, seq2, gap_open_penalty=8, gap_extend_penalty=1)\nmsa\n```\n\n\n```\nmsa, _, _ = local_pairwise_align_ssw(seq1, seq2)\nmsa\n```\n\nHow do the results look?\n\nIf you were truly evaluating a new heuristic, you'd want to compare many different inputs with the heuristic and the full algorithm. For now, just take it from me that ``local_pairwise_align_ssw`` is generally producing comparable results to ``local_pairwise_align_nucleotide``, and you can clearly see that it's running much faster. So, we'll use that implementation in this text when we need to perform fast local alignments.\n\n### [2.1.8.2](#8.2) Analyzing Smith-Waterman run time as a function of sequence length [edit]\n\n\nNext, let's apply this to pairs of sequences where we vary the length. We don't really care what the sequences are here, so we'll use [numpy's ``random`` module](http://docs.scipy.org/doc/numpy/reference/routines.random.html) to get random pairs of sequences.\n\nLet's first define a function to generate a random sequence of a specific length and type of biological sequence. Take a minute to understand that code, as we'll do this a few times throughout the text.\n\n\n```\nimport numpy as np\n\ndef random_sequence(moltype, length):\n result = []\n # Our \"alphabet\" here will consist of the standard characters in a\n # molecules alphabet.\n alphabet = list(moltype.nondegenerate_chars)\n for e in range(length):\n result.append(np.random.choice(alphabet))\n return moltype(''.join(result))\n```\n\nNow let's apply that function a few times. Execute this cell a few times to confirm that the sequences we get back are in fact changing each time.\n\n\n```\nprint(random_sequence(DNA, 10))\nprint(random_sequence(DNA, 10))\nprint(random_sequence(DNA, 25))\nprint(random_sequence(DNA, 50))\n```\n\nNow we'll define a loop where we align random pairs of sequences of increasing length, and compile the time it took to align the sequences. Here we want programmatic access to the runtimes, so we're going to use [Python's ``timeit`` module](https://docs.python.org/3/library/timeit.html) (which the ``%timeit`` magic function is based on).\n\n\n```\nimport timeit\n\ntimes = []\nseq_lengths = range(5000,110000,20000)\n\ndef get_time_function(seq_length):\n def f():\n seq1 = random_sequence(DNA, seq_length)\n seq2 = random_sequence(DNA, seq_length)\n local_pairwise_align_ssw(seq1, seq2)\n return f\n\nfor seq_length in seq_lengths:\n times.append(min(timeit.Timer(get_time_function(seq_length)).repeat(repeat=3, number=3)))\n```\n\nIf we look at the run times, we can see that they are increasing with increasing sequence lengths:\n\n\n```\nimport pandas as pd\nruntimes = pd.DataFrame(data=np.asarray([seq_lengths, times]).T, columns=[\"Sequence length\", \"Runtime (s)\"] )\nruntimes\n```\n\nThat's probably to be expected, but what we care about now is *how* the runtimes are increasing as a function of sequence length. Is the relationship between runtime and sequence length:\n* linear: $runtime \\approx constant \\times sequence\\ length$\n* quadratic: $runtime \\approx constant \\times {sequence\\ length}^2$\n* exponential: $runtime \\approx {constant}^{sequence\\ length}$\n* or something else?\n\nUltimately, we'd like to get an idea of how useful alignment would be in practice if our sequences were much longer, and specifically if sequence length might ultimately make sequence alignment too slow. Plotting these runtimes can help us to figure this out.\n\n\n```\nimport seaborn as sns\nax = sns.regplot(x=\"Sequence length\", y=\"Runtime (s)\", data=runtimes, fit_reg=False)\nax.set_xlim(0)\nax.set_ylim(0)\nax\n```\n\nThis looks to be a [quadratic relationship](http://en.wikipedia.org/wiki/Quadratic_time): the increase in runtime is proportional to the square of sequence length. If you think back to the computation of $F$ and $T$, this makes sense. If our sequences are each five bases long, our matrices will have five rows and five columns, so $5 \\times 5 = 25$ cells that need to be filled in by performing some numeric computations. If we double our sequences lengths to ten, our matrices will have ten rows and ten columns, so $10 \\times 10 = 100$ cells that need to be filled in. Because each of the numeric computations take roughly the same amount of time (you can take that on faith, or prove it to yourself using ``timeit``), when we double our sequence length we have four times as many cells to compute.\n\nWhen runtime scales quadratically, that can be a practical limitation for algorithm. We'd much prefer to see a linear relationship (i.e., if we double our sequence length, our runtime doubles). But this is an inherent issue with pairwise alignment, so it's one that we need to deal with.\n\nOne question you might have is whether developing a version of this algorithm which can run in parallel on multiple processors would be an effective way to make it scale to larger data sets. In the next cell, we look and how the plot would change if we could run the alignment process over four processors.\n\n\n```\n# if we could split this process over more processors (four, for example)\n# that would effectively reduce the runtime by 1/4\nparallel_runtimes = pd.DataFrame(data=np.asarray([seq_lengths, [t/4 for t in times]]).T, columns=[\"Sequence length\", \"Runtime (s)\"] )\nparallel_runtimes\n\nax = sns.regplot(x=\"Sequence length\", y=\"Runtime (s)\", data=parallel_runtimes, fit_reg=False)\nax.set_xlim(0)\nax.set_ylim(0)\nax\n```\n\nNotice that the runtimes in the plot are smaller, but shape of the curve is the same. While parallelization can reduce the runtime of an algorithm, it won't change its *computational complexity* (or how its runtime scales as a function of its input size). You can explore the computational complexity of different types of algorithms in the [Big-O Cheat Sheet](http://bigocheatsheet.com/), though it's a fairly advanced introduction to the topic (and one that's usually covered in the second or third year for Computer Science majors).\n\n### [2.1.8.3](#8.3) Conclusions on the scalability of pairwise sequence alignment with Smith-Waterman [edit]\n\n\nThese are pretty long sequences that we're working with here, and the runtime is still pretty reasonable (only a few seconds for DNA sequences around 100,000 bases), so that suggests this implementation of Smith-Waterman should work ok for aligning pairs of sequences, even if the sequences are fairly long. However, we're often interested in doing more than just pairwise alignment. For example, we may want to align many sequences to each other (which we'll explore in the Multiple Sequence Alignment chapter), or we may want to perform many pairwise alignments (which we'll explore in the Database Searching chapter). In the next chapter we'll begin exploring ways to address this scalability issue by approximating solutions to the problem.\n", "meta": {"hexsha": "f676c8313a3de0e74f98cd56a5c2a2470f16758c", "size": 86353, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IAB-notebooks/2/1.ipynb", "max_stars_repo_name": "gregcaporaso/built-iab-test", "max_stars_repo_head_hexsha": "c203b0a2ad76f6388464d075e3f90c22e3caa2fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IAB-notebooks/2/1.ipynb", "max_issues_repo_name": "gregcaporaso/built-iab-test", "max_issues_repo_head_hexsha": "c203b0a2ad76f6388464d075e3f90c22e3caa2fe", "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": "IAB-notebooks/2/1.ipynb", "max_forks_repo_name": "gregcaporaso/built-iab-test", "max_forks_repo_head_hexsha": "c203b0a2ad76f6388464d075e3f90c22e3caa2fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T18:30:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T18:30:05.000Z", "avg_line_length": 43.7673593512, "max_line_length": 1402, "alphanum_fraction": 0.6543142682, "converted": true, "num_tokens": 16129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.13117323055476698, "lm_q1q2_score": 0.058441548418704005}} {"text": "```python\n#from IPython.core.display import display, HTML\n#display(HTML(\"\"))\n```\n\n\n\n# Kinetic energy of eddy-like features from Sea Surface Altimetry.\n\n### Josué Martínez Moreno, Andy Hogg, Adele Morrison and Andrew Kiss.\n\n# Outline\n\n

      \n
      \n
        \n
      • Introduction
      • \n
      • Motivation
      • \n
      • Methods
      • \n
      • Data
      • \n
      • Results
      • \n
          \n
        • Validation
        • \n
        • Satellite vs Model
        • \n
        • Southern Ocean Trends
        • \n
        • Spatial Distribution
        • \n
        • Eddy Characteristics
        • \n
        \n
      • Discussion
      • \n
      • Future Plan
      • \n
      \n
    \n\n\n\n# Introduction\n
      \n
    • \n
      \n

      \n Mesoscale processes are capable of:\n

        \n
      • mixing
      • \n
      • transport tracers across ocean basins
      • \n
      • redistribute momentum, potential vorticity and energy
      • \n
      \n

      \n (Zhang et al., 2014; Chelton et al., 2007; Wyrtki et al., 1976)\n

      \n

      \n\n
    • \n

      \n They are commonly associated with: \n

      \n \n
      Transient processes included in Mesoscale
      \n
    • \n
    \n\n# Introduction\n
      \n

      \n They are commonly associated with: \n

      \n\n \n
      Transient processes included in Mesoscale
      \n\n \n
    \n\n# Eddy Process\n
    \n\n\n\n# Introduction\n\n

    \n Kinetic Energy has been used to understand temporal and spatial oceanic variability.\n

    \n

    \n (Kang and Curchitser, 2017; White and Heywood, 1995)\n

    \n\n
      \n
    • \n
      \n The kinetic energy (KE) decomposes into the time-mean (MKE), the time-varing (TKE) and second order terms:\n
      \n
      \n
      \n
      \n \\begin{equation}\n \\small\n\t\t\\underbrace{\\overline{u^2 + v^2}}_{KE} = \\underbrace{\\overline{u}^2 + \\overline{v}^2}_{MKE} + \\underbrace{\\overline{u'^2} + \\overline{v'^2}}_{TKE}.\n\t\\end{equation}\n
      \n \n \n
    • \n \n
      Snapshot of Transient Kinetic Energy
      \n
    • \n
    \n\n# Introduction\n\n
      \n
    • \n

      \n Up to 70% of the global TKE is located at:\n

        \n
      • Gulf Stream
      • \n
      • Kuroshio Current
      • \n
      • East Australian current
      • \n
      • Agulhas current
      • \n
      • and portions of the ACC
      • \n
      \n

      \n (Zhang et al., 2014; Chelton et al., 2007; Wyrtki et al., 1976)\n

      \n

      \n\n
    • \n \n
      Transient Kinetic Energy
      \n
    • \n
    \n\n# Introduction\n\n
      \n
    • \n

      \n Up to 70% of the global TKE is located at:\n

        \n
      • Gulf Stream
      • \n
      • Kuroshio Current
      • \n
      • East Australian current
      • \n
      • Agulhas current
      • \n
      • and portions of the ACC
      • \n
      \n

      \n (Zhang et al., 2014; Chelton et al., 2007; Wyrtki et al., 1976)\n

      \n

      \n\n
    • \n \n
      Transient Kinetic Energy
      \n
    • \n
    \n \n \n \n\n\n\n\n# Introduction\n\n
      \n
    • \n

      \n Up to 70% of the global TKE is located at:\n

        \n
      • Gulf Stream
      • \n
      • Kuroshio Current
      • \n
      • East Australian current
      • \n
      • Agulhas current
      • \n
      • and portions of the ACC
      • \n
      \n

      \n (Zhang et al., 2014; Chelton et al., 2007; Wyrtki et al., 1976)\n

      \n

      \n\n
    • \n \n
      Transient Kinetic Energy
      \n
    • \n
    \n \n \n \n\n\n\n\n# Introduction\n\n
      \n
    • \n

      \n Up to 70% of the global TKE is located at:\n

        \n
      • Gulf Stream
      • \n
      • Kuroshio Current
      • \n
      • East Australian current
      • \n
      • Agulhas current
      • \n
      • and portions of the ACC
      • \n
      \n

      \n (Zhang et al., 2014; Chelton et al., 2007; Wyrtki et al., 1976)\n

      \n

      \n\n
    • \n \n
      Transient Kinetic Energy
      \n
    • \n
    \n \n \n \n\n\n\n\n# Introduction\n\n
      \n
    • \n

      \n Up to 70% of the global TKE is located at:\n

        \n
      • Gulf Stream
      • \n
      • Kuroshio Current
      • \n
      • East Australian current
      • \n
      • Agulhas current
      • \n
      • and portions of the ACC
      • \n
      \n

      \n (Zhang et al., 2014; Chelton et al., 2007; Wyrtki et al., 1976)\n

      \n

      \n\n
    • \n \n
      Transient Kinetic Energy
      \n
    • \n
    \n \n \n \n\n\n\n\n# Introduction\n\n\n
      \n
    • \n

      \n Eddies contribute over 30% to the Transient Kinetic Energy field\n

      \n (Chelton et al., 2011)\n

      \n

      \n\n
    • \n \n
    • \n \n
      Transient Kinetic Energy
      \n
    \n\n# Motivation\n \n

    These regions located in the Southern Ocean show a significant increase of TKE anomaly over the last two decades.

    \n

    \n (Hogg et al., 2015)\n

    \n\n\n
    TKE anomaly trend for three Southern Ocean sectors - Modified from Hogg et al. (2015)
    \n\n## How much of the trend is due to each mesoscale process?\n\n\n
    TKE anomaly trend for three Southern Ocean sectors - Modified from Hogg et al. (2015)
    \n\n# Methods\n\n\n## Identification\n\n

    \n TrackEddy algorithm is an eddy tracking-reconstruction field algorithm from SSHa.\n

    \n\n
      \n
    • \n
      \n

      \n How we define an eddy:\n
      \n Assumptions:\n

        \n
      • Outer contour of an eddy is elliptical
      • \n
      • eddy area limited by the 1st baroclinic Rossby radius of deformation
      • \n
      • and eddies can be represented as Gaussians
      • \n
      \n

      \n (Fernandes et al., 2006; Klocker et. al., 2014). \n

      \n

      \n\n
    • \n \n
    • \n
    \n\n#### For more information: [Read The Docs](http://trackeddy.readthedocs.io/en/latest/?badge=latest) or [GitHub](https://github.com/Josue-Martinez-Moreno/trackeddy).\n\n# Methods\n\n## Reconstruction\n\n
      \n
    • \n

      \n

      \n TrackEddy steps:\n

        \n
      1. Identify each eddy like feature in SSH
      2. \n
      3. Fit an optimal Gaussian to each feature
      4. \n
      5. Reconstruct the perturbation field
      6. \n
      7. Calculate geostrophic velocities
      8. \n
      9. Calculate KE
      10. \n
      \n

      \n
    • \n \n
    • \n
    \n\n# Methods\n\n### KE decomposition\n
    \nThe total kinetic energy (KE) decomposes into the time-mean (MKE), the time-varing (TKE) and second order terms:\n\n\n\n

    \n
    \n\\begin{equation}\n \\normalsize\n\t\t\\underbrace{\\overline{u^2 + v^2}}_{KE} = \\underbrace{\\bar{u}^2 + \\bar{v}^2}_{MKE} + \\underbrace{\\overline{u'^2} + \\overline{v'^2}}_{TKE}.\n\\end{equation}\n
    \n
    \n\nWe define the time-varying state as the velocity of each transient process. Therefore TKE is decomposed as:\n\n

    \n
    \n\\begin{equation}\n \\normalsize\n\t\t\\underbrace{u'^2 + v'^2}_{TKE} = \\underbrace{u_{eddy}^2 + v_{eddy}^2}_{TEKE} + \\underbrace{u_{res}^2 + v_{res}^2}_{TRKE} + \\underbrace{2(u_{eddy}u_{res} + v_{eddy}v_{res})}_{TRKE}\n\t\\end{equation}\n
    \n
    \n
    \n\n# Components Magnitude\n
    \n
    \n
    \n
      \n
    • \n\\begin{equation}\n \\normalsize\n\t\t\\underbrace{u_{res}^2 + v_{res}^2}_{TRKE} +\n\t\\end{equation}\n
    • \n
    • \n\\begin{equation}\n \\normalsize\n\t\t\\underbrace{u_{res}^2 + v_{res}^2}_{TRKE} +\n\t\\end{equation}\n
    • \n
    • \n\\begin{equation}\n \\normalsize\n\t\t \\underbrace{2(u_{eddy}u_{res} + v_{eddy}v_{res})}_{TRKE}\n\t\\end{equation}\n
    • \n
    \n
    \n\n\n\n# Components Magnitude & Sign\n
    \n
    \n
    \n
      \n
    • \n\\begin{equation}\n \\normalsize\n\t\t\\underbrace{u_{res}^2 + v_{res}^2}_{TRKE} +\n\t\\end{equation}\n
    • \n
    • \n\\begin{equation}\n \\normalsize\n\t\t\\underbrace{u_{res}^2 + v_{res}^2}_{TRKE} +\n\t\\end{equation}\n
    • \n
    • \n\\begin{equation}\n \\normalsize\n\t\t \\underbrace{2(u_{eddy}u_{res} + v_{eddy}v_{res})}_{TRKE}\n\t\\end{equation}\n
    • \n
    \n
    \n\n\n\n# Components Magnitude Mean\n
    \n
    \n
    \n
      \n
    • \n\\begin{equation}\n \\normalsize\n\t\t\\overline{\\underbrace{u_{res}^2 + v_{res}^2}_{TRKE}} +\n\t\\end{equation}\n
    • \n
    • \n\\begin{equation}\n \\normalsize\n\t\t\\overline{\\underbrace{u_{res}^2 + v_{res}^2}_{TRKE}} +\n\t\\end{equation}\n
    • \n
    • \n\\begin{equation}\n \\normalsize\n\t\t\\overline{\\underbrace{2(u_{eddy}u_{res} + v_{eddy}v_{res})}_{TRKE}}\n\t\\end{equation}\n
    • \n
    \n
    \n\n\n\n# Data\n
      \n
    • \n

      Satellite

      \n \n
    • \n
    • \n

      Access-OM2

      \n \n
    • \n
    \n\n# Data\n
      \n
    • \n

      Satellite

      \n \n
    • \n
    • \n

      Access-OM2

      \n \n
    • \n
    \n\n# Data\n
      \n
    • \n

      Satellite

      \n \n
    • \n
    • \n

      Access-OM2

      \n \n
    • \n
    \n\n# Results\n## Validation\n\n
      \n
    • \n

      No interaction

      \n \n
    • \n
    • \n

      Kinetic energy comparison between control and reconstruction

      \n \n
    • \n
    \n\n# Results\n## Validation\n\n
      \n
    • \n

      Eddy-Eddy Interactions

      \n \n
    • \n
    • \n

      Kinetic energy comparison between control and reconstruction

      \n \n
    • \n
    \n\n# Results\n## Validation\n\n
      \n
    • \n

      Eddy-wave interaction

      \n \n
    • \n
    • \n

      Kinetic energy comparison between control and reconstruction

      \n \n
    • \n
    \n\n# Results\n## Validation\n\n
      \n
    • \n

      Eddy-jet interaction

      \n \n
    • \n
    • \n

      Kinetic energy comparison between control and reconstruction

      \n \n
    • \n
    \n\n# Results\n\n
      \n
    • \n

      Satellite

      \n
    • \n
    • \n

      Access-OM2

      \n
    • \n
    \n\n\n\n
      \n
    • \n

      Satellite

      \n
    • \n
    • \n

      Access-OM2

      \n
    • \n
    \n\n\n\n
      \n
    • \n

      Satellite

      \n
    • \n
    • \n

      Access-OM2

      \n
    • \n
    \n\n\n\n
      \n
    • \n

      Satellite

      \n \n
    • \n
    • \n

      Access-OM2

      \n \n
    • \n
    \n\n# Results\n## Spatial Distribution\n\n\n# Results\n## Southern Ocean Trend\n\n\n\n# Results\n## Eddy Characteristics \n\n\n\n# Discussion\n\n

    \n
      \n
    • Southern Ocean Eddies amplitude has increased in the last to decades!\n
    • \n

      \n
    • TEKE and $Eddy_{amp}$ hotspots share the location with TKE hotspots, horizonal heat transport, $CO^2$ uptake.\n
    • \n

      \n
    • In eddy dominated areas, eddies are responsible of $\\approx$ 50 % of the TKE Trend\n
    • \n

      \n\n
    \n\n# Discussion\n\n

    \n
      \n
    • TrackEddy systematically underestimate the energy contained by the synthetic fields by 12%\n
    • \n

      \n
    • TKE trends are a consequence of winds interacting with Eddies, Jets and Waves.\n
    • \n

      \n
    • The increase on the mean Eddy amplitude over time suggests an accumulation of Available Potential Energy.\n
    • \n

      \n
    \n\n# Future Plan\n## Regional TEKE Analysis\n\n\n\n# Future Plan\n## Heat Transport by Eddies\n\n\n\n\n\n\n### (Top) Daily $SSH_{SOSE}$ standard deviation over the 6 years Southern Ocean State Estimate. (Bottom) Eddy Heat Flux $EHF_{SOSE}$ \n(Foppert, A. et al. 2016.)\n\n# Future Plan\n## Available Potential Energy in Eddies\n\n\n(Luecke, C. et al. 2017)\n\n# Future Plan\n## Available Potential Energy in Eddies\n\n\n\n(Luecke, C. et al. 2017)\n\n# Schedule\n\n\n\n# Thank You!\n\n\n\n# Questions?\n", "meta": {"hexsha": "a0cc83d7249c80b71f7ee0817a71b1fb489fdc42", "size": 33817, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "presentations/Midterm_Review.ipynb", "max_stars_repo_name": "navidcy/josuemtzmo.github.io", "max_stars_repo_head_hexsha": "83b593de35fb8a76225e4f27077dc160a7ed5fc2", "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": "presentations/Midterm_Review.ipynb", "max_issues_repo_name": "navidcy/josuemtzmo.github.io", "max_issues_repo_head_hexsha": "83b593de35fb8a76225e4f27077dc160a7ed5fc2", "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": "presentations/Midterm_Review.ipynb", "max_forks_repo_name": "navidcy/josuemtzmo.github.io", "max_forks_repo_head_hexsha": "83b593de35fb8a76225e4f27077dc160a7ed5fc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5207581227, "max_line_length": 200, "alphanum_fraction": 0.5161309401, "converted": true, "num_tokens": 5102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.1311732152706269, "lm_q1q2_score": 0.058441541609168174}} {"text": "# Learning of constraints\n\n\n## Objective\nThis notebook contains a very simple example showing how to train a feedforward neural network to learn how to explain its predictions.\n\n\n## Outline\n- [Objective](#Objective)\n- [Problem description](#Problem-description)\n - [The course of the black box](#The-course-of-the-black-box)\n - [How to train like an adult](#How-to-train-like-an-adult)\n - [Learning of constraints](#Learning-of-constraints)\n - [Multi-label classification](#Multi-label-classification)\n- [Libraries](#Libraries)\n- [Dataset](#Dataset)\n- [Learning concepts](#Learning-concepts)\n- [**Explaining concepts**](#Explaining-concepts)\n- [References](#References)\n\n\n## Problem description\n\n\n### The course of the black box\n**Humans don't like black boxes**. We all (*humans*) suffer of incredulity. This cognitive bias prevents us from relying upon something we don't understand. In finding the trade-off between complexity and accuracy, we are often biased towards simple solutions. That's why we (*humans*) don't like deep learning. It's the Occam's razor revenge. Machine learning researchers are usually worried about the course of the dimensionality. But we actually need to realize that one of the main issues that is limiting deep learning applications is being a black box. The [universal approximation theorem](https://en.wikipedia.org/wiki/Universal_approximation_theorem) has coursed neural networks. **It's the course of the black box**. \n\nWhat is the actual issue here? Are neural networks intrinsically coursed? They are just optimizers with a scandalous number of parameters after all. How could we interpret a nonlinear decision function with millions of parameters? Well, in some sense we are doing it every single day, don't we? Human decisions and reasoning are a function of our brain and mind. Would this function have less parameters than an *artificial neural network*? I don't think so. So, what's the difference? Why do we trust our grannies but not our deep learning models? I think the main difference here is that our grannies can **explain** themselves. They can provide us a step-by-step explanation, *a logical reasoning*$^1$ that can help us understand what they are saying. Our nets don't do that... Nay, we dind't ask them! But how could we? \n\nLet's step back a little. Let's define what we *really* want to ask them (our nets, not our grannies).\n\n$^1$: it depends on your granny...\n\n### How to train like an adult\nSo, what do we *really* want? I think the problem is that we are training our networks like a child. So now we get answers as from a child. Would you blame your child because his/her answers are not logically sound? That would be ridiculous if not inappropriate. We need a paradigm shift. **Instead of training our net like a child, why don't train it like an adult?** What's the difference? We need to teach them logic. So, let's start with defining what kind of logic we need them to learn about.\n\nIn most cases, researchers might be interested in scientific interpretability. One way of thinking about scientific interpretability is in terms of logic. **A (*scientific*) argument is interpretable from a human standpoint, if it can be described by a limited set of concepts linked by logical rules**. A simple example is the syllogism:\n\n> All men are mortal.\n> \n> Socrates is a man.\n>\n> Therefore, Socrates is mortal.\n\nSo now our problem is: **how to make a neural network learn how to explain its predictions logically**?\n\n\n\n### Learning of constraints\nWe can divide the problem into **3 steps**.\n\n**First**, we need to teach our neural network basic concepts. How? As usual, just pick a problem and train your network (let's call it $N1$). We are now in the so called \"concept space\". For instance, the \"perceptual space\" of MNIST is an image of a digit, while the \"concept space\" is the \"label\" of that image, the digit, the abstract concept represented by the image. We, *humans*, tend to reason in this \"concept space\" rather than in our perceptual space. That's what we want from our net! So...\n\n**Second**, we need to teach our network the logical relationships between concepts. How? One option is to use (by an ironic twist of fate) another neural network! Let me give you a simple example. Let's say we have trained our network $N1$ to recognize the following concepts: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, even, and odd. Let's say we are interested in understanding interpreting the prediction \"even\". In other words, we want to understand how our network is interpreting the concept \"even\" with respect to the other concepts. The idea is to train another neural network $N2$ taking as inputs the predictions of the network $N1$ and having just one output representing the concept \"even\". So now we have a neural network ($N2$) learning the concept \"even\" using the concepts: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and odd (we need to drop \"even\" as we might have ended up with a tautology!).\n\n**Third**, we need to ask our network for a logical explanation. How? That's the fun part. We are going to generate the **truth table** of the network $N2$, representing its logical reasoning. Let's do it step by step:\n1. generate an artificial dataset in the concept space representing **all possible combinations of truth values taken by each concept**. To make it easier, we will assume that each concept can just take 2 truth values: TRUE and FALSE.\n2. feed the network $N2$ with this table.\n3. The output of the network will represent the truth degree of each combination of concepts.\n\nFor instance, let's take the combination:\n\n| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | odd |\n|-|-|-|-|-|-|-|-|-|-|-|\n| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |\n\nIf for this input the network predicts \"even\" with probability $\\approx 0$, we might have just discovered something new! That is: \"odd\" $\\implies$ not \"even\". That's a new concept!\n\nLet's take another input:\n\n| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | odd |\n|-|-|-|-|-|-|-|-|-|-|-|\n| 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |\n\nIf for this input the network predicts \"even\" with probability $\\approx 1$, we might have just discovered something new again! That is: \"two\" $\\implies$ \"even\". That's another new concept!\n\nSo now we have a very simple way of interrogating our deep learning model! We can ask for explanations and we can extract general logical rules representing its decisions.\n\n\n\n### Multi-label classification\nIn order to show a concrete example, in this notebook we consider a generic [**multi-label classification problem**](https://en.wikipedia.org/wiki/Multi-label_classification), that is a learning problem where each input example belongs to one or more classes. \n\nWe focus on **neural network-based** methods, that implicitly learn from supervisions.\n\nMore formally, we consider data belonging to the **perceptual space** $x \\in \\mathbb{R}^d$. Each sample $x$ is also associated with a boolean vector $y \\in \\mathbb{R}^n$. For any $x$, $y_i \\in \\{0, 1\\}$ represents the membership degree of the example $x$ to the $i$-th class.\n\nWe consider a multi-output feedforward neural network classifier. Each output unit is associated to a **task function** $f_i: \\mathbb{R}^d \\rightarrow [0,1]$, for $i=1,...,n$, that predicts how strongly an input example belongs to the considered class. For any $x \\in X$, $\\hat{y}_i = f_i(x) \\in [0, 1]$ represents the *predicted* membership degree of the example $x$ to the $i$-th class. We indicate with $f(x)$ the function that returns the $n$-dimensional vector $\\hat{y} \\in \\mathbb{R}^n$ with the outputs of all the task functions. Such vector belongs to the so-called **concept space**.\n\n\n\nThis is the \"standard network\" learning basic concepts. Let's now consider another network $\\psi_h: \\mathbb{R}^{n-1} \\rightarrow [0,1]$ whose input domain is the concept space (except for the target concept) and whose output represents the truth degree of the concept we want to explain.\n\n\n\nLet's now dive into the code...\n\n## Libraries\nFirst we need to import some useful libraries:\n\n\n```python\nimport torch\nimport numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.preprocessing import OneHotEncoder\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom itertools import product\nimport pandas as pd\n```\n\n## Dataset\n\nIn this notebook we will use a simplified version of the MNIST dataset called DIGITS. Each sample $x_i$ is an $8 \\times 8$-pixels' handritten image representing a digit, while the supervision $y_i$ represents its numeric value.\n\nWe can first load the dataset and have a look at some of his properties:\n\n\n```python\nX, y = load_digits(return_X_y=True)\n\nprint(f'X shape: {X.shape}\\nClasses: {np.unique(y)}')\n```\n\n X shape: (1797, 64)\n Classes: [0 1 2 3 4 5 6 7 8 9]\n\n\nAs you can see, the images are flattened in a $64$-length vector, but we can easily visualize samples by reshaping the input:\n\n\n```python\n# show the first ten images\nfigs = X[:10].reshape((10, 8, 8))\nplt.figure(figsize=[7, 7])\nfor i, fig in enumerate(figs):\n plt.subplot(5, 5, i+1)\n plt.title(f'Class: {y[i]}')\n sns.heatmap(fig, cbar=False)\n plt.axis('off')\nplt.tight_layout()\nplt.show()\n```\n\nAs we are framing our problem as a multi-task classification problem, we need to encode our supervisions in a one-hot representation:\n\n\n```python\nenc = OneHotEncoder()\ny1h = enc.fit_transform(y.reshape(-1, 1)).toarray()\n\nprint(f'Before: {y.shape}\\nAfter: {y1h.shape}')\n```\n\n Before: (1797,)\n After: (1797, 10)\n\n\nTo make it more fun, we will add two additional task functions: ODD (11-th column) and EVEN (12-th column).\n\n\n```python\ny2 = np.zeros((len(y), 2))\nfor i, yi in enumerate(y):\n if yi % 2:\n y2[i, 0] = 1\n else:\n y2[i, 1] = 1\ny1h2 = np.hstack((y1h, y2))\n\nprint(f'Target vector shape: {y1h2.shape}')\nfor i in range(10):\n print(f'Example ({y[i]}): {y1h2[i]}')\n```\n\n Target vector shape: (1797, 12)\n Example (0): [1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n Example (1): [0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]\n Example (2): [0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n Example (3): [0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 1. 0.]\n Example (4): [0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 1.]\n Example (5): [0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0.]\n Example (6): [0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1.]\n Example (7): [0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0.]\n Example (8): [0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1.]\n Example (9): [0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0.]\n\n\nWe are now ready to split our dataset into a training and a test set:\n\n\n```python\nX_train_np, X_test_np, y_train_np, y_test_np = train_test_split(X, y1h2, test_size=0.33, random_state=42)\n```\n\nFinally, we need to transoform our data into torch tensors to be processed by the network:\n\n\n```python\nx_train = torch.FloatTensor(X_train_np)\ny_train = torch.FloatTensor(y_train_np)\nx_test = torch.FloatTensor(X_test_np)\ny_test = torch.FloatTensor(y_test_np)\n```\n\n## Learning concepts\nWe will use a very simple (and quite standard) feedforward neural network with three layers, ReLU activations, and $12$ output units (one for each task function) with sigmoid activations. We are not using softmax as in our problem more than one predicate on the task function can be true at the same time (e.g. $isTwo(x)$ and $isEven(x)$ should be true at the same time).\n\n\n```python\nclass FeedForwardNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(FeedForwardNet, self).__init__()\n self.linear1 = torch.nn.Linear(D_in, H)\n self.linear2 = torch.nn.Linear(H, H)\n self.linear3 = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Tensors.\n \"\"\"\n h = self.linear1(x)\n h = torch.nn.functional.relu(h)\n h = self.linear2(h)\n h = torch.nn.functional.relu(h)\n h = self.linear3(h)\n y_pred = torch.sigmoid(h)\n return y_pred\n```\n\nWe can now generate an instance of the network:\n\n\n```python\ndin, dh, dout = x_train.shape[1], 20, y_train.shape[1]\nmodel = FeedForwardNet(din, dh, dout)\n\nprint(model)\n```\n\n FeedForwardNet(\n (linear1): Linear(in_features=64, out_features=20, bias=True)\n (linear2): Linear(in_features=20, out_features=20, bias=True)\n (linear3): Linear(in_features=20, out_features=12, bias=True)\n )\n\n\nThe train loop is quite standard:\n\n\n```python\nloss = torch.nn.BCELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01)\nmodel.train()\nepoch = 2000\nfor epoch in range(epoch):\n optimizer.zero_grad()\n\n # Forward pass\n y_pred = model(x_train)\n y_pred_np = y_pred.detach().numpy()\n\n # Compute Loss\n tot_loss = loss(y_pred, y_train)\n\n # compute accuracy\n y_pred_d = (y_pred > 0.5).detach().numpy()\n accuracy = ((y_pred_d == y_train_np).sum(axis=1) == y_train_np.shape[1]).mean()\n \n if epoch % 100 == 0:\n print(f'Epoch {epoch + 1}: '\n f'total loss: {tot_loss.item():.4f} '\n f'| accuracy: {accuracy:.4f} ')\n\n # Backward pass\n tot_loss.backward()\n optimizer.step()\n```\n\n Epoch 1: total loss: 0.8232 | accuracy: 0.0000 \n Epoch 101: total loss: 0.0236 | accuracy: 0.9327 \n Epoch 201: total loss: 0.0050 | accuracy: 0.9958 \n Epoch 301: total loss: 0.0017 | accuracy: 1.0000 \n Epoch 401: total loss: 0.0008 | accuracy: 1.0000 \n Epoch 501: total loss: 0.0004 | accuracy: 1.0000 \n Epoch 601: total loss: 0.0003 | accuracy: 1.0000 \n Epoch 701: total loss: 0.0002 | accuracy: 1.0000 \n Epoch 801: total loss: 0.0001 | accuracy: 1.0000 \n Epoch 901: total loss: 0.0001 | accuracy: 1.0000 \n Epoch 1001: total loss: 0.0001 | accuracy: 1.0000 \n Epoch 1101: total loss: 0.0001 | accuracy: 1.0000 \n Epoch 1201: total loss: 0.0001 | accuracy: 1.0000 \n Epoch 1301: total loss: 0.0000 | accuracy: 1.0000 \n Epoch 1401: total loss: 0.0000 | accuracy: 1.0000 \n Epoch 1501: total loss: 0.0000 | accuracy: 1.0000 \n Epoch 1601: total loss: 0.0000 | accuracy: 1.0000 \n Epoch 1701: total loss: 0.0000 | accuracy: 1.0000 \n Epoch 1801: total loss: 0.0000 | accuracy: 1.0000 \n Epoch 1901: total loss: 0.0000 | accuracy: 1.0000 \n\n\nOnce the network is trained we can compute the test accuracy:\n\n\n```python\ny_pred = model(x_test)\n\n# compute accuracy\ny_pred_round = (y_pred > 0.5).to(torch.float).detach().numpy()\naccuracy = ((y_pred_round == y_test_np).sum(axis=1) == y_test_np.shape[1]).mean()\n\nprint(f'accuracy: {accuracy:.4f}')\n```\n\n accuracy: 0.8973\n\n\n## Explaining concepts\nLet's now focus on the concept \"even\". Our objective is to find an explanation for \"even\" predictions. What \"even\" means in terms of the other task functions?\n\nLet's first define the $\\psi$ function as a one-layer feedforward neural network with $n-1$ input (one for each task function except for $f_{even}$) and one output representing the truth degree of the concept \"even\".\n\n\n```python\nclass ExplainEven(torch.nn.Module):\n def __init__(self, D_in):\n \"\"\"\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(ExplainEven, self).__init__()\n self.linear1 = torch.nn.Linear(D_in, 10)\n self.linear2 = torch.nn.Linear(10, 1)\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Tensors.\n \"\"\"\n h = self.linear1(x)\n h = self.linear2(h)\n y_pred = torch.sigmoid(h)\n return y_pred\n```\n\nWe can now generate the training set for this network. It is just the discretized output of the previous network:\n\n\n```python\ny_pred_train = model(x_train).detach().numpy().astype(float)\ny_pred_test = model(x_test).detach().numpy().astype(float)\n\nx_concepts_train_np, y_concepts_train_np = y_pred_train[:, :-1], y_pred_train[:, -1]\nx_concepts_test_np, y_concepts_test_np = y_pred_test[:, :-1], y_pred_test[:, -1]\n\nx_concepts_train, y_concepts_train = torch.FloatTensor(x_concepts_train_np), torch.FloatTensor(y_concepts_train_np)\nx_concepts_test, y_concepts_test = torch.FloatTensor(x_concepts_test_np), torch.FloatTensor(y_concepts_test_np)\n```\n\nWe are now ready to train our ExplainNet:\n\n\n```python\nD_in = y_pred_train.shape[1] - 1\neven_net = ExplainEven(D_in)\nprint(even_net)\n\noptimizer = torch.optim.Adam(even_net.parameters(), lr=0.01)\neven_net.train()\nepoch = 500\naccuracy = 0\nfor epoch in range(epoch):\n optimizer.zero_grad()\n # Forward pass\n y_pred = even_net(x_concepts_train)\n y_pred_np = y_pred.detach().numpy()\n\n # Compute Loss\n tot_loss = loss(y_pred.squeeze(), y_concepts_train) + 0.08 * even_net.linear1.weight.norm(1) * even_net.linear2.weight.norm(1)\n\n # compute accuracy\n y_pred_d = (y_pred > 0.5).detach().numpy().ravel()\n accuracy = (y_pred_d == (y_concepts_train_np>0.5)).mean()\n \n if epoch % 100 == 0:\n print(f'Epoch {epoch + 1}: '\n f'total loss: {tot_loss.item():.4f} '\n f'| accuracy: {accuracy:.4f} ')\n\n # Backward pass\n tot_loss.backward()\n optimizer.step()\n```\n\n ExplainEven(\n (linear1): Linear(in_features=11, out_features=10, bias=True)\n (linear2): Linear(in_features=10, out_features=1, bias=True)\n )\n Epoch 1: total loss: 2.5795 | accuracy: 0.5079 \n Epoch 101: total loss: 0.6931 | accuracy: 0.5079 \n Epoch 201: total loss: 0.6922 | accuracy: 0.5079 \n Epoch 301: total loss: 0.6710 | accuracy: 1.0000 \n Epoch 401: total loss: 0.4969 | accuracy: 1.0000 \n\n\n## Rule extraction\nLet's now find out how can we extract logical rules.\n\nLets just focus on a subset of weights (the ones representing strongest connections among concepts):\n\n\n```python\nweights, bias = [], []\nfor i, param in enumerate(even_net.parameters()):\n if i % 2 == 0:\n param_absneg = -torch.abs(param)\n idx = torch.topk(param_absneg, k=param_absneg.shape[1]-2)[1]\n for i in range(len(idx)):\n param[i, idx[i]] = 0\n param\n weights.append(param.detach().numpy())\n else:\n bias.append(param.detach().numpy())\n```\n\n\n```python\nbias\n```\n\n\n\n\n [array([ 0.3989522 , 0.13632365, -0.40638036, -0.03830609, -0.35561085,\n 0.05306427, 0.07716022, 0.04836779, -1.0059371 , 0.41719967],\n dtype=float32),\n array([0.47904056], dtype=float32)]\n\n\n\n\n```python\nfor i in even_net.parameters():\n print(i)\n```\n\n Parameter containing:\n tensor([[ 3.3663e-03, 0.0000e+00, 0.0000e+00, 2.7577e-03, 0.0000e+00,\n 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00],\n [ 0.0000e+00, 0.0000e+00, 0.0000e+00, -5.2165e-03, 0.0000e+00,\n 0.0000e+00, 0.0000e+00, -5.2380e-03, 0.0000e+00, 0.0000e+00,\n 0.0000e+00],\n [-3.3996e-03, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, -3.0479e-03,\n 0.0000e+00],\n [ 0.0000e+00, 3.5091e-03, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00, 3.0491e-03, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00],\n [-7.1541e-03, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 4.0887e-03],\n [ 0.0000e+00, 5.4402e-03, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 5.2893e-03, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00],\n [ 0.0000e+00, 0.0000e+00, -3.5255e-03, 0.0000e+00, 0.0000e+00,\n 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 3.4183e-03,\n 0.0000e+00],\n [ 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 5.4572e-03,\n 4.0927e-03],\n [ 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n 0.0000e+00, 0.0000e+00, 0.0000e+00, -5.5383e-03, 0.0000e+00,\n 2.8439e+00],\n [ 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, -5.1365e-03,\n 0.0000e+00, 0.0000e+00, -2.9250e-03, 0.0000e+00, 0.0000e+00,\n 0.0000e+00]], grad_fn=)\n Parameter containing:\n tensor([ 0.3990, 0.1363, -0.4064, -0.0383, -0.3556, 0.0531, 0.0772, 0.0484,\n -1.0059, 0.4172], requires_grad=True)\n Parameter containing:\n tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, -0.0032, 0.0000,\n -1.1097, 0.0000]], grad_fn=)\n Parameter containing:\n tensor([0.4790], requires_grad=True)\n\n\nNow let's use the corresponding concepts to extract the rules:\n\n\n```python\nfrom intoCNF import booleanConstraint\nf = booleanConstraint(weights,bias)\nf\n```\n\nFor very complex rules, we can use sympy to get more simple formulas:\n\n\n```python\nfrom sympy.logic import simplify_logic\nsf = simplify_logic(f[0])\nsf\n```\n\nNow recall that the 11th concept was represented by $isOdd$.\n\nNice! We have just learnt that our black box has learnt a very interesting concept: $\\neg isOdd(x) \\implies isEven(x)$!\n\nThat's all folks!\n\n## References\n\nGori, M. (2017). Machine Learning: A constraint-based approach. Morgan Kaufmann.\n\nMarra, G., Giannini, F., Diligenti, M., & Gori, M. (2019). Lyrics: a general interface layer to integrate ai and deep learning. arXiv preprint arXiv:1903.07534.\n\nCiravegna, G., Giannini, F., Gori, M., Maggini, M., & Melacci, S. Human-Driven FOL Explanations of Deep Learning. In 29th International Joint Conference on Artificial Intelligence (pp. 2234-2240).\n", "meta": {"hexsha": "660473f4f9c047a078c078ded8c8579c13e9fd4e", "size": 354368, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/learning_of_constraints_digits.ipynb", "max_stars_repo_name": "pietrobarbiero/constraint-learning", "max_stars_repo_head_hexsha": "178f6c4029dbf4120cc63e81f389309b44753e92", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-04T09:13:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-22T05:07:20.000Z", "max_issues_repo_path": "notebooks/learning_of_constraints_digits.ipynb", "max_issues_repo_name": "pietrobarbiero/constraint-learning", "max_issues_repo_head_hexsha": "178f6c4029dbf4120cc63e81f389309b44753e92", "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/learning_of_constraints_digits.ipynb", "max_forks_repo_name": "pietrobarbiero/constraint-learning", "max_forks_repo_head_hexsha": "178f6c4029dbf4120cc63e81f389309b44753e92", "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": 391.5668508287, "max_line_length": 206700, "alphanum_fraction": 0.9158135046, "converted": true, "num_tokens": 6960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.12252321732428781, "lm_q1q2_score": 0.05791470033156521}} {"text": "Probabilistic Programming and Bayesian Methods for Hackers \n========\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n#### Looking for a printed version of Bayesian Methods for Hackers?\n\n_Bayesian Methods for Hackers_ is now a published book by Addison-Wesley, available on [Amazon](http://www.amazon.com/Bayesian-Methods-Hackers-Probabilistic-Addison-Wesley/dp/0133902838)! \n\n\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assumes that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\nhelp(stats.beta)\n```\n\n Help on beta_gen in module scipy.stats._continuous_distns object:\n \n class beta_gen(scipy.stats._distn_infrastructure.rv_continuous)\n | A beta continuous random variable.\n | \n | %(before_notes)s\n | \n | Notes\n | -----\n | The probability density function for `beta` is:\n | \n | .. math::\n | \n | f(x, a, b) = \\frac{\\Gamma(a+b) x^{a-1} (1-x)^{b-1}}\n | {\\Gamma(a) \\Gamma(b)}\n | \n | for :math:`0 <= x <= 1`, :math:`a > 0`, :math:`b > 0`, where\n | :math:`\\Gamma` is the gamma function (`scipy.special.gamma`).\n | \n | `beta` takes :math:`a` and :math:`b` as shape parameters.\n | \n | %(after_notes)s\n | \n | %(example)s\n | \n | Method resolution order:\n | beta_gen\n | scipy.stats._distn_infrastructure.rv_continuous\n | scipy.stats._distn_infrastructure.rv_generic\n | builtins.object\n | \n | Methods defined here:\n | \n | fit(self, data, *args, **kwds)\n | Return MLEs for shape (if applicable), location, and scale\n | parameters from data.\n | \n | MLE stands for Maximum Likelihood Estimate. Starting estimates for\n | the fit are given by input arguments; for any arguments not provided\n | with starting estimates, ``self._fitstart(data)`` is called to generate\n | such.\n | \n | One can hold some parameters fixed to specific values by passing in\n | keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)\n | and ``floc`` and ``fscale`` (for location and scale parameters,\n | respectively).\n | \n | Parameters\n | ----------\n | data : array_like\n | Data to use in calculating the MLEs.\n | args : floats, optional\n | Starting value(s) for any shape-characterizing arguments (those not\n | provided will be determined by a call to ``_fitstart(data)``).\n | No default value.\n | kwds : floats, optional\n | Starting values for the location and scale parameters; no default.\n | Special keyword arguments are recognized as holding certain\n | parameters fixed:\n | \n | - f0...fn : hold respective shape parameters fixed.\n | Alternatively, shape parameters to fix can be specified by name.\n | For example, if ``self.shapes == \"a, b\"``, ``fa``and ``fix_a``\n | are equivalent to ``f0``, and ``fb`` and ``fix_b`` are\n | equivalent to ``f1``.\n | \n | - floc : hold location parameter fixed to specified value.\n | \n | - fscale : hold scale parameter fixed to specified value.\n | \n | - optimizer : The optimizer to use. The optimizer must take ``func``,\n | and starting position as the first two arguments,\n | plus ``args`` (for extra arguments to pass to the\n | function to be optimized) and ``disp=0`` to suppress\n | output as keyword arguments.\n | \n | Returns\n | -------\n | mle_tuple : tuple of floats\n | MLEs for any shape parameters (if applicable), followed by those\n | for location and scale. For most random variables, shape statistics\n | will be returned, but there are exceptions (e.g. ``norm``).\n | \n | Notes\n | -----\n | This fit is computed by maximizing a log-likelihood function, with\n | penalty applied for samples outside of range of the distribution. The\n | returned answer is not guaranteed to be the globally optimal MLE, it\n | may only be locally optimal, or the optimization may fail altogether.\n | If the data contain any of np.nan, np.inf, or -np.inf, the fit routine\n | will throw a RuntimeError.\n | \n | In the special case where both `floc` and `fscale` are given, a\n | `ValueError` is raised if any value `x` in `data` does not satisfy\n | `floc < x < floc + fscale`.\n | \n | Examples\n | --------\n | \n | Generate some data to fit: draw random variates from the `beta`\n | distribution\n | \n | >>> from scipy.stats import beta\n | >>> a, b = 1., 2.\n | >>> x = beta.rvs(a, b, size=1000)\n | \n | Now we can fit all four parameters (``a``, ``b``, ``loc`` and ``scale``):\n | \n | >>> a1, b1, loc1, scale1 = beta.fit(x)\n | \n | We can also use some prior knowledge about the dataset: let's keep\n | ``loc`` and ``scale`` fixed:\n | \n | >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)\n | >>> loc1, scale1\n | (0, 1)\n | \n | We can also keep shape parameters fixed by using ``f``-keywords. To\n | keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,\n | equivalently, ``fa=1``:\n | \n | >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)\n | >>> a1\n | 1\n | \n | Not all distributions return estimates for the shape parameters.\n | ``norm`` for example just returns estimates for location and scale:\n | \n | >>> from scipy.stats import norm\n | >>> x = norm.rvs(a, b, size=1000, random_state=123)\n | >>> loc1, scale1 = norm.fit(x)\n | >>> loc1, scale1\n | (0.92087172783841631, 2.0015750750324668)\n | \n | ----------------------------------------------------------------------\n | Methods inherited from scipy.stats._distn_infrastructure.rv_continuous:\n | \n | __init__(self, momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None)\n | Initialize self. See help(type(self)) for accurate signature.\n | \n | cdf(self, x, *args, **kwds)\n | Cumulative distribution function of the given RV.\n | \n | Parameters\n | ----------\n | x : array_like\n | quantiles\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | cdf : ndarray\n | Cumulative distribution function evaluated at `x`\n | \n | expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)\n | Calculate expected value of a function with respect to the\n | distribution by numerical integration.\n | \n | The expected value of a function ``f(x)`` with respect to a\n | distribution ``dist`` is defined as::\n | \n | ub\n | E[f(x)] = Integral(f(x) * dist.pdf(x)),\n | lb\n | \n | where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)``\n | distribution. If the bounds ``lb`` and ``ub`` correspond to the\n | support of the distribution, e.g. ``[-inf, inf]`` in the default\n | case, then the integral is the unrestricted expectation of ``f(x)``.\n | Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0``\n | outside a finite interval in which case the expectation is\n | calculated within the finite range ``[lb, ub]``.\n | \n | Parameters\n | ----------\n | func : callable, optional\n | Function for which integral is calculated. Takes only one argument.\n | The default is the identity mapping f(x) = x.\n | args : tuple, optional\n | Shape parameters of the distribution.\n | loc : float, optional\n | Location parameter (default=0).\n | scale : float, optional\n | Scale parameter (default=1).\n | lb, ub : scalar, optional\n | Lower and upper bound for integration. Default is set to the\n | support of the distribution.\n | conditional : bool, optional\n | If True, the integral is corrected by the conditional probability\n | of the integration interval. The return value is the expectation\n | of the function, conditional on being in the given interval.\n | Default is False.\n | \n | Additional keyword arguments are passed to the integration routine.\n | \n | Returns\n | -------\n | expect : float\n | The calculated expected value.\n | \n | Notes\n | -----\n | The integration behavior of this function is inherited from\n | `scipy.integrate.quad`. Neither this function nor\n | `scipy.integrate.quad` can verify whether the integral exists or is\n | finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and\n | ``cauchy(0).expect()`` returns ``0.0``.\n | \n | Examples\n | --------\n | \n | To understand the effect of the bounds of integration consider\n | \n | >>> from scipy.stats import expon\n | >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0)\n | 0.6321205588285578\n | \n | This is close to\n | \n | >>> expon(1).cdf(2.0) - expon(1).cdf(0.0)\n | 0.6321205588285577\n | \n | If ``conditional=True``\n | \n | >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True)\n | 1.0000000000000002\n | \n | The slight deviation from 1 is due to numerical integration.\n | \n | fit_loc_scale(self, data, *args)\n | Estimate loc and scale parameters from data using 1st and 2nd moments.\n | \n | Parameters\n | ----------\n | data : array_like\n | Data to fit.\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information).\n | \n | Returns\n | -------\n | Lhat : float\n | Estimated location parameter for the data.\n | Shat : float\n | Estimated scale parameter for the data.\n | \n | isf(self, q, *args, **kwds)\n | Inverse survival function (inverse of `sf`) at q of the given RV.\n | \n | Parameters\n | ----------\n | q : array_like\n | upper tail probability\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | x : ndarray or scalar\n | Quantile corresponding to the upper tail probability q.\n | \n | logcdf(self, x, *args, **kwds)\n | Log of the cumulative distribution function at x of the given RV.\n | \n | Parameters\n | ----------\n | x : array_like\n | quantiles\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | logcdf : array_like\n | Log of the cumulative distribution function evaluated at x\n | \n | logpdf(self, x, *args, **kwds)\n | Log of the probability density function at x of the given RV.\n | \n | This uses a more numerically accurate calculation if available.\n | \n | Parameters\n | ----------\n | x : array_like\n | quantiles\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | logpdf : array_like\n | Log of the probability density function evaluated at x\n | \n | logsf(self, x, *args, **kwds)\n | Log of the survival function of the given RV.\n | \n | Returns the log of the \"survival function,\" defined as (1 - `cdf`),\n | evaluated at `x`.\n | \n | Parameters\n | ----------\n | x : array_like\n | quantiles\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | logsf : ndarray\n | Log of the survival function evaluated at `x`.\n | \n | nnlf(self, theta, x)\n | Return negative loglikelihood function.\n | \n | Notes\n | -----\n | This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the\n | parameters (including loc and scale).\n | \n | pdf(self, x, *args, **kwds)\n | Probability density function at x of the given RV.\n | \n | Parameters\n | ----------\n | x : array_like\n | quantiles\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | pdf : ndarray\n | Probability density function evaluated at x\n | \n | ppf(self, q, *args, **kwds)\n | Percent point function (inverse of `cdf`) at q of the given RV.\n | \n | Parameters\n | ----------\n | q : array_like\n | lower tail probability\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | x : array_like\n | quantile corresponding to the lower tail probability q.\n | \n | sf(self, x, *args, **kwds)\n | Survival function (1 - `cdf`) at x of the given RV.\n | \n | Parameters\n | ----------\n | x : array_like\n | quantiles\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | sf : array_like\n | Survival function evaluated at x\n | \n | ----------------------------------------------------------------------\n | Methods inherited from scipy.stats._distn_infrastructure.rv_generic:\n | \n | __call__(self, *args, **kwds)\n | Freeze the distribution for the given arguments.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution. Should include all\n | the non-optional arguments, may include ``loc`` and ``scale``.\n | \n | Returns\n | -------\n | rv_frozen : rv_frozen instance\n | The frozen distribution.\n | \n | __getstate__(self)\n | \n | __setstate__(self, state)\n | \n | entropy(self, *args, **kwds)\n | Differential entropy of the RV.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information).\n | loc : array_like, optional\n | Location parameter (default=0).\n | scale : array_like, optional (continuous distributions only).\n | Scale parameter (default=1).\n | \n | Notes\n | -----\n | Entropy is defined base `e`:\n | \n | >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))\n | >>> np.allclose(drv.entropy(), np.log(2.0))\n | True\n | \n | freeze(self, *args, **kwds)\n | Freeze the distribution for the given arguments.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution. Should include all\n | the non-optional arguments, may include ``loc`` and ``scale``.\n | \n | Returns\n | -------\n | rv_frozen : rv_frozen instance\n | The frozen distribution.\n | \n | interval(self, alpha, *args, **kwds)\n | Confidence interval with equal areas around the median.\n | \n | Parameters\n | ----------\n | alpha : array_like of float\n | Probability that an rv will be drawn from the returned range.\n | Each value should be in the range [0, 1].\n | arg1, arg2, ... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information).\n | loc : array_like, optional\n | location parameter, Default is 0.\n | scale : array_like, optional\n | scale parameter, Default is 1.\n | \n | Returns\n | -------\n | a, b : ndarray of float\n | end-points of range that contain ``100 * alpha %`` of the rv's\n | possible values.\n | \n | mean(self, *args, **kwds)\n | Mean of the distribution.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | mean : float\n | the mean of the distribution\n | \n | median(self, *args, **kwds)\n | Median of the distribution.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | Location parameter, Default is 0.\n | scale : array_like, optional\n | Scale parameter, Default is 1.\n | \n | Returns\n | -------\n | median : float\n | The median of the distribution.\n | \n | See Also\n | --------\n | rv_discrete.ppf\n | Inverse of the CDF\n | \n | moment(self, n, *args, **kwds)\n | n-th order non-central moment of distribution.\n | \n | Parameters\n | ----------\n | n : int, n >= 1\n | Order of moment.\n | arg1, arg2, arg3,... : float\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information).\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | rvs(self, *args, **kwds)\n | Random variates of given type.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information).\n | loc : array_like, optional\n | Location parameter (default=0).\n | scale : array_like, optional\n | Scale parameter (default=1).\n | size : int or tuple of ints, optional\n | Defining number of random variates (default is 1).\n | random_state : None or int or ``np.random.RandomState`` instance, optional\n | If int or RandomState, use it for drawing the random variates.\n | If None, rely on ``self.random_state``.\n | Default is None.\n | \n | Returns\n | -------\n | rvs : ndarray or scalar\n | Random variates of given `size`.\n | \n | stats(self, *args, **kwds)\n | Some statistics of the given RV.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional (continuous RVs only)\n | scale parameter (default=1)\n | moments : str, optional\n | composed of letters ['mvsk'] defining which moments to compute:\n | 'm' = mean,\n | 'v' = variance,\n | 's' = (Fisher's) skew,\n | 'k' = (Fisher's) kurtosis.\n | (default is 'mv')\n | \n | Returns\n | -------\n | stats : sequence\n | of requested moments.\n | \n | std(self, *args, **kwds)\n | Standard deviation of the distribution.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | std : float\n | standard deviation of the distribution\n | \n | support(self, *args, **kwargs)\n | Return the support of the distribution.\n | \n | Parameters\n | ----------\n | arg1, arg2, ... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information).\n | loc : array_like, optional\n | location parameter, Default is 0.\n | scale : array_like, optional\n | scale parameter, Default is 1.\n | Returns\n | -------\n | a, b : float\n | end-points of the distribution's support.\n | \n | var(self, *args, **kwds)\n | Variance of the distribution.\n | \n | Parameters\n | ----------\n | arg1, arg2, arg3,... : array_like\n | The shape parameter(s) for the distribution (see docstring of the\n | instance object for more information)\n | loc : array_like, optional\n | location parameter (default=0)\n | scale : array_like, optional\n | scale parameter (default=1)\n | \n | Returns\n | -------\n | var : float\n | the variance of the distribution\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from scipy.stats._distn_infrastructure.rv_generic:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n | \n | random_state\n | Get or set the RandomState object for generating random variates.\n | \n | This can be either None or an existing RandomState object.\n | \n | If None (or np.random), use the RandomState singleton used by np.random.\n | If already a RandomState instance, use it.\n | If an int, use a new RandomState instance seeded with seed.\n \n\n\n\n```python\nhelp(stats.bernoulli.rvs)\n```\n\n Help on method rvs in module scipy.stats._distn_infrastructure:\n \n rvs(*args, **kwargs) method of scipy.stats._discrete_distns.bernoulli_gen instance\n Random variates of given type.\n \n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n size : int or tuple of ints, optional\n Defining number of random variates (Default is 1). Note that `size`\n has to be given as keyword, not as positional argument.\n random_state : None or int or ``np.random.RandomState`` instance, optional\n If int or RandomState, use it for drawing the random variates.\n If None, rely on ``self.random_state``.\n Default is None.\n \n Returns\n -------\n rvs : ndarray or scalar\n Random variates of given `size`.\n \n\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json, matplotlib\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nplt.style.use('ggplot')\n\nimport scipy.stats as stats\n\n# 一般用于Beta分布建模伯努利试验事件成功的概率\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials) / 2, 2, k + 1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials) - 1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$ pass. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2 * p / (1 + p), color=\"#348ABD\", lw=3)\n# plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2 * (0.2) / 1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Is my code bug-free?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1. / 3, 2. / 3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.ylim(0,1)\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n#### Expected Value\nExpected value (EV) is one of the most important concepts in probability. The EV for a given probability distribution can be described as \"the mean value in the long run for many repeated samples from that distribution.\" To borrow a metaphor from physics, a distribution's EV acts like its \"center of mass.\" Imagine repeating the same experiment many times over, and taking the average over each outcome. The more you repeat the experiment, the closer this average will become to the distributions EV. (side note: as the number of repeated experiments goes to infinity, the difference between the average outcome and the EV becomes arbitrarily small.)\n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots, \\; \\; \\lambda \\in \\mathbb{R}_{>0} $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1. / l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0, 1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```python\nimport pymc as pm\n\n# 由于对于alpha的假设分布是Exp,Exp的期望E是1/alpha,\n# 它也近似与样本的均值?这个逻辑其实我没太懂\nalpha = 1.0 / count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = pm.Exponential(\"lambda_1\", alpha)\nlambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\ntau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```python\nprint(\"Random output:\", tau.random(), tau.random(), tau.random())\n```\n\n Random output: 62 14 68\n\n\n\n```python\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. Deterministic functions will be covered in Chapter 2. \n\n\n```python\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n# Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n /Users/weicc/miniconda3/lib/python3.6/site-packages/pymc/MCMC.py:81: UserWarning: Instantiating a Model object directly is deprecated. We recommend passing variables directly to the Model subclass.\n warnings.warn(message)\n\n\n [-----------------100%-----------------] 40000 of 40000 complete in 5.8 sec\n\n\n```python\nhelp(mcmc.sample)\n```\n\n Help on method sample in module pymc.MCMC:\n \n sample(iter, burn=0, thin=1, tune_interval=1000, tune_throughout=True, save_interval=None, burn_till_tuned=False, stop_tuning_after=5, verbose=0, progress_bar=True) method of pymc.MCMC.MCMC instance\n sample(iter, burn, thin, tune_interval, tune_throughout, save_interval, verbose, progress_bar)\n \n Initialize traces, run sampling loop, clean up afterward. Calls _loop.\n \n :Parameters:\n - iter : int\n Total number of iterations to do\n - burn : int\n Variables will not be tallied until this many iterations are complete, default 0\n - thin : int\n Variables will be tallied at intervals of this many iterations, default 1\n - tune_interval : int\n Step methods will be tuned at intervals of this many iterations, default 1000\n - tune_throughout : boolean\n If true, tuning will continue after the burnin period (True); otherwise tuning\n will halt at the end of the burnin period.\n - save_interval : int or None\n If given, the model state will be saved at intervals of this many iterations\n - verbose : boolean\n - progress_bar : boolean\n Display progress bar while sampling.\n - burn_till_tuned: boolean\n If True the Sampler would burn samples until all step methods are tuned.\n A tuned step methods is one that was not tuned for the last `stop_tuning_after` tuning intervals.\n The burn-in phase will have a minimum of 'burn' iterations but could be longer if\n tuning is needed. After the phase is done the sampler will run for another\n (iter - burn) iterations, and will tally the samples according to the 'thin' argument.\n This means that the total number of iteration is update throughout the sampling\n procedure.\n If burn_till_tuned is True it also overrides the tune_thorughout argument, so no step method\n will be tuned when sample are being tallied.\n - stop_tuning_after: int\n the number of untuned successive tuning interval needed to be reach in order for\n the burn-in phase to be done (If burn_till_tuned is True).\n \n\n\n\n```python\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```python\nhelp(plt.hist)\n```\n\n Help on function hist in module matplotlib.pyplot:\n \n hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)\n Plot a histogram.\n \n Compute and draw the histogram of *x*. The return value is a tuple\n (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*, [*patches0*,\n *patches1*,...]) if the input contains multiple data. See the\n documentation of the *weights* parameter to draw a histogram of\n already-binned data.\n \n Multiple data can be provided via *x* as a list of datasets\n of potentially different length ([*x0*, *x1*, ...]), or as\n a 2-D ndarray in which each column is a dataset. Note that\n the ndarray form is transposed relative to the list form.\n \n Masked arrays are not supported at present.\n \n Parameters\n ----------\n x : (n,) array or sequence of (n,) arrays\n Input values, this takes either a single array or a sequence of\n arrays which are not required to be of the same length.\n \n bins : int or sequence or str, optional\n If an integer is given, ``bins + 1`` bin edges are calculated and\n returned, consistent with `numpy.histogram`.\n \n If `bins` is a sequence, gives bin edges, including left edge of\n first bin and right edge of last bin. In this case, `bins` is\n returned unmodified.\n \n All but the last (righthand-most) bin is half-open. In other\n words, if `bins` is::\n \n [1, 2, 3, 4]\n \n then the first bin is ``[1, 2)`` (including 1, but excluding 2) and\n the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which\n *includes* 4.\n \n Unequally spaced bins are supported if *bins* is a sequence.\n \n With Numpy 1.11 or newer, you can alternatively provide a string\n describing a binning strategy, such as 'auto', 'sturges', 'fd',\n 'doane', 'scott', 'rice' or 'sqrt', see\n `numpy.histogram`.\n \n The default is taken from :rc:`hist.bins`.\n \n range : tuple or None, optional\n The lower and upper range of the bins. Lower and upper outliers\n are ignored. If not provided, *range* is ``(x.min(), x.max())``.\n Range has no effect if *bins* is a sequence.\n \n If *bins* is a sequence or *range* is specified, autoscaling\n is based on the specified bin range instead of the\n range of x.\n \n Default is ``None``\n \n density : bool, optional\n If ``True``, the first element of the return tuple will\n be the counts normalized to form a probability density, i.e.,\n the area (or integral) under the histogram will sum to 1.\n This is achieved by dividing the count by the number of\n observations times the bin width and not dividing by the total\n number of observations. If *stacked* is also ``True``, the sum of\n the histograms is normalized to 1.\n \n Default is ``None`` for both *normed* and *density*. If either is\n set, then that value will be used. If neither are set, then the\n args will be treated as ``False``.\n \n If both *density* and *normed* are set an error is raised.\n \n weights : (n, ) array_like or None, optional\n An array of weights, of the same shape as *x*. Each value in *x*\n only contributes its associated weight towards the bin count\n (instead of 1). If *normed* or *density* is ``True``,\n the weights are normalized, so that the integral of the density\n over the range remains 1.\n \n Default is ``None``.\n \n This parameter can be used to draw a histogram of data that has\n already been binned, e.g. using `np.histogram` (by treating each\n bin as a single point with a weight equal to its count) ::\n \n counts, bins = np.histogram(data)\n plt.hist(bins[:-1], bins, weights=counts)\n \n (or you may alternatively use `~.bar()`).\n \n cumulative : bool, optional\n If ``True``, then a histogram is computed where each bin gives the\n counts in that bin plus all bins for smaller values. The last bin\n gives the total number of datapoints. If *normed* or *density*\n is also ``True`` then the histogram is normalized such that the\n last bin equals 1. If *cumulative* evaluates to less than 0\n (e.g., -1), the direction of accumulation is reversed.\n In this case, if *normed* and/or *density* is also ``True``, then\n the histogram is normalized such that the first bin equals 1.\n \n Default is ``False``\n \n bottom : array_like, scalar, or None\n Location of the bottom baseline of each bin. If a scalar,\n the base line for each bin is shifted by the same amount.\n If an array, each bin is shifted independently and the length\n of bottom must match the number of bins. If None, defaults to 0.\n \n Default is ``None``\n \n histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, optional\n The type of histogram to draw.\n \n - 'bar' is a traditional bar-type histogram. If multiple data\n are given the bars are arranged side by side.\n \n - 'barstacked' is a bar-type histogram where multiple\n data are stacked on top of each other.\n \n - 'step' generates a lineplot that is by default\n unfilled.\n \n - 'stepfilled' generates a lineplot that is by default\n filled.\n \n Default is 'bar'\n \n align : {'left', 'mid', 'right'}, optional\n Controls how the histogram is plotted.\n \n - 'left': bars are centered on the left bin edges.\n \n - 'mid': bars are centered between the bin edges.\n \n - 'right': bars are centered on the right bin edges.\n \n Default is 'mid'\n \n orientation : {'horizontal', 'vertical'}, optional\n If 'horizontal', `~matplotlib.pyplot.barh` will be used for\n bar-type histograms and the *bottom* kwarg will be the left edges.\n \n rwidth : scalar or None, optional\n The relative width of the bars as a fraction of the bin width. If\n ``None``, automatically compute the width.\n \n Ignored if *histtype* is 'step' or 'stepfilled'.\n \n Default is ``None``\n \n log : bool, optional\n If ``True``, the histogram axis will be set to a log scale. If\n *log* is ``True`` and *x* is a 1D array, empty bins will be\n filtered out and only the non-empty ``(n, bins, patches)``\n will be returned.\n \n Default is ``False``\n \n color : color or array_like of colors or None, optional\n Color spec or sequence of color specs, one per dataset. Default\n (``None``) uses the standard line color sequence.\n \n Default is ``None``\n \n label : str or None, optional\n String, or sequence of strings to match multiple datasets. Bar\n charts yield multiple patches per dataset, but only the first gets\n the label, so that the legend command will work as expected.\n \n default is ``None``\n \n stacked : bool, optional\n If ``True``, multiple data are stacked on top of each other If\n ``False`` multiple data are arranged side by side if histtype is\n 'bar' or on top of each other if histtype is 'step'\n \n Default is ``False``\n \n normed : bool, optional\n Deprecated; use the density keyword argument instead.\n \n Returns\n -------\n n : array or list of arrays\n The values of the histogram bins. See *density* and *weights* for a\n description of the possible semantics. If input *x* is an array,\n then this is an array of length *nbins*. If input is a sequence of\n arrays ``[data1, data2,..]``, then this is a list of arrays with\n the values of the histograms for each of the arrays in the same\n order. The dtype of the array *n* (or of its element arrays) will\n always be float even if no weighting or normalization is used.\n \n bins : array\n The edges of the bins. Length nbins + 1 (nbins left edges and right\n edge of last bin). Always a single array even when multiple data\n sets are passed in.\n \n patches : list or list of lists\n Silent list of individual patches used to create the histogram\n or list of such list if multiple input datasets.\n \n Other Parameters\n ----------------\n **kwargs : `~matplotlib.patches.Patch` properties\n \n See also\n --------\n hist2d : 2D histograms\n \n Notes\n -----\n \n \n .. note::\n In addition to the above described arguments, this function can take a\n **data** keyword argument. If such a **data** argument is given, the\n following arguments are replaced by **data[]**:\n \n * All arguments with the following names: 'weights', 'x'.\n \n Objects passed as **data** must support item access (``data[]``) and\n membership test (`` in data``).\n \n\n\n\n```python\nfigsize(12.5, 10)\n# histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, 1.])\nplt.xlim([35, len(count_data) - 20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n\n```python\nlambda_1_samples.shape, lambda_2_samples.shape, tau_samples.shape\n```\n\n\n\n\n ((30000,), (30000,), (30000,))\n\n\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nlambda_1_samples.mean(), lambda_2_samples.mean()\n```\n\n\n\n\n (17.75208776187856, 22.725028961573948)\n\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n((lambda_2_samples - lambda_1_samples) / lambda_1_samples).mean()\n```\n\n\n\n\n 0.28176482490146304\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nidx = tau_samples < 45\n\nlambda_1_samples[idx].mean()\n```\n\n\n\n\n 17.756220911341753\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "da4ea9c05e6ae2face32f5c102783b378558b3d6", "size": 407855, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_stars_repo_name": "codeunsolved/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "7e19f04ba1df69dbfa8fefacb0391970f7d30942", "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": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_issues_repo_name": "codeunsolved/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "7e19f04ba1df69dbfa8fefacb0391970f7d30942", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb", "max_forks_repo_name": "codeunsolved/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "7e19f04ba1df69dbfa8fefacb0391970f7d30942", "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": 186.1501597444, "max_line_length": 95988, "alphanum_fraction": 0.8574542423, "converted": true, "num_tokens": 21298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.19193278182505782, "lm_q1q2_score": 0.05772293558778001}} {"text": "```python\n# %load /Users/facai/Study/book_notes/preconfig.py\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\n#sns.set(font='SimHei', font_scale=2.5)\n#plt.rcParams['axes.grid'] = False\n\nimport numpy as np\n\nimport pandas as pd\n#pd.options.display.max_rows = 20\n\n#import sklearn\n\n#import itertools\n\n#import logging\n#logging.basicConfig()\n#logger = logging.getLogger()\n#logger.setLevel(logging.DEBUG)\n\nfrom IPython.display import Image\n```\n\nChapter 5 Monte Carlo Methods\n================\n\nMonte Carlo methods require only *experience*: sample sequences of states, actions, and rewards from actual or simulated interaction with an environment.\n\nrequirements: averaging sample returns => we define Monte Carlo methods only for episodic tasks.\n\n### 5.1 Monte Carlo Prediction\n\nthe value of a state: expected return starting from that state.\n\nAn obvious way to estimate it from experience: simply to average the returns observed after visits to that state.\n\n$s$ may be visited multiple times in the same episode:\n+ first-visit MC method\n+ every-visit MC method\n\n\n```python\nImage('./res/first_visit_mc.png')\n```\n\nMonte Carlo methods do not *bootstrap*: the estimate for one state does not build upon the estimate of any other state.\n\nThe computational expense of estimating the value of a single state is independent of the number of states. \n=> One can generate many sample episodes starting from the states of interest, averaging returns from only these states, ignoring all others.\n\n### 5.2 Monte Carlo Estimation of Action Values\n\nIf a model is not available, useful to estimate *action* values $q_\\pi(s, a)$ rather than *state* values.\n\nmaintain exploration problem: many state-action pairs may never be visited.\n+ exploring starts: every pair has a nonzero probability of being selected as start point.\n+ make policy stochasic with a nonzero probability of selecting all actions in each state.\n\n### 5.3 Monte Carlo Control\n\n$\\pi(s) \\doteq \\operatorname{arg max}_a q(s, a)$\n\n\n```python\nImage('./res/gpi.png')\n```\n\n\n```python\nImage('./res/monte_carlo_es.png')\n```\n\n### 5.4 Monte Carlo Control without Exploring Starts\n\nensure that all actions are selected infinitely often is for the agent to continue to select them:\n+ on-policy: evaluate or imporve the policy that is used to make decisions.\n+ off-policy: evaluate or improve a policy different from that used to generate the data.\n\npolicy is *soft*, meaning that $\\pi(a \\mid s) > 0$ for all $s \\in \\mathcal{S}$ and all $a \\in \\mathcal{A}(s)$, but gradually shifted closer and closer to a deterministic optimal policy.\n\n$\\epsilon$-soft policies: $\\pi(a \\mid s) \\geq \\frac{\\epsilon}{|\\mathcal{A}(s)|}$ for all states and actions, for some $\\epsilon > 0$.\n+ $\\epsilon$-greedy policies: most of time greedy, sometimes random.\n+ For any $\\epsilon$-soft policy $\\pi$, any $\\epsilon$-greedy policy with respect to $q_\\pi$ is guaranteed to be better than or equal to $\\pi$.\n\n\n```python\nImage('./res/on_epsilon_soft.png')\n```\n\n### 5.5 Off-policy Prediction via Importances Sampling\n\nuse two policies:\n+ target policy $\\pi$: the potimal policy that is learned about.\n+ behavior policy $b$: more exploratory policy that is used to generate behavior.\n\nassumption of *coverage*: $\\pi(a \\mid s) > 0$ implies $b(a \\mid s) > 0$.\n\nwe wish to estimate $v_\\pi$ or $q_\\pi$, but all we have are episodes following another policy $b$, where $b \\neq \\pi$. \n=> importance sampling: a general technique for estimating expected values under one distribution given samples from another. \n=> importance-sampling ratio $\\rho_{t:T-1}$:\n\nGiven a starting state $S_t$, we have: $\\operatorname{Pr}\\{A_t, S_{t+1}, A_{t+1}, \\cdots, S_T \\mid S_t, A_{t:T-1} \\sim \\pi\\} = \\prod_{K=t}^{T-1} \\pi(A_k \\mid S_k) p(S_{k+1} \\mid S_k, A_k)$\n\n\\begin{equation}\n \\rho_{t:T-1} \\doteq \\prod_{K=t}^{T-1} \\frac{\\pi(A_k \\mid S_k)}{b(A_k \\mid S_k)}\n\\end{equation}\n\nSo we can have the right expected value by:\n\n\\begin{align}\n \\mathbb{E}[G_t \\mid S_t] &= v_b(S_t) \\\\\n \\mathbb{E}[\\rho_{t:T-1} G_t \\mid S_t] &= v_\\pi(S_t)\n\\end{align}\n\nTo estimate $v_\\pi(s)$, we simply scale the returns by the ratios and average the results:\n+ ordinary importance sampling: $V(s) \\doteq \\frac{\\sum_{t \\in \\mathcal{J}(s)} \\rho_{t:T(t)-1} G_t}{|\\mathcal{J}(s)|}$: unbiased, but it can be extreme.\n+ weighted importance sampling: $V(s) \\doteq \\frac{\\sum_{t \\in \\mathcal{J}(s)} \\rho_{t:T(t)-1} G_t}{\\sum_{t \\in \\mathcal{J}(s)} \\rho_{t:T(t)-1}}$: biased, but its variance is bounded.\n\n### 5.6 Incremental Implementation\n\n\n```python\nImage('./res/off_policy_predict.png')\n```\n\n### 5.7 Off-policy Monte Carlo Control\n\n\n```python\nImage('./res/off_policy_control.png')\n```\n\nPotential problem: this method learns only from the tails of episodes, when all of the remaining actions in the episode are greedy. If nongreedy actions are commom => greatly slow learning.\n\n### 5.8 Disounting-aware Importance Sampling\n\n### 5.9 Per-decision Importance Sampling\n\n\n```python\n\n```\n", "meta": {"hexsha": "ca6fbf2ca3cd3f92e53bac02e957df91429f7a26", "size": 519325, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Reinforcement_Learing_An_Introduction/Monte_Carlo_Methods/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "Reinforcement_Learing_An_Introduction/Monte_Carlo_Methods/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "Reinforcement_Learing_An_Introduction/Monte_Carlo_Methods/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 1518.4941520468, "max_line_length": 116432, "alphanum_fraction": 0.9500389929, "converted": true, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296919173767833, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.05741241481015368}} {"text": "```\n#@title Copyright 2020 The Cirq Developers\n# 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# QAOA: Max-Cut\n\n\n \n \n \n \n
    \n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
    \n\nIn this tutorial, we implement the quantum approximate optimization algorithm (QAOA) for determining the Max-Cut of the Sycamore processor's hardware graph (with random edge weights). To do so, we will:\n\n1. Define a random set of weights over the hardware graph.\n2. Construct a QAOA circuit using Cirq.\n3. Calculate the expected value of the QAOA cost function.\n4. Create an outer loop optimization to minimize the cost function.\n5. Compare cuts found from QAOA with random cuts.\n\n\n```\ntry:\n import cirq\nexcept ImportError:\n print(\"installing cirq...\")\n !pip install --quiet cirq\n import cirq\n print(\"installed cirq.\")\n```\n\n## 1. Defining a random set of weights over the hardware graph\nIn order to make the problem easily embeddable on a quantum device, we will look at the problem of Max-Cut on the same graph that the device's qubit connectivity defines, but with random valued edge weights.\n\n\n```\nimport cirq_google\nimport sympy\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nworking_device = cirq_google.Sycamore\nprint(working_device)\n```\n\nSince a circuit covering the entire Sycamore device cannot be easily simulated, a small subset of the device graph will be used instead.\n\n\n```\nimport networkx as nx\n\n# Set the seed to determine the problem instance.\nnp.random.seed(seed=11)\n\n# Identify working qubits from the device.\ndevice_qubits = working_device.qubits\nworking_qubits = sorted(device_qubits)[:12]\n\n# Populate a networkx graph with working_qubits as nodes.\nworking_graph = working_device.metadata.nx_graph.subgraph(working_qubits)\n\n# Add random weights to edges of the graph. Each weight is a 2 decimal floating point between 0 and 5.\nnx.set_edge_attributes(working_graph, {e: {'weight': np.random.randint(0, 500) / 100} for e in working_graph.edges})\n\n# Draw the working_graph on a 2d grid\npos = {q:(q.col, -q.row) for q in working_graph.nodes()}\nnx.draw(working_graph, pos=pos, with_labels=True, node_size=1000)\nplt.show()\n```\n\n## 2. Construct the QAOA circuit\nNow that we have created a Max-Cut problem graph, it's time to generate the QAOA circuit following [Farhi et al.](https://arxiv.org/abs/1411.4028). For simplicity $p = 1$ is chosen.\n\n\n```\nfrom cirq.contrib.svg import SVGCircuit\n\n# Symbols for the rotation angles in the QAOA circuit.\nalpha = sympy.Symbol('alpha')\nbeta = sympy.Symbol('beta')\n\nqaoa_circuit = cirq.Circuit(\n # Prepare uniform superposition on working_qubits == working_graph.nodes\n cirq.H.on_each(working_graph.nodes()),\n\n # Do ZZ operations between neighbors u, v in the graph. Here, u is a qubit,\n # v is its neighboring qubit, and w is the weight between these qubits.\n (cirq.ZZ(u, v) ** (alpha * w['weight']) for (u, v, w) in working_graph.edges(data=True)),\n\n # Apply X operations along all nodes of the graph. Again working_graph's\n # nodes are the working_qubits. Note here we use a moment\n # which will force all of the gates into the same line.\n cirq.Moment(cirq.X(qubit) ** beta for qubit in working_graph.nodes()),\n \n # All relevant things can be computed in the computational basis.\n (cirq.measure(qubit) for qubit in working_graph.nodes()),\n)\nSVGCircuit(qaoa_circuit)\n```\n\n## 3. Calculating the expected value of the QAOA cost Hamiltonian\nNow that we have created a parameterized QAOA circuit, we need a way to calculate expectation values of the cost Hamiltonian. For Max-Cut, the cost Hamiltonian is\n\n$$\n H_C = \\frac{1}{2} \\sum_{\\langle i, j\\rangle} w_{ij} (1 - Z_i Z_j )\n$$\n\nwhere $\\langle i, j \\rangle$ denotes neighboring qubits, $w_{ij}$ is the weight of edge $ij$, and $Z$ is the usual Pauli-$Z$ matrix. The expectation value of this cost Hamiltonian is $\\langle \\alpha, \\beta | H_C | \\alpha, \\beta \\rangle$ where $|\\alpha, \\beta\\rangle$ is the quantum state prepared by our `qaoa_circuit`. This is the cost function we need to estimate.\n\n> Pauli-$Z$ has eigenvalues $\\pm 1$. If qubits $i$ and $j$ are in the same eigenspace, then $\\langle Z_i Z_j \\rangle = 1$ and so $\\frac{1}{2} w_{ij} \\langle 1 - Z_i Z_j \\rangle = 0$. In the Max-Cut language, this means that edge $ij$ does not contribute to the cost. If qubits $i$ and $j$ are in the opposite eigenspace, then $\\langle Z_i Z_j \\rangle = -1$ and so $\\frac{1}{2} w_{ij} \\langle 1 - Z_i Z_j \\rangle = w_{ij}$. In the Max-Cut language, this means that edge $ij$ contributes its weight $w_{ij}$ to the cost. \n\nTo estimate the cost function, we need to estimate the (weighted) sum of all $ZZ$ pairs in the graph. Since these terms are diagonal in the same basis (namely, the computational basis), they can measured simultaneously. Given a set of measurements (samples), the function below estimates the cost function.\n\n> *Note*: We say \"estimate the cost\" instead of \"compute the cost\" since we are sampling from the circuit. This is how the cost would be evaluated when running QAOA on a real quantum processor.\n\n\n```\ndef estimate_cost(graph, samples):\n \"\"\"Estimate the cost function of the QAOA on the given graph using the\n provided computational basis bitstrings.\"\"\"\n cost_value = 0.0\n\n # Loop over edge pairs and compute contribution.\n for u, v, w in graph.edges(data=True):\n u_samples = samples[str(u)]\n v_samples = samples[str(v)]\n\n # Determine if it was a +1 or -1 eigenvalue.\n u_signs = (-1)**u_samples\n v_signs = (-1)**v_samples\n term_signs = u_signs * v_signs\n\n # Add scaled term to total cost.\n term_val = np.mean(term_signs) * w['weight']\n cost_value += term_val\n\n return -cost_value\n```\n\nNow we can sample from the `qaoa_circuit` and use `estimate_expectation` to calculate the expectation value of the cost function for the circuit. Below, we use arbitrary values for $\\alpha$ and $\\beta$.\n\n\n```\nalpha_value = np.pi / 4\nbeta_value = np.pi / 2\nsim = cirq.Simulator()\n\nsample_results = sim.sample(\n qaoa_circuit, \n params={alpha: alpha_value, beta: beta_value}, \n repetitions=20_000\n)\nprint(f'Alpha = {round(alpha_value, 3)} Beta = {round(beta_value, 3)}')\nprint(f'Estimated cost: {estimate_cost(working_graph, sample_results)}')\n```\n\n## 4. Outer loop optimization\nNow that we can compute the cost function, we want to find the optimal cost. There are lots of different techniques to choose optimal parameters for the `qaoa_circuit`. Since there are only two parameters here ($\\alpha$ and $\\beta$), we can keep things simple and sweep over incremental pairings using `np.linspace` and track the minimum value found along the way.\n\n\n```\n# Set the grid size = number of points in the interval [0, 2π).\ngrid_size = 5\n\nexp_values = np.empty((grid_size, grid_size))\npar_values = np.empty((grid_size, grid_size, 2))\n\nfor i, alpha_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)):\n for j, beta_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)):\n samples = sim.sample(\n qaoa_circuit,\n params={alpha: alpha_value, beta: beta_value},\n repetitions=20000\n )\n exp_values[i][j] = estimate_cost(working_graph, samples)\n par_values[i][j] = alpha_value, beta_value\n```\n\nWe can now visualize the cost as a function of $\\alpha$ and $\\beta$.\n\n\n```\nplt.title('Heatmap of QAOA Cost Function Value')\nplt.xlabel(r'$\\alpha$')\nplt.ylabel(r'$\\beta$')\nplt.imshow(exp_values)\nplt.show()\n```\n\nThis heatmap is coarse because we selected a small `grid_size`. To see more detail in the heatmap, one can increase the `grid_size`. \n\n## 5. Compare cuts\n\nWe now compare the optimal cut found by QAOA to a randomly selected cut. The helper function draws the `working_graph` and colors nodes in different sets different colors. Additionally, we print out the cost function for the given cut.\n\n\n```\ndef output_cut(S_partition):\n \"\"\"Plot and output the graph cut information.\"\"\"\n\n # Generate the colors.\n coloring = []\n for node in working_graph:\n if node in S_partition:\n coloring.append('blue')\n else:\n coloring.append('red')\n\n # Get the weights\n edges = working_graph.edges(data=True)\n weights = [w['weight'] for (u,v, w) in edges]\n\n nx.draw_circular(\n working_graph,\n node_color=coloring,\n node_size=1000,\n with_labels=True,\n width=weights)\n plt.show()\n size = nx.cut_size(working_graph, S_partition, weight='weight')\n print(f'Cut size: {size}')\n```\n\nAs an example, we can test this function with all nodes in the same set, for which the cut size should be zero.\n\n\n```\n# Test with the empty S and all nodes placed in T.\noutput_cut([])\n```\n\nTo get cuts using the QAOA we will first need to extract the best control parameters found during the sweep:\n\n\n```\nbest_exp_index = np.unravel_index(np.argmax(exp_values), exp_values.shape)\nbest_parameters = par_values[best_exp_index]\nprint(f'Best control parameters: {best_parameters}')\n```\n\nEach bitstring can be seen as a candidate cut in the graph. The qubits that measured 0 correspond to that qubit being in one cut partition and a qubit that measured to 1 corresponds to that qubit being in the other cut partition. Now that we've found good parameters for the `qaoa_circuit`, we can just sample some bistrings, iterate over them and pick the one that gives the best cut:\n\n\n```\n# Number of candidate cuts to sample.\nnum_cuts = 100\ncandidate_cuts = sim.sample(\n qaoa_circuit,\n params={alpha: best_parameters[0], beta: best_parameters[1]},\n repetitions=num_cuts\n)\n\n# Variables to store best cut partitions and cut size.\nbest_qaoa_S_partition = set()\nbest_qaoa_T_partition = set()\nbest_qaoa_cut_size = -np.inf\n\n# Analyze each candidate cut.\nfor i in range(num_cuts):\n candidate = candidate_cuts.iloc[i]\n one_qubits = set(candidate[candidate==1].index)\n S_partition = set()\n T_partition = set()\n for node in working_graph:\n if str(node) in one_qubits:\n # If a one was measured add node to S partition.\n S_partition.add(node)\n else:\n # Otherwise a zero was measured so add to T partition.\n T_partition.add(node)\n\n cut_size = nx.cut_size(\n working_graph, S_partition, T_partition, weight='weight')\n \n # If you found a better cut update best_qaoa_cut variables.\n if cut_size > best_qaoa_cut_size:\n best_qaoa_cut_size = cut_size\n best_qaoa_S_partition = S_partition\n best_qaoa_T_partition = T_partition\n```\n\nThe QAOA is known to do just a little better than random guessing for Max-Cut on 3-regular graphs at `p=1`. You can use very similar logic to the code above, but now instead of relying on the QAOA to decide your `S_partition` and `T_partition` you can just pick then randomly:\n\n\n```\nimport random\n\nbest_random_S_partition = set()\nbest_random_T_partition = set()\nbest_random_cut_size = -9999\n\n# Randomly build candidate sets.\nfor i in range(num_cuts):\n S_partition = set()\n T_partition = set()\n for node in working_graph:\n if random.random() > 0.5:\n # If we flip heads add to S.\n S_partition.add(node)\n else:\n # Otherwise add to T.\n T_partition.add(node)\n\n cut_size = nx.cut_size(\n working_graph, S_partition, T_partition, weight='weight')\n \n # If you found a better cut update best_random_cut variables.\n if cut_size > best_random_cut_size:\n best_random_cut_size = cut_size\n best_random_S_partition = S_partition\n best_random_T_partition = T_partition\n```\n\n\n```\nprint('-----QAOA-----')\noutput_cut(best_qaoa_S_partition)\n\nprint('\\n\\n-----RANDOM-----')\noutput_cut(best_random_S_partition)\n```\n\nFor this problem instance, one should see that $p = 1$ QAOA performs better, on average, than randomly guessing.\n", "meta": {"hexsha": "86b0923faf356145cb1759bbbac249f2af3318af", "size": 19760, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/qaoa.ipynb", "max_stars_repo_name": "LLcat1217/Cirq", "max_stars_repo_head_hexsha": "b88069f7b01457e592ad69d6b413642ef11a56b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T22:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T22:17:39.000Z", "max_issues_repo_path": "docs/tutorials/qaoa.ipynb", "max_issues_repo_name": "LLcat1217/Cirq", "max_issues_repo_head_hexsha": "b88069f7b01457e592ad69d6b413642ef11a56b8", "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/qaoa.ipynb", "max_forks_repo_name": "LLcat1217/Cirq", "max_forks_repo_head_hexsha": "b88069f7b01457e592ad69d6b413642ef11a56b8", "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": 34.425087108, "max_line_length": 539, "alphanum_fraction": 0.5875, "converted": true, "num_tokens": 3312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.14414884751767365, "lm_q1q2_score": 0.057092769706841455}} {"text": "```python\nfrom IPython.core.display import HTML\nfrom IPython.display import Image\n\nimport numpy as np\nimport sympy as sp\nfrom sympy import oo\nfrom utils import symplot, symdisp, round_expr\n\nHTML(\"\"\"\n\n\"\"\")\n```\n\n\n\n\n\n\n\n\n\n\n# *Circuitos Elétricos I - Semana 6*\n\n## Elementos armazenadores de energia\n\nComparação entre capacitores convencionais, supercapacitores e baterias de lítio. A tabela abaixo mostra as especificações necessários para cada dispositivo armazenar ∼1 megajoule (MJ) de energia (300 watts-hora). 1 MJ de energia irá alimentar um laptop com um consumo médio de 50 W por 6 horas. Observe na primeira coluna que uma bateria de íon de lítio pode conter 1000 vezes mais energia do que um capacitor convencional.\n\n$$\n\\begin{array}{|c|c|c|c|c|c|}\n\\hline \\text { Dispositivo } & \\begin{array}{c}\n\\text { Energia } \\\\\n\\text { específica } \\\\\n\\text { [Wh/kg]} \\\\\n\\end{array} & \\begin{array}{c}\n\\text { Energia } \\\\\n\\text { específica } \\\\\n\\text { [MJ/kg] }\n\\end{array} & \\begin{array}{c}\n\\text { Densidade de} \\\\\n\\text { Energia } \\\\\n\\text { [MJ / L] }\n\\end{array} & \\begin{array}{c}\n\\text { Volume } \\\\\n\\text { requerido para } \\\\\n\\text { armazenar 1 MJ } \\\\\n\\text { [L] }\n\\end{array} & \\begin{array}{c}\n\\text { Peso } \\\\\n\\text { requerido para } \\\\\n\\text { armazenar 1 MJ } \\\\\n\\text { [kg] }\n\\end{array} \\\\\n\\hline \\begin{array}{c}\n\\text { Capacitor convencional} \\\\\n\\end{array} & 0.01-0.1 & 4 \\times 10^{-5}-4 \\times 10^{-4} & 6 \\times 10^{-5}-6 \\times 10^{-4} & 17000-1700 & 25000-2500 \\\\\n\\text { Supercapacitor } & 1-10 & 0.004-0.04 & 0.006-0.06 & 166-16 & 250-25 \\\\\n\\text { Bateria de Íons de Lítio } & 100-250 & 0.36-0.9 & 1-2 & 1-0.5 & 2.8-1.1 \\\\\n\\hline\n\\end{array}\n$$\n\nFonte: Fawwaz Ulaby, Michel M. Maharbiz and Cynthia M. Furse, $\\textit{ Circuit Analysis and Design}$, Michigan Publishing Services, 2018\n\n\n## Resumo dos elementos passivos ideais de dois terminais\n\n$$\n\\begin{array}{|l|c|c|c|}\n\\hline \\text { Propriedade } & R & L & C \\\\\n\\hline \\text { Relação } i-v & i=\\frac{v}{R} & i=\\frac{1}{L} \\int_{t_{0}}^{t} v(\\tau) d \\tau+i\\left(t_{0}\\right) & i=C \\frac{d v}{d t} \\\\\n\\text { Relação } v-i & v=Ri & v=L \\frac{d i}{d t} & v=\\frac{1}{C} \\int_{t_{0}}^{t} i(\\tau) d \\tau+v\\left(t_{0}\\right) \\\\\np \\text { (potência }) & p=Ri^{2} & p=L i \\frac{d i}{d t} & p=C v \\frac{d v}{d t} \\\\\nw \\text { (energia armazenada) } & 0 & w=\\frac{1}{2} L i^{2} & w=\\frac{1}{2} C v^{2} \\\\\n\\text { Associação em série } & R_{\\mathrm{eq}}=R_{1}+R_{2} & L_{\\mathrm{eq}}=L_{1}+L_{2} & \\frac{1}{C_{\\mathrm{eq}}}=\\frac{1}{C_{1}}+\\frac{1}{C_{2}} \\\\\n\\text { Associação em paralelo } & \\frac{1}{R_{\\mathrm{eq}}}=\\frac{1}{R_{1}}+\\frac{1}{R_{2}} & \\frac{1}{L_{\\mathrm{eq}}}=\\frac{1}{R_{1}}+\\frac{1}{R_{2}} & C_{\\mathrm{eq}}=C_{1}+C_{2} \\\\\n\\text { Comportamento em regime estacionário } & \\text { sem mudanças } & \\text { curto-circuito } & \\text { circuito aberto } \\\\\n\\text { Pode } v \\text { variar instantaneamente? } & \\text { sim } & \\text { sim } & \\text { não } \\\\\n\\text { Pode } i \\text { variar instantaneamente? } & \\text { sim } & \\text { não } & \\text { sim }\\\\ \\hline\n\\end{array}\n$$\n\n### Problema 1\n \nPara o circuito abaixo, determine $v_{C1}$, $v_{C2}$ e $i_{L}$ assumindo que o circuito encontra-se em regime estacionário.\n\n\n\n### Problema 2\n \nNo circuito abaixo, sabe-se que $i_0(t)= 50e^{-8000t}[\\cos(6000t)+2\\mathrm{sen}(6000t)]$ mA, para $t\\geq 0^+$. Determine $v_{C}(0^+)$, $v_{L}(0^+)$ e $v_{R}(0^+)$.\n\n\n\n\n\n```python\n# define variável tempo \nt = sp.symbols('t', real=True)\n\n# expressão para a corrente no circuito\ni0 = 50*sp.exp(-8000*t)*(sp.cos(6000*t)+2*sp.sin(6000*t))*1e-3\n\n# plota gráfico da corrente\ntmax = 1e-3\nintervalo = np.linspace(0, tmax, num = 1000)\nsymplot(t, i0, intervalo, funLabel='$i_0(t)$')\n```\n\n\n```python\n# valores dos parâmetros do circuito\nR = 320\nL = 20e-3\nC = 0.5e-6\n```\n\n\n```python\n# calcula tensão no indutor\nvL = L*sp.diff(i0, t)\nvL = sp.simplify(vL)\n\nprint('Tensão no indutor:')\nsymdisp('v_L(t) = ', vL, 'V')\n```\n\n Tensão no indutor:\n\n\n\n$\\displaystyle v_L(t) = \\left(- 22.0 \\sin{\\left(6000 t \\right)} + 4.0 \\cos{\\left(6000 t \\right)}\\right) e^{- 8000 t}\\;V$\n\n\n\n```python\nsymdisp('v_L(0^+) = ', vL.evalf(subs={t:0}), 'V')\n```\n\n\n$\\displaystyle v_L(0^+) = 4.0\\;V$\n\n\n\n```python\n# calcula tensão no resistor\nvR = R*i0\nvR = sp.simplify(vR)\n\nprint('Tensão no resistor:')\nsymdisp('v_R(t) = ', vR, 'V')\n```\n\n Tensão no resistor:\n\n\n\n$\\displaystyle v_R(t) = \\left(32.0 \\sin{\\left(6000 t \\right)} + 16.0 \\cos{\\left(6000 t \\right)}\\right) e^{- 8000 t}\\;V$\n\n\n\n```python\nsymdisp('v_R(0^+) = ', vR.evalf(subs={t:0}), 'V')\n```\n\n\n$\\displaystyle v_R(0^+) = 16.0\\;V$\n\n\n\n```python\n# calcula tensão no capacitor (LKT)\nvC = vR + vL\nvC = sp.simplify(vC)\n\nprint('Tensão no capacitor:')\nsymdisp('v_C(t) = ', vC, 'V')\n```\n\n Tensão no capacitor:\n\n\n\n$\\displaystyle v_C(t) = \\left(10.0 \\sin{\\left(6000 t \\right)} + 20.0 \\cos{\\left(6000 t \\right)}\\right) e^{- 8000 t}\\;V$\n\n\n\n```python\nsymdisp('v_C(0^+) = ', vC.evalf(subs={t:0}), 'V')\n```\n\n\n$\\displaystyle v_C(0^+) = 20.0\\;V$\n\n\n\n```python\n# checagem de vC(t) via integração de i0\n\nvC = -(1/C)*sp.integrate(i0, (t, 0, t)) + 20\nvC = sp.simplify(vC)\n\nsymdisp('v_C(t) = ', vC, 'V')\n```\n\n\n$\\displaystyle v_C(t) = \\left(10.0 \\sin{\\left(6000 t \\right)} + 20.0 \\cos{\\left(6000 t \\right)}\\right) e^{- 8000 t}\\;V$\n\n\n\n```python\nsymplot(t, [vC, vR, vL], intervalo, funLabel=['$v_C(t)$ ','$v_R(t)$','$v_L(t)$'])\n```\n", "meta": {"hexsha": "eb29f5af9d218506ab3f4c9dbf120f274d4498a9", "size": 46992, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 6.2.ipynb", "max_stars_repo_name": "Jefferson-Lopes/ElectricCircuits", "max_stars_repo_head_hexsha": "bf2075dc0731cacece75f7b0b378c180630bdf85", "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": "Jupyter notebooks/Circuitos Eletricos I - Semana 6.2.ipynb", "max_issues_repo_name": "Jefferson-Lopes/ElectricCircuits", "max_issues_repo_head_hexsha": "bf2075dc0731cacece75f7b0b378c180630bdf85", "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": "Jupyter notebooks/Circuitos Eletricos I - Semana 6.2.ipynb", "max_forks_repo_name": "Jefferson-Lopes/ElectricCircuits", "max_forks_repo_head_hexsha": "bf2075dc0731cacece75f7b0b378c180630bdf85", "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": 93.984, "max_line_length": 19696, "alphanum_fraction": 0.8319926796, "converted": true, "num_tokens": 2224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.1602660263115288, "lm_q1q2_score": 0.057018630634284265}} {"text": "\n

    \n\n
    \n

    10. Markov chains

    \n \n\n\n

    \n

    Andrej Košir, Lucami, FE

    \n

    Kontakt: prof. dr. Andrej Košir, andrej.kosir@lucami.fe.uni-lj.si, skype=akosir_sid

    \n
    \n\n\n

    \n
    1
    \n\n\n## ■ Intro\n\n- Goals: \n - Markov chain modeling\n - Markov chain state analysis \n- Stochastic process on finite states, most useful and used. We limit to:\n - Discrete times\n - Discrete state space (finite or countably many states)\n- Case: user behavior\n- Usage\n - Finite state machine analysis: software, TC \u000bsystem, ...\n - Models in economy\n- What are questions:\n - Distributions of visits\n - Long term behavior\n - Absorption of states\n\n\n\n
    \n\n
    \n
    \n\n
    \n\n
    \n
    \n\n\n

    \n
    2
    \n\n\n## ■ Sections \n\n\n10.1. Definition, basic characteristics\n\n■ Markov chain definition $\\large{*}$\n\n■ Transition matrix, distribution of states $\\large{*}$\n\n\n10.2. Classification of states\n\n■ Communication of states and period $\\large{*}$\n\n■ Recurrent and transient state $\\large{*}$\n\n■ Ergodic Markov chain and return times\n\n■ Stationary (limit) distribution $\\large{*}$\n \n■ Finite Markov chain $\\large{*}$\n\n\n10.3. Transition matrix estimation\n\n■ Transition probability estimation\n\n■ Confidence intervals and quantiles\n\n■ Sample size determination\n\n■ Numerical aspect\n\n■ Case: telecommunication service user modeling\n\n\n\n

    \n
    3
    \n\n\n## 10.1. Definition, basic characteristics\n\n■ Markov chain definition\n\n■ Transition matrix, distribution of states\n\n\n\n

    \n
    4
    \n\n\n## ■ Markov chain definition\n\n\n- State space $S$, $m=|S|$\n - Finite, countable, continuous\n\n\n- Time $T$\n - Discrete, continuous\n\n\n- Stochastic process: \n$$ X_n : T \\to S $$\n\n\n- Discrete Markov chain is a discrete time discrete space Markov chain having Markov property\n$$ P[X_{n+1}|_{X_n, X_{n-1}, \\ldots, X_0}] = P[X_{n+1}|_{X_n}] = P[X_1|_{X_0}] $$\n\n\n- Transition probability of one step\n$$ p_{ij} = P[X_{n+1}=j|_{X_n=i}] $$\n\n\n- Finite state space means there is a matrix of transition probabilities\n$$ P = [p_{ij}], \\; i,j\\in S. $$\n - Row sums are equal to 1. \n\n\n\n

    \n
    5
    \n\n\n\n```python\nimport numpy as np\nfrom sympy import Matrix\nfrom sympy.functions import re\n\n# Case 1 \n# Transition matrix\nP = np.array([[0.7, 0.2, 0.1, 0.0], \n [0.2, 0.5, 0.2, 0.1], \n [0.05, 0.15, 0.6, 0.2], \n [0.0, 0.2, 0.0, 0.8]])\n```\n\n## ■ Transition matrix, distribution of states\n\n\n\n- Transition matrix for $n$ steps\n - $p_{ij}^{(n)} = P[X_{k+n}|_{X_k=i}]$, $P^{(n)}=[p_{ij}^{(n)}]$\n - From total probability formula\n $$ P^{(n)} = P^n $$\n \n\n- Distribution of states: \n$$ \\pi_i^n = P[X_n=i], \\pi^n = [\\pi_1^n, \\ldots, \\pi_i^n] $$\n - Initial distribution: $\\pi^0$. If initial state $X_0=i_0$ is known\n $$ \\pi^0=\\delta_{i_0 i} $$\n - From total probability formula:\n $$ \\pi^n = P^{(n)} \\pi^0 $$\n - More on limit distribution later\n\n\n\n

    \n
    6
    \n\n\n## 10.2. Classification of states\n\n\n■ Communication of states and period\n\n■ Recurrent and transient state\n\n■ Ergodic Markov chain and return times\n\n■ Stationary (limit) distribution\n\n■ Finite Markov chain\n\n\n\n

    \n
    7
    \n\n\n## ■ Communication of states and period\n\n\n- Accessible state\n - State $j$ is accessible from state $i$ if $\\exists n: p_{ij}^{(n)}>0$. Notation $i\\leftrightarrow j$\n - Two states communicate if $i\\rightarrow$ and $i \\leftarrow j$, denoted by $i\\leftrightarrow j$\n - „Communicate“ is equivalent relation\n\n\n- Markov chain is irreducible if there are only one single communicating class\n\n\n- Period of state $i$ ia denoted by $d(i)$ is greatest common divisor of all $n$ such that $P_{ii}^{(n)} > 0$: \n - If $i\\leftrightarrow j$ then $d(i) = d(j)$;\n - State is aperiodic if $d(i)=1$;\n\n\n\n- State $i$ is zero state if \n$$ \\lim_{n\\to\\infty} P_{ii}^{(n)} = 0. $$\n\n\n

    \n
    8
    \n\n\n\n```python\n# ---------------------------------------------------------------------------------------------------\n# Classification of states\nprint ('Transition matrix P=\\n', P)\nprint ('\\nTransition matrix P^2=\\n', np.linalg.matrix_power(P, 2))\n\n# All entries of P^2 are non-zero\n# => All atates are connected\n```\n\n Transition matrix P=\n [[0.7 0.2 0.1 0. ]\n [0.2 0.5 0.2 0.1 ]\n [0.05 0.15 0.6 0.2 ]\n [0. 0.2 0. 0.8 ]]\n \n Transition matrix P^2=\n [[0.535 0.255 0.17 0.04 ]\n [0.25 0.34 0.24 0.17 ]\n [0.095 0.215 0.395 0.295]\n [0.04 0.26 0.04 0.66 ]]\n\n\n\n```python\n# ---------------------------------------------------------------------------------------------------\n# Decompose transition matrix\n# Use Jordan decomposition\n#mP = Matrix(P)\n#mB, mJ = mP.jordan_form()\n#B, J = np.array(mB), np.array(mJ)\nB = np.array([[-0.5,-0.776313,0.659526,-0.413722],\n [-0.5,-0.212847,-0.11514,0.830469],\n [-0.5,0.283275,-0.73692,-0.123153],\n [-0.5,0.521335,0.0933625,-0.352121]])\nJ = np.array([[1.,0,0,0],\n [0,0.718345,0,0],\n [0,0,0.553349,0],\n [0,0,0,0.328305]])\n\n# Test decomposition\nerr_mat = P - np.dot(B, np.dot(J, np.linalg.inv(B)))\nprint ('\\nDecomposition error norm = ', np.linalg.norm(err_mat))\n```\n\n \n Decomposition error norm = 7.249920892047682e-07\n\n\n## ■ Recurrent and transient state\n\n\n- Probability of return after exactly $n$ steps\n$$ f_{ij}^n = P[X_n=j|_{X_{n-1}\\ne j, \\ldots, X_1\\ne j, X_0=i}] $$\n\n\n- Random variable of transitions from $i$ to $j$ is denoted by $T_{i}$ and its distribtion is \n$$ T_{ij} \\sim \\left(\\matrix{0 & 1 & 2 & \\ldots \\cr f_{ij}^0 & f_{ij}^1 & f_{ij}^2 & \\ldots}\\right) $$\n - Denote $T_i = T_{ii}$\n - Denote $\\sum_{n=0}^\\infty f_{ii}^n = f_{ii}^*$. Value \n $$ 1 - f_{ii}^* $$\n is a probability that Markov Chain newer returns to state 𝑖 after leaving it. \n\n\n- State $i$ is **recurrent** if $f_{ii}^* = 1$. State is **transient** if it is not recurrent.\n - Recurrence and transience are communicating class properties\n\n\n- We have: state $i$ is recurrent if and only if\n$$ \\sum_{n=1}^\\infty P_{ii}^{(n)} = \\infty $$\n\n- Also: if $i\\leftrightarrow j$ then both states are either transient or recurrent \n\n\n\n

    \n
    9
    \n\n\n\n```python\n# Recurent, transient? \n\n# Eigenvalues\neigVals, eigVecs = np.linalg.eig(P.T)\n\n# Get it sorted\nidx = eigVals.argsort()[::-1] \neigVa = eigVals[idx]\neigVc = eigVecs[:,idx]\n\nlas_bf = (1./(1-eigVa[1:4]))-1\nprint ('las_bf', las_bf)\n \nsumJn = np.diag(np.insert(las_bf, 0, np.inf))\nprint ('\\nSum J^n\\n', sumJn)\n\nsumPn = np.dot(B, np.dot(sumJn, np.linalg.inv(B)))\nprint ('\\nSum P^n\\n', sumPn)\n\n# Since all diagonal elements of sum P^n are infinity\n# => all states are recurrent\n```\n\n las_bf [2.55044912 1.23888596 0.48877142]\n \n Sum J^n\n [[ inf 0. 0. 0. ]\n [0. 2.55044912 0. 0. ]\n [0. 0. 1.23888596 0. ]\n [0. 0. 0. 0.48877142]]\n \n Sum P^n\n [[inf inf inf inf]\n [inf inf inf inf]\n [inf inf inf inf]\n [inf inf inf inf]]\n\n\n\n```python\ndef inf_sum(a_lst):\n return [(la/(1.0-la) if la < 1 else np.infty) for la in a_lst]\n\n# ---------------------------------------------------------------------------------------------------\n# Are states recurrent?\n# Compute sum of P^n\nsumJ = np.diag(inf_sum(np.diag(J)))\nsumP = np.dot(B, np.dot(sumJ, np.linalg.inv(B)))\n\nprint ('\\nSum of P^n = \\n', sumP)\n# => All states are reccurent \n```\n\n \n Sum of P^n = \n [[inf inf inf inf]\n [inf inf inf inf]\n [inf inf inf inf]\n [inf inf inf inf]]\n\n\n## ■ Ergodic Markov chain and return times\n\n\n- Markov chain is **Ergodic** if it is \n - Irreducible\n - Recurrent (all states are recurrent)\n - Aperiodic (all states are aperiodic)\n - Nonzero (all states are positive)\n \n \n- Expected return time: \n$$ E(T_i) = \\sum_{n=0}^\\infty n f_{ii}^{(n)} $$\n\n\n- In ergodic Markov chain\n$$ \\lim_{n\\to\\infty} P_{ii}^{(n)} = \\frac{1}{E(T_i)} $$\n$$ \\lim_{n\\to\\infty} P_{ij}^{(n)} = \\lim_{n\\to\\infty} P_{ii}^{(n)} $$ \n\n\n- Recurrent **zero** state $i$:\n$$ \\lim_{n\\to\\infty} P_{ii}^{(n)} = 0 \\; \\Leftrightarrow \\; E(T_i) = \\infty $$\n\n\n- Recurrent **positive** = **ergodic** state $i$: \n$$ \\lim_{n\\to\\infty} P_{ii}^{(n)} > 0 \\; \\Leftrightarrow \\; E(T_i) < \\infty $$\n\n\n\n

    \n
    10
    \n\n\n\n```python\ndef inf_lim(a_lst):\n return [(0 if la < 1 else 1) for la in a_lst]\n\n# ---------------------------------------------------------------------------------------------------\n# Zero or positive states?\n# Compute lim of P^n\nlimJ = np.diag(inf_lim(np.diag(J)))\nlimP = np.dot(B, np.dot(limJ, np.linalg.inv(B)))\n\nprint ('\\nlim of P^n = \\n', limP)\n\n# Since all lim P^n are positive\n# => all states are positive\n\n# Expected times of visits\nETi = 1.0/np.diag(limP)\n\nprint ('\\nExpected number of visits py states:\\n', ETi)\n```\n\n \n lim of P^n = \n [[0.21301781 0.27218919 0.18934915 0.32544385]\n [0.21301781 0.27218919 0.18934915 0.32544385]\n [0.21301781 0.27218919 0.18934915 0.32544385]\n [0.21301781 0.27218919 0.18934915 0.32544385]]\n \n Expected number of visits py states:\n [4.69444311 3.67391519 5.28124903 3.07272668]\n\n\n## ■ Stationary (limit) distribution\n\n\n- State distribution after $n$ steps \n$$ \\pi_i^n = P[X_n=i], \\qquad \\pi^n = [\\pi_1^n, \\ldots, \\pi_i^n] $$\n\n\n- Stationary (limit) distribution: \n $$ \\pi = \\lim_{n\\to\\infty} \\pi^n $$\n - When uniquely defined: when all states are recurrent positive\n\n\n- Ergodic MC: stationary distribution exists\n- Stationary distribution of ergodic MC chain is left eigenvector of transition matrix: \n $$ \\pi^\\top = \\pi^\\top P. $$\n\n\n- Note: in an ergodic MC a stationary distribution independent of initial distribution $\\pi^0$.\n\n\n\n

    \n
    11
    \n\n\n\n```python\n# ---------------------------------------------------------------------------------------------------\n# Limit distribuion\neigVals, eigVecs = np.linalg.eig(P.T)\npi = eigVecs[:, 0]/sum(eigVecs[:, 0])\n\nprint ('\\neigVals=\\n', eigVals)\n#print '\\neigVecs=\\n', eigVecs\nprint ('\\nLimit distribution =', pi)\n```\n\n \n eigVals=\n [1. 0.32830522 0.71834549 0.55334929]\n \n Limit distribution = [0.21301775 0.27218935 0.18934911 0.32544379]\n\n\n## ■ Probability of absorption\n\n\n- Absorption: chain never leave a subset of states $S_0 \\subset S$\n\n\n- What is the probability of absorption?\n\n\n- If a chain starts in transient state, then either:\n 1. It leaves a set of transient states with probability of 1\n 2. It enters a set of recurrent states with probability of 1\n\n\n- Absorbing states $i$: the only state of an absorbing state\nWe have: $i$ absorbing if and only if \n$P_{ii}=1$\n\n\n- Let $i\\in S$ be a transient state, $S_e$ a set of recurrent states:
    \nProbability of absorption: $\\pi_i(S_e)$ is the probability MC with $X_0=i$ gets absorbed into the set of states $S_e$\n\n\n- We have\n$$ \\lim_{n\\to\\infty} P_{ij}^{(n)} = \\pi_i(S_e)\\pi_j. $$\n\n\n\n

    \n
    12
    \n\n\n## ■ Finite Markov chain\n\n\n- Finite number of states $|S|=m < \\infty$.\n\n\n- Each finite MC has recurrent states!\n\n\n- All recurrent states are positive, that is ergodic and has finite expected return time\n$$ \\lim_{n\\to\\infty} P_{ii}^{(n)} > 0. $$\n\n\n- Classification of states: all states are $S=S_m\\cup S_e$, where\n - Transient states: $S_m$\n - Ergodic states: $S_e$\n \n \n- Transient matrix is of a block form:\n - Ergodic states: $1, \\ldots, m-K$\n - Transient state: $m-K+1, \\ldots, m$\n $$ P = \\left[\\matrix{S & 0 \\cr R & Q}\\right] $$\n\n- Fundamental matrix:\n$$ N = (I - Q)^{-1}. $$\n\n\n\n \n

    \n
    13
    \n\n\n\n```python\n# Case 2\nc2P = np.array(\n [[0.7, 0.3, 0.0, 0.0], \n [0.2, 0.8, 0.0, 0.0], \n [0.05, 0.15, 0.6, 0.2], \n [0.0, 0.2, 0.0, 0.8]])\n\nprint ('Transition matrix P=\\n', c2P)\n\n```\n\n Transition matrix P=\n [[0.7 0.3 0. 0. ]\n [0.2 0.8 0. 0. ]\n [0.05 0.15 0.6 0.2 ]\n [0. 0.2 0. 0.8 ]]\n\n\n\n```python\n# ---------------------------------------------------------------------------------------------------\n# Classification of states\nprint ('Transition matrix P=\\n', c2P)\nprint ('\\nTransition matrix P^2=\\n', np.linalg.matrix_power(c2P, 2))\nprint ('\\nTransition matrix P^3=\\n', np.linalg.matrix_power(c2P, 3))\n\n# Matrix multiplications by blocks\n# => 2 x 2 block of zeros stayes the same\n# => There are two connected classes of states\n```\n\n Transition matrix P=\n [[0.7 0.3 0. 0. ]\n [0.2 0.8 0. 0. ]\n [0.05 0.15 0.6 0.2 ]\n [0. 0.2 0. 0.8 ]]\n \n Transition matrix P^2=\n [[0.55 0.45 0. 0. ]\n [0.3 0.7 0. 0. ]\n [0.095 0.265 0.36 0.28 ]\n [0.04 0.32 0. 0.64 ]]\n \n Transition matrix P^3=\n [[0.475 0.525 0. 0. ]\n [0.35 0.65 0. 0. ]\n [0.1375 0.3505 0.216 0.296 ]\n [0.092 0.396 0. 0.512 ]]\n\n\n\n```python\n# ---------------------------------------------------------------------------------------------------\n# Limit distribuion\neigVals, eigVecs = np.linalg.eig(c2P.T)\n\n\n# Get it sorted\nidx = eigVals.argsort()[::-1] \neigenValues = eigVals[idx]\neigenVectors = eigVecs[:,idx]\n\n# Normalize eigenvector\npi = eigenVectors[:, 0]/sum(eigenVectors[:, 0])\n\nprint ('\\neigVals=\\n', eigenValues)\n#print '\\neigVecs=\\n', eigenVectors\nprint ('\\nLimit distribution =', pi)\n```\n\n \n eigVals=\n [1. 0.8 0.6 0.5]\n \n Limit distribution = [ 0.4 0.6 -0. -0. ]\n\n\n\n```python\n# ---------------------------------------------------------------------------------------------------\n# Decompose transition matrix\n# Use Jordan decomposition\n#mP = Matrix(c2P)\n#mB, mJ = mP.jordan_form()\n#B, J = np.array(mB), np.array(mJ)\nc2B = np.array([[1.0, 0, 0, 10.0/4],\n [1.0, 0, 0, -3.0/2],\n [1.0, 1.0, 1.0, -7.0/8],\n [1.0, 1.0, 0, 1.0]])\nc2J = np.array([[1.0,0,0,0],\n [0,4.0/5,0,0],\n [0,0,3.0/5,0],\n [0,0,0,1.0/2]])\n\n# Test decomposition\nerr_mat = c2P - np.dot(c2B, np.dot(c2J, np.linalg.inv(c2B)))\nprint ('\\nDecomposition error norm = ', np.linalg.norm(err_mat))\n```\n\n \n Decomposition error norm = 1.9675159943996247e-16\n\n\n\n```python\ndef prd(a,b):\n if np.isinf(a) and b == 0:\n return 0\n if np.isinf(b) and a == 0:\n return 0\n return a*b\n\ndef myDot(A,B):\n nA1, nA2, nB2 = A.shape[0], A.shape[1], B.shape[1]\n AB = np.zeros((nA1,nB2))\n for i in range(nA1):\n for j in range(nB2):\n curr = 0\n for k in range(nA2):\n curr += prd(A[i,k], B[k,j])\n AB[i, j] = curr\n return AB\n\n# Classification of states\n# Recurent, transient? \n\n# Eigenvalues\neigVals, eigVecs = np.linalg.eig(c2P.T)\n\n# Get it sorted\nidx = eigVals.argsort()[::-1] \neigVa = eigVals[idx]\neigVc = eigVecs[:,idx]\n\nlas_bf = (1./(1-eigVa[1:4]))-1\nsumJn = np.diag(np.insert(las_bf, 0, np.inf))\n\nsumPn = myDot(c2B, myDot(sumJn, np.linalg.inv(c2B)))\nprint ('\\nSum P^n\\n', sumPn)\n\n# Since diagonal elements of sum P^n i=1 and i=2 are infinity\n# => states i=1 and i=2 are recurrent\n# Since diagonal elements of sum P^n i=3 and i=4 are finite\n# => states i=3 and i=4 are transient\n\n```\n\n \n Sum P^n\n [[inf inf 0. 0. ]\n [inf inf 0. 0. ]\n [inf inf 1.5 2.5]\n [inf inf 0. 4. ]]\n\n\n\n```python\ndef inf_lim(a_lst):\n return [(0 if la < 1 else 1) for la in a_lst]\n\n# ---------------------------------------------------------------------------------------------------\n# Zero or positive states?\n# Compute lim of P^n\nlimJ = np.diag(inf_lim(np.diag(c2J)))\nlimP = np.dot(c2B, np.dot(limJ, np.linalg.inv(c2B)))\n\nprint ('\\nlim of P^n = \\n', limP)\n\n# Since all lim P^n are positive\n# => all states are positive\n\n# Expected times of visits\nETi = 1.0/np.diag(limP)\n\nprint ('\\nExpected number of visits py states:\\n', ETi)\n\n```\n\n \n lim of P^n = \n [[0.4 0.6 0. 0. ]\n [0.4 0.6 0. 0. ]\n [0.4 0.6 0. 0. ]\n [0.4 0.6 0. 0. ]]\n \n Expected number of visits py states:\n [2.5 1.66666667 inf inf]\n\n\n /home/nbuser/anaconda3_501/lib/python3.6/site-packages/ipykernel/__main__.py:16: RuntimeWarning: divide by zero encountered in true_divide\n\n\n\n```python\n# ---------------------------------------------------------------------------------------------------\n# Limit distribuion\neigVals, eigVecs = np.linalg.eig(c2P.T)\n\n\n# Get it sorted\nidx = eigVals.argsort()[::-1] \neigenValues = eigVals[idx]\neigenVectors = eigVecs[:,idx]\n\n# Normalize eigenvector\npi = eigenVectors[:, 0]/sum(eigenVectors[:, 0])\n\nprint ('\\neigVals=\\n', eigenValues)\n#print '\\neigVecs=\\n', eigenVectors\nprint ('\\nLimit distribution =', pi)\n```\n\n \n eigVals=\n [1. 0.8 0.6 0.5]\n \n Limit distribution = [ 0.4 0.6 -0. -0. ]\n\n\n## ■ Number of visits of a transient state\n\n\n- Random variable $n_i$: number of visits of a state $i$ in an arbitrary long time\n\n\n- Expected number of visits of a state $j$ if initial state is $𝑖$: \n $$ E_i[n_j] < \\infty $$\n\n- We have: if state $i$ is transient: \n$$ E_i[n_j] = \\sum_{k=1}^\\infty P_{ij}^{(k)} $$\n\n- Also - fundamental matrix gives expected values:\n$$ \\left[E_i[n_j]\\right] = N $$ \n\n\n\n\n

    \n
    14
    \n\n\n\n```python\n# Expected number of visits of recurent states\nm = 4 # |S|\nK = 2 # number of recurent states\n\nQ = c2P[K:m, K:m]\nprint ('Part of transition matrix Q = \\n', Q)\n\nN = np.linalg.inv(np.eye(m-K)-Q)\nprint ('\\nFundamental matrix N =\\n', N)\n```\n\n Part of transition matrix Q = \n [[0.6 0.2]\n [0. 0.8]]\n \n Fundamental matrix N =\n [[2.5 2.5]\n [0. 5. ]]\n\n\n## 10.3 Transition matrix estimation\n\n\n■ Transition probability estimation\n\n■ Confidence intervals and quantiles\n\n■ Sample size determination\n\n■ Numerical aspect\n\n■ Case: telecommunication service user modeling\n\n\n

    \n
    15
    \n\n\n## ■ Transition probability estimation\n\n- Transition probability \n$$ p_{ij} = \\frac{n_k}{n} $$\nis a statistical estimation;\n\n\n- Parameter estimation\n - estimate and termine\n - expected value $\\overline{x}$\n - standard deviation $\\sigma$\n - for a selected risk level $\\alpha$ compute $z_\\alpha$ (if normal distribution $z_{0.05}=1.96$)\n - Confidence interval: \n$$ CI = [\\overline{x} - z_\\alpha\\frac{\\sigma}{\\sqrt{n}}, \\overline{x} + z_\\alpha\\frac{\\sigma}{\\sqrt{n}}] $$\n - Sample size: determined from a preset confidence interval length \n $$ |CI| = 2 z_\\alpha\\frac{\\sigma}{\\sqrt{n}} $$\n\n\n\n\n\n\n\n\n

    \n
    16
    \n\n\n## ■ Confidence intervals and quantiles\n\n\n- Confidence interval visualization\n\n\n\n\n\n

    \n
    17
    \n\n\n## ■ Transition matrix estimation sample size determination\n\n\n- From confidence interval size\n\n\n- Confidence interval for risk level $\\alpha=0.05$ ($z_\\alpha=1.96$)\n$$ CI = [p_0 - z_\\alpha\\sqrt{p_0(1-p_0)/n}, p_0 + z_\\alpha\\sqrt{p_0(1-p_0)/n}] $$\n\n\nFor $p=0.65$ and $|CI|=\\Delta p$ at $\\alpha=0.05$\n$$ n\\geq \\frac{4 z_\\alpha^2}{\\Delta p^2} p_0 (1-p_0) $$\nwe get\n - for $\\Delta p=0.01:$ $n\\geq 34959$,\n - for $\\Delta p=0.02:$ $n\\geq 175$,\n - for $\\Delta p=0.04:$ $n\\geq 88$.\n \n\n\n

    \n
    18
    \n\n\n## ■ Numerical aspect of transition matrix computation\n\n\n- We need matrix power \n$$ P^n = P^{(n)} $$\n\n\n- Jordan decomposition\n$$ P = B J B^{-1}, $$\nwhere $J$ is Jordan canonical form. \n\n\n- For each class of states we have\n$$ J = \\lambda I + R $$\nand \n$$ P^n = B J^n B^{-1} $$\n\n

    \n
    19
    \n\n\n## ■ Case: telecommunication service user modeling\n\n\n- A set of telecommunication users $U$\n\n\n- We split them into classes: $U=U_1 \\cup U_2 \\cup U_3 \\cup U_4$\n - Very satisfied: $U_1$\n - Satisfied: $U_2$\n - Not satisfied: $U_3$\n - Churners: $U_4$\n\n\n- Initial distribution: estimation of users\n\n- Results:\n - Recurrent - transients states\n - Stationary distribution\n\n\n\n

    \n
    20
    \n\n\n## ■ Conclusion\n\n\n- Most useful: finite Markov chain\n- Check the transition matrix assumption: stationarity \n\n\n

    \n
    21
    \n\n", "meta": {"hexsha": "7b9cf65dafb066943d8cf843e38dd6873231ae56", "size": 38849, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AKosir-OPvTK-Lec10_MarkovChains_ANGL.ipynb", "max_stars_repo_name": "andrejkk/OPvTK", "max_stars_repo_head_hexsha": "769b4dc144fa07e4604d945df5672f14741154b5", "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": "AKosir-OPvTK-Lec10_MarkovChains_ANGL.ipynb", "max_issues_repo_name": "andrejkk/OPvTK", "max_issues_repo_head_hexsha": "769b4dc144fa07e4604d945df5672f14741154b5", "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": "AKosir-OPvTK-Lec10_MarkovChains_ANGL.ipynb", "max_forks_repo_name": "andrejkk/OPvTK", "max_forks_repo_head_hexsha": "769b4dc144fa07e4604d945df5672f14741154b5", "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": 29.587966489, "max_line_length": 194, "alphanum_fraction": 0.4824062395, "converted": true, "num_tokens": 7294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11436852316318395, "lm_q1q2_score": 0.05673751862695749}} {"text": "# 附录 D:贝叶斯神经网络\n\n【原文】Goan, E., & Fookes, C. (2020). Bayesian Neural Networks: An Introduction and Survey. https://arxiv.org/abs/2006.12024\n\n【摘要】神经网络已经为许多机器学习任务提供了最先进的结果,例如计算机视觉、语音识别和自然语言处理领域的检测、回归和分类任务等。尽管取得了成功,但它们通常是在频率学派框架内实施的,这意味着其无法对预测中的不确定性进行推断。本文介绍了贝叶斯神经网络及一些开创性研究,对不同近似推断方法进行了比较,并提出未来改进的一些方向。\n\n---\n\n\n\n## 1 引言\n\n长期以来,仿生学一直是技术发展的基础。科学家和工程师反复使用物理世界的知识来模仿自然界对经过数十亿年演变而来的复杂问题的优雅解决方案。生物仿生学在统计学和机器学习中的重要例子是感知器的发展 `[1]`,它提出了一个基于神经元生理学的数学模型。机器学习团体已使用该概念开发高度互连的神经元阵列统计模型,以创建神经网络。\n\n虽然神经网络的概念早在几十年前就已为人所知,但其应用直到最近才显现出来。神经网络研究的停滞很大程度上由三个关键因素造成:\n\n- 缺乏足够的算法来训练这些网络。\n- 训练复杂网络所需的大量数据。\n- 训练过程所需大量计算资源。\n\n1986 年,`[3]` 引入了反向传播算法解决了网络的有效训练问题。虽然有了有效的训练手段,但网络规模不断扩大,仍然需要相当多计算资源。该问题在 `[4,5,6]` 中得到了解决,其表明通用 GPU 可有效执行训练所需的许多操作。随着硬件不断进步,能够捕获和存储真实世界数据的传感器数量不断增加。通过高效训练方法、改进的计算资源和庞大的数据集,复杂神经网络的训练已经变得真正可行。\n\n在绝大多数情况下,神经网络都是在频率主义框架内使用的;通过使用有效的数据,用户可以定义网络结构和成本函数,然后对其进行优化,以获得模型参数的点估计。增加神经网络参数(权重)的数量或网络深度会增加神经网络的容量,使其能够表示强非线性函数,进而允许神经网络处理更复杂的任务。但频率主义框架也很容易由于参数过多而产生过拟合问题,但使用大型数据集和正则化方法(如寻找最大后验估计),可以限制网络所学习函数的复杂性,并有助于避免过拟合。\n\n神经网络已经为许多机器学习和人工智能应用提供了最先进的结果,例如图像分类 `[6,7,8]` ,目标检测 `[9,10,11]` 和语音识别 `[12,13,14,15]` 。其他网络(如 `DeepMind` `[16]` 开发的 `AlphaGo` 模型)更加突出了神经网络在开发人工智能系统方面的潜力,吸引了广泛受众。随着神经网络性能的不断提高,某些行业对神经网络的开发和应用越来越显著。神经网络目前已经大量用于制造 `[17]` 、资产管理 `[18]` 和人机交互技术 `[19,20]`。\n\n不过,自从神经网络在工业中部署以来,也发生了许多事故。这些系统的故障导致模型出现不道德或不安全的行为,包括一些对边缘化群体表现出较大(性别和种族)偏见的模型 `[21,22,23]`,或者导致生命损失的极端案例 `[24,25]`。神经网络是一种统计黑盒模型,这意味着决策过程并非基于定义良好而直观的协议。相反,决策以一种无法解释的方式做出。因此,在社会和安全关键环境中使用这些系统会引起相当大的伦理关注。鉴于此,欧盟发布了一项新规定,明确用户拥有对人工智能系统所做决定的“解释权” `[26,27]`。由于不清楚系统操作或设计的原则方法,其他领域的专家仍然对采用神经网络技术感到担忧 `[28,29,30]`。这激发了对可解释人工智能的研究尝试 `[31]`。\n\n神经网络的在工程上的充分设计需要合理地理解其能力和局限性;尽量在部署前就找出其不足,而避免在悲剧发生以后再调查其缺陷。由于神经网络是一个统计黑匣子,当前理论尚无法解释和说明其决策过程。`普通神经网络的频率学派观点`为决策提供了缺乏解释和过度自信的估计,使其不适用于诸如医疗诊断、自动驾驶汽车等高风险领域。而贝叶斯统计提供了一种自然方式来推断预测中存在的不确定性,并可以深入解释做出决策的原因。\n\n图 1 比较了执行同一回归任务的简单神经网络方法和贝叶斯方法,说明了度量不确定性的重要性。虽然两种方法在训练数据范围内都执行得很好,但贝叶斯方法提供了预测输出的完全分布,而神经网络方法仅提供了的点估计。贝叶斯方法输出分布的特点,允许开发更多可靠的模型,因为它可以识别预测中的不确定性。考虑到神经网络是人工智能系统最有前途的技术,“如何让人们信任神经网络的预测结果” 也就随之变得越加重要了。\n\n\n\n图 1:在紫色区域没有训练数据的回归任务中,神经网络与传统概率方法的比较。(a) 使用具有 2 个隐藏层的神经网络的回归输出;(b) 使用高斯过程框架的回归,灰色条表示从均值开始 ±2 标准差范围。\n\n贝叶斯观点使我们能够解决神经网络目前面临的许多挑战。为此,在神经网络的参数上放置一个分布,由此得到的神经网络被称为`贝叶斯神经网络(Bayesian Neural Networks,BNN)`。\n\n贝叶斯神经网络的目标是拥有一个高容量模型,该模型能够展示贝叶斯分析的重要理论优势。最近已经有不少研究致力于将贝叶斯近似应用于实际神经网络中,而由于贝叶斯方法的计算/空间复杂度问题,这些研究面临的主要挑战集中在:**如何在合理计算资源约束下,部署能够提供准确预测能力的模型。**\n\n本文目的是向读者提供容易理解的贝叶斯神经网络介绍,同时伴随对该领域一些开创性工作和实验的调研,以激发对当前方法能力和局限性的讨论。涉及贝叶斯神经网络的资料太多,无法一一列举,因此本文仅列出了其中具有里程碑性质的关键项。同样,许多成果的推导也被省略了,仅列出了最后结果,并附有对原始来源的引用。\n\n同时,我们鼓励受相关研究启发的读者参考之前的一些调研报告:`[32]` 调研了贝叶斯神经网络的早期发展,`[33]` 讨论了对神经网络进行全面贝叶斯处理的细节,以及 `[34]` 调研了近似贝叶斯推断在现代网络结构中的应用。\n\n本文应该适合所有统计领域的读者,但更感兴趣的读者可能是那些熟悉机器学习概念的人。尽管机器学习和贝叶斯概率方法都很重要 `[2,35]`,但实践中许多现代机器学习方法和贝叶斯统计研究之间存在分歧。希望这项调研能够有助于突出贝叶斯神经网络的现代研究与统计学之间的相似之处,强调概率观点对机器学习的重要性,并促进机器学习和统计学领域未来的合作。\n\n## 2 文献调研\n\n### 2.1 神经网络\n\n在讨论贝叶斯神经网络之前,简要介绍神经计算的基本原理,并定义本文使用的符号。本调研将重点介绍感兴趣的主要网络结构 -- 多层感知器 ( `MLP` ) 网络。 `MLP` 是神经网络的基础,现代体系结构如卷积网络具有等价的 `MLP` 表示。`图 2` 显示了一个简单的 `MLP` ,它有一个适合于回归或分类的隐藏层。\n\n\n\n
    \n图 2:用于单变量二分类任务或回归任务的单隐层神经网络体系结构示例。图中节点表示对输入状态执行求和和激活等操作的神经元或状态。箭头为指示神经元间连接的权重参数。\n
    \n\n
    \n\n对于`图 2` 中具有 $N_1$ 维输入 $\\mathbb{x}$ 的网络 $f$ ,其输出可以被建模为:\n\n$$\n\\phi_{j}=\\sum_{i=1}^{N_{1}} φ\\left(x_{i} w_{i j}^{1}\\right) \\tag{1}\n$$\n\n$$\nf_{k}=\\sum_{j=1}^{N_{2}} g\\left(\\phi_{j} w_{j k}^{2}\\right) \\tag{2}\n$$\n\n参数 $w$ 表示与后续层神经元之间的加权连接,上标表示层号。公式 1 表示 $N_2$ 个隐藏层神经元的输出。公式 2 表示网络的第 $k$ 个输出来自前一个隐藏层 $N_2$ 个神经元输出的加权总和。该模型方案可扩展为包括许多隐藏层,每一层的输入是前一层的输出。通常在每一层中都会添加一个偏差值,不过为简单起见,在本文中省略了。\n\n公式 1 指隐藏层中每个神经元(或节点)的状态,被表示为仿射变换形式,然后是非线性变换 $φ(·)$,这通常被称为激活函数。早期的感知器使用的激活函数是符号函数 $sign(.)$,但由于其导数等于零已很少使用。更常用的激活函数包括:`sigmoid`、`Tanh`、`RELU` 和 `Leaky-RELU` [36,37]。`图 3` 展示了这些激活函数及其导数。当使用 `sigmoid` 函数时,式 1 等价于 `Logistic 回归`,这意味着网络输出变成了多个 `Logistic 回归模型`的和。\n\n\n\n
    \n图 3:神经网络中常用的激活函数示例。激活函数的输出显示为蓝色,激活函数的导数显示为红色。函数有:
    \n (a) sigmoid;(b) Tanh;(c) Relu;(d) Leaky-relu。请注意 y 轴的比例变化。\n
    \n\n对于回归模型,应用于输出单元的 $g(·)$ 函数通常为恒等函数,而对于二分类问题, $g(·)$ 一般为 `sigmoid 函数` ,对于多分类问题, $g(·)$ 为 `Softmax 函数`。\n\n公式 1 和公式 2 可以使用矩阵表示法实现,通过将数据集中的输入向量堆叠为 $X$ 中的一列来实现。而后前向传播可以被执行为:\n\n$$\n\\boldsymbol{\\Phi}=φ\\left(\\mathbf{X}^{T} \\mathbf{W}^{1}\\right) \\tag{3}\n$$\n\n$$\n\\mathbf{F}=g\\left(\\mathbf{\\Phi} \\mathbf{W}^{2}\\right) \\tag{4}\n$$\n\n虽然矩阵表示法更简洁,但此处选择求和表示法来描述网络是有考虑的。希望该求和符号能够使本文后面讨论的核和统计理论的关系变得更加清晰。\n\n在神经网络学习的频率主义框架内,最大似然估计或最大后验估计是通过最小化相对于权重的代价函数 $J(x,y)$ 来实现的。该代价函数的最小化可通过反向传播来执行,其基本步骤是:基于当前参数计算模型输出,找到相对于参数的偏导数然后更新每个参数。\n\n$$\nw_{t+i}=w_{t}-\\alpha \\frac{\\partial J(x, y)}{\\partial w_{t}} \\tag{5}\n$$\n\n公式 5 说明了反向传播法用于更新模型参数的迭代过程,其中 $α$ (有时用 $\\eta$) 表示学习率,下标表示训练过程中的迭代。神经网络反向传播应用链式规则,逐层求出网络中不同层参数的偏导数。这意味着,当隐藏层数量增加时,反向传播过程比较容易导致神经网络的前部层出现梯度消失问题,由此产生了对不连续、非线性类型激活函数的偏好,例如 `RELU`,因为 `RELU` 的梯度较大,有助于反向传播并防止梯度消失现象( `图 3` )。\n\n### 2.2 贝叶斯神经网络\n\n#### (1)为神经网络引入贝叶斯\n\n频率主义框架将模型权重视为尚未知的确切值,而非随机变量,同时将数据视为随机变量。这似乎与直觉相背,因为直觉上应该是根据手头已有的信息(数据),判断未知的模型权重(变量)是多少。\n\n相对而言,贝叶斯统计建模是一种更符合直觉的方法,其视数据为可获得的已知信息,而将未知的权重视为随机变量。其基本逻辑是:将未知参数(或隐变量)视为随机变量,希望在可观测的训练数据支持下,掌握这些参数(或隐变量)的分布。\n\n在贝叶斯神经网络的学习过程中(在贝叶斯语境下通常被称为 **推断**),`未知权重` 可以在 `先验信息` 和 `观测到的信息` 基础上推断出来。这是个逆概率问题,可用贝叶斯定理来阐述。\n\n贝叶斯模型中权重 $w$ 是隐(潜)变量,通常无法直接观测到其真实分布,而贝叶斯定理使用 **能够被观测到的概率** 来表示 **不可观测的权重的分布**,形成以观测数据为条件的权重分布 $p(w|D)$,这被称之为 **后验分布(Posterior Distribution)**,简称**后验(Posterior)**。\n\n在讨论学习过程前,让我们先观察和分析下权重和数据之间的联合分布 $p(w,D)$ 。根据联合概率公式,该分布可以由我们对权重的**先验信念** $p(w)$ 和我们对 **似然(Likelihood)** 的选择 $p(D|w)$ 来定义:\n\n$$\np(\\boldsymbol{\\omega}, \\mathcal{D})=p(\\boldsymbol{\\omega}) p(\\mathcal{D} \\mid \\boldsymbol{\\omega}) \\tag{6}\n$$\n\n在神经网络中,式 6 中的似然项 $p(D|w)$ 与神经网络中的最大似然法有着天然联系,由所假设的神经网络结构和所选择的损失函数来定义。例如:对于损失函数为均方误差、且噪声方差已知的等方差的单变量回归问题,似然是以神经网络的输出为平均值的一个高斯分布。\n\n$$\np(\\mathcal{D} \\mid \\boldsymbol{\\omega}) = \\mathcal{N}\\left(\\mathbf{f}^{\\omega}(\\mathcal{D}), \\sigma^{2}\\right)\n$$\n\n在该回归模型中,一般假设 $\\mathcal{D}$ 中的所有样本点是独立同分布的(i.i.d),从联合概率分布角度,这意味着可将似然分解成 $N$ 个独立项的乘积:\n\n$$\np(\\mathcal{D} \\mid \\boldsymbol{\\omega})=\\prod_{i=1}^{N} \\mathcal{N}\\left(\\mathbf{f}^{\\omega}\\left(\\mathbf{x}_{i}\\right), \\sigma^{2}\\right) \\tag{7}\n$$\n\n在贝叶斯框架内,首先需要指定待求权重的先验分布,以包含人们关于权重理应如何分布的信念。由于神经网络的黑箱性质,指定有意义的先验非常具有挑战性。不过经验主义告诉我们,在许多频率主义的神经网络中,训练后得到的权重值通常较小,而且大致集中在 0 附近。因此可以考虑使用 **小方差的零均值高斯分布** 作为权重的先验分布,或使用 **以零为中心的尖板分布(spike-slab)** 作为先验来促进模型的稀疏性。\n\n>注 1:贝叶斯神经网络中,将权重先验设置为零均值高斯先验较为常见。\n\n>注 2:尖板(Spike-slab)分布是两个高斯分布的叠加,其中一个峰值很高方差很小,而另外一个峰值很低方差很大。虽然是两个高斯分布的叠加,但尖板分布并不是高斯似然的共轭先验,无法得到后验的封闭解。\n\n在指定先验和似然后,应用贝叶斯定理可计算得到模型权重的后验分布:\n\n$$\n\\pi(\\boldsymbol{\\omega} \\mid \\mathcal{D})=\\frac{p(\\boldsymbol{\\omega}) p(\\mathcal{D} \\mid \\boldsymbol{\\omega})}{\\int p(\\boldsymbol{\\omega}) p(\\mathcal{D} \\mid \\boldsymbol{\\omega}) d \\boldsymbol{\\omega}}=\\frac{p(\\boldsymbol{\\omega}) p(\\mathcal{D} \\mid \\boldsymbol{\\omega})}{p(\\mathcal{D})} \\tag{8}\n$$\n\n后验中的分母项为边缘似然(也称证据),其相对于模型权重而言是一个乘性常量,起到对后验进行归一化的作用,以确保后验是一个有效分布。因此也被称为 **归一化因子**。\n\n>注3:边缘似然并非一定要计算出来,有时只需要知道后验的相对概率即可完成推断任务。特别是当问题规模较大时,计算边缘似然代价极高,此时常用的 MCMC 和变分等现代推断方法,都会巧妙地处理归一化因子问题,避免棘手的边缘似然计算问题。\n\n#### (2)基于后验分布做预测\n\n根据后验分布可以预测任何感兴趣的量。其基本的预测方法就是在后验分布上通过积分(或求和)求待预测对象的期望:\n\n$$\n\\mathbb{E}_{\\pi}[f]=\\int f(\\boldsymbol{\\omega}) \\pi(\\boldsymbol{\\omega} \\mid \\mathcal{D}) d \\boldsymbol{\\omega} \\tag{9}\n$$\n\n所有我们感兴趣的预测量(均值、方差、区间等)基本都可以写成上述期望值形式,或者说,预测量都是基于后验分布的某个期望值,它们之间唯一的不同在于期望函数 $f(w)$ 。通过公式可直观地看出,预测值可被视为函数 $f$ 经后验 $π(w)$ 加权后的平均值 。\n#### (3)基于后验分布做推断\n\n贝叶斯推断任务是基于后验分布 $\\pi(\\boldsymbol{\\omega} \\mid \\mathcal{D})$ ,推断出任一随机变量或随机变量子集的后验分布或条件概率分布。因此,贝叶斯推断过程实际上是对某一模型权重的边缘化概率和条件概率计算过程。\n\n与频率主义框架中使用优化方法不同,贝叶斯推断可以使用边缘化方法让我们能够了解模型的生成过程。例如:对于分类任务,可以将类别视为一个隐变量,并由类别与权重共同作为待求随机变量集合,构建生成式模型。然后通过学习过程得到类别与权重的联合后验分布,最后通过边缘化方法计算得到类别变量的概率分布。\n\n上一节的案例中,假设了噪声方差 $σ$ 等先验的参数已知(其实可以泛化到任一先验的参数),但实践中较少出现此情况,通常需要将先验分布的参数(如:高斯分布的均值 $\\mu$ 和标准差 $\\sigma$ )视为随机变量进行推断。贝叶斯框架支持此类推断,被称为分层贝叶斯模型(Hierarchical Bayesian Model)。其推断方式与权重的推断类似,即将先验分布的参数视为隐变量,并为之分配先验(即先验分布的参数的先验,被称为 **超先验**)。在完成整体的后验推断任务后,对这些超先验参数做边缘化处理,进而得到其后验分布。有关如何对贝叶斯神经网络执行此操作的更多说明,请参考 `[33,38]`。\n\n>注:先验分布的某些参数未知时,可以假设该未知参数也是一个随机变量,且服从某一先验分布,而其后验分布也需要从数据中学得,相关知识请参阅 `分层贝叶斯模型` 。\n\n#### (4) 后验分布的计算难题\n\n对于许多模型,式 8 的后验计算仍然很困难,这主要由边缘似然(证据)的计算导致。对于非共轭模型或存在隐变量的非线性模型(如前馈神经网络),边缘似然几乎不可能有封闭解,而且高维模型的计算更为困难。但是,在贝叶斯框架内,后续很多预测和推断任务又都依赖于后验分布的计算。因此,大量研究集中在“采用什么方法来克服后验分布的计算难题”上。其中比较常见的思路是降低后验求解的要求,即不求后验分布的精确解,退而求其次,计算其近似解。这种后验的近似解法通常被称为 **近似推断**,而常用的方法包括 **MCMC 方法** 和 **变分推断法** 等。\n>注4: 在贝叶斯推断方法中,由于问题规模的增大,传统的精确推断方法已经基本上不再使用了,但还是应当记住其中一些经典推断方法的名字,如:变量消除法、信念传播法等,参见 Dophne Koller 教授的 [《概率图模型原理与技术》](https://mitpress.mit.edu/books/probabilistic-graphical-models) 一书。\n### 2.3 贝叶斯神经网络的推断\n\n#### 2.3.1 早期的主要探索\n\n根据本文和之前的调研报告 `[39]`,基本可以认为贝叶斯神经网络的第一个实例是在 1989 年的 `[40]` 中发表的。该论文通过对神经网络损失函数的统计解释,强调了其统计学特性,并证明了均方误差最小化(MSE)等价于求高斯先验分布的最大似然估计(MLE)。重要的是:通过给神经网络权重指定先验,可用贝叶斯定理获得适当的后验。此工作虽然给出了对神经网络非常关键的贝叶斯见解,但并没有提供计算边缘似然的方法,也就意味着没有提出比较实用的推断方案。`Denker` 和 `LeCun` `[41]` 1991 年对该工作进行了扩展,提供了一种使用拉普拉斯分布进行近似推断的实用方法。\n\n##### (1)早期讨论的主要问题\n\n神经网络是一种通用的函数逼近器。已经有文献表明,当单隐层网络中的参数数量趋近于无穷大时,可以表示任意函数 `[42,43,44]` 。这意味着只要模型有足够参数,就可用单层神经网络来逼近任何训练数据。但与大家熟知的多项式回归模型类似,虽然表达任意函数的能力增强了,但会导致严重的过拟合问题。\n\n在 1991 年 `Gull` 和 `Skilling` `[45]` 的工作基础上,`MacKay` 于 1992 年发表的文章 `《Bayesian interpolation》[46]` 展示了如何使用贝叶斯框架处理模型设计和模型比较任务。该工作描述了两个层次的推断任务:一是用于拟合模型参数的推断、二是用于评估模型适用性的推断。\n\n##### (2)用于参数推断的统计模型\n\n第一类推断是贝叶斯规则用于模型参数更新的典型应用:\n\n$$\nP\\left(\\boldsymbol{\\omega} \\mid \\mathcal{D}, \\mathcal{H}_{i}\\right)=\\frac{P\\left(\\mathcal{D} \\mid \\boldsymbol{\\omega}, \\mathcal{H}_{i}\\right) P\\left(\\boldsymbol{\\omega} \\mid \\mathcal{H}_{i}\\right)}{P\\left(\\mathcal{D} \\mid \\mathcal{H}_{i}\\right)} \\tag{10}\n$$\n\n其中 $\\omega$ 是统计模型中的参数, $\\mathcal{D}$ 是训练数据, $\\mathcal{H}_i$ 是用于此类推断的第 $i$ 个模型(在参数推断任务中,一般视模型为固定的)。上式可以描述为:\n\n$$\n\\text{Posterior}=\\frac{\\text { Likelihood } \\times \\text { Prior }}{\\text { Evidence }} \n$$\n\n注意式 10 中的归一化常数也被称为模型 $\\mathcal{H}_i$ 的边缘似然。对于大多数模型,后验的计算非常困难,只能采用近似的方法。而该论文的主要贡献是提出了边缘似然的拉普拉斯近似方法。\n\n##### (3)用于模型选择的统计推断模型\n\n除了计算参数的后验,该论文还探讨了如何对模型 $\\mathcal{H}_i$ 进行评估。其中模型的后验被设计为:\n\n$$\nP\\left(\\mathcal{H}_{i} \\mid \\mathcal{D}\\right) \\propto P\\left(\\mathcal{D} \\mid \\mathcal{H}_{i}\\right) P\\left(\\mathcal{H}_{i}\\right) \\tag{11}\n$$\n\n该公式可以解释为:\n\n$$\n\\text{Model Posterior} \\propto \\text{Evidence} \\times \\text{Model Prior}\n$$\n\n式 11 中的数据依赖项必须依赖于该模型的边缘似然 $P\\left(\\mathcal{D} \\mid \\mathcal{H}_{i}\\right) $。尽管之前我们对其做出 `后验归一化常数` 的解释很好理解,但和前面所提到的一样,对于大多数贝叶斯神经网络来说,求边缘似然非常困难。\n\n>注5:计算边缘似然的本质是求后验分布的积分。\n>注6:此处总体理解是将贝叶斯定理用于了模型比较和选择,但必须以计算边缘似然为前提条件。模型比较和选择本身是贝叶斯统计框架中非常重要的一个部分,其潜在的研究动向是模型的自动评估和选择,按照 Zoubin 报告中的说法,这可行是自动机器学习的下一个风口。\n\n##### (4)直接求解边缘似然的早期尝试\n\n很多现代方法(如:MCMC 和变分法)通常都巧妙地规避了边缘似然的计算问题,但在该早期论文中,却实实在在提出了一种近似计算边缘似然的解决方案,虽然该方案基本已经无人使用。\n\n该论文假设边缘似然呈高斯分布,并提出了边缘似然的拉普拉斯近似:\n\n\\begin{align} \nP\\left(\\mathcal{D} \\mid \\mathcal{H}_{i}\\right) &=\\int P\\left(\\mathcal{D} \\mid \\boldsymbol{\\omega}, \\mathcal{H}_{i}\\right) P\\left(\\boldsymbol{\\omega} \\mid \\mathcal{H}_{i}\\right) d \\boldsymbol{\\omega} \\\\ \n& \\approx P\\left(\\mathcal{D} \\mid \\boldsymbol{\\omega}_{\\mathrm{MAP}}, \\mathcal{H}_{i}\\right)\\left[P\\left(\\boldsymbol{\\omega}_{\\mathrm{MAP}} \\mid \\mathcal{H}_{i}\\right) \\Delta \\omega\\right]' \\\\ \n&=P\\left(\\mathcal{D} \\mid \\boldsymbol{\\omega}_{\\mathrm{MAP}}, \\mathcal{H}_{i}\\right)\\left[P\\left(\\boldsymbol{\\omega}_{\\mathrm{MAP}} \\mid \\mathcal{H}_{i}\\right)(2 \\pi)^{\\frac{k}{2}} \\mathrm{det}^{-\\frac{1}{2}} \\mathbf{A}\\right] \\\\ \n&=\\text { Best Likelihood Fit } \\times \\text { Occam Factor } \n\\end{align}\n\n这可以解释为对模型边缘似然的一种黎曼近似,通过两个要素来表示:\n\n- 一是用于表示边缘似然高斯分布峰值(或众数)的 `最佳似然拟合(Best Likelihood Fit)`。\n- 二是表示高斯分布峰值附近曲线特征宽度的`奥卡姆因子(Occam Factor)`。\n\n奥卡姆因子可理解为给定模型 $\\mathcal{H}_i$ 的后验分布宽度 $∆w$ 与先验范围 $∆w_0$ 之比,计算公式为:\n\n$$\n\\text{Occam Factor} =\\frac{\\Delta \\omega}{\\Delta \\omega_{0}} \\tag{15}\n$$\n\n这意味着奥卡姆因子是参数空间中从先验到后验的变化率。图 4 展示了此概念:在先验一致的情况下,一个能够表示大范围数据的复杂模型( $\\mathcal{H}_2$ )将拥有更宽的边缘似然,因此具有更大的奥卡姆因子。而简单模型($\\mathcal{H}_1$ )捕获复杂生成过程的能力较弱,但较小范围的数据能够更确定地建模,从而产生较小的奥卡姆因子。这导致模型复杂性的天然正规化:从模型复杂性方面,不必要的复杂模型通常会导致较宽的后验分布、较大的奥卡姆因子以及给定模型较低的边缘似然。\n\n从先验角度考虑,一个弱信息先验(分散平坦, $∆w_0$ 较大)会导致较小的奥卡姆因子,这直观地解释了贝叶斯设置中的正则化现象(即所谓 “贝叶斯方法内置奥卡姆剃刀”)。\n\n\n\n
    图 4:边缘似然在模型评估中发挥的作用。
    \n\n简单模型 $\\mathcal{H}_1$ 能以更大的强度预测较小范围的数据,而复杂模型 $\\mathcal{H}_2$ 尽管预测强度较低,但能够预测更大范围的数据,改编自 [46,47]。\n\n如前所述,使用该证据框架需要计算边缘似然,这是贝叶斯建模中最关键的挑战。考虑到近似计算边缘似然所需的大量成本,利用该证据框架比较许多不同的模型似乎不可行。尽管如此,它仍然是一个可以用来评估贝叶斯神经网络的解决方案。\n\n对于大多数感兴趣的神经网络结构,目标函数是非凸的,具有许多局部极小值。每一个局部极小都可以看作是推断问题的一个可能解。`MacKay` 以此为动机,使用所有局部最小值对应的 `证据函数(Evidence·Function)` 来进行模型比较 `[48]` 这允许在不需要大量计算的情况下评估模型方案的复杂性。\n\n#### 2.3.2 变分推断方法\n\n机器学习领域在优化问题上表现一直比较出色。其中许多最大似然模型(如支持向量机和线性高斯模型)的目标函数都是凸函数,但神经网络的目标函数往往是高度非凸的,具有许多局部极小值。针对该问题,机器学习社区开发出了类似反向传播 `[3]`的基于梯度的优化方法。因此,很快就有人联想到,是否能够将这些优化方法用到后验推断任务上?\n\n答案是肯定的, `变分推断(Variational Inference )` 就是该优化方法在贝叶斯统计中的推广。\n\n##### (1)什么是变分推断?\n\n变分推断是一种近似推断方法,它将贝叶斯推断过程中所需的边缘概率计算视为一个优化问题 `[49,50,51]` 。变分推断首先为后验假设一个参数化形式的分布族,然后通过对参数的优化找到该分布族中最接近真实后验分布的解。这种分布族的假设简化了计算,并提供了可操作性。\n\n具体而言就是:\n\n(1)假设后验分布可以由在参数集 $w$ 上定义的某个函数 $q_\\theta(w)$ 来近似表示(被称为变分分布);\n\n(2)假设该函数可以被经 $\\theta$ 参数化的某一分布族控制;\n\n(3)通过优化参数 $\\theta$ 来调整变分分布 $q_θ(w)$,使 $q_θ(w)$ 与真实后验 $p(w|\\mathcal{D})$ 之间的差异性逐渐减小;\n\n(4)通过渐进地优化,逐步得到与真实后验 $p(w|\\mathcal{D})$ 非常相似的 $q_θ(w)$ ;\n\n(5)将所有基于 $p(w|\\mathcal{D})$ 的后续任务(如边缘概率计算、条件概率计算等),迁移到 $q_θ(w)$ 做近似实现。\n\n按照这个原理,变分推断需要一种度量变分分布与真实分布之间相似程度的手段作为目标函数,而 `KL 散度` 是最常用的一种:\n\n$$\n\\text{KL}\\left(q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega}) \\| p(\\boldsymbol{\\omega} \\mid \\mathcal{D})\\right)=\\int q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega}) \\log \\frac{q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega})}{p(\\boldsymbol{\\omega} \\mid \\mathcal{D})} d \\boldsymbol{\\omega} \\tag{16}\n$$\n\n分布 $q$ 到分布 $p$ 的 `KL 散度`越小,说明两者之间越相似。\n\n>注6:根据定义, KL 散度不符合交换律,即 $KL(p \\| q) \\neq KL(q \\| p)$。 \n\n对于变分推断,可将式 16 用作参数 $\\theta$ 的目标函数,将推断问题转变成 $\\theta$ 的最优化求解问题。式 16 可进一步扩展为:\n\n\\begin{align}\n\\mathrm{KL}\\left(q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega}) \\| p(\\boldsymbol{\\omega} \\mid \\mathcal{D})\\right)&= \\mathbb{E}_{q}\\left[\\log \\frac{q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega})}{p(\\boldsymbol{\\omega})}-\\log p(\\mathcal{D} \\mid \\boldsymbol{\\omega})\\right]+\\log p(\\mathcal{D})\\\\ \n&=\\mathrm{KL}\\left(q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega}) \\| p(\\boldsymbol{\\omega})\\right)-\\mathbb{E}_{q}[\\log p(\\mathcal{D} \\mid \\boldsymbol{\\omega})]+\\log p(\\mathcal{D})\\\\\n&=-\\mathcal{F}\\left[q_{\\theta}\\right]+\\log p(\\mathcal{D})\n\\end{align}\n\n其中:\n\n$$\n\\mathcal{F}\\left[q_{\\theta}\\right]=-\\mathrm{KL}\\left(q_{\\theta}(\\boldsymbol{\\omega}) \\| p(\\boldsymbol{\\omega})\\right)+\\mathbb{E}_{q}[\\log p(\\mathcal{D} \\mid \\boldsymbol{\\omega})]\n$$\n\n式中包含 $\\mathcal{F}[q_θ]$ 所在的负值项,负号是为强调 `它是一个与目标分布不同但等价的派生分布` ,并与参考文献表示方法保持一致。\n\n现在将式 19 作为目标函数,并利用反向传播和梯度下降来优化。由于其第二项(对数边缘似然)为一常数,其与参数 $\\theta$ 无关,关于 $\\theta$ 的导数为零。因此,导数中只剩下包含变分参数的项 $\\mathcal{F}[q_θ]$ ,通常被称为边缘似然的下界(ELBO) `[49,52]` 。\n\n根据式 19 :\n\n(1) `KL 散度` 严格 ≥ 0 且仅当两个分布相等时才等于零(实际上很难出现相等);\n\n(2)对数边缘似然 $\\log p(\\mathcal{D})$ 等于 `KL 散度`与`边缘似然下界(ELBO)`之和;\n\n(3)换一种解释为:变分分布到真实分布的 `KL 散度` 是`对数边缘似然`与`边缘似然下界 ELBO` 之差。\n\n(4)原优化问题为 “最小化 KL 散度来求取最近似后验的变分分布” ,经 `式 19` 后,转换成了新问题 “最大化 ELBO 以求取最近似后验的变分分布” ,而新问题中消去了(对数)边缘似然的计算项,只需让 ELBO 最大化即可,效率得到较大提升。\n\n图 5 可视化地说明了三者之间的关系。\n\n\n\n
    \n\n图 5:最小化 $q_\\theta$ 到 $p(w|\\mathcal{D})$ 的 KL 散度等效于最大化边缘似然的下界 ELBO。\n当变分分布到真实后验分布的 KL 散度被最小化时,边缘似然下界 $\\mathcal{F}[q_θ]$ 收紧到对数边缘似然。\n因此,最小化 KL 散度等效于最大化边缘似然下界 `ELBO` (改编自 `[53]` )。\n
    \n\n>变分推断的要点:\n>(1)它是一种近似推断,需要构造变分分布的形式;\n>(2)采用最优化方法求解变分分布的参数,进而获得后验分布的近似形式;\n>(3)将优化目标从最小化变分分布到真实后验分布的 KL 散度,转换为最大化边缘似然下界 `ELBO` ,从而消去了边缘似然的高复杂度计算,提升了计算效率。\n\n\n##### (2)如何构造变分分布?-- 从随机变量的独立假设开始\n\n`Hinton` 和 `Van Camp` `[54]` 首次将变分推断应用于贝叶斯神经网络,试图解决神经网络中的过拟合问题。他们认为,通过使用神经网络模型权重的概率视角,权重包含的信息量会减少,神经网络会得到简化。该表述从信息论`(特别是最小描述性长度,Minimum Descriptive Length)` 角度出发,但导致了相当于变分推断的框架。\n\n`Hinton` 等人的研究使用了 `平均场变分贝叶斯 (MFVB)` 方法。 平均场变分贝叶斯方法假设 `变分分布对参数实施了因子分解` ,而 `Hinton` 等人则进一步假设 `变分分布对参数实施了由若干独立的高斯分布构成的因子分解`:\n\n>Hinton 等人的方法本质上是假设所有的权重是相互独立的随机变量,并且每个随机变量都服从高斯分布。而根据概率公式,变分分布可分解为各权重因子分布的乘积。而参数 $\\theta$ 则是所有 $\\{\\mu_i,\\sigma_i\\}$ 构成的集合。\n\n$$\nq_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega})=\\prod_{i=1}^{P} \\mathcal{N}\\left(w_{i} \\mid \\mu_{i}, \\sigma_{i}^{2}\\right) \\tag{20}\n$$\n\n其中 $P$ 是神经网络中权重的数量。对于只有一个隐层的回归神经网络,该变分分布因采用高斯分布而存在封闭解。在贝叶斯统计方法中能够获得封闭解是一种非常理想的特性,可以极大地减少执行推断所需的时间。\n\n##### (3)变分分布构造的优化 -- 捕获随机变量间的相关性\n\n`Hinton` 等人的工作存在几个问题,其中最突出的问题是假设变分分布被因子分解为若干个独立网络权重的高斯分布。众所周知,神经网络中的权重之间并不独立,而是存在强相关性。因子分解方法实际上是通过牺牲权重之间的相关性来简化了计算。`Mackay` 在对贝叶斯神经网络的早期调研中强调了该问题 `[32]`,并提出通过对隐层的输入做预处理,可以获得更全面的近似后验分布。\n\n`Barber` 和 `Bishop` `[53]` 再次强调了该问题,并扩展了 `[54]` 中的工作,通过使用 `满秩高斯` 的协方差模型来捕获权重间的相关性, 并构造了变分分布。对于使用 Sigmoid 激活函数的单隐层回归神经网络,该工作使用适当缩放的误差函数替换了 Sigmoid 激活函数,并提供了评估 `ELBO` 的解析表达式。\n\n>注:该方法依然需要采用数值方法来计算 `ELBO` 封闭解中的某些项,并非完全的封闭解。\n\n此方案的问题是参数数量过多。完全协方差模型的参数数量是神经网络权重数量的二次函数。为此,`Barber` 和 `Bishop` 对因子分解中经常使用的协方差提出了一种限制形式,\n\n$$\n\\mathbf{C}=\\operatorname{diag}\\left(d_{1}^{2}, \\ldots, d_{n}^{2}\\right)+\\sum_{i=1}^{s} \\mathbf{s}_{i} \\mathbf{s}_{i}^{T} \\tag{21}\n$$\n\n其中,$diag$ 运算符根据长度为 $n$ 的向量 $d$ 创建对角线矩阵,$n$ 为模型中权重的数量。该形式与网络中隐藏单元的数量呈线性关系。\n\n上述 `Hinton`、`Bishop` 等两项工作为将反向传播方法应用于解决贝叶斯问题做出了贡献。使这两个研究领域的特性可以合并,发挥各自优势。这些工作使我们具备了使用神经网络在概率意义上处理大数据集复杂回归任务的能力。\n\n##### (4)变分推断的局限性\n\n上述变分推断方法也存在局限性。`Hinton` 、 `Van Camp` 、 `Barber` 和 `Bishop` 的工作都集中在发展一种封闭形式的网络表示,对神经网络施加了许多限制。如前面所讨论的,`[54]` 假设后验分布被因子分解为独立的权重分布,无法捕获权重之间的相关性。 `[53]` 虽然捕获了协方差结构,但作者将其分析限制在使用误差函数来近似 Sigmoid 激活函数上,而该函数的梯度幅度较低容易造成梯度消失,因此无法向深层网络扩展。**此外两种方法都存在一个非常关键的局限性,即假设模型为单隐层神经网络。**\n\n如前所述,神经网络可通过添加额外的隐藏单元来任意地逼近任何函数。但现代神经网络实验表明,通过增加网络中隐层的数量,可以用更少的隐藏单元来表示相同的复杂函数,并由此产生了“深度学习”,其中深度指的就是隐藏层的数量。当试图近似各层之间的完全协方差结构(即捕获不同权重之间的相关性)时,减少权重变量的数量变得尤其重要。例如,可以捕获层内隐藏单元之间的相关性,同时假设层间参数相互独立。此类假设可以显著减少相关系数的数量,进而减少复杂度。现代出现了很多拥有很深层数、数以亿计权重的神经网络,但目前大多只能提供频率学派擅长的点估计,因此开发超出单层的实用概率解释需求越来越迫切。\n\n```{note}\n由于此处重点在贝叶斯神经网络的变分推断问题,所以一些传统概率模型中的变分推断方法(如 ADVI 等最新的进展)没有体现出来,需要补充。\n```\n\n#### 2.3.3 蒙特卡洛推断方法\n\n到目前为止,我们的重点一直放在寻找后验分布的良好近似上,但后验的精确表示通常不是最终目标,我们实际感兴趣的主要任务是预测点和预测区间。我们希望在信心充分的情况下做出良好预测。之所以强调后验的良好近似,是因为预测点和区间等任务都必须根据后验分布 $π(w|D)$ 来计算期望值。该期望值在式 9 中已经给出,在此为方便再次给出:\n\n$$\n\\mathbb{E}_{\\pi}[f]=\\int f(\\boldsymbol{\\omega}) \\pi(\\boldsymbol{\\omega} \\mid \\mathcal{D}) d \\boldsymbol{\\omega} \n$$\n\n这就是强调后验计算方法的原因,因为准确的预测和推断依赖于棘手的后验分布(或其近似)。\n\n##### (1)什么是蒙特卡洛方法?\n\n前述近似和优化方法(如变分推断或拉普拉斯近似)对后验形式有强假设和限制,而这些限制常导致不准确的预测。根据式 9 的解释,统计模型关心的预测和推断问题需要后验分布,但似乎并不一定需要知道后验分布的具体数学形式。由此催生了一种基于随机数的推断方法,即蒙特卡洛推断方法。\n\n其思路是:只要具备逐点计算先验值和似然值的条件,就能从真实后验分布中获得样本。这在贝叶斯框架内肯定能够得到满足,因为似然值可由用户模型和似然假设得出,而先验值可由先验分布得出。进一步,如果能够依据后验的取值概率从后验分布的不同区域采集不同数量的样本(基本原则是:取值概率值高的区域多采点,取值概率低的区域少采点),就能够通过样本构成对式 9 期望值的近似,从而实现预测和推断任务。随着抽取样本的数量增加,期望值可以无限趋近于真值。\n\n换句话说,蒙特卡洛方法会根据权重空间中每个区域的相对概率来确定从该区域抽取样本的次数。例如:如果后验分布中区域 A 的概率是区域 B 的两倍,那么从 A 抽取的样本将是从 B 抽得样本的两倍。因此,即使不能解析计算出整个后验,也可以使用蒙特卡洛方法从后验中获得样本。\n\n>注6:后验公式中分母的边缘似然项仍然很难计算,这导致很难计算后验分布的绝对概率值。而蒙特卡洛方法仅依据相对概率来确定不同区域的采样数量,很巧妙地规避了边缘似然计算问题,这是其一大优势。但蒙特卡洛方法需要一定时间的预热才能够达到收敛状态,这对于那些时效性要求较高,尤其是超大规模的问题可能不是一个好的选择。\n\n##### (2)马尔可夫链蒙特卡洛( MCMC )\n\n蒙特卡洛方法为预测量期望值的计算提供了一条技术途径,但如果完全随机采样的话,采样效率会非常低。因此,“如何能用较小的采样次数获得有效的采样方案” 成为蒙特卡洛方法的关键问题。马尔可夫链蒙特卡洛( `MCMC` )方法根据此需求应运而生。\n\n`MCMC 方法` 出发点很朴素:如果随机采样效率低的话,能否将采样过程限制在一个合理的路径上,使得在该路径上所有采样点构成的集合(或子集),符合按照取值概率确定采样数量的原则要求。这样的话,只需要在路径上采样,而不是在权重空间里随机采样,采样效率会得到大大提升。\n\n那么是否能够构造出这样的一条合理路径呢?答案是肯定的,那就是马尔可夫链。\n\n首先理解什么是马尔科夫链。可以将我们想要的路径建模为一条链,该链由一系列状态(在 MC 中,每个状态可理解为一个采样点)以及状态之间的转移概率构成。当这条链上的每个状态转移到其他状态的概率只与当前状态相关时,这条链就称为马尔科夫链。有了马尔科夫链,我们就可以任取一个初始点,然后依据状态转移概率随机游走。可以设想,如果当前状态到其他所有可能状态之间的转移概率都相同时,意味着下一个状态和当前状态无关,其效果等价于在整个权重空间中做随机采样。但如果能够找到一条马尔科夫链,其状态转移概率正比于目标分布(如贝叶斯分析中的后验分布)的取值概率,那么采样过程就变成了在该状态链上移动的过程。而且随着链长度的增长,采样结果将无限趋近于真实分布。\n\n上述思想表明, `MCMC 方法` 可以从任意分布中采样,而不用关心分布的具体形态。进而将公式 9 的预测公式转换为如下的蒙特卡洛积分求和形式:\n\n$$\n\\mathbb{E}_{\\pi}[f]=\\int f(\\boldsymbol{\\omega}) \\pi(\\boldsymbol{\\omega} \\mid \\mathcal{D}) d \\boldsymbol{\\omega} \\approx \\frac{1}{N} \\sum_{i=1}^{N} f\\left(\\boldsymbol{\\omega}_{i}\\right) \\tag{22}\n$$\n\n其中 $w_i$ 表示来自后验分布的一个独立样本。\n\n `MCMC` 不需要像变分推断那样对后验分布做出假设,而且当样本数量趋于无穷大时,`MCMC` 会收敛到真实后验。由于避免了假设限制,只要有足够时间和计算资源,就可以得到一个更接近真实预测值的解。当然,这对贝叶斯神经网络来说是一个重要挑战,因为多维复杂后验分布的 `MCMC` 收敛过程有可能需要很长时间。\n\n >注:根据 MCMC 的原理,决定采样有效性和效率的关键是状态转移策略的设计。事实上,根据转移策略的不同,已经发展出了很多种 MCMC 采样方法,比较常见的有 Gibbs 采样、 Metropolis-Hasting采样、HMC 汉密尔顿采样、NUTS 不掉头采样等,感兴趣的读者请参阅[附录A](http://localhost:4000/2021/03/01/%E8%B4%9D%E5%8F%B6%E6%96%AF%E7%BB%9F%E8%AE%A1/2021-03-01-%E8%AE%A1%E7%AE%97-%E8%B4%9D%E5%8F%B6%E6%96%AF%E6%8E%A8%E6%96%AD%E9%97%AE%E9%A2%98/)。\n\n##### (3)汉密尔顿蒙特卡洛(HMC)\n\n传统 `MCMC` 方法的马尔科夫链中随机产生新值,因此存在随机游走的特点。而贝叶斯神经网络的后验存在复杂性和高维性特点,随机游走特性使推断很难在合理时间内完成。为避免随机游走,可在马尔科夫链迭代过程中加入了梯度信息,以加速迭代过程。在诸如 Gibbs采样、M-H采样等众多方法中, `汉密尔顿采样(HMC)` 是一种利用了梯度信息的高效方法。 `HMC` 最初被用于统计物理 `[58]`,但 `Neal` 强调 `HMC` 具备解决贝叶斯推断的潜力,并专门研究了其在贝叶斯神经网络和更广泛统计领域中的应用 `[38]` 。\n\n鉴于 `HMC` 最初为物理动力学而提出,因此通过物理类比来建立统计学直觉比较容易理解。首先我们将感兴趣的权重 $\\mathbf{w}$ 视为位置变量,则可以想象 $N$ 个权重参数形成了一个 $N$ 维的权重空间,其中每一个点都有相应的概率值。然后,引入一个辅助变量 $\\mathbf{v}$ 来模拟当前位置的动量,该辅助变量没有统计学意义,只是为帮助系统动力学研究而引入的。通过位置和动量,可以表示系统的势能 $U(\\mathbf{w})$ 和动能 $K(\\mathbf{v})$。\n\n根据动力学原理,系统总能量为动能和势能的总和:\n\n$$\nH(\\mathbf{w}, \\mathbf{v})=U(\\mathbf{w})+K(\\mathbf{v}) \\tag{23}\n$$\n\n当系统与外界没有能量交换时,其总能量将保持不变,即 $H(\\mathbf{w}, \\mathbf{v})$ 为常数。此时的系统被称为 `汉密尔顿(Hamiltonian)系统` ,并可用微分方程组表示 `[59]`:\n\n$$\n\\frac{dw_{i}}{dt}=\\frac{\\partial H}{\\partial v_{i}} \\tag{24}\n$$\n\n$$\n\\frac{d v_{i}}{d t}=-\\frac{\\partial H}{\\partial w_{i}} \\tag{25}\n$$\n\n其中 $t$ 表示时间,$i$ 表示 $\\mathbf{w}$ 和 $\\mathbf{v}$ 中的个体元素。\n\n通过 `正则分布(canonical distribution)` 可以将系统动力学中的物理解释与概率解释联系起来:\n\n$$\nP(\\mathbf{w}, \\mathbf{v})=\\frac{1}{Z} \\exp (-H(\\mathbf{w}, \\mathbf{v}))=\\frac{1}{Z} \\exp (-U(\\mathbf{w})) \\exp (-K(\\mathbf{v})) \\tag{26}\n$$\n\n其中 $Z$ 是归一化常数,$H(\\mathbf{w},\\mathbf{v})$ 是公式 23 中定义的总能量。从该联合分布可看出,位置变量和动量变量相互独立。\n\n预测的最终目标是获得点或区间,在贝叶斯框架内,关键量是后验分布。为此,可将势能设置为:\n\n$$\nU(\\mathbf{w})=-\\log (p(\\mathbf{w}) p(\\mathcal{D} \\mid \\mathbf{w}))\\tag{27}\n$$\n\n在 `HMC` 中,动能可以从一系列函数中自由选择。但通常选取 $\\mathbf{v}$ 的边缘分布为以原点为中心的对角高斯:\n\n$$\nK(\\mathbf{v})=\\mathbf{v}^{T} M^{-1} \\mathbf{v}\\tag{28}\n$$\n\n$M$ 为对角矩阵,在物理解释中,被视为是变量的 “质量” 。\n\n>但需注意,虽然该动能函数最为常用,但不一定是最合适的。`[55]` 综述了其他高斯动能的选择和设计,并着重做出了几何解释。同时必须强调,选择合适的动能函数仍然是一个开放的研究课题,尤其是非高斯函数的情况。\n\n汉密尔顿动力学使总能量保持不变,当以无限精度实现时,所提出的动力学是可逆的。可逆性是满足详细平衡条件的充分条件,这是确保目标分布(试图从其采样的后验分布)保持不变所必需的。在实际应用中,变量离散化会产生数值误差。最常用的离散化方法是 `跳步(LeapFrog)法` 。跳步法指定步长 $\\epsilon$ 以及在接受更新前可能使用的步数 $L$ 。跳步法首先执行动量 $\\mathbf{v}$ 的一半更新,接着是位置 $\\mathbf{w}$ 的完全更新,然后是动量的剩余一半更新 `[59]`:\n\n$$\nv_{i}\\left(t+\\frac{\\epsilon}{2}\\right)=v_{i}(t)+\\frac{\\epsilon}{2} \\frac{d v_{i}}{d t}(v(t)) \\tag{29}\n$$\n\n$$\nw_{i}(t+\\epsilon)=w_{i}(t)+\\epsilon \\frac{d w_{i}}{d t}(w(t)) \\tag{30}\n$$\n\n$$\nv_{i}(t+\\epsilon)=v_{i}\\left(t+\\frac{\\epsilon}{2}\\right)+\\frac{\\epsilon}{2} \\frac{d v_{i}}{d t}\\left(v\\left(t+\\frac{\\epsilon}{2}\\right)\\right)\\tag{31}\n$$\n\n如果步长 $\\epsilon$ 的取值能够使该动力系统保持稳定,则可以证明跳步法保持了汉密尔顿的总能量。\n\n对于使用式 22 近似的期望值,采样要求各样本 $\\mathbf{w}_i$ 独立于其他样本,HMC 中可通过使用多个跳步 $L$ 来实现这种独立性要求。基本做法是,在 $L$ 个 $\\epsilon$ 步长之后,推荐新的采样点,从而降低样本之间的相关性。Metropolis 步骤可以用来确定新值是否被接受为马尔可夫链中的最新状态 `[59]` 。\n\n>注:Metropolis 步骤在 MCMC 中用于判定新推荐值是否被接受。\n\n\n##### (4)在贝叶斯神经网络中应用 HMC\n\n `[38]` 建议的贝叶斯神经网络,引入超先验 $p(γ)$ 对先验的参数和似然的参数(方差或精度)进行建模。该超先验采用高斯分布,似然也建模为高斯分布。为保证条件共轭,$γ$ 的先验采用伽玛分布。这允许使用 `Gibbs 采样` 来执行对超参数的推断。进而后验分布 $P(w|D)$ 的采样转换为联合后验 $P(w,γ|D)$ 的采样,其采样过程实际上是在超参数的 `Gibbs 采样`和模型参数的汉密尔顿动力学之间交替进行。`[38]` 展示了 `HMC` 在简单贝叶斯神经网络模型中的优越性能,并与`随机游走 MCMC` 和 `Langevin 方法`进行了比较 。\n\n\n### 2.4 深层贝叶斯神经网络\n\n#### (1) 早期停滞\n\n在 `Neal`、`MacKay` 和 `Bishop` 于 90 年代提出早期工作之后,对贝叶斯神经网络的研究沉寂了一段时间,其实整个神经网络领域的研究几乎都停滞了,主要是因为训练神经网络的计算需求太高。神经网络能够以任意精度捕获任何函数,但准确捕获复杂函数需要具有许多参数的大型网络。即使从传统频率主义观点来看,训练如此庞大的网络很困难,而研究信息量更大的贝叶斯神经网络,计算需求会更高。\n\n不过在证明了 GPU 可以加速训练大型网络后,人们对神经网络的研究热情又重新燃起。GPU 实现了在反向传播期间执行大规模线性代数并行,这种加速计算允许训练更深层次的网络。随着 GPU 在优化复杂网络方面的成熟以及此类模型取得的巨大成功,人们也对贝叶斯神经网络重新产生了兴趣。\n\n#### (2) 深层贝叶斯网络的变分推断法\n\n`现代贝叶斯神经网络研究主要集中在变分推断方法上,因为这些问题可以使用反向传播方法来优化`。考虑到大多成功的现代神经网络均为深层次网络,文献 `[54,53]` 中的原始变分推断方法(侧重于利用单个隐层的回归神经网络的解析近似)变得不适用。现代神经网络呈现出不同的体系结构,具有不同维度、隐藏层、激活函数和应用。需要在概率意义上重新审视神经网络的更一般的方法。\n\n考虑到现代神经网络的大规模性,稳健的推断能力通常需要建立在大数据集上。而对于大数据集,做全数据集的对数似然评估变得不可行。为解决该问题,产生了采用随机梯度下降(SGD)和小批量数据来近似似然的方法。这时变分的目标函数就变成:\n\n$$\n\\mathcal{L}(\\boldsymbol{\\omega}, \\boldsymbol{\\theta})=-\\frac{N}{M} \\sum_{i=1}^{N} \\mathbb{E}_{q}\\left[\\log \\left(p\\left(\\mathcal{D}_{i} \\mid \\boldsymbol{\\omega}\\right)\\right)\\right]+\\mathrm{KL}\\left(q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega}) \\| p(\\boldsymbol{\\omega})\\right) \\tag{32}\n$$\n\n其中小批量数据 $D_i⊂D$ ,$N$ 为批量数,每个 $D_i$ 的批大小均为 $M$ 。这为训练期间利用大数据集提供了有效方法。每传入一个 $D_i$ 之后,应用反向传播来更新一次模型参数。不过这种似然的子采样会在推断过程中引入随机噪声,因此得名随机梯度下降(SGD) 。该随机噪声在所有单独子集的评估过程中会被平均掉 `[61]` 。SGD 是利用变分推断方法训练神经网络和贝叶斯神经网络的最常用方法。\n\nGraves 在 2011 年发表了一篇关于贝叶斯神经网络研究复兴的关键论文`《Practical variational inference for neural networks》[62]`。这项工作提出了一种以因子分解的高斯分布作为后验近似的 `MFVB` 处理方法。其关键贡献是梯度的计算。变分推断目标(即边缘似然下界 `ELBO` 最大化)可被视为两个期望的总和:\n\n$$\n\\mathcal{F}\\left[q_{\\theta}\\right]=\\mathbb{E}_{q}[\\log (p(\\mathcal{D} \\mid \\boldsymbol{\\omega}))]-\\mathbb{E}_{q}\\left[\\log q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega})-\\log p(\\boldsymbol{\\omega})\\right] \\tag{33}\n$$\n\n这两个期望是优化模型参数所需要的,因此需要计算期望的梯度。该论文显示了如何使用 `[63]` 提出的高斯梯度特性计算参数的梯度,并对参数进行更新:\n\n$$\n\\nabla_{\\boldsymbol{\\mu}} \\mathbb{E}_{p(\\boldsymbol{\\omega})}[f(\\boldsymbol{\\omega})]=\\mathbb{E}_{p(\\boldsymbol{\\omega})}\\left[\\nabla_{\\boldsymbol{\\omega}} f(\\boldsymbol{\\omega})\\right] \\tag{34}\n$$\n\n$$\n\\nabla_{\\Sigma} \\mathbb{E}_{p(\\boldsymbol{\\omega})}[f(\\boldsymbol{\\omega})]=\\frac{1}{2} \\mathbb{E}_{p(\\boldsymbol{\\omega})}\\left[\\nabla_{\\boldsymbol{\\omega}} \\nabla_{\\boldsymbol{\\omega}} (\\boldsymbol{\\omega})\\right] \\tag{35}\n$$\n\n蒙特卡洛积分可以应用于公式 34 和 35 以估计均值和方差的梯度。该框架允许对 `ELBO` 进行优化,以推广到任意对数损失参数模型。\n\n#### (3) 梯度估计的改进方法\n\n虽然解决了将变分推断应用于具有更多隐层的复杂贝叶斯神经网络问题,但由于估计梯度时采用的蒙特卡洛方法具有巨大的方差,在实际使用中仍然显示出性能上的不足 `[64]` ,因此,开发减少蒙特卡洛估计方差的参数梯度估计方法成为变分推断中一个重要的研究课题 `[65]` 。 其中: `打分函数估计器(Score Function Estimators)` 和 `路径导数估计器(Pathwise Derivative Estimator)` 是梯度的两种最常见的近似估计方法。\n\n打分函数估计器依赖于对对数导数特性的使用:\n\n$$\n\\frac{\\partial}{\\partial \\theta} p(x \\mid \\theta)=p(x \\mid \\theta) \\frac{\\partial}{\\partial \\theta} \\log p(x \\mid \\theta) \\tag{36}\n$$\n\n利用该性质,可形成对期望导数的蒙特卡洛估计,这在变分推断中经常使用:\n\n\\begin{align} \n\\nabla_{\\theta} \\mathbb{E}_{q}[f(\\omega)] &=\\int f(\\omega) \\nabla_{\\theta} q_{\\theta}(\\omega) \\partial \\omega \\\\\n &=\\int f(\\omega) q_{\\theta}(\\omega) \\nabla_{\\theta} \\log \\left(q_{\\theta}(\\omega)\\right) \\partial \\omega \\\\ \n & \\approx \\frac{1}{L} \\sum_{i=1}^{L} f\\left(\\omega_{i}\\right) \\nabla_{\\theta} \\log \\left(q_{\\theta}\\left(\\omega_{i}\\right)\\right) \n \\end{align} \n\n打分函数梯度估计的一个常见问题是表现出相当大的方差 `[65]`。减少蒙特卡洛估计方差的最常见方法之一是引入控制变量 `[66]`。\n\n变分推断文献中常用的第二种梯度估计器是路径导数估计器 。这项工作建立在 `重参数化技巧` `[67,68,69]` 基础上,其中随机变量被表示为确定性的和可微的表达式。例如,对于参数为 $θ=\\{\\mu,\\sigma\\}$ 的高斯分布:\n\n$$\n\\begin{align*} \n\\boldsymbol{\\omega} & \\sim \\mathcal{N}\\left(\\boldsymbol{\\mu}, \\boldsymbol{\\sigma}^{2}\\right) \\\\ \\boldsymbol{\\omega}=g(\\boldsymbol{\\theta}, \\boldsymbol{\\epsilon}) &=\\boldsymbol{\\mu}+\\boldsymbol{\\sigma} \\odot \\boldsymbol{\\epsilon} \\tag{38}\n\\end{align*}\n$$\n\n其中 $\\epsilon∼N(0,I)$ 和 $\\odot$ 表示 Hadamard 积。使用这种方法可以对期望的蒙特卡洛估计进行有效采样。正如文 `[68]` 所示,当 $w=g(θ,\\epsilon)$ 时,有 $q(w|θ)dw=p(\\epsilon)d\\epsilon$, 因此,可以证明:\n\n$$\n\\begin{align*}\n\\int q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega}) f(\\boldsymbol{\\omega}) d \\boldsymbol{\\omega} &=\\int p(\\boldsymbol{\\epsilon}) f(\\boldsymbol{\\omega}) d \\boldsymbol{\\epsilon} \\\\ &=\\int p(\\boldsymbol{\\epsilon}) f(g(\\boldsymbol{\\theta}, \\boldsymbol{\\epsilon})) d \\boldsymbol{\\epsilon} \\\\ \\approx \\frac{1}{M} \\sum_{i=1}^{M} f\\left(g\\left(\\boldsymbol{\\theta}, \\boldsymbol{\\epsilon}_{i}\\right)\\right) &=\\frac{1}{M} \\sum_{i=1}^{M} f\\left(\\boldsymbol{\\mu}+\\boldsymbol{\\sigma} \\odot \\boldsymbol{\\epsilon}_{i}\\right) \\tag{39}\n\\end{align*}\n$$\n\n由于式 39 相对于 θ 是可微的,因此可使用梯度下降法来优化该期望的近似。这是变分推断中的一个重要属性,因为变分推断的目标中包含通常难以处理的对数似然期望值。`重参数化技巧` 是路径梯度估计器的基础。路径估计因其比打分函数估计更低的方差而更受欢迎 `[68,65]` 。\n\n#### (4) 近似推断与正则化\n\n对神经网络进行贝叶斯处理的一个关键好处是能够从模型及其预测中提取不确定性。这是最近在神经网络背景下引起高度兴趣的研究课题。\n\n新的研究通过将现有正则化技术(如 `Dropout` `[70]` )与近似推断联系起来,为神经网络的不确定性估计带来了有前途的发展。丢弃(Dropout)是一种随机正则化技术,它是为解决点估计网络中常见的过拟合问题而提出的。在训练过程中,Dropout 引入了一个独立的随机变量,该变量是伯努利分布的,并将每个单独的权重元素乘以该分布中的样本。例如,实现 `Dropout` 的简单 `MLP` 是这样的形式,\n\n$$\n\\rho_{u} \\sim \\operatorname{Bernoulli}(p) \\notag\n$$\n\n$$\n\\phi_{j}=\\theta\\left(\\sum_{i=1}^{N_{1}}\\left(x_{i} \\rho_{u}\\right) w_{i j}\\right) \\tag{40}\n$$\n\n由式 40 可以看出,Dropout 的应用 `以与重参数化技巧类似的方式` 将随机性引入网络参数。一个关键区别是:在 `Dropout` 情况下,随机性被引入到输入空间,而不是贝叶斯推断所需的参数空间。`Yarin Gal` `[39]` 证明了这种相似性,并演示了如何将 `Dropout` 引入的噪声有效地传递到网络权重:\n\n$$\n\\mathbf{W}_{\\rho}^{1} =\\operatorname{diag}(\\boldsymbol{\\rho}) \\mathbf{W}^{1} \\tag{41}\n$$\n\n$$\n\\boldsymbol{\\Phi}_{\\rho}=a\\left(\\mathbf{X}^{T} \\mathbf{W}_{\\rho}^{1}\\right) \\tag{42}\n$$\n\n其中 $ρ$ 是从伯努利分布采样的向量,$\\operatorname{diag}(·)$ 运算符从向量创建平方对角矩阵。如此可以看出,一个 `Dropout` 变量在权重矩阵的每一行之间被共享,从而允许维持行间的某些相关性。通过查看权重参数的随机分量,该公式适用于使用变分框架的近似推断。在这项工作中,近似后验是伯努利分布与权重乘积的形式。\n\n应用重参数化技巧获得相对于网络参数的偏导数,然后形成 `ELBO` 并执行反向传播以最大化下界。蒙特卡洛积分被用来逼近解析上难以处理的对数似然。通过用两个小方差高斯分布的混合模型来近似伯努利后验,得到 `ELBO` 中近似后验与先验分布之间的 KL 散度。\n\n在上述工作同时,`Kingma` 等人 `[71]` 也发现了 `Dropout` 和其在变分框架中的应用潜力。与 `Dropout` 引入的典型伯努利分布随机变量相比,`[71]` 将注意力集中在引入高斯随机变量 `[72]` 。文中表明在选择与参数无关的适当先验情况下,使用 `Dropout` 的神经网络可被视为近似推断。\n\n`Kingma` 等人还希望使用改进的局部重参数化来降低随机梯度中的方差。这不是在应用仿射变换之前从权重分布进行采样,而是在之后执行采样。例如,考虑 `MFVB` 的情况,其中假设每个权重是独立的高斯 $$W_{ij}∼N(µ_{ij},σ^2_{ij})$$ 。在仿射变换 $$\\phi_j=\\sum_{i=1}^{N_1}(x_iρ_i)w_{ij}$$ 之后, $\\phi_j$ 的条件后验分布也将是因子分解的高斯形式:\n\n\\begin{align}\nq\\left(\\phi_{j} \\mid \\mathbf{x}\\right) &=\\mathcal{N}\\left(\\gamma_{j}, \\delta_{j}^{2}\\right) \\\\\n\\gamma_{j} &=\\sum_{i=1}^{N} x_{i} \\mu_{i, j} \\\\\n\\delta_{j}^{2} &=\\sum_{i=1}^{N} x_{i}^{2} \\sigma_{i, j}^{2}\n\\end{align}\n\n相对于权重 $w$ 本身的分布,从 $\\phi$ 的分布中采样更有利,因为这使得梯度估计器的方差与训练期间使用的小批次数量呈线性关系。\n\n上述工作对于解决机器学习研究中缺乏严谨性的问题很重要。例如,最初的 `Dropout` 论文 `[70]` 缺乏任何重要的理论基础。相反,该方法引用了有性繁殖理论`[73]`作为方法动机,并在很大程度上依赖于所给出的实证结果。这些结果在许多高影响力的研究项目中得到了进一步的证明,但这些项目仅仅将其作为一种正规化方法来使用。`[39]` 和 `[71]` 中的工作表明,该方法有理论上的合理解释。在试图减少网络过拟合影响时,频率主义方法论依赖于弱合理性的成功经验,而贝叶斯分析提供了丰富的理论体系,导致对神经网络强大近似能力的有意义理解。\n\n#### (5) 概率反向传播方法\n\n虽然解决了将变分推断应用于具有更多隐层的复杂贝叶斯神经网络问题,但实际实现还是显示出性能不足,这归因于梯度计算的蒙特卡洛近似带来的巨大方差。`Hernandez` 等人 `[64]` 承认了这一局限性,并提出了一种新的贝叶斯神经网络实用推断方法,名为概率反向传播 (`PBP`)。`PBP` 偏离了典型的变分推断方法,取而代之的是采用 `假设密度滤波(Assumed Density Filtering, ADF)方法 [74]`。在该方法中,通过应用贝叶斯规则以迭代方式更新后验概率:\n\n$$\np\\left(\\boldsymbol{\\omega}_{t+1} \\mid \\mathcal{D}_{t+1}\\right)=\\frac{p\\left(\\boldsymbol{\\omega}_{t} \\mid \\mathcal{D}_{t}\\right) p\\left(\\mathcal{D}_{t+1} \\mid \\boldsymbol{\\omega}_{t}\\right)}{p\\left(\\mathcal{D}_{t+1}\\right)} \\tag{46}\n$$\n\n与以预测误差为目标函数的传统网络训练不同,`PBP` 使用前向传播来计算目标的对数边缘概率,并更新网络参数的后验分布。在 `[75]` 中定义的矩匹配方法使用了反向传播的变种来更新后验,同时在近似分布和变分分布之间保持等效均值和方差:\n\n\\begin{align*}\n\\mu_{t+1} &=\\mu_{t}+\\sigma_{t} \\frac{\\partial \\log p\\left(\\mathcal{D}_{t+1}\\right)}{\\partial \\mu} \\\\ \n\\sigma_{t+1} &=\\sigma_{t}+\\sigma_{t}^{2}\\left[\\left(\\frac{\\partial p\\left(\\mathcal{D}_{t+1}\\right)}{\\partial \\mu_{t}}\\right)^{2}-2 \\frac{\\partial p\\left(\\mathcal{D}_{t+1}\\right)}{\\partial \\sigma}\\right]` \n\\end{align*}\n\n在多个小数据集上的实验结果表明,与简单回归问题的 `HMC` 方法相比,该方法在预测精度和不确定性估计方面具有合理的性能 `[64]` 。这种方法的关键问题是在线训练带来的计算瓶颈。该方法可能适用于某些应用,或者适用于在现有贝叶斯神经网络可用时用额外的附加数据更新现有贝叶斯神经网络,但是对于大数据集推断,该方法在计算性能上令人望而却步。\n\n#### (6) 反向传播贝叶斯方法\n\n`Blundell` 等人提出了一种很有前途的贝叶斯神经网络近似推断方法,名为 “`Bayes by Backprop” [76]`。该方法利用重参数化技巧来展示如何找到期望导数的无偏估计。对于可重参数化为确定性且可微函数 $w=g(\\epsilon,θ)$ 的随机变量 $w \\sim q_\\theta(\\omega)$,任意函数 $f(w,θ)$ 的期望的导数可表示为:\n\n\\begin{align*}\n\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} \\mathbb{E}_{q}[f(\\boldsymbol{\\omega}, \\boldsymbol{\\theta})]` &=\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} \\int q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega}) f(\\boldsymbol{\\omega}, \\boldsymbol{\\theta}) d \\boldsymbol{\\omega} \\\\ \n&=\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} \\int p(\\boldsymbol{\\epsilon}) f(\\boldsymbol{\\omega}, \\boldsymbol{\\theta}) d \\boldsymbol{\\epsilon} \\\\ \n&=\\mathbb{E}_{q(\\epsilon)}\\left[\\frac{\\partial f(\\boldsymbol{\\omega}, \\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\omega}} \\frac{\\partial \\boldsymbol{\\omega}}{\\partial \\boldsymbol{\\theta}}+\\frac{\\partial f(\\boldsymbol{\\omega}, \\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}}\\right]\n\\end{align*}\n\n\n在 `Bayes by Backprop` 算法中,函数 $f(w,θ)$ 被设为:\n\n$$\nf(\\boldsymbol{\\omega}, \\boldsymbol{\\theta})=\\log \\frac{q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega})}{p(\\boldsymbol{\\omega})}-\\log p(\\mathbf{X} \\mid \\boldsymbol{\\omega}) \\tag{52}t\n$$\n\n这个 $f(w,θ)$ 可被视为式 17 中执行的期望的自变量,它是下界的一部分。组合公式 51 和 52 :\n\n$$\n\\mathcal{L}(\\boldsymbol{\\omega}, \\boldsymbol{\\theta})=\\mathbb{E}_{q}[f(\\boldsymbol{\\omega}, \\boldsymbol{\\theta})]=\\mathrm{e}_{q}\\left[\\log \\frac{q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega})}{p(\\boldsymbol{\\omega})}-\\log p(\\mathcal{D} \\mid \\boldsymbol{\\omega})\\right]=-\\mathcal{F}\\left[q_{\\boldsymbol{\\theta}}\\right] \\tag{53}\n$$\n\n是 `ELBO` 的相反数,意味着 `Bayes By Backprop` 旨在最小化近似后验和真实后验之间的 KL 散度,可以使用蒙特卡洛积分来近似公式 53 中的代价:\n\n$$\n\\mathcal{F}\\left[q_{\\boldsymbol{\\theta}}\\right] \\approx \\sum_{i=1}^{N} \\log \\frac{q_{\\boldsymbol{\\theta}}\\left(\\boldsymbol{\\omega}_{i}\\right)}{p\\left(\\boldsymbol{\\omega}_{i}\\right)}-\\log p\\left(\\mathbf{X} \\mid \\boldsymbol{\\omega}_{i}\\right)\\tag{54}\n$$\n\n其中 $w_i$ 是来自 $q_θ(w)$ 的 第 $i$ 个样本。通过公式 54 中的近似,可以使用公式 51 所示结果来找到无偏梯度。\n\n对于 `Bayes by Backprop` 算法,假设一个完全因子分解的高斯后验,使得 $θ={\\mu,\\rho}$ ,其中 $\\sigma=\\text{softplus}(\\rho)$ 用于确保标准偏差参数为正。由此,网络中的权重分布 $w∼\\mathcal{N}(\\mu,softplus(\\rho)^2)$ 被重参数化为:\n\n$$\n\\boldsymbol{\\omega}=g(\\boldsymbol{\\theta}, \\boldsymbol{\\epsilon})=\\mu+\\operatorname{softplus}(\\boldsymbol{\\rho}) \\odot \\boldsymbol{\\epsilon} \\tag{55}\n$$\n\n在该贝叶斯神经网络中,可训练参数为 $\\mu$ 和 $\\rho$ 。由于使用了全因子分解分布,根据公式 20,近似后验的对数可表示为:\n\n$$\n\\log q_{\\boldsymbol{\\theta}}(\\boldsymbol{\\omega})=\\sum_{l, j, k} \\log \\left(\\mathcal{N}\\left(w_{l j k} ; \\mu_{l j k}, \\sigma_{l j k}^{2}\\right)\\right) \\tag{56}\n$$\n\n算法 1 描述了完整的 `Bayes by Backprop` 算法。\n\n\n\n\n### 2.5 贝叶斯神经网络的高斯过程特性与深度高斯过程\n\n#### (1)贝叶斯神经网络的高斯过程特性\n\n`Neal[38]` 还给出了推导和实验结果,以说明对于只有一个隐层的网络,当隐藏单元的数量接近无穷大时,会出现网络输出的高斯过程先验,论文将高斯先验置于参数之上。图 6 说明了该结果。\n\n\n\n
    \n\n图 6:当在参数上放置高斯先验时,随着网络规模的增加,在网络输出上导致高斯过程先验。实验复制自 [38,p.33]。图中的每个点对应于一个神经网络的输出(参数从其先验分布中采样),x 轴为 f(0.2),y 轴为 f(−0.4)。对于每个网络,隐藏单元的数量是图(a)对应着 1 个单元,图(b)对应着 3 个单元,图(c)对应着 10 个单元,图(d)对应着 100 个单元。\n
    \n\n从公式 1 和公式 2 可以看出神经网络和高斯过程之间的这种重要联系:\n\n具有单个隐藏层的神经网络是应用于输入数据的 N 个参数化基函数的总和。如果方程 1 中每个基函数的参数是随机变量,则方程 2 成为随机变量的和。在中心极限定理下,随着隐层数 $N→∞$,输出变为高斯。由于输出被描述为无限个基函数的和,因此可以将输出视为高斯过程。\n\n根据这一结果的完整推导和图 6 中所示的图,`[38]` 显示了如何在有限的计算资源下实现近似高斯性质,以及如何保持该和的大小。`Williams` 随后展示了针对不同激活函数如何分析协方差函数的形式 `[77]`。高斯过程与具有单一隐层的无限宽网络之间的关系最近扩展到了深层神经网络 `[78]`。\n\n#### (2)深度高斯过程\n\n上述联系促进了在贝叶斯神经网络中的许多研究工作。高斯过程提供了许多我们希望获得的特性,例如可靠的不确定性估计、可解释性和鲁棒性。但高斯过程在提供这些好处同时,代价却是随着数据集大小的增加,预测性能和所需计算资源呈指数级增长。高斯过程和贝叶斯神经网络之间的这种联系推动了两个建模方案的合并:既保持神经网络中看到的预测性能和灵活性,又融入了高斯过程带来的稳健性和概率属性。这导致了深度高斯过程的发展。\n\n深度高斯过程是单个高斯过程的级联,前一个高斯过程的输出用作新高斯过程的输入 `[79,80]`,与神经网络非常相似。这种高斯过程的堆叠允许从高斯过程的组合中学习非高斯密度。高斯过程的一个关键挑战是适应大数据集,因为单个高斯过程的`格拉姆矩阵(Gram Matrix)`的维度与数据点的数量是平方关系。由于级联中的每个单独高斯过程都会产生一个独立的`格拉姆矩阵(Gram Matrix)`,因此该问题会被深度高斯过程放大。此外,由于产生的是非线性函数,深度高斯过程的边缘似然在分析上是难以处理的。在 `[82]` 工作的基础上,`Damianou` 和 `Lawrence` `[79]` 使用变分推断方法来创建易于处理的近似,并将计算复杂度降低到稀疏高斯过程中常见的计算复杂度 `[83]`。\n\n>Neil Lawrence 提供了对深度高斯过程的完整介绍、代码和讲座 [81]。\n\n深度高斯过程展示了高斯过程如何从神经网络中受益。`Gal` 和 `Ghahramani [84,85,86]` 阐明了如何用贝叶斯神经网络来近似深度高斯过程。这是一个可预期的结果;鉴于 `Neal [38]` 发现具有单个隐藏层的无限宽网络收敛到一个高斯过程,通过连接多个无限宽的层,整个网络可以收敛到一个深度高斯过程。\n\n>当每层中隐藏单元的数量接近∞时,贝叶斯神经网络近似成为深度高斯过程。\n\n#### (3)高斯过程的协方差函数与激活函数的选择\n\n除了对深度高斯过程的分析外,`[84,85,86]` 在 `[77]` 工作的基础上分析了贝叶斯神经网络中使用的现代非线性激活函数与高斯过程的协方差函数之间的关系。该工作可能允许在神经网络中更原则性地选择激活功能,类似于高斯过程的激活功能。哪些激活函数会产生一个稳定的过程?过程的预期长度尺度是多少?这些问题或许可以用高斯过程现有的丰富理论来解决。\n\n高斯过程属性不限于 `多层感知机贝叶斯神经网络` 。最近的研究已经表明,在卷积贝叶斯神经网络中产生高斯过程性质的某些关系和条件 `[87,88]`。这一结果是可预期的,因为卷积神经网络可以被视为具有某种权重结构的多层感知机。该论文工作说明实施权重结构如何导致形成高斯过程。`Van der Wilk [89]` 等人提出了卷积高斯过程,它实现了一种类似于在卷积神经网络中看到的面片操作,来定义函数上的高斯过程先验。该方法的实现需要使用近似方法,因为对于大数据集的评估成本高得令人望而却步,甚至在单个面片上的评估都是令人望而却步的。生成的点由变分推断框架形成(以减少需要评估的数据点数量和面片数量)。\n\n### 2.6 当前贝叶斯神经网络的局限性\n\n#### (1)存在的主要问题\n\n虽然人们已付出了很大努力来开发在神经网络中执行推断的贝叶斯方法,但这些方法存在很大局限性,文献中还存在许多空白。其中一个关键限制是严重依赖变分推断方法。在变分推断框架内,最常用的方法是 `MFVB 方法` 。`MFVB` 通过强制参数之间的独立性假设,提供了一种表示近似后验分布的方法。该假设允许使用因子分解来构建近似后验分布。这种独立性假设大大降低了近似推断的计算复杂度,但损失了概率精度。\n\n变分推断方法还存在一个问题,即结果模型过于自信,其预测均值可能是准确的,但方差被大大低估了 `[90,91,92,51,93]`。文献 `[2]` 的`第 10.1.2 节`和文献 `[35]` 的 `第 21.2 节` 描述了这一现象,两个章节都附有举例和直观的数字来说明这一性质。这种问题存在于当前贝叶斯神经网络的大部分研究中 `[39]`。\n\n最近的一些工作希望通过使用噪声对比先验 `[94]` 或使用校准数据集 `[95]` 来解决该问题。`[96]` 的作者使用了 concrete 分布 `[97]` 来近似 `MC Dropout 方法` 中的 `Bernoulli` 参数 `[85]`,允许对其进行优化,从而得到校准更好的后验方差。尽管做出了大量努力,在贝叶斯神经网络的变分推断框架内制定可靠且校准的不确定性估计任务仍然没有得到解决。\n\n有理由认为,当前变分推断方法的局限性可能受到所选择近似分布的影响,特别是 `MFVB方法` 经常使用的独立高斯分布。如果使用更全面的近似分布,会不会生成与已知或未知数据更加一致的预测呢?\n\n对于一般的变分推断方法, `[98,49]` 提出了混合模型近似,但该方法的 $N$ 个混合分量的引入增加了 $N$ 倍的参数数量。`[99]` 在贝叶斯神经网络中引入了 `矩阵-正态近似后验(Matrix-Normal approximate posteriors)` ,这与`满秩高斯`相比减少了模型中变分参数的数量,但没有对协方差结构建模。`MC Dropout` 在折中低熵近似后验的情况下,能够在权重矩阵行内保持一定的相关性信息。\n\n#### (2)标准化流推断方法\n\n最近提出了一种新的变分推断方法,通过使用 `标准化流(Normalising Flows)`来捕获更复杂的后验分布 `[100,101]`。在标准化流中,初始分布通过一系列可逆函数的“流动”,产生更复杂的分布。这可以在变分推断框架内通过`分期推断`实现 `[102]`。分期推断引入了一个推断网络,将输入数据映射到生成式模型的变分参数,然后利用这些参数从生成式过程的后验中采样。标准化流的使用已扩展到贝叶斯神经网络 `[103]`。这种方法出现了与计算复杂性相关的问题,以及分期推断的局限性。\n\n标准化流需要计算雅可比行列式,这对于某些模型来说可能计算过于昂贵。通过将标准化流限制为包含数值稳定的可逆运算,可以降低计算复杂度 `[102,104]`。这些限制已被证明严重限制了推断过程的灵活性,以及由此产生的后验近似的复杂性 `[105]`。\n\n#### (3)改进目标函数\n\n如前所述,在变分推断框架中,选择近似分布,然后最大化 `ELBO`。这个 `ELBO` 源于在真实后验和近似后验之间应用 `KL 散度`,但这回避了一个问题,为什么要使用 `KL 散度`呢?`KL 散度`是评估两个分布间相似性的一个众所周知的度量,它满足散度的所有关键性质(即 `KL 散度`为正,并且仅当两个分布相等时为零)。散度可以让我们知道近似分布是否接近真实分布,但无法知道离真实分布有多近。为什么不用定义明确的距离来代替散度呢?\n\n贝叶斯推断的目标是在先验知识和观测数据的分布下识别最适合模型的参数。变分推断框架将推断视为优化问题,优化参数以最小化近似分布和真实分布之间的 `KL 散度`(最大化 `ELBO`)。通过将边缘似然从目标函数中分离出来,能够计算相对于易处理量的导数。由于边际似然与参数无关,当求导数时,该分量消失。这就是使用`KL 散度`的关键原因,因为它允许我们从目标函数中分离出难以处理的量,然后在使用梯度信息执行优化时,目标函数将被评估为零。\n\n`KL 散度`已被证明是 `α-散度族` 的一部分。`α散度`表示为:\n\n$$\nD_{\\alpha}[p(\\omega) \\| q(\\omega)]=\\frac{1}{\\alpha(1-\\alpha)}\\left(1-\\int p(\\omega)^{\\alpha} q(\\omega)^{1-\\alpha} d \\omega\\right) \\tag{57}\n$$\n\n`正向 KL 散度` $q(\\omega) \\| p(\\omega)$ 可以在公式 57 中 $α$ 趋近于 −1 时生成,而`反向 KL 散度` $p(\\omega) \\| q(\\omega)$ 则在 $α$ 趋近于 +1 时生成。虽然在变分推断中使用`正向 KL 散度`通常会导致低估方差,但是使用`反向 KL 散度`通常会高估方差 `[2]`。类似地,当$α=0$ 时,式 57 中的 `海灵格距离(Hellinger distance)` 将升高:\n\n$$\nD_{H}(p(\\omega) \\| q(\\omega))^{2}=\\int\\left(p(\\omega)^{\\frac{1}{2}}-q(\\omega)^{\\frac{1}{2}}\\right)^{2} d \\omega \\tag{58}\n$$\n\n这是一个有效距离,因为它满足三角形不等式并且是对称的。与两个 KL 散度相比,海灵格距离的最小化在方差估计上提供了合理的折衷 `[107]`。虽然这些措施可能提供理想的质量,但它们不适合在变分推断中直接使用,因为难以处理的边缘似然不能与其他项分开。虽然这些度量不能立即使用,但它说明了客观度量的变化如何导致不同的近似。通过对目标函数使用不同的度量,可以找到更准确的后验期望。\n\n#### (4)改进 MCMC 的可能性\n\n绝大多数现代方法都围绕着变分推断方法展开,这在很大程度上归功于 SGD 。现存许多复杂的工具来简化和加速自动微分和反向传播的实现 `[108,109,110,111,112,113,114]`。变分推断的另一个好处是它接受似然的子采样。子采样减少了对大数据集进行训练所需的计算开销。这是传统 MCMC 方法在贝叶斯神经网络领域失宠的关键原因。\n\n`MCMC` 具有丰富的理论发展、渐近保证和实用的收敛诊断能力,是进行贝叶斯推断的黄金标准。传统 `MCMC方法` 需要从完全联合似然(即所有样本)中采样来执行更新,要求在提出任何新点前看到所有训练数据。\n\n目前,`子采样 MCMC(Sub-sampling MCMC)` 或 `随机梯度 MCMC(SG-MCMC) 方法`已在 `[61,115,116]` 中提出,并应用于贝叶斯神经网络`[117]`。已有研究表明,MCMC 内的朴素子采样将使随机更新的轨迹偏离后验 `[118]`。这种偏离消除了传统 MCMC 方法在理论上的优势,使其不如计算开销更低的变分推断方法。为使采样方法变得可行,需要发展确保收敛于后验分布的新子采样方法。\n\n## 3 现代贝叶斯神经网络的比较\n\n\n### 3.1 两种现代贝叶斯推断方法\n\n从文献调研情况来看,当前贝叶斯神经网络中两种最重要的近似推断方法是 `反向传播贝叶斯(Bayes by Backprop)[76]` 和 `MC Dropout [85]`。这些方法被认为是贝叶斯神经网络中最有前途、影响最大的`变分推断方法`。两种推断方法都足够灵活,并且可以使用 SGD,从而使其部署到大型数据集成为可能。鉴于这些方法的突出之处,有必要对其进行比较,看看它们的表现如何。\n\n为比较这些方法,进行了一系列简单的同方差回归任务。在这些回归模型中,似然为高斯分布。有了这个,可以写出未标准化的后验:\n\n$$\np(\\boldsymbol{w} \\mid \\mathcal{D}) \\propto p(\\boldsymbol{w}) \\mathcal{N}\\left(\\mathbf{f}^{\\boldsymbol{w}}(\\mathcal{D}), \\sigma^{2} \\mathbf{I}\\right) \\tag{59}\n$$\n\n其中 $f_w(D)$ 是贝叶斯神经网络表示的函数。在 `Bayes by Backprop` 和 `MC Dropout`\n两个模型中,均采用高斯混合模型对 spike-slab 先验建模。然后用各自方法,求出模型的近似后验 $q_θ(w)$。\n\n对于 `Bayes by Backprop`,近似后验分布是完全分解的高斯分布,而对于 `MC Dropout`,近似后验分布是缩放了的伯努利分布。利用模型的近似后验,可以使用蒙特卡洛积分做出点或区间预测。前两个点可以近似为 `[39]`:\n\n\\begin{align*}\n \\mathbb{E}_{q}\\left[\\mathbf{y}^{*}\\right] & \\approx \\frac{1}{N} \\sum_{i=1}^{N} \\mathbf{f}^{\\boldsymbol{w}_{i}}\\left(\\mathbf{x}^{*}\\right)\\\\\n\\mathbb{E}_{q}\\left[\\mathbf{y}^{* T} \\mathbf{y}^{*}\\right] & \\approx \\sigma^{2} \\mathbf{I}+\\frac{1}{N} \\sum_{i=1}^{N} \\mathbf{f}^{\\boldsymbol{w}_{i}}\\left(\\mathbf{x}^{*}\\right)^{T} \\mathbf{f}^{\\boldsymbol{w}_{i}}\\left(\\mathbf{x}^{*}\\right) \n\\end{align*}\n\n\n其中星号上标表示来自测试集中的新输入/输出样本 $x^∗,y^∗$ 。\n\n用于评估这些模型的数据集是来自高影响力论文的 `simple toy 数据集`,其中提供了类似的实验作为经验证据 `[76,119]`。然后将两种贝叶斯神经网络方法与高斯过程模型进行比较。图 7 显示了这些结果。\n\n\n\n
    \n\n图 7:贝叶斯神经网络与高斯过程在三个玩具数据集的回归任务上的比较。
    \n顶行:由 `Bayes by Backprop [76]` 训练的贝叶斯神经网络;中间行:用 `MC Dropout [39]` 训练的贝叶斯神经网络,底部:使用 `GPflow 软件包` 基于 `Mattern52 核` 拟合的高斯过程模型 `[120]`。 两个贝叶斯神经网络均包含两个 `RELU` 激活的隐藏层。训练数据用深灰色散点表示,平均值用紫色表示,真实测试函数用蓝色表示,阴影区域表示 $1\\sigma$ 和 $2 \\sigma$ 。\n\n
    \n\n对图 7 中所示回归结果的分析显示,在预测中的偏差和方差方面表现不同:\n1. 用 `Bayes by Backprop` 和分解后的高斯近似后验数据训练的模型显示出合理的训练数据分布预测结果。尽管与高斯过程相比,训练数据区域外的方差被显著低估了。\n2. 具有缩放伯努利近似后验的 `MC Dropout` 对于训练数据区域外的方差更大了,尽管在训练数据的区域内保持了不必要的高方差。\n3. 对这些模型的超参数进行了微调。通过更好地选择超参数,可以获得更好的结果,特别是对于 `MC Dropout` 。或者,可以使用更完整的贝叶斯方法,其中将超参数视为隐变量,并对这些变量执行边缘化。\n\n值得注意的是,上述方法在计算和实际应用中都遇到了困难。`MC Dropout` 方法非常灵活,因为它对先验分布的选择不那么敏感。它还设法用更少的样本和训练迭代来适应更复杂的分布。最重要的是显著节省了计算资源。考虑到使用 `MC Dropout` 训练一个模型通常与训练多个现有的深层网络相同,因此推断与传统网络同时进行。`MC Dropout` 也没有增加网络的参数数量,而 `Bayes by Backprop` 需要两倍的参数。在实际情况下应考虑这些因素。如果被建模的数据是平滑的,有足够的数量,并且允许额外的时间进行推断,使用 `Bayes by Backprop` 可能更可取。对于功能复杂、数据稀疏、时间要求较严格的大型网络,`MC Dropout` 可能更合适。\n\n### 3.2 卷积贝叶斯神经网络\n\n虽然 `MLP` 是神经网络的基础,但最突出的神经网络架构是卷积神经网络。这些网络在图像分类任务方面表现出色,其预测性能远远超过先前基于核或特征工程的方法。卷积神经网络不同于典型的 `MLP` ,它使用类似于卷积的算子代替 `MLP` 的内积,单个卷积层的输出可以表示为:\n\n$$\n\\boldsymbol{\\Phi}=u\\left(\\mathbf{X}^{T} * \\mathbf{W}\\right) \\tag{62}\n$$\n\n其中 $u(·)$ 是非线性激活,$∗$ 表示类卷积运算。输入 $X$ 和权重矩阵 $W$ 不再局限于向量或矩阵,可以是多维数组。CNN 可以被写成等效的 `MLP` 模型,从而允许利用反向传播进行训练 `[122]`。\n\n在现有研究方法基础上,发展出一种新型贝叶斯卷积神经网络 (BCNN)。该网络将 `Bayes by Backprop` 方法扩展到适合于图像分类的卷积神经网络模型`[76]` 。卷积层中的每个权重被假定为独立的,从而允许对每个单独的参数进行因子分解。\n\n通过实验研究了 `BCNN` 的预测性能及其不确定性估计的质量。这些网络被配置用于 `MNIST 手写数字数据集`的分类 `[123]`。\n\n由于该任务是分类任务,因此 `BCNN` 的似然被设置为 SoftMax 函数,\n\n$$\n\\operatorname{softmax}\\left(\\mathbf{f}_{i}^{\\omega}\\right)=\\frac{\\mathbf{f}_{i}^{\\omega}(\\mathcal{D})}{\\sum_{j} \\exp \\left(\\mathbf{f}_{j}^{\\omega}(\\mathcal{D})\\right)} \\tag{63}\n$$\n\n未标准化的后验可以表示为:\n\n$$\np(\\boldsymbol{\\omega} \\mid \\mathcal{D}) \\propto p(\\boldsymbol{\\omega}) \\times \\operatorname{softmax}\\left(\\mathbf{f}^{\\boldsymbol{\\omega}}(\\mathcal{D})\\right) \\tag{64}\n$$\n\n利用 `Bayes by Backprop`求出近似后验。可使用式 60 找到测试样本的预测平均值,并且使用 蒙特卡洛积分来近似可信区间 `[35]`。\n\n`[123]` 在均为 LeNet 架构的普通 CNN 网络与 BCNN 网络间做了比较 。使用 BCNN 的平均输出进行分类,并使用可信区间来评估模型的不确定性。在 MNIST 数据集中的 10,000 张测试图像上,两个网络的总体预测显示出接近的性能。BCNN 的测试预测准确率为 98.99%,而普通网络的预测准确率为 99.92%,略有提高。虽然竞争性预测性能是必不可少的,但 BCNN 的主要好处是提供了有关预测不确定性的有价值信息。难以分类的数字示例显示在附录中,并附有平均预测值和每类 95% 可信区间的曲线图。从这些例子中,可以看到这些具有挑战性的图像的大量预测不确定性,这些不确定性可以用来在实际场景中做出更明智的决策。\n\n这种不确定性信息对于许多感兴趣的场景来说是无价的。随着统计模型越来越多地用于包含人类交互的复杂任务,这些系统中的许多系统基于其感知的世界模型做出负责任的决策至关重要。例如,神经网络在自动驾驶汽车的开发中被大量使用。由于场景的高度可变性和与人类互动相关的复杂性,自动驾驶汽车的开发是一项令人难以置信的具有挑战性的壮举。目前的技术不足以安全地实现这项任务,正如前面讨论的那样,这些技术的使用已导致多人死亡 `[24,25]`。在这样一个高度复杂的系统中对所有变量进行建模是不可能的。这伴随着不完美的模型和对近似推断的依赖,重要的是模型可以传达与决策相关的任何不确定性。至关重要的是,我们必须承认,所有模型从本质上都是错误的。这就是为什么概率模型在此场景中更受青睐的原因:有一个基本理论来处理数据中的异质性,并解释模型中未包含变量引起的不确定性。至关重要的是,用于此类复杂场景的模型在用于此类复杂和高风险场景时能够传达其不确定性。\n\n## 4 结论\n\n本调研报告阐明了典型神经网络和特殊模型设计中存在的过度自信预测问题,而贝叶斯分析被证明可用来解决这些问题。尽管对贝叶斯神经网络来说,精确推断仍然是分析和计算上的难题,但实践表明,可以依靠近似推断方法获得较为精确的近似后验。\n\n贝叶斯神经网络中的许多近似推断方法都围绕 `MFVB` 方法展开。这为优化变分参数提供了一个易于处理的下限。这些方法在易用性、预测均值的准确性、可接受的参数数目等方面具有吸引力。文献调研和实验结果表明,在完全因子分解的 `MFVB` 方法中所做的假设会导致过度自信的预测。同时文献也表明,这些 `MFVB` 方法可以推广到更复杂的模型,如卷积神经网络。对于图像分类任务,贝叶斯卷积神经网络的预测性能与基于点估计的卷积神经网络相当(稍弱),但贝叶斯卷积神经网络能够为预测提供可信区间,而这为难以分类的数据点提供了高度信息性和直观性的不确定性度量。\n\n本文突出了贝叶斯分析解决机器学习社区中常见挑战的能力。这些结果还突显了当前用于贝叶斯神经网络的近似推断方法的不足,甚至可能提供不准确的方差信息。不仅要确定网络是如何运行的,而且要确定现代大型网络如何才能实现精确推断,这有待进一步研究。将 `MCMC` 等推断方法扩展到大数据集上允许更有原则性的推断。`MCMC` 提供了评估收敛和推断质量的诊断方法。对变分推断的类似诊断允许研究人员和实践者评估他们假设后验的质量,并告知改进该假设的方法。实现这些目标将使我们能够获得更精确的后验近似。由此,我们将能够充分确定模型知道什么,也可以确定模型不知道什么。\n\n## 参考文献\n\n1. F. Rosenblatt, “The perceptron: A probabilistic model for information storage and organization in the brain.” Psychological Review, vol. 65, no. 6, pp. 386 – 408, 1958.\n2. C. Bishop, Pattern recognition and machine learning. New York: Springer, 2006.\n3. D. E. Rumelhart, G. E. Hinton, and R. J. Williams, “Learning representations by back-propagating errors,” nature, vol. 323, no. 6088, p. 533, 1986.\n4. K.-S. Oh and K. Jung, “GPU implementation of neural networks,” Pattern Recognition, vol. 37, no. 6, pp. 1311–1314, 2004.\n5. D. C. Ciresan, U. Meier, L. M. Gambardella, and J. Schmidhuber, “Deep big simple neural nets excel on handwritten digit recognition,” CoRR, 2010.\n6. A. Krizhevsky, I. Sutskever, and G. E. Hinton, “Imagenet classification with deep convolutional neural networks,” in Advances in neural information processing systems,2012, pp. 1097–1105.\n7. K. Simonyan and A. Zisserman, “Very deep convolutional networks for large-scale image recognition,” CoRR, 2014.\n8. C. Szegedy, W. Liu, Y. Jia, P. Sermanet, S. Reed, D. Anguelov, D. Erhan, V. Vanhoucke, A. Rabinovich et al., “Going deeper with convolutions,” in CVPR, 2015.\n9. R. Girshick, J. Donahue, T. Darrell, and J. Malik, “Rich feature hierarchies for accurate object detection and semantic segmentation,” in Proceedings of the IEEE conference on computervision and pattern recognition, 2014, pp. 580–587.\n10. S. Ren, K. He, R. Girshick, and J. Sun, “Faster r-cnn: Towards real-time object detection with region proposal networks,” in Advances in neural information processing systems, 2015, pp. 91–99.\n11. J. Redmon, S. Divvala, R. Girshick, and A. Farhadi, “You only look once: Unified,real-time object detection,” in Proceedings of the IEEE conference on computervision and pattern recognition, 2016, pp. 779–788.\n12. A. Mohamed, G. E. Dahl, and G. Hinton, “Acoustic modeling using deep belief networks,” IEEE Transactions on Audio, Speech, and Language Processing, vol. 20, no. 1, pp. 14–22, 2012.\n13. G. E. Dahl, D. Yu, L. Deng, and A. Acero, “Context-dependent pre-trained deep neural networks for large-vocabulary speech recognition,” IEEE Transactions on audio,speech, and language processing, vol. 20, no. 1, pp. 30–42, 2012.\n14. G. Hinton, L. Deng, D. Yu, G. E. Dahl, A.-r. Mohamed, N. Jaitly, A. Senior, V. Vanhoucke, P. Nguyen, T. N. Sainath et al., “Deep neural networks for acoustic modeling in speech recognition: The sharedviews of four research groups,” IEEE Signal Processing Magazine, vol. 29, no. 6, pp. 82–97, 2012.\n15. D. Amodei, S. Ananthanarayanan, R. Anubhai, J. Bai, E. Battenberg, C. Case, J. Casper, B. Catanzaro, Q. Cheng, G. Chen, J. Chen, J. Chen, Z. Chen, M. Chrzanowski, A. Coates, G. Diamos, K. Ding, N. Du, E. Elsen, J. Engel, W. Fang, L. Fan, C. Fougner, L. Gao, C. Gong, A. Hannun, T. Han, L. Johannes, B. Jiang, C. Ju, B. Jun, P. LeGresley, L. Lin, J. Liu, Y. Liu, W. Li, X. Li, D. Ma, S. Narang, A. Ng, S. Ozair, Y. Peng, R. Prenger, S. Qian, Z. Quan, J. Raiman, V. Rao, S. Satheesh, D. Seetapun, S. Sengupta, K. Srinet, A. Sriram, H. Tang, L. Tang, C. Wang, J. Wang, K. Wang, Y. Wang, Z. Wang, Z. Wang, S. Wu, L. Wei, B. Xiao, W. Xie, Y. Xie, D. Yogatama, B. Yuan, J. Zhan, and Z. Zhu, “Deep speech 2 : End-to-end speech recognition in english and mandarin,” in Proceedings of The 33rd International Conference on Machine Learning, ser. Proceedings of Machine Learning Research, M. F. Balcan and K. Q. Weinberger, Eds., vol. 48. New York, New York, USA: PMLR, 20–22 Jun 2016, pp. 173–182.\n16. D. Silver, J. Schrittwieser, K. Simonyan, I. Antonoglou, A. Huang, A. Guez, T. Hubert, L. Baker, M. Lai, A. Bolton et al., “Mastering the game of go without human knowledge,” Nature, vol. 550, no. 7676, p. 354, 2017.\n17. “Smartening up with artificial intelligence (ai) - what’s in it for germany and its industrial sector?” McKinsey & Company, Inc, Tech. Rep., 4 2017. `[Online].Available: https://www.mckinsey.de/files/170419 mckinsey ki final m.pdf\n18. E. V. T. V. Serooskerken, “Artificial intelligence in wealth and asset management,” Pictet on Robot Advisors, Tech. Rep., 1 2017.[Online]. Available: https://perspectives.pictet.com/wp-content/uploads/2016/12/Edgar-van-Tuyll-van-Serooskerken-Pictet-Report-winter-2016-2.pdf\n19. A. van den Oord, T. Walters, and T. Strohman, “Wavenet launches in the google assistant.” `[Online]. Available: https://deepmind.com/blog/wavenet-launches-google-assistant/\n20. Siri Team, “Deep learning for siri’s voice: On-device deep mixture density networks for hybrid unit selection synthesis,” 8 2017. `[Online]. Available: https://machinelearning.apple.com/2017/08/06/siri-voices.html\n21. J. Wakefield, “Microsoft chatbot is taught to swear on twitter.” `[Online]. Available:www.bbc.com/news/technology-35890188\n22. J. Guynn, “Google photos labeled black people ’gorillas’.” `[Online]. Available: https://www.usatoday.com/story/tech/2015/07/01/ google-apologizes-after-photos-identify-black-people-as-gorillas/29567465/\n23. J. Buolamwini and T. Gebru, “Gender shades: Intersectional accuracy disparities in commercial gender classification,” in Conference on fairness, accountability and transparency, 2018, pp. 77–91.\n24. Tesla Team, “A tragic loss.” `[Online]. Available: https://www.tesla.com/en GB/blog/tragic-loss\n25. ABC News, “Uber suspends self-driving car tests after vehicle hits and kills woman crossing the street in arizona,” 2018. `[Online]. Available: http://www.abc.net.au/news/2018-03-20/uber-suspends-self-driving-car-tests-after-fatal-crash/9565586\n26. Council of European Union, “Regulation (eu) 2016/679 of the european parliment and of the council,” 2016.\n27. B. Goodman and S. Flaxman, “European union regulations on algorithmic decision making and a right to explanation,” AI magazine, vol. 38, no. 3, pp. 50–57, 2017.\n28. M. Vu, T. Adali, D. Ba, G. Buzsaki, D. Carlson, K. Heller, C. Liston, C. Rudin, V. Sohal, A. Widge, H. Mayberg, G. Sapiro, and K. Dzirasa, “A sharedvision for machine learning in neuroscience,” JOURNAL OF NEUROSCIENCE, vol. 38, no. 7, pp. 1601–1607, 2018.\n29. A. Holzinger, C. Biemann, C. S. Pattichis, and D. B. Kell, “What do we need to build explainable ai systems for the medical domain?” arXiv preprint arXiv:1712.09923, 2017.\n30. R. Caruana, Y. Lou, J. Gehrke, P. Koch, M. Sturm, and N. Elhadad, “Intelligible models for healthcare: Predicting pneumonia risk and hospital 30-day readmission,” in Proceedings of the 21th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining. ACM, 2015, pp. 1721–1730.\n31. D. Gunning, “Explainable artificial intelligence (xai),” Defense Advanced Research Projects Agency (DARPA), nd Web, 2017.\n32. D. J. MacKay, “Probable networks and plausible predictionsa review of practical bayesian methods for supervised neural networks,” Network: computation in neural systems, vol. 6, no. 3, pp. 469–505, 1995.\n33. J. Lampinen and A. Vehtari, “Bayesian approach for neural networks review and case studies,” Neural networks, vol. 14, no. 3, pp. 257–274, 2001.\n34. H. Wang and D.-Y. Yeung, “Towards bayesian deep learning: A survey,” arXiv preprint arXiv:1604.01662, 2016.\n35. K. Murphey, Machine learning, a probabilistic perspective. Cambridge, MA: MIT Press, 2012.\n36. X. Glorot, A. Bordes, and Y. Bengio, “Deep sparse rectifier neural networks,” in AISTATS, 2011, pp. 315–323.\n37. A. L. Maas, A. Y. Hannun, and A. Y. Ng, “Rectifier nonlinearities improve neural network acoustic models,” in ICML, vol. 30, 2013, p. 3.\n38. R. M. Neal, Bayesian learning for neural networks. Springer Science & Business Media, 1996, vol. 118.\n39. Y. Gal, “Uncertainty in deep learning,” University of Cambridge, 2016.\n40. N. Tishby, E. Levin, and S. A. Solla, “Consistent inference of probabilities in layered networks: predictions and generalizations,” in International 1989 Joint Conference on Neural Networks, 1989, pp. 403–409 vol.2.\n41. J. S. Denker and Y. Lecun, “Transforming neural-net output levels to probability distributions,” in NeurIPS, 1991, pp. 853–859.\n42. G. Cybenko, “Approximation by superpositions of a sigmoidal function,” Mathematics of control, signals and systems, vol. 2, no. 4, pp. 303–314, 1989.\n43. K.-I. Funahashi, “On the approximate realization of continuous mappings by neural networks,” Neural networks, vol. 2, no. 3, pp. 183–192, 1989.\n44. K. Hornik, “Approximation capabilities of multilayer feedforward networks,” Neural networks, vol. 4, no. 2, pp. 251–257, 1991.\n45. S. F. Gull and J. Skilling, “Quantified maximum entropy memsys5 users manual,” Maximum Entropy Data Consultants Ltd, vol. 33, 1991.\n46. D. J. MacKay, “Bayesian interpolation,” Neural computation, vol. 4, no. 3, pp. 415–447, 1992.\n47. ——, “Bayesian methods for adaptive models,” Ph.D. dissertation, California Institute of Technology, 1992.\n48. ——, “A practical bayesian framework for backpropagation networks,” Neural computation, vol. 4, no. 3, pp. 448–472, 1992.\n49. M. I. Jordan, Z. Ghahramani, T. S. Jaakkola, and L. K. Saul, “An introduction to variational methods for graphical models,” Machine learning, vol. 37, no. 2, pp. 183–233, 1999.\n50. M. J. Wainwright, M. I. Jordan et al., “Graphical models, exponential families, and variational inference,” Foundations and Trends R ? in Machine Learning, vol. 1, no.1–2, pp. 1–305, 2008.\n51. D. M. Blei, A. Kucukelbir, and J. D. McAuliffe, “Variational inference: A review for statisticians,” Journal of the American Statistical Association, vol. 112, no. 518, pp. 859–877, 2017.\n52. M. D. Hoffman, D. M. Blei, C. Wang, and J. Paisley, “Stochastic variational inference,” The Journal of Machine Learning Research, vol. 14, no. 1, pp. 1303–1347, 2013.\n53. D. Barber and C. M. Bishop, “Ensemble learning in bayesian neural networks,” NATO ASI SERIES F COMPUTER AND SYSTEMS SCIENCES, vol. 168, pp. 215–238,1998.\n54. G. E. Hinton and D. Van Camp, “Keeping the neural networks simple by minimizing the description length of the weights,” in Proceedings of the sixth annual conference on Computational learning theory. ACM, 1993, pp. 5–13.\n55. M. Betancourt, “A conceptual introduction to hamiltonian monte carlo,” arXiv preprint arXiv:1701.02434, 2017.\n56. M. Betancourt, S. Byrne, S. Livingstone, M. Girolami et al., “The geometric foundations of hamiltonian monte carlo,” Bernoulli, vol. 23, no. 4A, pp. 2257–2298, 2017.\n57. G. Madey, X. Xiang, S. E. Cabaniss, and Y. Huang, “Agent-based scientific simulation,” Computing in Science & Engineering, vol. 2, no. 01, pp. 22–29, jan 2005.\n58. S. Duane, A. D. Kennedy, B. J. Pendleton, and D. Roweth, “Hybrid monte carlo,” Physics letters B, vol. 195, no. 2, pp. 216–222, 1987.\n59. R. M. Neal et al., “MCMC using hamiltonian dynamics,” Handbook of markov chain monte carlo, vol. 2, no. 11, p. 2, 2011.\n60. S. Brooks, A. Gelman, G. Jones, and X.-L. Meng, Handbook of markov chain monte carlo. CRC press, 2011.\n61. M. Welling and Y. Teh, “Bayesian learningvia stochastic gradient langevin dynamics,” Proceedings of the 28th International Conference on Machine Learning, ICML 2011, pp. 681–688, 2011.\n62. A. Graves, “Practical variational inference for neural networks,” in Advances in Neural Information Processing Systems 24, J. Shawe-Taylor, R. S. Zemel, P. L. Bartlett,F. Pereira, and K. Q. Weinberger, Eds. Curran Associates, Inc., 2011, pp. 2348–2356.\n63. M. Opper and C. Archambeau, “The variational gaussian approximation revisited,” Neural computation, vol. 21, no. 3, pp. 786–792, 2009.\n64. J. M. Hern´ andez-Lobato and R. Adams, “Probabilistic backpropagation for scalable learning of bayesian neural networks,” in International Conference on Machine Learning, 2015, pp. 1861–1869.\n65. J. Paisley, D. Blei, and M. Jordan, “Variational bayesian inference with stochastic search,” arXiv preprint arXiv:1206.6430, 2012.\n66. J. R. Wilson, “Variance reduction techniques for digital simulation,” American Journal of Mathematical and Management Sciences, vol. 4, no. 3-4, pp. 277–312, 1984.\n67. M. Opper and C. Archambeau, “The variational gaussian approximation revisited,” Neural computation, vol. 21 3, pp. 786–92, 2009.\n68. D. P. Kingma and M. Welling, “Auto-encoding variational bayes,” arXiv preprint arXiv:1312. 6114, 2013.\n69. D. J. Rezende, S. Mohamed, and D. Wierstra, “Stochastic backpropagation and approximate inference in deep generative models,” in Proceedings of the 31st International Conference on Machine Learning (ICML), 2014, pp. 1278–1286.\n70. N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever, and R. Salakhutdinov, “Dropout: A simple way to prevent neural networks from overfitting,” The Journal of Machine Learning Research, vol. 15, no. 1, pp. 1929–1958, 2014.\n71. D. P. Kingma, T. Salimans, and M. Welling, “Variational dropout and the local reparameterization trick,” in Advances in Neural Information Processing Systems, 2015, pp. 2575–2583.\n72. S. Wang and C. Manning, “Fast dropout training,” in international conference on machine learning, 2013, pp. 118–126.\n73. A. Livnat, C. Papadimitriou, N. Pippenger, and M. W. Feldman, “Sex, mixability, and modularity,” Proceedings of the National Academy of Sciences, vol. 107, no. 4, pp. 1452–1457, 2010.\n74. M. Opper and O. Winther, “A bayesian approach to on-line learning,” On-line learning in neural networks, pp. 363–378, 1998.\n75. T. P. Minka, “A family of algorithms for approximate bayesian inference,” Ph.D. dissertation, Massachusetts Institute of Technology, 2001.\n76. C. Blundell, J. Cornebise, K. Kavukcuoglu, and D. Wierstra, “Weight uncertainty in neural networks,” arXiv preprint arXiv:1505.05424, 2015.\n77. C. K. Williams, “Computing with infinite networks,” in Advances in neural information processing systems, 1997, pp. 295–301.\n78. J. Lee, J. Sohl-dickstein, J. Pennington, R. Novak, S. Schoenholz, and Y. Bahri, “Deep neural networks as gaussian processes,” in International Conference on Learning Representations, 2018.\n79. A. Damianou and N. Lawrence, “Deep gaussian processes,” in AISTATS, 2013, pp. 207–215.\n80. A. Damianou, “Deep gaussian processes and variational propagation of uncertainty,” Ph.D. dissertation, University of Sheffield, 2015.\n81. N. Lawrence, “Deep gaussian processes,” 2019. `[Online]. Available: http://inverseprobability.com/talks/notes/deep-gaussian-processes.html\n82. A. Damianou, M. K. Titsias, and N. D. Lawrence, “Variational gaussian process dynamical systems,” in NeurIPS, 2011, pp. 2510–2518.\n83. M. Titsias, “Variational learning of inducing variables in sparse gaussian processes,” in Proceedings of the Twelth International Conference on Artificial Intelligence and Statistics, ser. Proceedings of Machine Learning Research, D. van Dyk and M. Welling, Eds., vol. 5. Hilton Clearwater Beach Resort, Clearwater Beach, Florida USA: PMLR, 16–18 Apr 2009, pp. 567–574.\n84. Y. Gal and Z. Ghahramani, “Dropout as a bayesian approximation: Insights and applications,” in Deep Learning Workshop, ICML, vol. 1, 2015, p. 2.\n85. ——, “Dropout as a bayesian approximation: Representing model uncertainty in deep learning,” in ICML, 2016, pp. 1050–1059.\n86. ——, “Dropout as a bayesian approximation: Appendix,” arXiv preprint arXiv:1506.02157, 2015.\n87. A. Garriga-Alonso, L. Aitchison, and C. E. Rasmussen, “Deep convolutional networks as shallow gaussian processes,” arXiv preprint arXiv:1808.05587, 2018.\n88. R. Novak, L. Xiao, Y. Bahri, J. Lee, G. Yang, D. A. Abolafia, J. Pennington, and J. Sohl-dickstein, “Bayesian deep convolutional networks with many channels are gaussian processes,” in International Conference on Learning Representations, 2019.\n89. M. Van der Wilk, C. E. Rasmussen, and J. Hensman, “Convolutional gaussian processes,” in Advances in Neural Information Processing Systems, 2017, pp. 2849–2858.\n90. D. J. MacKay and D. J. Mac Kay, Information theory, inference and learning algorithms. Cambridge university press, 2003.\n91. B. Wang and D. Titterington, “Inadequacy of interval estimates corresponding to variational bayesian approximations.” in AISTATS. Barbados, 2005.\n92. R. E. Turner and M. Sahani, “Two problems with variational expectation maximisation for time-series models,” in Bayesian Time Series Models, D. Barber, A. T. Cemgil, and S. Chiappa, Eds. Cambridge University Press, 2011.\n93. R. Giordano, T. Broderick, and M. I. Jordan, “Covariances, robustness, and variational bayes,” Journal of Machine Learning Research, vol. 19, no. 51, pp. 1–49, 2018.\n94. D. Hafner, D. Tran, A. Irpan, T. Lillicrap, and J. Davidson, “Reliable uncertainty estimates in deep neural networks using noise contrastive priors,” arXiv preprint arXiv:1807.09289, 2018.\n95. V. Kuleshov, N. Fenner, and S. Ermon, “Accurate uncertainties for deep learning using calibrated regression,” arXiv preprint arXiv:1807.00263, 2018.\n96. Y. Gal, J. Hron, and A. Kendall, “Concrete dropout,” in Advances in Neural Information Processing Systems, 2017, pp. 3581–3590.\n97. C. J. Maddison, A. Mnih, and Y. W. Teh, “The concrete distribution: A continuous relaxation of discrete random variables,” arXiv preprint arXiv:1611.00712, 2016.\n98. T. S. Jaakkola and M. I. Jordan, “Improving the mean field approximationvia the use of mixture distributions,” in Learning in graphical models. Springer, 1998, pp. 163–173.\n99. C. Louizos and M. Welling, “Structured and efficient variational deep learning with matrix gaussian posteriors,” in International Conference on Machine Learning, 2016, pp. 1708–1716.\n100. E. G. Tabak and E. Vanden-Eijnden, “Density estimation by dual ascent of the log-likelihood,” Commun. Math. Sci., vol. 8, no. 1, pp. 217–233, 03 2010.\n101. E. G. Tabak and C. V. Turner, “A family of nonparametric density estimation algorithms,” Communications on Pure and Applied Mathematics, vol. 66, no. 2, pp. 145–164, 2013.\n102. D. J. Rezende and S. Mohamed, “Variational inference with normalizing flows,” arXiv preprint arXiv:1505.05770, 2015.\n103. C. Louizos and M. Welling, “Multiplicative normalizing flows for variational bayesianneural networks,” in Proceedings of the 34th International Conference on Machine Learning - Volume 70, ser. ICML’17. JMLR.org, 2017, pp. 2218–2227.\n104. L. Dinh, J. Sohl-Dickstein, and S. Bengio, “Density estimation using real NVP,”CoRR, vol. abs/1605.08803, 2016.\n105. C. Cremer, X. Li, and D. K. Duvenaud, “Inference suboptimality in variational au-toencoders,” CoRR, vol. abs/1801.03558, 2018.\n106. S.-i. Amari, Differential-geometrical methods in statistics. Springer Science & Busi-ness Media, 2012, vol. 28.\n107. T. Minka et al., “Divergence measures and message passing,” Technical report, Mi-crosoft Research, Tech. Rep., 2005.\n108. Y. Jia, E. Shelhamer, J. Donahue, S. Karayev, J. Long, R. Girshick, S. Guadarrama,and T. Darrell, “Caffe: Convolutional architecture for fast feature embedding,” arXiv preprint arXiv:1408.5093, 2014.\n109. F. Chollet, “keras,” https://github.com/fchollet/keras, 2015.\n110. M. Abadi, A. Agarwal, P. Barham, E. Brevdo, Z. Chen, C. Citro, G. S. Corrado,A. Davis, J. Dean, M. Devin, S. Ghemawat, I. J. Goodfellow, A. Harp, G. Irving,M. Isard, Y. Jia, R. J´ ozefowicz, L. Kaiser, M. Kudlur, J. Levenberg, D. Man´ e,R. Monga, S. Moore, D. G. Murray, C. Olah, M. Schuster, J. Shlens, B. Steiner,I. Sutskever, K. Talwar, P. A. Tucker, V. Vanhoucke, V. Vasudevan, F. B.vi´ egas,O.vinyals, P. Warden, M. Wattenberg, M. Wicke, Y. Yu, and X. Zheng, “Tensor-flow: Large-scale machine learning on heterogeneous distributed systems,” CoRR,vol. abs/1603.04467, 2016.\n111. J. V. Dillon, I. Langmore, D. Tran, E. Brevdo, S. Vasudevan, D. Moore, B. Patton,A. Alemi, M. D. Hoffman, and R. A. Saurous, “Tensorflow distributions,” CoRR, vol. abs/1711.10604, 2017.\n112. P. Adam, G. Sam, C. Soumith, C. Gregory, Y. Edward, D. Zachary, L. Zeming, D. Al-ban, A. Luca, and L. Adam, “Automatic differentiation in pytorch,” in Proceedings of Neural Information Processing Systems, 2017.\n113. T. Chen, M. Li, Y. Li, M. Lin, N. Wang, M. Wang, T. Xiao, B. Xu, C. Zhang, and Z. Zhang, “Mxnet: A flexible and efficient machine learning library for heterogeneous distributed systems,” CoRR, vol. abs/1512.01274, 2015.\n114. A. Kucukelbir, D. Tran, R. Ranganath, A. Gelman, and D. M. Blei, “Automatic Differentiation Variational Inference,” arXiv e-prints, p. arXiv:1603.00788, Mar 2016.\n115. S. Patterson and Y. W. Teh, “Stochastic gradient riemannian langevin dynamics on the probability simplex,” in Advances in Neural Information Processing Systems 26,C. J. C. Burges, L. Bottou, M. Welling, Z. Ghahramani, and K. Q. Weinberger, Eds.Curran Associates, Inc., 2013, pp. 3102–3110.\n116. T. Chen, E. Fox, and C. Guestrin, “Stochastic gradient hamiltonian monte carlo,” in Proceedings of the 31st International Conference on Machine Learning, ser. Proceed-ings of Machine Learning Research, E. P. Xing and T. Jebara, Eds., vol. 32. PMLR, 22–24 Jun 2014, pp. 1683–1691.\n117. C. Li, C. Chen, D. Carlson, and L. Carin, “Preconditioned Stochastic Gradient Langevin Dynamics for Deep Neural Networks,” arXiv e-prints, Dec. 2015.\n118. M. Betancourt, “The fundamental incompatibility of scalable hamiltonian montecarlo and naive data subsampling,” in Proceedings of the 32Nd International Confer-ence on International Conference on Machine Learning - Volume 37, ser. ICML’15.JMLR.org, 2015, pp. 533–540.\n119. I. Osband, C. Blundell, A. Pritzel, and B. V. Roy, “Deep explorationvia bootstrapped DQN,” CoRR, vol. abs/1602.04621, 2016.\n120. A. G. d. G. Matthews, M. van der Wilk, T. Nickson, K. Fujii, A. Boukouvalas,P. Le´ on-villagr´ a, Z. Ghahramani, and J. Hensman, “GPflow: A Gaussian process library using TensorFlow,” Journal of Machine Learning Research, vol. 18, no. 40, pp. 1–6, 4 2017.\n121. Y. LeCun, B. Boser, J. S. Denker, D. Henderson, R. E. Howard, W. Hubbard, and L. D. Jackel, “Backpropagation applied to handwritten zip code recognition,” Neural\ncomputation, vol. 1, no. 4, pp. 541–551, 1989.\n122. I. Goodfellow, Y. Bengio, and A. Courville, Deep learning. MIT Press, 2016.\n123. Y. Lecun, L. Bottou, Y. Bengio, and P. Haffner, “Gradient-based learning applied to document recognition,” Proceedings of the IEEE, vol. 86, no. 11, pp. 2278–2324, Nov 1998.\n", "meta": {"hexsha": "a596997a8a1271e1192fa8dce81a51217b6f7aa4", "size": 75324, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BayesianAnalysiswithPython2nd/notebook/Append-04-BayesianNN_Tutorial.ipynb", "max_stars_repo_name": "xishansnow/BayesianAnalysiswithPython2nd", "max_stars_repo_head_hexsha": "ea217f95a01caf52570c83638b04c8ede4781d8b", "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": "BayesianAnalysiswithPython2nd/notebook/Append-04-BayesianNN_Tutorial.ipynb", "max_issues_repo_name": "xishansnow/BayesianAnalysiswithPython2nd", "max_issues_repo_head_hexsha": "ea217f95a01caf52570c83638b04c8ede4781d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-25T09:10:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T09:10:03.000Z", "max_forks_repo_path": "BayesianAnalysiswithPython2nd/notebook/Append-04-BayesianNN_Tutorial.ipynb", "max_forks_repo_name": "xishansnow/BayesianAnalysiswithPython2nd", "max_forks_repo_head_hexsha": "ea217f95a01caf52570c83638b04c8ede4781d8b", "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": 75.7786720322, "max_line_length": 1000, "alphanum_fraction": 0.6645823376, "converted": true, "num_tokens": 40706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.13296425050508956, "lm_q1q2_score": 0.05668553296551248}} {"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# Phases of a Trajectory\n\nDymos uses the concept of *phases* to support intermediate boundary constraints and path constraints on variables in the system.\nEach phase represents the trajectory of a dynamical system, and may be subject to different equations of motion, force models, and constraints.\nMultiple phases may be assembled to form one or more trajectories by enforcing compatibility constraints between them.\n\nFor implicit and explicit phases, the equations-of-motion or process equations are defined via an ordinary differential equation.\n\nAn ODE is of the form\n\n\\begin{align} \n \\frac{\\partial \\textbf x}{\\partial t} = \\textbf f(t, \\textbf x, \\textbf u)\n\\end{align}\n\nwhere\n$\\textbf x$ is the vector of *state variables* (the variable being integrated),\n$t$ is *time* (or *time-like*),\n$\\textbf u$ is the vector of *parameters* (an input to the ODE),\nand\n$\\textbf f$ is the *ODE function*.\n\nDymos can treat the parameters $\\textbf u$ as either static **parameters** or dynamic **controls**.\nIn addition, Dymos automatically calculates the first and second time-derivatives of the controls.\nThese derivatives can then be utilized as via constraints or as additional parameters to the ODE.\nSubsequently, the optimal control problem as solved by Dymos can be expressed as:\n\n\\begin{align}\n \\textrm{Minimize}:& \\quad J = \\textbf f_{obj}(t, \\textbf x, \\textbf u, \\dot{\\textbf u}, \\ddot{\\textbf u}) \\\\\n \\textrm{subject to:}& \\\\\n &\\textrm{system dynamics} \\quad &\\frac{\\partial \\textbf x}{\\partial t} &= \\textbf f_{ode}(t, \\textbf x, \\textbf u, \\dot{\\textbf u}, \\ddot{\\textbf u}) \\\\\n &\\textrm{initial time bounds} \\quad &t_{0,lb} &\\,\\le\\, t_0 \\,\\le\\, t_{0,ub} \\\\\n &\\textrm{elapsed time bounds} \\quad &t_{p,lb} &\\,\\le\\, t_p \\,\\le\\, t_{p,ub} \\\\\n &\\textrm{state bounds} \\quad &\\textbf x_{lb} &\\,\\le\\, \\textbf x \\,\\le\\, \\textbf x_{ub} \\\\\n &\\textrm{control bounds} \\quad &\\textbf u_{lb} &\\,\\le\\, \\textbf u \\,\\le\\, \\textbf u_{ub} \\\\\n &\\textrm{nonlinear boundary constraints} \\quad &\\textbf g_{b,lb} &\\,\\le\\, \\textbf g_{b}(t, \\textbf x, \\textbf u, \\dot{\\textbf u}, \\ddot{\\textbf u}) \\,\\le\\, \\textbf g_{b,ub} \\\\\n &\\textrm{nonlinear path constraints} \\quad &\\textbf g_{p,lb} &\\,\\le\\, \\textbf g_{p}(t, \\textbf x, \\textbf u, \\dot{\\textbf u}, \\ddot{\\textbf u}) \\,\\le\\, \\textbf g_{p,ub} \\\\\n\\end{align}\n\nThe ability to utilize control derivatives in the equations of motion provides some unique capabilities, namely the ability to\neasily solve problems using _differential inclusion_, which will be demonstrated in the examples.\n\nThe solution techniques used by the Phase classes in Dymos generally fall into two categories:\nimplicit and explicit phases. They differ in underlying details but both allow for the same\ngeneral form of the optimal control problem.\n\n[Segments](segments.ipynb)\n\n[Variables](variables.ipynb)\n\n[Constraints](constraints.ipynb)\n\n[Objective](objective.ipynb)\n\n[Timeseries Outputs](timeseries.ipynb)\n", "meta": {"hexsha": "6b0626f41b11c66c9bc6ca44d8134a047616b343", "size": 5686, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/features/phases/phases.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/features/phases/phases.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/features/phases/phases.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": 41.503649635, "max_line_length": 205, "alphanum_fraction": 0.584593739, "converted": true, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.12085324198975819, "lm_q1q2_score": 0.05665486704219182}} {"text": "\n# Logbook\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.run import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\n\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 463 ('figure.dpi : 100 ## figure dots per inch')\n\n\n## Nomenclature\n\nHere is a cell link: [Logbook](#logbook)\n\n## 2020-11-26\n* Loaded the KVLCC2 roll decay tests: [01.1_select_suitable_MDL_test_KVLCC2](01.1_select_suitable_MDL_test_KVLCC2.ipynb)\n\n## 2020-11-27\n* Selected two roll decays at 0 knots (the other one hade different frequency) [01.2_select_suitable_MDL_test_KLVCC2](01.2_select_suitable_MDL_test_KLVCC2.ipynb). Also found that the \"integration\" gave much better result than the \"derivation\". But \"derivation\" can be used as initial guess to the \"integration\". \n\n## 2020-11-30\n* Got different result with SI method here: [02.1_ikeda_Be_assumption](02.1_ikeda_Be_assumption.ipynb#different) (Which is a bit strange)\n* Got some progress in understanding the $B_e$ : [02.2_ikeda_Be_assumption](02.2_ikeda_Be_assumption.ipynb#different)\n\n## 2020-12-01\n* The relation between $\\zeta$ and damping $B$ can be expressed as $\\zeta = B_1/(2*omega0*A_44)$ wich seems to work for linear model: [02.2_ikeda_Be_assumption](02.2_ikeda_Be_assumption.ipynb#zeta-B)\n * The equivalent linearized damping is an approximation only according to the same notebook.\n * Energy transfer between potential, kinetic and loss damping: [02.2_ikeda_Be_assumption](02.2_ikeda_Be_assumption.ipynb#energy)\n * The $B_e$ can be calculated so that the lossed energy from a linear model is the same as a higher order model: [02.2_ikeda_Be_assumption](02.2_ikeda_Be_assumption.ipynb#B_e). This again shows that the $B_e$ according to is an approximation only.\n\n## 2020-12-02\n* Managed to run ScoreII for the KVLCC2: [04.1_KVLCC2_Ikeda_method](04.1_KVLCC2_Ikeda_method.ipynb)\n * Needed to reduce the KXX to get correct natural frequency (This should be investigated).\n * Got some agreement for heave compared to report: *RE40178362-01-00-A Trafikverket.pdf*\n * The eddy component is dominating (and probably wrong): [eddy](04.1_KVLCC2_Ikeda_method.ipynb#eddy)\n * The mid section coefficient exceeds (CMID) the limits: [limits_kawahara](04.1_KVLCC2_Ikeda_method.ipynb#limits_kawahara)\n* **Conclusions**: \n * The KVLCC2 at zero speed has very low wave damping and is therefore not a suitable candidate for this study!\n * Any other of the ships with sections and higher wave damping could be selected?\n\n\n## 2020-12-04\n* Got some inspiration from Francesco to use the anlytical solution to calculate $B_e$ : [02.3_ikeda_Be_assumption](02.3_ikeda_Be_assumption.ipynb)\n * It gave significantly better linear approximation than Himeno.\n * **BUT!** If the $B_2$ is divided by **2** in the Himeno $B_e$ equation they are very similar. Where does this **2** come from?\n\n### Meeting with Martin K\n* 20189033-dsec-multi-mission-vessel* \"back track error\" Martin K uploaded these files.\n* Low wave damping at 0 speed for KVLCC2 is not necesarrilly a bad thing (let's look at speed also)\n\n## 2020-12-07\n* Analyzed the KVLCC2 at speed: [01.3_select_suitable_MDL_test_KLVCC2_speed](01.3_select_suitable_MDL_test_KLVCC2_speed.ipynb)\n * The damping is now higher\n * The ship got a yaw rate at the end of test. The OffsetTransformer was used again and it seems to have a great positive impact on the performance of the *Derivation\" approach.\n \n* Calculated Ikeda and SI at speed: [04.2_KVLCC2_Ikeda_method_speed](04.2_KVLCC2_Ikeda_method_speed.ipynb)\n * SI wave damping goes \"bananas\"\n * Ikeda is much better\n\n## 2020-12-08\n* Made comparison between model test and Ikeda (with and without speed) :[04.3_KVLCC2_Ikedas_model_tests](04.3_KVLCC2_Ikedas_model_tests.ipynb).\n * Got very good agreement for both speeds!\n * Got even better result when looking at the time simulations with the predicted damping.\n\n## 2020-12-15\n* Found good agreement between Python and Motions in the prevous project repo: *20189033-dsec-multi-mission-vessel*. Motions seem to incorporate the viscous damping coefficients in a correct way now.\n\n### Meeting with Wengang, Jonas and Martin K\n...\n\n## 2020-12-16\n* Based on the results in Figure 4.5 in Francescos Lic. Paper I started to think about what will happen with the viscous damping at frequencies off the natural frequency (where the PIT damping is defined). I made a variation of frequency with Ikeda suggesting quite large differences in the viscous damping at off frequencies: [04.4_KVLCC2_Ikedas_model_frequency](04.4_KVLCC2_Ikedas_model_frequency.ipynb#frequency).\n\n## 2020-12-15\n* Realized that roll decay tests can actually capture damping at other roll frequencies than the natural frequency. If $B_e$ is used one can transfer between amplitudes but also frequency! [04.4_KVLCC2_Ikedas_model_frequency](04.4_KVLCC2_Ikedas_model_frequency.ipynb#himeno)\n\n## 2020-12-21\n* Analyzed the first result from Motions (inviscid) : [06.1_KVLCC2_motions](06.1_KVLCC2_motions.ipynb)\n * Motions result have much higher $B_W$ than ScoresII : [plot](06.1_KVLCC2_motions.ipynb#damping)\n * Bilge radius=2.4 m gives huge B_E! : [plot](06.1_KVLCC2_motions.ipynb#damping)\n * B_E definatelly need to be examined!\n \n\n## 2020-12-22\n* Testing the barge formula for eddy damping :\n$$ B_{e}=\\left(\\frac{2}{\\pi}\\right) \\rho L d^{4}\\left(H_{0}^{2}+1-\\frac{O G}{d}\\right)\\left(H_{0}^{2}+\\left(1-\\frac{O G}{d}\\right)^{2}\\right) R_{0} \\omega $$\n* This one did not work the $B_E$ is far to large: [07.1_ikeda_barge](07.1_ikeda_barge.ipynb)\n* Looked at the original Ikeda model test to obtain eddy damping. The current results seem to be wrong to a factor of about 2: [08.1_ikeda_eddy](08.1_ikeda_eddy.ipynb)\n\n## 2020-12-29\n* The section area coefficient goes \"balistic\" when sigma exceeds 0.995: [sigma](06.1_KVLCC2_motions.ipynb#sigma). Perhaps limiting the sigma? But to what value? The choice has a major impact on the result, and will be very prone to bias.\nJust a small change of R and sigma will however have a huge impact on the eddy damping according to Ikedas' experiements:\n\n\n\n\n## 2021-01-04\n* Limited the $C_mid$ to 0.99 in accordance to the Kawahara limits.\n* Made a more clean version of the sigma variation: [08.2_ikeda_eddy_sigma](08.2_ikeda_eddy_sigma.ipynb) \n* Also made a combined model: [plot](06.1_KVLCC2_motions.ipynb#combined_damping)\n\n## 2021-01-05\n* renamed the *combined model* to *hybrid model*\n* Rerun the hybrid model for the results at speed and got better results than at 0 knots: [plot](06.1_KVLCC2_motions.ipynb#combined_damping)\n* Also looked at the impact of the damping in [simulation](06.1_KVLCC2_motions.ipynb#simulation)\n\n\n## 2021-01-07\n* implemented so that multiple ikeda implementations can be evaluated [here](06.1_KVLCC2_motions.ipynb#combined_damping)\n* mid section coefficient most often exceeds 0.99 [plot](09.1_sigma_statistics.ipynb)\n* Made a [speed plot](06.1_KVLCC2_motions.ipynb#speed).\n\n## 2021-01-08\n* Made a comparison with many tests and Ikeda (with ScoresII wave damping) [ikeda many compare](10.2_ikeda_many.ipynb#compare).\n* The Ikeda underpredicts the damping at 0 speed: [10.2_ikeda_many](10.2_ikeda_many.ipynb#zero_speed).\n* removing the sigma limit increased the accuracy even for the one ship without bilge keel, which is surpricing.\n* As seen for the KVLCC2 the damping at zero speed is underpredicted.\n* Influence with without bilge keel: [10.2_ikeda_many](10.2_ikeda_many.ipynb#speed).\n* Looked for other ships without bilge keels and many speeds: [4_select_suitable_MDL_test](01.4_select_suitable_MDL_test.ipynb)\n * The only available are ships with very strange shapes, skegs and brackets etc. Which are not so relevant to use.\n * Found one that has 2 speeds and very rectangular midsections, the ship is like a box.\n \n\n## 2021-01-12\n* Loaded the exact geometry: [11.1_KVLCC2_geometry](11.1_KVLCC2_geometry.ipynb)\n* Changed to exact bilge radius [06.1_KVLCC2_motions](06.1_KVLCC2_motions.ipynb)\n\n## 2021-01-15\n* Failed to reproduce the results from Ikeda's cylinder experiements according to the equations availab\n* Fitted a [Descision tree](08.3_ikeda_eddy_regression.ipynb#tree) to predict the C_r coefficient to reproduce Ikeda's experiments.\n* Applied this new model to the cross sections of the KVLCC2 wish gave a significant improvement in the 0 speed results: [06.1_KVLCC2_motions](06.1_KVLCC2_motions.ipynb#combined_damping)\n* Is this a good day for Machine Learning?! :D\n\n\n## 2021-01-18\n* The damping from various Motions run differ quite a bit: [motions_sensitivity](06.1_KVLCC2_motions.ipynb#combined_damping#motions_sensitivity)\n\n## 2021-01-19\n* Made a notebook that further confirmes that the results from Motions are in fact quite different with respect to damping [06.2_KVLCC2_motions_interaction_problem](06.2_KVLCC2_motions_interaction_problem.ipynb).\n* The instable behaviour in Motions is most likely due to memory effects, where waves generated from previous roll oscillation is overtaking the ship. This is hapening after about 35 seconds. There is a theory that the reason that this is not visible in the MDL model tests is because the motions decay much faster under the presens of viscous damping. This means that the overtaking waves from previous oscillations are much smaller. New simulations in Motions including the viscous damping coefficients will be conducted to confirm this theory.\n* Calculated the viscous damping at speed as input to Motions [06.1_KVLCC2_motions.ipynb](06.1_KVLCC2_motions.ipynb#viscous-damping).\n* The memory effect seem to be somewhat integrated over time so that the solutions diverges after about 35 seconds. This means that the results after this point are quite unrealiable, where is also where the small amplitudes are found. It was therefore decided to conduct a roll decay simulation in Motion starting at a much smaller (5 degrees) initial roll angle.\n\n## 2021-01-22\n* Looked at the Motions + Ikeda visc. simulations which shows very good agreement with the MDL tests: [12.1_motions_ikeda](12.1_motions_ikeda.ipynb)\n* There is still some instable damping results for smaller amplitudes, that seem to start after about 35 seconds. So there seem to be something happning at that point in time.\n\n## 2021-01-27\n* Created a notebook that generates roll decay models for all motions results: [13.1_models_motions](13.1_models_motions.ipynb)\n\n## 2021-03-29\nSuspecting the the speed dependancy for eddy damping in ikeda's method is quite arbitrary. Investigated this here: [15.1_B_E_speed_db_analysis.ipynb](15.1_B_E_speed_db_analysis.ipynb)\n\n## References\n
    \n\n\n```python\nimport re\nbody = r'model (see Section \\ref{eq_linear}).'\nre.search(r'Section \\\\ref\\{eq_([^}]+)', body).group(1)\n```\n\n\n\n\n 'linear'\n\n\n\n\n```python\nbody = \"\"\"fskfgkfdjgkjf\n\nkjkjk\n\"\"\"\n\nprint(body)\n```\n\n fskfgkfdjgkjf\n \n kjkjk\n \n\n\n\n```python\nbody.replace('\\n\\n','\\n\\n\\quad')\n```\n\n\n\n\n 'fskfgkfdjgkjf\\n\\n\\\\quadkjkjk\\n'\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "499e46414f35e3b5b3be1ce268ea3b26d39f58da", "size": 21030, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/logbook.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "notebooks/logbook.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "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": "notebooks/logbook.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 38.8007380074, "max_line_length": 555, "alphanum_fraction": 0.6438421303, "converted": true, "num_tokens": 3619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.12085322774082716, "lm_q1q2_score": 0.0566548603624265}} {"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# Independence; joint/marginal/conditional probability; covariance and correlation\n\n## Statistical independence\n\nTwo random variables $X$ and $Y$ are said to be *independent* when their joint probability is equal to the product of the probabilities of each:\n\n$$\nP(X, Y) = P(X) P(Y) \\ . \n$$\n\nThis means, in terms of conditional probabilities,\n\n$$\nP(X | Y) = \\frac{P(X, Y)}{P(Y)} = \\frac{P(X)P(Y)}{P(Y)} = P(X) \\ ,\n$$\n\nthat is, the probability of $X$ occurring is not affected by the occurring of $Y$. This is typically how independence is defined, in word terms: the occurrence of one event does not influence the occurrence of the other. \n\n### IID variables\n\nI.I.D. stands for *independent* and *identically distributed*, it's a shortening used all over in statistics. IID variables are [independent](independence.ipynb) but also distributed in the same way. \n\nThe concept is the basic assumptions of many foundational results in statistics.\n\n## The joint probability\n\nThe joint probability of one or more events is the probability that they happen together. If $X$, $Y$, $Z$, ... are the random variables, their joint probability is written as\n\n$$\nP(X, Y, Z, \\ldots)\n$$\n\nor as \n\n$$\nP(X \\cap Y \\cap Z \\ldots)\n$$\n\n### The case of independent variables\n\nIf the variables are independent, their joint probability reduces to the product of their probabilities: $P(X_1, X_2, \\ldots, X_n) = \\Pi_{i=1}^n P(X_i)$. \n\n## The marginal probability\n\n\n
    \n \n
    Image by IkamusumeFan (Own work) [CC BY-SA 3.0], via Wikimedia Commons
    \n
    \n\n\nIf we have the joint probability of two or more random variables, the marginal probability of each is the probability related to that variable and to its own space of events; it expresses the probability of the variable when the value of the other one is not known. It calculated by summing the joint probability over the space of events of the other variable. More specifically, given $P(X, Y) = P(X=x, Y=y)$,\n\n$$\nP(X=x) = \\sum_y P(X=x, Y=y) \\ .\n$$\n\nThe illustration here shows points extracted from a joint probability (the black dots) and the marginal probabilities as well.\n\n## The conditional probability\n\nThe conditional probability expresses the probability that an event occurrs given that another one has occurred. With $Y$ being the (variable related to the) event that has occurred and $X$ the (variable related to the) event whose probability of occurrence we are interested in, it is defined as\n\n$$\nP(X | Y) = \\frac{P(X, Y)}{P(Y)} \\ ,\n$$\n\nthat is, as the ratio of the joint probability of the two to the probability of $Y$. \n\nIn the case of more than two variables we can write the joint probability as\n\n$$\nP(X_1, X_2, \\ldots, X_n) = P(X_1 | X_2, \\ldots, X_n) P(X_2, \\ldots, X_n)\n$$\n\nand can repeat the process to isolate them one by one, obtaining\n\n$$\nP(\\cap_{i=1}^n X_i) = \\Pi_{i=1}^n P(X_i | \\cap_{j=i+1}^{n} X_j) \\ ,\n$$\n\nwhich is known as the [chain rule](https://en.wikipedia.org/wiki/Chain_rule_(probability). \n\n### In the case of independence\n\nThis is easy, we would have\n\n$$\nP(X | Y) = \\frac{P(X, Y)}{P(Y)} = \\frac{P(X) P(Y)}{P(Y)} = P(X) \\ ,\n$$\n\nwhich indicates what is suggested by the definition itself: independent variables mean that the happening of one does not influence the happening of the other. \n\n## Covariance and correlation\n\n### Covariance\n\nGiven the random variables $X$ and $Y$ with respective means $\\mu_x$ and $\\mu_y$, their *covariance* is defined as\n\n$$\n\\text{cov}(X, Y) = \\mathbb{E}[(X - \\mu_x)((Y - \\mu_y)]\n$$\n\nIt is a measure of how jointly the two variables vary: a positive covariance means that when $X$ grows, $Y$ grows as well and a negative covariance means that when $X$ grows, $Y$ decreases. \n \n### Correlation\n\nThe word *correlation* is measured by a *correlation coefficient* which exists in several definitions depending on what is exactly measured; it is always a sort of normalised covariance. \nThe correspondent of the covariance itself is Pearson's definition, which defines the correlation coefficient as the covariance normalised by the product of the standard deviations of the two variables:\n\n$$\n\\rho_{xy} = \\frac{\\text{cov}(x, y)}{\\sigma_x \\sigma_y} = \\frac{\\mathbb{E}[(x - \\mu_x)(y - \\mu_y)]}{\\sigma_x \\sigma_y} \\ ,\n$$\n\nand it can also be written as \n\n$$\n\\begin{align}\n \\rho_{xy} &= \\frac{\\mathbb{E}[(xy - x \\mu_y - \\mu_x y + \\mu_x \\mu_y)]}{\\sigma_x \\sigma_y} \\\\\n &= \\frac{\\mathbb{E}[xy] - \\mu_x\\mu_y - \\mu_y\\mu_x + \\mu_x\\mu_y}{\\sigma_x \\sigma_y} \\\\\n &= \\frac{\\mathbb{E}[xy] - \\mu_x\\mu_y}{\\sigma_x \\sigma_y} \\ .\n\\end{align}\t\t\t\n$$\n\nThe correlation coefficient has these properties:\n\n* $-1 \\leq \\rho_{xy} \\leq 1$\n* It is symmetric: $\\rho_{xy} = \\rho_{yx}$\n* If the variables are independent, then $\\rho_{xy} = 0$ (but the reverse is not true)\n\n### Independence and correlation\n\nLet's expand on the last point there really. We said that if two random variables are independent, then the correlation coefficient is zero. This is easy to prove as it follows directly from the definition above (also bear in mind [Fubini's theorem](https://en.wikipedia.org/wiki/Fubini's_theorem)):\n\n$$\n\\mathbb{E}[XY] = \\int_{\\Omega_X } \\int_{\\Omega_Y} \\text{d} x \\text{d} y \\ xy P(x,y) = \\int_{\\Omega_X } \\int_{\\Omega_Y} \\text{d} x \\text{d} y \\ xy P(x) P(y) = \\mu_x \\mu_y \\ .\n$$\n\nThe reverse is not true. Look at this amazing Q&A on [Cross Validated](https://stats.stackexchange.com/questions/12842/covariance-and-independence#) for a well explained counter-example.\n\n### Correlation and the relation between variables\n\n\n\nCorrelation says \"how much\" it happens that when $x$ grows, $y$ grows as well. It is not a measure of the slope of the linear relation between $x$ and $y$. This is greatly illustrated in the figure above (from Wikipedia's [page](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient)), which reports sets of data points with $x$ and $y$ and their correlation coefficient. \n\nIn the center figure, because the variance of $y$ is 0, then the correlation is undefined. In the bottom row, the relation between variables is not linear, the correlation does not capture that.\n\n\n```python\n\n```\n", "meta": {"hexsha": "7f690bd21821b9b04c3d46fedb476ca4a302e76e", "size": 12211, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "prob-stats-data-analysis/foundational/independence-joint-marg-conditional-covariance.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": "prob-stats-data-analysis/foundational/independence-joint-marg-conditional-covariance.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": "prob-stats-data-analysis/foundational/independence-joint-marg-conditional-covariance.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": 37.6882716049, "max_line_length": 419, "alphanum_fraction": 0.5410695275, "converted": true, "num_tokens": 2339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.2200070946316962, "lm_q1q2_score": 0.05650486023364084}} {"text": "```python\n#we may need some code in the ../python directory and/or matplotlib styles\nimport sys\nimport os\nsys.path.append('../python/')\n\n#set up matplotlib\nos.environ['MPLCONFIGDIR'] = '../mplstyles'\nprint(os.environ['MPLCONFIGDIR'])\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n#got smarter about the mpl config: see mplstyles/ directory\nplt.style.use('standard')\nprint(mpl.__version__) \nprint(mpl.get_configdir())\n\n\n#fonts\n# Set the font dictionaries (for plot title and axis titles)\ntitle_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',\n 'verticalalignment':'bottom'} # Bottom vertical alignment for more space\naxis_font = {'fontname':'Arial', 'size':'32'}\nlegend_font = {'fontname':'Arial', 'size':'22'}\n\n#fonts global settings\nmpl.rc('font',family=legend_font['fontname'])\n\n\n#set up numpy\nimport numpy as np\n```\n\n ../mplstyles\n 3.0.3\n /home/phys/villaa/analysis/misc/nrFano_Constraint/mplstyles\n\n\n# Multiple Scatters for Edelweiss Detector \n\nIn a real detector when calculating the nuclear recoil band from $^{252}$Cf calibration data, we expect there to be multiple-scattering of neutrons. This effect will generally widen the ionization yield distribution of a sample. In that case, it is generally difficult to tell the difference between a widening of the yield distribution resulting from an effective NR Fano factor (the effect we're interested in) and from simply multiple scatters. In general the latter, in the Edelweiss study that we are focusing on, is not large enough to explain the observed ionization yield discrepancies. \n\nTo show this we have simulated neutron-scattering events in the detector of the same size as the Edelweiss detectors (cylindrial with 70 mm diameter and 20 mm thickness). The input spectrum is approximately that which will result from a $^{252}$Cf source. \n\nThe data set comes from a simulation (`Geant4`) with a $^{252}$Cf source and a large amount of local (polyethylene) shielding. This means that the spectrum is a good approximation to one that would be found in a standard shielded low-background apparatus. In particular, one would expect that this is an envrionment which produces a conservative (near maximal) amount of widening because lower-energy neutrons are generally more likely to multiple-scatter. If the detector were exposed to a neutron $^{252}$Cf source with _less_ shielding around the result would almost certainly be that less broadening in the ionization yield distributions would be observed.\n\nThe data is stored in an `hdf5` file with the following elements that describe the data set for nuclear recoils. \n\nkey name|NumPy structure|Description \n:-|:-|:-\nnr_energies|double array with shape (totalevents,17)|energies of each scatter, up to 17 scatters\nnr_hits|integer array with shape (totalevents,)|number of scatters in detector\n\n\n\n```python\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport h5py\nf = h5py.File(\"data/k100_252Cf_shield_Edw_NRs_large.h5\",\"r\")\n\n\nfor i in f['nr_Fano']:\n print(i)\n```\n\n nr_energies\n nr_hits\n\n\n\n```python\nprint(np.shape(f['nr_Fano/nr_energies']))\nprint(np.shape(f['nr_Fano/nr_hits']))\n\n#get the data variables\nnr_energies = np.asarray(f['nr_Fano/nr_energies'])\nnr_hits = np.asarray(f['nr_Fano/nr_hits'])\n\nnrsum = np.sum(nr_energies*1000,1)\nprint(np.shape(nrsum))\nprint(np.shape(nrsum[nrsum>5]))\n```\n\n (347463, 24)\n (347463,)\n (347463,)\n (88110,)\n\n\nThe first and simplest thing we can do with the data is to simply plot the recoil spectrum. This can give us a rather good starting point for understanding the \"correct\" true-$E_r$ distribution as has been used in the previous notes: `ERNR_bands.ipynb` and `QEr_2D_joint.ipynb`. \n\nIn particular we've used the model:\n\n\\begin{equation}\nP(E_r) = \\frac{1}{\\alpha}e^{-\\alpha E_r},\n\\end{equation}\n\nand it has been argued that a good choice for $\\alpha$ would be around 1/100 keV$^{-1}$. \n\nBelow, I sum across all of the hits in each event to come up with a distribution in true recoil energy for this $^{252}$Cf simulation. \n\n\n```python\n#make some histograms\n\nxmax = 100\nn_ss,nx_ss = np.histogram(np.sum(nr_energies[nr_hits==1,:],1)*1000,100,range=(0,xmax)) #energies in MeV\nn_ms,nx_ms = np.histogram(np.sum(nr_energies[nr_hits>1,:],1)*1000,100,range=(0,xmax))\n\n\nxc = (nx_ss[:-1] + nx_ss[1:]) / 2\n```\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nymin=0.1\nymax=1e4\n\nX = np.arange(0,xmax,0.1)\nalpha=1/100.0\nPEr = lambda Er: (1/alpha)*np.exp(-alpha*Er)\n\n\nax1.step(xc,n_ms, where='mid',color='r', linestyle='-', \\\n label='multiple scatters', linewidth=2)\nax1.step(xc,n_ss, where='mid',color='k', linestyle='-', \\\n label='single scatters', linewidth=2)\nax1.plot(X,(500*alpha)*PEr(X),color='orange',linestyle='--',linewidth=3,label='c$_0\\cdot$P($E_r$) model')\n\n\n\n\n#tlabel = 'Thresh. {0} eV$_{{\\mathrm{{ee}}}}$'.format(18)\n#ax1.axvline(thresh, color='k', linestyle='--', lw=2, alpha=0.8,label=tlabel)\n#erange_x = np.arange(thresh-sigthr, thresh+sigthr, 0.01)\n#ax1.fill_between(erange_x, ymin, ymax, facecolor='r', alpha=0.3)\n\nax1.set_yscale('log')\nax1.set_xlim(0, xmax) #in pairs\nax1.set_ylim(0.1,1e5)\nax1.set_xlabel('deposited energy [keV]',**axis_font)\nax1.set_ylabel('counts',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\n#plt.savefig('figures/figure.png')\nplt.show()\n```\n\nThe model obviously does not fit the simulated distribution well at all. The simulated distribution _does not_ look like a pure decaying exponential. below about 5 keV the distribution (for both singles and multiples samples) seems to have a much faster decay when the recoil energy is increased. \n\nAbove 5 keV, however, the distribution predicted by the simulation does appear to be close to a single exponential, but not with a decay constant of 1/100 keV$^{-1}$. Below we try a fit to discover a closer value for the decay constant that is reasonable. \n\n\n```python\n#first compute the errors on each bin with just the counts\nerr_ss = np.sqrt(n_ss)\nerr_ms = np.sqrt(n_ms)\n\n#now construct a likelihood function (really just a chisquare)\ndef lnlike(theta, x, y, yerr):\n a,b = theta\n model = a*(b)*np.exp(-(1/b)*x)\n inv_sigma2 = 1.0/(yerr**2)\n return -0.5*(np.sum((y-model)**2*inv_sigma2))\n\nimport scipy.optimize as op\nnll = lambda *args: -2*lnlike(*args)\n\nbounds = op.Bounds([0.0,1e-5],[1000.0,1000])\nresult = op.minimize(nll, [0.1,(100.0)], args=(xc[xc>5], n_ss[xc>5], err_ss[xc>5]),bounds=bounds)\nas_ml,bs_ml = result['x']\n\nprint(result)\n\nresult = op.minimize(nll, [0.1,(100.0)], args=(xc[xc>5], n_ms[xc>5], err_ms[xc>5]),bounds=bounds)\nams_ml,bms_ml = result['x']\n\nprint(result)\n```\n\n fun: 1804.5914055291069\n hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>\n jac: array([-9.09494702e-05, -7.95807864e-04])\n message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n nfev: 114\n nit: 24\n status: 0\n success: True\n x: array([118.52005196, 19.36061553])\n fun: 1007.2614234923533\n hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>\n jac: array([2.27373675e-05, 2.27373675e-05])\n message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n nfev: 90\n nit: 24\n status: 0\n success: True\n x: array([77.65293398, 27.05333297])\n\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nymin=0.1\nymax=1e4\n\n\nPEr_s_ml = lambda Er: (as_ml*bs_ml)*np.exp(-(1/bs_ml)*Er)\nPEr_ms_ml = lambda Er: (ams_ml*bms_ml)*np.exp(-(1/bms_ml)*Er)\n\n\nax1.errorbar(xc,n_ms, yerr=err_ms,color='r', marker='o', \\\n markersize=4,linestyle='none',label='multiple scatters', linewidth=2)\nax1.errorbar(xc,n_ss, yerr=err_ss,color='k', marker='o', \\\n markersize=4,linestyle='none',label='single scatters', linewidth=2)\n#ax1.step(xc,n_ss, where='mid',color='k', linestyle='-', \\\n# label='single scatters', linewidth=2)\nax1.plot(X,PEr_s_ml(X),color='orange',linestyle='--',linewidth=3,label='ML fit model (singles)')\nax1.plot(X,PEr_ms_ml(X),color='steelblue',linestyle='--',linewidth=3,label='ML fit model (multiples)')\n\n\n\n\n#tlabel = 'Thresh. {0} eV$_{{\\mathrm{{ee}}}}$'.format(18)\nax1.axvline(5, color='k', linestyle='--', lw=2, alpha=0.8,label='fit threshold')\n#erange_x = np.arange(thresh-sigthr, thresh+sigthr, 0.01)\n#ax1.fill_between(erange_x, ymin, ymax, facecolor='r', alpha=0.3)\n\nax1.set_yscale('log')\nax1.set_xlim(0, xmax) #in pairs\nax1.set_ylim(0.1,1e5)\nax1.set_xlabel('deposited energy [keV]',**axis_font)\nax1.set_ylabel('counts',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\nplt.savefig('figures/ms_spectrum_fit.png')\nplt.show()\n```\n\nFrom the fits above the single-scatter sample has $\\alpha$ closer to 1/18 keV$^{-1}$ and the multiple-scatter sample has a value near 1/25 keV$^{-1}$. It is also clear that both samples will fit better to a function that is not a single exponential. It may be true that a \"broken\" exponential, where the decay parameter changes around 50 keV will work better. \n\nSince we don't have a need for that kind of precision here we simply recognize that when the singles and the multipe-scatter samples are combined the distribution will be dominated by single scatters below around 40 keV, and the single and multiple scatters could plausibly have the same shape above 40 or 50 keV. Therefore we should chose the best-fitting model for the singles sample, and use $\\alpha$=1/18 keV$^{-1}$ where precision in the recoil distribution might be important. \n\n## Modeling the Ionization Yield of Simulated Data\n\nThe `Geant4` simulation we executed does not include the detailed physics of the detector (sometimes called _detector_ Monte Carlo in the SuperCDMS collaboration). Therefore, we must use the individual energy deposits in each particle event (called _hits_) to model the ionization yield, Q, and measured recoil energy, $\\tilde{E}_r$. \n\nIn addition to the ionization yield modeling, we will also include modeling of the resolution of the ionization and heat readout, similar to the GGA3 detector of Edelweiss. \n\nThe basic procedure is:\n\n1. calculate the average electron-equivalent energy for every individual hit (scatter) in every individual event\n2. calculate the average number of e/h pairs for each hit using the electron-equivalent energy\n3. fluctuate the number of e/h pairs based on the variance in the number $\\sigma_N = \\sqrt{F\\bar{N}}$\n4. calculate the heat energy for each hit using the number of e/h pairs calculated above (recoil energy plus luke)\n5. calculate the ionization energy for each hit using $\\epsilon N$ \n6. sum the electron-equivalent energy over all hits in an event to get $E_I$, the total ionization energy\n7. sum the heat energy over all hits in an event to get $E_H$, the total heat energy\n8. add a random amount distributed like $N(0,\\sigma_I(E_I))$ to the ionization energy\n9. add a random amount distributed like $N(0,\\sigma_H(E_H))$ to the total phonon energy\n10. calculate the measured recoil energy for each event as $\\tilde{E}_r = (1+(V/\\epsilon))E_H - (V/\\epsilon)E_I$\n11. calculate the ionization yield for each event like $Q = E_I/\\tilde{E}_r$\n\n\n\n```python\n#constants\nV=4.0 #volts\neps = 3.0/1000 #keV per pair, I usually use 3.3 for the numerator, but Edw. uses 3.\nFWHM_to_SIG = 1 / (2*np.sqrt(2*np.log(2)))\n\n#yield models\na=0.16\nb=0.18\nQbar = lambda Er: a*Er**b\n```\n\n\n```python\n#start getting the resolutions\nimport EdwRes as er\n\naH_sim=0.035\nheatRes_GGA3 = er.get_heatRes_func(0.4, 2.7,aH_sim*FWHM_to_SIG)\n#heatRes_GGA3 = er.get_heatRes_func(0.4, 2.7)\n\nsigI_GGA3 = er.get_ionRes_func(1.3, 1.5, 3.1)\n\nsigh_GGA3v = np.vectorize(heatRes_GGA3)\nsigi_GGA3v = np.vectorize(sigI_GGA3)\n```\n\n\n```python\n#include a nominal Fano factor\nF=0.0 #for NRs the factor is probably much higher than this\n\nEnr = nr_energies*1000 #initial energies are in MeV\nEnr_ss = nr_energies[nr_hits==1]*1000 #initial energies are in MeV\n\n#step 1\nEIhit_av = Qbar(Enr)*Enr\nEIhit_av_ss = Qbar(Enr_ss)*Enr_ss\n\n#step 2\nNhit_av = EIhit_av/eps\nNhit_av_ss = EIhit_av_ss/eps\n\n#step 3\nNhit = np.around(np.random.normal(Nhit_av,np.sqrt(F*Nhit_av))).astype(np.float)\nNhit_ss = np.around(np.random.normal(Nhit_av_ss,np.sqrt(F*Nhit_av_ss))).astype(np.float)\n\n#step 4\nEHhit = (Enr + Nhit*V/1000.0)/(1+(V/(1000*eps)))\nEHhit_ss = (Enr_ss + Nhit_ss*V/1000.0)/(1+(V/(1000*eps)))\n\n#step 5\nEIhit = eps*Nhit\nEIhit_ss = eps*Nhit_ss\n\n#step 6\nEI = np.sum(EIhit,1)\nEI_ss = np.sum(EIhit_ss,1)\n\n#step 7\nEH = np.sum(EHhit,1)\nEH_ss = np.sum(EHhit_ss,1)\n\n#step 8\nEI = EI + np.random.normal(0.0,sigi_GGA3v(EI))\nEI_ss = EI_ss + np.random.normal(0.0,sigi_GGA3v(EI_ss))\n\n#step 9\nEH = EH + np.random.normal(0.0,sigh_GGA3v(EH))\nEH_ss = EH_ss + np.random.normal(0.0,sigh_GGA3v(EH_ss))\n\n#step 10\nErnr = (1+(V/(1000*eps)))*EH - (V/(1000*eps))*EI\nErnr_ss = (1+(V/(1000*eps)))*EH_ss - (V/(1000*eps))*EI_ss\n\n#step 11\nQ = EI/Ernr\nQ_ss = EI_ss/Ernr_ss\n\n```\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\n\nX = np.arange(0.1,150,0.1)\n#ax1.plot(Erer,Yer,'o',color='k', label='ER band',linewidth=2,markersize=3)\nax1.plot(Ernr,Q,'o',color='b', label='NR band',linewidth=2,markersize=3)\nax1.plot(Ernr_ss,Q_ss,'o',color='m', label='NR band (singles)',linewidth=2,markersize=3)\nax1.plot(X,Qbar(X),'k--',label='Sim Yield Model')\n\n#ax1.plot(X,ynr_muv(X),'r--',label='NR mu')\n#ax1.plot(X,ynr_muv(X)+3*ynr_sigv(X),'r-',label='NR 3$\\\\sigma$')\n#ax1.plot(X,ynr_muv(X)-3*ynr_sigv(X),'r-',label=None)\n\n#ax1.plot(X,yer_muv(X),color='orange',linestyle='--',label='ER mu')\n#ax1.plot(X,yer_muv(X)+3*yer_sigv(X),color='orange',linestyle='-',label='ER 3$\\\\sigma$')\n#ax1.plot(X,yer_muv(X)-3*yer_sigv(X),color='orange',linestyle='-',label=None)\n\n\n\n#ax1.axvline(t(t_test[idx]), color='k', linestyle='-', lw=2, alpha=0.8,label=None)\n\n\nymin = 0\nymax = 1.5\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('linear')\nax1.set_xlim(0, 150) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\n#plt.savefig('figures/figure.png')\nplt.show()\n```\n\nThe figure above shows the Q,$\\tilde{E}_r$ distribution for all recoils (blue) and for only single-scatters (magenta). It is clear that there is some broadening due to multiple-scattering. The broadening is rather modest compared to what was observed in Edelweiss [REF] but we seek to quantify it in this note, and devise a systematic correction for the width increase that Edelweiss has measured to the \"effective single-scatter width increase.\" It is this latter quantity that is directly related to the energy-dependent effective Fano factor for nulcear recoils. \n\n## Energy-Binned Yield Distribution Fitting\n\nBy using a set of bins in recoil-energy, $\\tilde{E}_r$, we can use the simulated data above to quantify the effect of multiple scattering on the yield distributions. \n\nIn order to emulate the points in the Edelweiss paper [REF], we construct energy bins the same as in the paper. \n\nenergy bin|interval (keV)\n:-|:-\n0|\\[5,10)\n1|\\[10,20)\n2|\\[20,30)\n3|\\[30,40)\n4|\\[40,50)\n5|\\[50,70)\n6|\\[70,150)\n\nIn the lowest bin we use a threshold of 5 keV because below that is not useful. As a matter of fact, the fits are only utilized in the 6 higher energy bins because we are primarily interested in behavior above 10 keV. \n\nFor each energy bin, we plot the ionization yield projection histogram and fit a Gaussian model to it to extract the approximate width (1$\\sigma$ interval) and the uncertainty on this width. \n\n\n```python\nimport pandas as pds\n\n#create a dataframe\nnr_df = pds.DataFrame(data={'yield':Q, 'energy':Ernr})\nnr_ss_df = pds.DataFrame(data={'yield':Q_ss, 'energy':Ernr_ss})\n\n#bin the data\nbins = [5, 10, 20, 30, 40, 50, 70,150]\nnr_df['binned'] = pds.cut(nr_df['energy'],bins)\nnr_ss_df['binned'] = pds.cut(nr_ss_df['energy'],bins)\n\n#print stats in each bin\ns = nr_df.groupby(pds.cut(nr_df['energy'], bins=bins)).size()\ns_ss = nr_ss_df.groupby(pds.cut(nr_ss_df['energy'], bins=bins)).size()\nprint (s)\nprint(s_ss)\n\n#create list of vectors for histogrammin'\nhist = nr_df.groupby(pds.cut(nr_df['energy'], bins=bins))['yield'].apply(list)\nhist_ss = nr_ss_df.groupby(pds.cut(nr_ss_df['energy'], bins=bins))['yield'].apply(list)\nprint(hist)\nprint(hist_ss)\n```\n\n energy\n (5, 10] 20232\n (10, 20] 22805\n (20, 30] 12878\n (30, 40] 8239\n (40, 50] 5771\n (50, 70] 7381\n (70, 150] 9417\n dtype: int64\n energy\n (5, 10] 10391\n (10, 20] 10641\n (20, 30] 5230\n (30, 40] 3159\n (40, 50] 2137\n (50, 70] 2640\n (70, 150] 3228\n dtype: int64\n energy\n (5, 10] [0.032690527079618836, 0.23429720527497516, 0....\n (10, 20] [0.32869057123164563, 0.31584577761695476, 0.1...\n (20, 30] [0.27196964228133685, 0.324003183745733, 0.253...\n (30, 40] [0.28293694373261996, 0.24788324864841876, 0.4...\n (40, 50] [0.3550569040235691, 0.31933476691524176, 0.26...\n (50, 70] [0.2533400358103817, 0.35606731973979855, 0.29...\n (70, 150] [0.309453460999562, 0.3515279849027079, 0.3838...\n Name: yield, dtype: object\n energy\n (5, 10] [0.32382904834277054, 0.12854667606222492, 0.1...\n (10, 20] [0.2254855220851931, 0.27774393956027016, 0.21...\n (20, 30] [0.2646375634413314, 0.26632555680817427, 0.24...\n (30, 40] [0.2467079869764424, 0.2827942404513602, 0.319...\n (40, 50] [0.2537359041975915, 0.3016920506411402, 0.304...\n (50, 70] [0.3525948658110235, 0.3560442666903634, 0.340...\n (70, 150] [0.38355080834905597, 0.36735398204604286, 0.3...\n Name: yield, dtype: object\n\n\n\n```python\n#make a lot of histograms\nqbins = np.linspace(0,0.6,40)\nxcq = (qbins[:-1] + qbins[1:]) / 2\n\nqhistos = np.zeros((np.shape(qbins)[0]-1,0))\nqhistos_ss = np.zeros((np.shape(qbins)[0]-1,0))\nqerrs = np.zeros((np.shape(qbins)[0]-1,0))\nqerrs_ss = np.zeros((np.shape(qbins)[0]-1,0))\n\nqamps = np.zeros((np.shape(bins)[0]-1,))\nqamps_ss = np.zeros((np.shape(bins)[0]-1,))\nqmus = np.zeros((np.shape(bins)[0]-1,))\nqmus_ss = np.zeros((np.shape(bins)[0]-1,))\nqsigs = np.zeros((np.shape(bins)[0]-1,))\nqsigs_ss = np.zeros((np.shape(bins)[0]-1,))\nqsigerrs = np.zeros((np.shape(bins)[0]-1,))\nqsigerrs_ss = np.zeros((np.shape(bins)[0]-1,))\n\n\nfor i,Qv in enumerate(hist):\n n,nx = np.histogram(Qv,bins=qbins)\n n = np.reshape(n,(np.shape(n)[0],1))\n qhistos = np.append(qhistos,n,axis=1)\n qerrs = np.append(qerrs,np.sqrt(n),axis=1)\n qerrs[qerrs==0]=1\n \nfor i,Qv in enumerate(hist_ss):\n n,nx = np.histogram(Qv,bins=qbins)\n n = np.reshape(n,(np.shape(n)[0],1))\n qhistos_ss = np.append(qhistos_ss,n,axis=1)\n qerrs_ss = np.append(qerrs_ss,np.sqrt(n),axis=1)\n qerrs_ss[qerrs_ss==0]=1\n\n \n#now construct a likelihood function (really just a chisquare)\ndef lnlikeg(theta, x, y, yerr):\n a,b,c = theta\n model = a*np.exp(-(x-b)**2/(2*c**2))\n inv_sigma2 = 1.0/(yerr**2)\n return -0.5*(np.sum((y-model)**2*inv_sigma2))\n\n\nnllg = lambda *args: -2*lnlikeg(*args)\n\n#also construct a residual function for use with lmfit\nimport lmfit as lmf\n\ndef residual(params, x, data, eps_data):\n amp = params['amp']\n mean = params['mean']\n sig = params['sig']\n\n\n model = amp * np.exp(-(x-mean)**2/(2*sig**2))\n\n return (data-model) / eps_data\n\n\nstartamps = [0.1,0.1,0.1,0.1,0.05,0.02,0.03]\nstartmus = [0.25,0.25,0.3,0.3,0.3,0.35,0.34]\nstartsigs = [0.1,0.1,0.05,0.05,0.05,0.05,0.03]\n\nfor i,h in enumerate(hist):\n print('fitting {}'.format(i))\n\n #do it with scipy optimize\n bounds = op.Bounds([0.0,0.001,1e-6],[100,1.0,1.0])\n qsum = np.sum(qhistos[:,i])\n result = op.minimize(nllg, [startamps[i],startmus[i],startsigs[i]], args=(xcq, qhistos[:,i]/qsum, qerrs[:,i]/qsum),bounds=bounds)\n qamps[i],qmus[i],qsigs[i] = result['x']\n print('SCIPY result--multiples')\n print(result['x'])\n qsum_ss = np.sum(qhistos_ss[:,i])\n result = op.minimize(nllg, [startamps[i],startmus[i],startsigs[i]], args=(xcq, qhistos_ss[:,i]/qsum_ss, qerrs_ss[:,i]/qsum_ss),bounds=bounds)\n qamps_ss[i],qmus_ss[i],qsigs_ss[i] = result['x']\n print('SCIPY result--singles')\n print(result['x'])\n \n #do it with lmfit\n params = lmf.Parameters()\n params.add('amp', value=startamps[i])\n params.add('mean', value=startmus[i])\n params.add('sig', value=startsigs[i])\n lmfout = lmf.minimize(residual, params, args=(xcq, qhistos[:,i]/qsum, qerrs[:,i]/qsum))\n #print(lmf.fit_report(lmfout))\n print('lmfit result--multiples')\n print(lmf.report_fit(lmfout.params))\n qamps[i] = lmfout.params['amp'].value\n qmus[i] = lmfout.params['mean'].value\n qsigs[i] = lmfout.params['sig'].value\n qsigerrs[i] = np.sqrt(lmfout.covar[2,2])\n\n params = lmf.Parameters()\n params.add('amp', value=startamps[i])\n params.add('mean', value=startmus[i])\n params.add('sig', value=startsigs[i])\n lmfout = lmf.minimize(residual, params, args=(xcq, qhistos_ss[:,i]/qsum_ss, qerrs_ss[:,i]/qsum_ss))\n #print(lmf.fit_report(lmfout))\n print('lmfit result--singles')\n print(lmf.report_fit(lmfout.params))\n qamps_ss[i] = lmfout.params['amp'].value\n qmus_ss[i] = lmfout.params['mean'].value\n qsigs_ss[i] = lmfout.params['sig'].value\n qsigerrs_ss[i] = np.sqrt(lmfout.covar[2,2])\n #print(lmfout.params['sig'])\n #print(lmfout.covar)\n #print(np.sqrt(lmfout.covar[2,2]))\n #print(np.sqrt(np.sum(lmfout.covar[2,:]**2)))\n\nprint(qsigs)\nprint(qsigerrs)\nprint(qsigs_ss)\nprint(qsigerrs_ss)\n```\n\n fitting 0\n SCIPY result--multiples\n [0.04314356 0.20437032 0.15839547]\n SCIPY result--singles\n [0.04323717 0.21415336 0.1556244 ]\n lmfit result--multiples\n [[Variables]]\n amp: 0.04314356 +/- 5.0858e-04 (1.18%) (init = 0.1)\n mean: 0.20437030 +/- 0.00214011 (1.05%) (init = 0.25)\n sig: 0.15839551 +/- 0.00188594 (1.19%) (init = 0.1)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.598\n C(mean, sig) = -0.550\n C(amp, mean) = 0.189\n None\n lmfit result--singles\n [[Variables]]\n amp: 0.04323717 +/- 5.3202e-04 (1.23%) (init = 0.1)\n mean: 0.21415337 +/- 0.00205321 (0.96%) (init = 0.25)\n sig: 0.15562439 +/- 0.00184253 (1.18%) (init = 0.1)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.610\n C(mean, sig) = -0.486\n C(amp, mean) = 0.174\n None\n fitting 1\n SCIPY result--multiples\n [0.07076694 0.24062624 0.08665687]\n SCIPY result--singles\n [0.07082904 0.25177584 0.08617589]\n lmfit result--multiples\n [[Variables]]\n amp: 0.07076691 +/- 8.8464e-04 (1.25%) (init = 0.1)\n mean: 0.24062624 +/- 8.7684e-04 (0.36%) (init = 0.25)\n sig: 0.08665691 +/- 6.7002e-04 (0.77%) (init = 0.1)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.603\n None\n lmfit result--singles\n [[Variables]]\n amp: 0.07082893 +/- 0.00127136 (1.79%) (init = 0.1)\n mean: 0.25177574 +/- 0.00124782 (0.50%) (init = 0.25)\n sig: 0.08617603 +/- 9.5268e-04 (1.11%) (init = 0.1)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.605\n None\n fitting 2\n SCIPY result--multiples\n [0.11382608 0.26698147 0.05384961]\n SCIPY result--singles\n [0.11949086 0.28175409 0.05110986]\n lmfit result--multiples\n [[Variables]]\n amp: 0.11382608 +/- 8.4617e-04 (0.74%) (init = 0.1)\n mean: 0.26698147 +/- 3.2711e-04 (0.12%) (init = 0.3)\n sig: 0.05384962 +/- 2.3092e-04 (0.43%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.577\n None\n lmfit result--singles\n [[Variables]]\n amp: 0.11949070 +/- 0.00177500 (1.49%) (init = 0.1)\n mean: 0.28175404 +/- 6.1182e-04 (0.22%) (init = 0.3)\n sig: 0.05110994 +/- 4.5226e-04 (0.88%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.594\n None\n fitting 3\n SCIPY result--multiples\n [0.14466671 0.28434765 0.04228082]\n SCIPY result--singles\n [0.16277935 0.29959319 0.03752698]\n lmfit result--multiples\n [[Variables]]\n amp: 0.14466668 +/- 0.00182481 (1.26%) (init = 0.1)\n mean: 0.28434766 +/- 4.4087e-04 (0.16%) (init = 0.3)\n sig: 0.04228083 +/- 3.0421e-04 (0.72%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.567\n None\n lmfit result--singles\n [[Variables]]\n amp: 0.16277936 +/- 0.00229383 (1.41%) (init = 0.1)\n mean: 0.29959319 +/- 4.3576e-04 (0.15%) (init = 0.3)\n sig: 0.03752698 +/- 3.0170e-04 (0.80%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.570\n None\n fitting 4\n SCIPY result--multiples\n [0.16490979 0.29791776 0.03695967]\n SCIPY result--singles\n [0.20481184 0.31532795 0.02990511]\n lmfit result--multiples\n [[Variables]]\n amp: 0.16490986 +/- 0.00284211 (1.72%) (init = 0.05)\n mean: 0.29791775 +/- 5.3128e-04 (0.18%) (init = 0.3)\n sig: 0.03695966 +/- 3.5748e-04 (0.97%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.558\n None\n lmfit result--singles\n [[Variables]]\n amp: 0.20481177 +/- 0.00209510 (1.02%) (init = 0.05)\n mean: 0.31532796 +/- 2.4887e-04 (0.08%) (init = 0.3)\n sig: 0.02990512 +/- 1.7988e-04 (0.60%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.585\n None\n fitting 5\n SCIPY result--multiples\n [0.e+00 1.e-03 1.e-06]\n SCIPY result--singles\n [0.24189341 0.33249515 0.02534415]\n lmfit result--multiples\n [[Variables]]\n amp: 0.18093017 +/- 0.00515580 (2.85%) (init = 0.02)\n mean: 0.31190783 +/- 8.0438e-04 (0.26%) (init = 0.35)\n sig: 0.03325183 +/- 5.2609e-04 (1.58%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.554\n C(mean, sig) = -0.194\n C(amp, mean) = 0.108\n None\n lmfit result--singles\n [[Variables]]\n amp: 0.24189334 +/- 0.00189645 (0.78%) (init = 0.02)\n mean: 0.33249516 +/- 1.6142e-04 (0.05%) (init = 0.35)\n sig: 0.02534416 +/- 1.1689e-04 (0.46%) (init = 0.05)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.586\n None\n fitting 6\n SCIPY result--multiples\n [0.18960062 0.33896949 0.0306643 ]\n SCIPY result--singles\n [0.26747705 0.36267954 0.02281349]\n lmfit result--multiples\n [[Variables]]\n amp: 0.18959813 +/- 0.00879578 (4.64%) (init = 0.03)\n mean: 0.33896936 +/- 0.00128147 (0.38%) (init = 0.34)\n sig: 0.03066471 +/- 7.5284e-04 (2.46%) (init = 0.03)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.528\n C(mean, sig) = -0.329\n C(amp, mean) = 0.174\n None\n lmfit result--singles\n [[Variables]]\n amp: 0.26747696 +/- 0.00421570 (1.58%) (init = 0.03)\n mean: 0.36267954 +/- 2.9280e-04 (0.08%) (init = 0.34)\n sig: 0.02281350 +/- 2.0950e-04 (0.92%) (init = 0.03)\n [[Correlations]] (unreported correlations are < 0.100)\n C(amp, sig) = -0.582\n None\n [0.15839551 0.08665691 0.05384962 0.04228083 0.03695966 0.03325183\n 0.03066471]\n [0.00188594 0.00067002 0.00023092 0.00030421 0.00035748 0.00052609\n 0.00075284]\n [0.15562439 0.08617603 0.05110994 0.03752698 0.02990512 0.02534416\n 0.0228135 ]\n [0.00184253 0.00095268 0.00045226 0.0003017 0.00017988 0.00011689\n 0.0002095 ]\n\n\n\n```python\nfig,axs = plt.subplots(2,3,figsize=(20.0,11.0),sharex=True,sharey=True)\n\nX = np.arange(0,0.6,0.005)\nfunc = lambda x,a,b,c: a*np.exp(-(x-b)**2/(2*c**2))\nfuncv = np.vectorize(func)\n\nfor i,ax in enumerate(np.ndarray.flatten(axs)):\n #ax.set_title('markevery=%s' % str(case))\n #ax.plot(x, y, 'o', ls='-', ms=4, markevery=case)\n ax.text(0.025,0.3,\"{:2.1f} keV $\\leq$ $E_r$ $<$ {:2.1f} keV\".format(bins[i+1],bins[i+2]),fontsize=24)\n idx=i+1\n ax.plot(X,funcv(X,qamps[i+1],qmus[i+1],qsigs[i+1]),color='b',linestyle=\"-\",linewidth=2)\n ax.plot(X,funcv(X,qamps_ss[i+1],qmus_ss[i+1],qsigs_ss[i+1]),color='m',linestyle=\"-\",linewidth=2)\n ax.step(xcq,qhistos[:,idx]/np.sum(qhistos[:,idx]), where='mid',color='b', linestyle='-', \\\n label='all scatters', linewidth=2)\n ax.step(xcq,qhistos_ss[:,idx]/np.sum(qhistos_ss[:,idx]), where='mid',color='m', linestyle='-', \\\n label='single scatters', linewidth=2)\n ax.set_yscale('linear')\n #ax1.set_yscale('linear')\n ax.set_xlim(0, 0.6) \n ax.set_ylim(0,0.35)\n if(i>2):\n ax.set_xlabel(r'ionization yield',**axis_font)\n if((i==0)|(i==3)):\n ax.set_ylabel('PDF',**axis_font)\n ax.grid(True)\n ax.yaxis.grid(True,which='minor',linestyle='--')\n if(idx==1):\n ax.legend(loc=(0.1,0.5),prop={'size':22})\n for axis in ['top','bottom','left','right']:\n ax.spines[axis].set_linewidth(2)\n \nplt.tight_layout() \nplt.show()\n```\n\nIn each of the energy bins the ionization yield distribution fit results are summarized in the following table. \n\nenergy bin|interval (keV)|all-scatters width (keV)|all-scatters uncertainty (keV)|single-scatters width (keV)| single-scatters uncertainty (keV)\n:-|:-|:-|:-|:-|:-\n0|\\[5,10)| 0.164 | 0.004 | 0.150 | 0.004\n1|\\[10,20)|0.087 | 0.001 | 0.086 |0.001\n2|\\[20,30) | 0.053 |0.001 |0.051 | 0.001\n3|\\[30,40) | 0.040 |0.001 |0.037 |0.001\n4|\\[40,50) | 0.035 | 0.000 |0.032 |0.001\n5|\\[50,70) | 0.030 | 0.001 |0.025 |0.000\n6|\\[70,150) |0.029 | 0.001 |0.023 |0.000\n\n\n\nbelow are some cells that show how to use emcee\n\n\n```python\n# #show the errors on a fit\n# #https://emcee.readthedocs.io/en/v2.2.1/user/line/#maximum-likelihood-estimation\n# def lnprior(theta):\n# a, b, c = theta\n# if 0.0 < a < 100 and 0.00001 < b < 1.0 and 1e-6 < c < 1.0:\n# return 0.0\n# return -np.inf\n\n# def lnprob(theta, x, y, yerr):\n# lp = lnprior(theta)\n# if not np.isfinite(lp):\n# return -np.inf\n# return lp + lnlikeg(theta, x, y, yerr)\n\n# ndim, nwalkers = 3, 100\n# pos = [result[\"x\"] + 1e-4*np.random.randn(ndim) for i in range(nwalkers)]\n\n\n```\n\n\n```python\n# qsum = np.sum(qhistos[:,1])\n# x = xcq\n# y = qhistos[:,1]/qsum\n# yerr = qerrs[:,1]/qsum\n\n\n# import emcee\n# sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(x, y, yerr))\n\n# sampler.run_mcmc(pos, 5000);\n```\n\n\n```python\n# samples = sampler.chain[:, 50:, :].reshape((-1, ndim))\n\n# import corner\n# #fig = corner.corner(samples, labels=[\"$a$\", \"$b$\", \"$c$\"],\n# # truths=[qamps[1], qmus[1], qsigs[1]])\n# fig = corner.corner(samples, labels=[\"$a$\", \"$b$\", \"$c$\"])\n```\n\n## Multiple-Scatter Systematic\n\nThe Edelweiss paper quotes the enlargement of the ionization-yield width as a simple factor, constant across all recoil energy bins. They call this factor \"C.\" Based on the results in this note, it is sensible to quote an energy-dependent systematic uncertainty on top of that constant factor. This will impact the energy-dependent systematic uncertainty on our extracted Fano factor. \n\nThe reason it makes sense to proceed this way is that the correction to the width is small, at most 0.006, whereas the value of \"C\" that we are attributing to the effective nuclear-recoil Fano factor, is around 0.04 across all energies. Quoting this as a systematic will underscore the fact that this is a relatively inprecise extraction, whereas if we were to correct the width for multiple scatters, it may lead to a misleading assessement of the final uncertainty on the extracted effective nuclear-recoil Fano factor. \n\nRecall, that in the Edelweiss paper [REF], a Gaussian approximation was used wherein the width in ionization yield could be written as:\n\n\\begin{equation}\n\\sigma_Q(\\tilde{E}_r) \\simeq \\frac{1}{\\tilde{E}_r} \\sqrt{\\left(1+\\frac{V}{\\epsilon}\\bar{Q}\\right)^2\\sigma_I^2 + \\left(1+\\frac{V}{\\epsilon}\\right)^2\\bar{Q}^2\\sigma_H^2}.\n\\end{equation}\n\nFor comparison, we can plot this along with our measured widths for detector GGA3. \n\n\n```python\n#make functions for analytical bands\n#modify heat resolution by adding aH\n\naH=0.065\nheatRes_GGA3_new = er.get_heatRes_func(0.4, 2.7,aH*FWHM_to_SIG)\n#heatRes_GGA3_new = er.get_heatRes_func(0.4, 2.7)\nsigh_GGA3v_new = np.vectorize(heatRes_GGA3_new)\n\naH2=0.035\nheatRes_GGA3_new2 = er.get_heatRes_func(0.4, 2.7,aH2*FWHM_to_SIG)\n#heatRes_GGA3_new = er.get_heatRes_func(0.4, 2.7)\nsigh_GGA3v_new2 = np.vectorize(heatRes_GGA3_new2)\n\n#new resolution functions \nEhee = lambda Er: ((1+(V/(1000*eps))*Qbar(Er))*Er)/(1+(V/(1000*eps)))\nEIee = lambda Er: Qbar(Er)*Er\n\n\nsigH_NR = lambda Er: sigh_GGA3v_new(Ehee(Er))\n\nsigH_NR2 = lambda Er: sigh_GGA3v_new2(Ehee(Er))\n\nsigI_NR = lambda Er: sigi_GGA3v(EIee(Er))\n\n\n\nsigQnr = lambda Etr: (1/Etr)*np.sqrt((1+(V/(1000*eps))*Qbar(Etr))**2*sigI_NR(Etr)**2 + (1+(V/(1000*eps)))**2 \\\n *Qbar(Etr)**2*sigH_NR(Etr)**2)\n\nsigQnr2 = lambda Etr: (1/Etr)*np.sqrt((1+(V/(1000*eps))*Qbar(Etr))**2*sigI_NR(Etr)**2 + (1+(V/(1000*eps)))**2 \\\n *Qbar(Etr)**2*sigH_NR2(Etr)**2)\n\nprint(sigQnr(20))\nprint(sigH_NR(10))\nprint(sigI_NR(10))\nsigQnrv = np.vectorize(sigQnr)\nsigQnrv2 = np.vectorize(sigQnr2)\n```\n\n 0.05881961755608948\n 0.23096523083266213\n 0.8431667681790007\n\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\n\nbins = np.asarray(bins)\nxE = (bins[:-1] + bins[1:]) / 2\n\nX=np.arange(0.1,160,0.1)\n\n\nax1.plot(X,sigQnrv(X),color='r',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH))\nax1.plot(X,sigQnrv2(X),color='k',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH2))\nax1.plot(X,np.sqrt(sigQnrv(X)**2+0.023**2),color='r',linestyle=\"-\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.023))\nax1.plot(X,np.sqrt(sigQnrv2(X)**2+0.025**2),color='k',linestyle=\"-\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.025))\nax1.errorbar(xE,qsigs, yerr=qsigerrs,color='b', marker='o', \\\n markersize=4,linestyle='none',label='all scatters', linewidth=2)\nax1.errorbar(xE,qsigs_ss, yerr=qsigerrs_ss,color='m', marker='o', \\\n markersize=4,linestyle='none',label='single scatters', linewidth=2)\n\n\n\nymin = 0.012\nymax = 0.06\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(0, 160) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\nplt.savefig('figures/ms_width0.png')\nplt.show()\n```\n\nThere are some puzzling features of these results in comparison with the Edw. model predictions (red curves above). Even though we used a F=0 throughout, the simulated data is larger than the model that Edw. predicts by a substantial amount, even after using the increased $a_H$ of 0.035 mentioned in their paper for GGA3. In fact an $a_H$ of 0.065 seems to be a closer approximation. \n\nOf course, this is the _nuclear_ recoil band with single-scatters only. The Edw. paper doesn't have any way to check what the prediction should be for a nuclear recoil band would be _without_ the effective Fano factor and with only single-scatters. It is possible that our model prediction (and hence our simulated data) is systematically wider for the NR band than the Gaussian model used by Edw. \n\nProbably the best way to check this is to:\n\n1. extract the widths for the ER band model from simulated data.\n2. plot over those the 1$\\sigma$ lines for both the Edw. model and our v2 model with F=0. We expect our model to agree with the simulated data, and we believe the method of simulation above is close to physical. \n3. make the same checks for the NR bands. \n\nNote the only real difference between the ER and NR bands with F=0 is the assumed energy spectrum (flat for ERs and exponential for NRs) and point of evaluation of the resolutions (i.e. need to use electron-equivalent for the $\\sigma_I$ evaluation).\n\nThese checks should be done in a separate note. \n\nFinally, it can be seen from the above plot that adding a constant widening factor (in quadrature) of C=0.02 on top of an $a_H$ of 0.065 will give widths roughly consistent with the full recoil sample (i.e. including multiple-scatters). This value of C is less than the quoted average of 0.04 by about a factor of 2. Therefore after an arbitrary upward empirical correction to the single-scatter yield widths the observed bands are wider by a quadrature addition of 0.02. \n\nThe multiple-scatter predictions for the model are still well short of the final widths reported by Edelweiss, so there is room for an effective nuclear-recoil Fano contribution. \n\n# Consistent Binning and Bootstrap Sampling\n\nIt was found (see notebooks `yield_width_compare.ipynb` and `fitting_errors.ipynb`) that going to a more consistent binning and using a bootstrap-sampling to compute the standard deviations solved many of the puzzling features in the above. \n\nThe non-uniform binning makes sense with experimental data because the number of nuclear-recoil counts falls off quasi-exponentially. So for the higher energies a reasonable sample size can only be obtained by increasing the energy bin width. Since the expected width of the yield distribution is changing (sometimes rather rapidly) over the bin, it means that a bin-centering correction should be applied, and it was not applied above. In order not to dealve too deeply into the details of that correction, we simply use smaller and more consistent bins here. Since we are using simulated data the sample sizes are not as severely limited as they are in the case of experimental data. Slight evidence of a bin-centering correction can be seen in the Edelweiss paper [REF]. \n\nEven when the binning is corrected, it is seen that even for rather large samples (of 1000 events), fittig a histogram with 40 bins from 0.0 to 0.6 in yield leads to under-reporting the width of the fit, even in the cases where the fits look quite good (no detailed error analysis was done on the fit, we simply use the scaled errors of the `lmfit` minimizer). For this reason we moved to bootstrap-resampling which is a method that can provide accurate estimates of distribution statistics and their confidence intervals even for small samples. It relies on resampling the data with replacement, the library used is called [bootstrapped](https://pypi.org/project/bootstrapped/) and seems to work well. \n\n**NOTE: This package has a version of 0.0.2 and I got it after a very cursory internet search. Its development (if it's still being developed) will probably be _volatile_.**\n\nSo, to start this off lets modify the binning of our data, we use the same binning as in `yield_width_compare.ipynb`:\n\n\n```python\n#create a dataframe\nnr_df = pds.DataFrame(data={'yield':Q, 'energy':Ernr})\nnr_ss_df = pds.DataFrame(data={'yield':Q_ss, 'energy':Ernr_ss})\n\n#bin the data\nbins = [0, 10, 20, 30, 40, 50, 60,70,80,90,100,110,120,130,140,150]\nnr_df['binned'] = pds.cut(nr_df['energy'],bins)\nnr_ss_df['binned'] = pds.cut(nr_ss_df['energy'],bins)\n\n#print stats in each bin\ns = nr_df.groupby(pds.cut(nr_df['energy'], bins=bins)).size()\ns_ss = nr_ss_df.groupby(pds.cut(nr_ss_df['energy'], bins=bins)).size()\n#print (s)\n#print(s_ss)\n\n#create list of vectors for histogrammin'\nhist = nr_df.groupby(pds.cut(nr_df['energy'], bins=bins))['yield'].apply(list)\nhist_ss = nr_ss_df.groupby(pds.cut(nr_ss_df['energy'], bins=bins))['yield'].apply(list)\n#print(hist)\n#print(hist_ss)\n```\n\n\n```python\n#go through the samples and get the bootstrap estimators\nimport bootstrapped.bootstrap as bs\nimport bootstrapped.stats_functions as bs_stats\n\n\nqbootsigs = np.zeros((np.shape(bins)[0]-1,))\nqbootsigerrsu = np.zeros((np.shape(bins)[0]-1,))\nqbootsigerrsl = np.zeros((np.shape(bins)[0]-1,))\n\nqbootsigs_ss = np.zeros((np.shape(bins)[0]-1,))\nqbootsigerrsu_ss = np.zeros((np.shape(bins)[0]-1,))\nqbootsigerrsl_ss = np.zeros((np.shape(bins)[0]-1,))\n\nprint(np.shape(qbootsigs))\nprint(np.shape(qbootsigerrsu))\nprint(np.shape(qbootsigerrsl))\nprint(np.shape(qbootsigs_ss))\nprint(np.shape(qbootsigerrsu_ss))\nprint(np.shape(qbootsigerrsl_ss))\n\nfor i,Qv in enumerate(hist):\n print(np.shape(Qv))\n Qv = np.asarray(Qv)\n #print(Qv[0:10])\n try:\n bsr = bs.bootstrap(Qv, stat_func=bs_stats.std,iteration_batch_size=100)\n except MemoryError as e:\n print('There was a memory error - too much memory to be allocated')\n \n print(bsr)\n qbootsigs[i] = np.std(Qv)\n qbootsigerrsu[i] = bsr.upper_bound\n qbootsigerrsl[i] = bsr.lower_bound\n \n#change over to size of error bars, not confidence interval \nqbootsigerrsu = qbootsigerrsu - qbootsigs\nqbootsigerrsl = -qbootsigerrsl + qbootsigs\n \nfor i,Qv in enumerate(hist_ss):\n print(np.shape(Qv))\n Qv = np.asarray(Qv)\n #print(Qv[0:10])\n try:\n bsr = bs.bootstrap(Qv, stat_func=bs_stats.std,iteration_batch_size=100)\n except MemoryError as e:\n print('There was a memory error - too much memory to be allocated')\n qbootsigs_ss[i] = np.std(Qv)\n qbootsigerrsu_ss[i] = bsr.upper_bound\n qbootsigerrsl_ss[i] = bsr.lower_bound\n \n#change over to size of error bars, not confidence interval \nqbootsigerrsu_ss = qbootsigerrsu_ss - qbootsigs_ss\nqbootsigerrsl_ss = -qbootsigerrsl_ss + qbootsigs_ss\n```\n\n (15,)\n (15,)\n (15,)\n (15,)\n (15,)\n (15,)\n (171482,)\n 130.28419695421192 (42.41443167458445, 229.1183415260692)\n (22805,)\n 0.0885154293206289 (0.0876178479135536, 0.08941570807655053)\n (12878,)\n 0.05386016376659373 (0.05319572179615925, 0.05454380442022407)\n (8239,)\n 0.04229385972731089 (0.04166398062904478, 0.04292477721941994)\n (5771,)\n 0.0370787553399476 (0.03645676916783976, 0.03772253401461866)\n (4225,)\n 0.0340023803193902 (0.033304537168591275, 0.034691303709532675)\n (3156,)\n 0.032563897955721614 (0.03179941499521473, 0.033322962725941936)\n (2493,)\n 0.03136462017317629 (0.030555281425321344, 0.032184482044040494)\n (1943,)\n 0.030650716618908072 (0.02975775916889492, 0.03155875497973107)\n (1464,)\n 0.031041887512827434 (0.030045432445974116, 0.03204156060612387)\n (1115,)\n 0.029785268402918803 (0.028659135619544394, 0.030961664466623934)\n (814,)\n 0.030372616806941748 (0.029039159074510608, 0.031739129845390165)\n (662,)\n 0.02960702625561379 (0.028259346894636675, 0.03100096237390509)\n (514,)\n 0.031193830598122703 (0.02947592625429104, 0.032986244863545414)\n (412,)\n 0.03301865581644106 (0.031185154746906217, 0.03498784029485559)\n (81872,)\n (10641,)\n (5230,)\n (3159,)\n (2137,)\n (1518,)\n (1122,)\n (900,)\n (699,)\n (469,)\n (386,)\n (280,)\n (205,)\n (154,)\n (135,)\n\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\n\nbins = np.asarray(bins)\nxE = (bins[:-1] + bins[1:]) / 2\n\nX=np.arange(0.1,160,0.1)\n\n\n#ax1.plot(X,sigQnrv(X),color='r',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH))\nax1.plot(X,sigQnrv2(X),color='r',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH2))\nax1.plot(X,np.sqrt(sigQnrv(X)**2+0.02**2),color='r',linestyle=\"-\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.02))\nax1.plot(X,np.sqrt(sigQnrv(X)**2+0.04**2),color='k',linestyle=\":\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.04))\nax1.errorbar(xE,qbootsigs, yerr=(qbootsigerrsl,qbootsigerrsu),color='b', marker='o', \\\n markersize=4,linestyle='none',label='all scatters', linewidth=2)\nax1.errorbar(xE,qbootsigs_ss, yerr=(qbootsigerrsl_ss,qbootsigerrsu_ss),color='m', marker='o', \\\n markersize=4,linestyle='none',label='single scatters', linewidth=2)\n\n\n\nymin = 0.012\nymax = 0.06\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(0, 160) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\n#ax1.legend(loc=1,prop={'size':22})\n#ax1.legend(loc='upper right', bbox_to_anchor=(1, 0.5),prop={'size':22})\nlgd = ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\n#plt.tight_layout()\n#plt.savefig('figures/ms_width1.png')\nplt.savefig('figures/ms_width1.png', bbox_extra_artists=(lgd,), bbox_inches='tight')\nplt.show()\n```\n\nThis plot is much more understandable. We see that the single-scatters are more consistent with the baseline resolution model that was used to generate the data ($a_H$=0.035). The addition of multiple scatters effectively changes the yield width by adding 0.02 in quadrature. However, it takes a change of 0.045 in quadrature to give a yield width that is asymtotically in agreement with the measured Edelweiss yield widths (0.05 or so). \n\nThis means that even after adding in the multiple scattering, the yield measured by Edelweiss is still significantly larger than would be expected. \n\n# Bin-Centering Correction\n\nBecause finite bins (as opposed to infinitessimal ones) are being used to determine the yield variance, the points are expected to be systematically displaced from the predicted curves (which predict the widths at a _single_ true recoil energy). \n\nThe effect of such things can be seen in the difference between the first yield-width points given above (with uneven and often large binning) and the second. The second uses smaller and evenly spaced bins and the results are correspondingly different. \n\nOne of the problems with calculating the yield widths for finite bins is that the number of counts may not be uniform across all energies in the bin. One way to make a _very rough_ correction for this is to quote the data point at the point of the mean energy across the bin, not the central energy. This is done below, the effect is small for the bins above about 25 keV, and these are the points that are most relevant to this analysis.\n\n\n```python\n#create list of vectors for histogrammin'\nhist_E = nr_df.groupby(pds.cut(nr_df['energy'], bins=bins))['energy'].apply(list)\nhist_ss_E = nr_ss_df.groupby(pds.cut(nr_ss_df['energy'], bins=bins))['energy'].apply(list)\n\nprint(hist_E)\n```\n\n energy\n (0, 10] [0.840087659782423, 5.398318870458236, 7.81514...\n (10, 20] [18.09289075039505, 14.193804124154767, 15.759...\n (20, 30] [24.823728498150274, 21.250005266454945, 24.67...\n (30, 40] [32.18481747957077, 31.2318733791751, 30.43824...\n (40, 50] [41.78550307236901, 41.877506278197565, 42.920...\n (50, 60] [53.953578627180185, 58.749228389136036, 54.55...\n (60, 70] [60.84350077452007, 66.35489246087852, 64.6851...\n (70, 80] [74.87272542917611, 73.9445558118253, 78.17819...\n (80, 90] [81.01647789922626, 86.55027137002855, 88.9713...\n (90, 100] [99.5383191130899, 93.84488481772836, 97.51083...\n (100, 110] [105.30550082009653, 109.06612999419889, 104.4...\n (110, 120] [115.37366867978777, 112.42108112514335, 110.7...\n (120, 130] [124.42316182528249, 124.76778848004706, 127.0...\n (130, 140] [131.15549195303595, 130.97458642716347, 135.5...\n (140, 150] [145.2579435425256, 142.3954244697553, 147.940...\n Name: energy, dtype: object\n\n\n\n```python\nqbootEs = np.zeros((np.shape(bins)[0]-1,))\nqbootEs_ss = np.zeros((np.shape(bins)[0]-1,))\n\nfor i,Ev in enumerate(hist_E):\n #print(np.mean(Ev))\n qbootEs[i] = np.mean(Ev)\n \nfor i,Ev in enumerate(hist_ss_E):\n #print(np.mean(Ev))\n qbootEs_ss[i] = np.mean(Ev)\n```\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\n\n\nX=np.arange(0.1,160,0.1)\n\n\n#ax1.plot(X,sigQnrv(X),color='r',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH))\nax1.plot(X,sigQnrv2(X),color='r',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH2))\nax1.plot(X,np.sqrt(sigQnrv(X)**2+0.02**2),color='r',linestyle=\"-\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.02))\nax1.plot(X,np.sqrt(sigQnrv(X)**2+0.04**2),color='k',linestyle=\":\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.04))\nax1.errorbar(qbootEs,qbootsigs, yerr=(qbootsigerrsl,qbootsigerrsu),color='b', marker='o', \\\n markersize=4,linestyle='none',label='all scatters', linewidth=2)\nax1.errorbar(qbootEs_ss,qbootsigs_ss, yerr=(qbootsigerrsl_ss,qbootsigerrsu_ss),color='m', marker='o', \\\n markersize=4,linestyle='none',label='single scatters', linewidth=2)\n\n\n\nymin = 0.012\nymax = 0.06\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(0, 160) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\n#ax1.legend(loc=1,prop={'size':22})\n#ax1.legend(loc='upper right', bbox_to_anchor=(1, 0.5),prop={'size':22})\nlgd = ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\n#plt.tight_layout()\n#plt.savefig('figures/ms_width1.png')\nplt.savefig('figures/ms_width2_bc_corr.png', bbox_extra_artists=(lgd,), bbox_inches='tight')\nplt.show()\n```\n\nA second reason that the finite binning changes the answers is that the width of the distribution (and the mean) are changing over the bin. The smaller the bins are the less significant these affects can be, but they can be corrected for. \n\nImagine taking the ionization yield mean as a function of recoil energy and a local approximate to the yield standard deviation as a function of variance as thus:\n\n\\begin{equation}\n\\bar{Q}(E_r) = \\mathrm{0.16}E_r^{\\mathrm{0.18}}, \n\\end{equation}\n\nand\n\n\\begin{equation}\n\\tilde{\\sigma}_i(E_r) = m(E_r - E_i) + \\sigma_i,\n\\end{equation}\n\nwhere $m$ is the slope of the yield standard deviation with energy, $E_i$ is the energy the value is quoted at in the bin (see the previous correction), and $\\sigma_i$ is the measured value of the yield width across the bin. \n\nThe true measurement is the width of a normalized sum of distributions across the bin with the centers at $\\bar{Q}(E_r)$ and widths $\\tilde{\\sigma}_i(E_r)$. \n\nOne way we can approximate how different this width should be from the width evaluated near the center of the bin is to compute a correction factor for each bin, $i$. The correction factor, $c_i$, is defined as follows:\n\n\\begin{equation}\nc_i \\equiv \\frac{\\tilde{\\sigma}_i(E_r)}{width\\left( \\sum_k n_k \\frac{1}{\\sqrt{2\\pi\\tilde{\\sigma}_i(E_r)^2}}\\exp \\left[ -(\\bar{Q}(E_r)-Q)/2\\tilde{\\sigma}_i(E_r) \\right ] \\right)}.\n\\end{equation}\n\nIn the above equation the $n_k$ are the normalizations for each sub-bin $k$, they add to unity. For each sub-bin a corresponding normal yield distribution is used, but the means of each separate yield distribution and the widths are given by the continuous functions of $E_r$ above. The correction factor is the ratio of the width calculated with these sub-bin yield distributions and the central value, $\\tilde{\\sigma}_i$. \n\nIn what follows I use 10 sub-bin yield distributions for every data point. For the smaller consistent binning used in the bottom half of this note, the correction factors are not more than 2%, except for the first two bins which have a poorly estimated $\\tilde{\\sigma}(E_r)$ (so much sow that it can be negative!). The corrections for those bins are taken to be 1. \n\n\n```python\nimport imp\nimport histogram_yield as hy\nimp.reload(hy)\n\nqbootcorrs = np.ones((np.shape(bins)[0]-1,))\nqbootcorrs_ss = np.ones((np.shape(bins)[0]-1,))\n\nfor i,Ev in enumerate(hist_E):\n if((i>0)&(i<(np.shape(qbootsigs)[0]-1))):\n m = (qbootsigs[i+1] -qbootsigs[i-1])/(qbootEs[i+1]-qbootEs[i-1])\n elif (i>0):\n m = (qbootsigs[i] -qbootsigs[i-1])/(qbootEs[i]-qbootEs[i-1])\n elif (i<(np.shape(qbootsigs)[0]-1)):\n m = (qbootsigs[i+1] -qbootsigs[i])/(qbootEs[i+1]-qbootEs[i])\n intercept = qbootsigs[i]\n #print(xE[i])\n #print(qbootEs[i])\n fsig = lambda E: m*(E-qbootEs[i]) + intercept\n #print(fsig(qbootEs[i]))\n sigcorr = hy.bc_corr(Ev,fsig,10)\n #print(qbootsigs[i]/sigcorr)\n qbootcorrs[i] = (qbootsigs[i]/sigcorr)\n\n#first two are absurd because of negative projected sigma (FIXME)\nqbootcorrs[0] = 1\nqbootcorrs[1] = 1\n \nfor i,Ev in enumerate(hist_ss_E):\n if((i>0)&(i<(np.shape(qbootsigs_ss)[0]-1))):\n m = (qbootsigs_ss[i+1] -qbootsigs_ss[i-1])/(qbootEs_ss[i+1]-qbootEs_ss[i-1])\n elif (i>0):\n m = (qbootsigs_ss[i] -qbootsigs_ss[i-1])/(qbootEs_ss[i]-qbootEs_ss[i-1])\n elif (i<(np.shape(qbootsigs_ss)[0]-1)):\n m = (qbootsigs_ss[i+1] -qbootsigs_ss[i])/(qbootEs_ss[i+1]-qbootEs_ss[i])\n intercept = qbootsigs_ss[i]\n #print(xE[i])\n #print(qbootEs[i])\n fsig = lambda E: m*(E-qbootEs_ss[i]) + intercept\n #print(fsig(qbootEs[i]))\n sigcorr = hy.bc_corr(Ev,fsig,10)\n #print(qbootsigs_ss[i]/sigcorr)\n qbootcorrs_ss[i] = (qbootsigs_ss[i]/sigcorr)\n\n#first two are absurd because of negative projected sigma (FIXME)\nqbootcorrs_ss[0] = 1\nqbootcorrs_ss[1] = 1\n\nprint(qbootcorrs)\nprint(qbootcorrs_ss)\n```\n\n [1. 1. 0.98668171 0.99293332 0.99463941 0.99574783\n 0.99655977 0.99701956 0.9975585 0.9980364 0.99810081 0.99842573\n 0.99861321 0.99867079 0.99896236]\n [1. 1. 0.98415012 0.99008324 0.99091736 0.99228766\n 0.99294778 0.9929718 0.99398164 0.99340793 0.99296611 0.99516953\n 0.99521396 0.99647367 0.99691189]\n\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\n\n\nX=np.arange(0.1,160,0.1)\n\n\n#ax1.plot(X,sigQnrv(X),color='r',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH))\nax1.plot(X,sigQnrv2(X),color='r',linestyle=\"--\",linewidth=2,label='single-scatter yield model (aH={:1.3})'.format(aH2))\nax1.plot(X,np.sqrt(sigQnrv(X)**2+0.02**2),color='r',linestyle=\"-\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.02))\nax1.plot(X,np.sqrt(sigQnrv(X)**2+0.04**2),color='k',linestyle=\":\",linewidth=2,\\\n label='single-scatter yield model (+ C={:1.3f} in quad.)'.format(0.04))\nax1.errorbar(qbootEs,qbootsigs*qbootcorrs, yerr=(qbootsigerrsl*qbootcorrs,qbootsigerrsu*qbootcorrs),color='b', marker='o', \\\n markersize=4,linestyle='none',label='all scatters', linewidth=2)\nax1.errorbar(qbootEs_ss,qbootsigs_ss*qbootcorrs_ss, yerr=(qbootsigerrsl_ss*qbootcorrs_ss,qbootsigerrsu_ss*qbootcorrs_ss),color='m', marker='o', \\\n markersize=4,linestyle='none',label='single scatters', linewidth=2)\n\n\n\nymin = 0.012\nymax = 0.06\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(0, 160) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\n#ax1.legend(loc=1,prop={'size':22})\n#ax1.legend(loc='upper right', bbox_to_anchor=(1, 0.5),prop={'size':22})\nlgd = ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_linewidth(2)\n\n#plt.tight_layout()\n#plt.savefig('figures/ms_width1.png')\nplt.savefig('figures/ms_width3_bc_corr_full.png', bbox_extra_artists=(lgd,), bbox_inches='tight')\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "27f0236bec84edf1a010fe5e55c44bba8bc7d176", "size": 972274, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "analysis_notebooks/ms_correction.ipynb", "max_stars_repo_name": "villano-lab/nrFano_paper2019", "max_stars_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:38:54.000Z", "max_issues_repo_path": "analysis_notebooks/ms_correction.ipynb", "max_issues_repo_name": "villano-lab/nrFano_paper2019", "max_issues_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "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": "analysis_notebooks/ms_correction.ipynb", "max_forks_repo_name": "villano-lab/nrFano_paper2019", "max_forks_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "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": 535.9834619625, "max_line_length": 174524, "alphanum_fraction": 0.9348948959, "converted": true, "num_tokens": 19260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.12592275335433112, "lm_q1q2_score": 0.05610230389873199}} {"text": "# Problem Set 2, Spring 2020, Villas-Boas\n\nDue Tuesday, February 25 at 9:30am\n\nSubmit materials (Jupyter notebook with all code cells run) as one pdf on [Gradescope](https://www.gradescope.com/courses/85265).\n\n# Exercise 1: Food expenditures, food at home, away from home, in US, by region\n\n## Guidelines\n\nThis exercise should be completed using R . Remember, when you want output to show in the notebook, you need to *explicitly* call the object in your R code. For example, if I want to show the mean of food at home expenditures per capita (*FAHE*), I can’t just type `MeanFAHE <- mean(FAHE)` because that will just save the output to `MeanFAHE`. Instead, I need to then type `MeanFAHE` on its own so it displays the output. __Answers that do not display any output will be graded as incorrect.__\n\nTo write comments in your script (text that will display and will not be read as commands), type a `#` at the beginning of the line you want to be a comment. Use these as notes to keep track of which question you are trying to answer, the purpose of each command, etc.\n\n\n\n```R\n# Here is an example of a comment in a code cell. Note that running this cell (shift + enter) does not do anything\n# because these lines are commented, even if there is a normal command in them. For instance,\n# 4 + 4\n# or\n# library(tidyverse)\n```\n\n**To get started:**\n\n* This time you are opening a STATA-formatted \".dta\" file, so you will use the `read_dta()` function instead of the import function that was applied to a \".csv\" spreadsheet in Problem Set 1. You will need to load the `haven` package to do this. Your command should look like this: \n\n`DataName <- read_dta(\"file_name\")`\n\n* Exercise 1 requires both R work and written answers. Exercise 2 does not require any coding. \n\n**hint:** the function `group_by()` in the `tidyverse` package might be helpful. Section 2 Notes will give some examples of how to use the function.) The function takes two arguments: first the name of the data, second the variable whose values we want to group on: `group_by(data, varname)`. Grouping the data doesn't modify the data itself, instead it changes how the data behaves when we pass it to other `tidyverse` functions. If when we use `summarise()` on our data after using `group_by()`, we will produce separate sets of summary statistics for each level of the grouping variable. \n\nFor example, if we were working with the `sleep75` dataset with information on the average time slept per night, $sleep$, and each person's gender, $male$, we could first group on gender by running `sleep75 <- group_by(gender)`. If we then wanted to look at the average sleep per night and number of observations *split by gender*, we could run `summarise(sleep75, avg_sleep = mean(sleep), count = n())` which will yield a table that has two rows of summary statistics: one row for females (`male = 0`) and one row for males (`male =1`)\n\n\n| male\t|\tavg_sleep |\t count |\n| :----------- | :----------------------- |:------|\n| 0 | 7.54 | 306 |\n| 1 | 7.67 | 400 |\n\nWhen you are done with the grouped commands and want to make sure you perform calculations on the entire dataset, you can use the `ungroup()` function to ungroup the data.\n\n\n## R Tips\n\n* See the Coding Bootcamp Parts 1 and 2 for some basic operations (i.e. counting observations, scatterplots, generating variables). See also all the Lecture R command files to replicate lectures where we did most of what you are asked to do here : e.g., Lecture4.R, Lecture5.R\n* The command `table()` lists all values a variable takes in the sample and the number of times it takes each value.\n* To summarize data for a specified subset of the observations, you can use `filter()` to subset the data, and then either `summary()` for simple summary statistics or `summarise()` in __tidyverse__ to generate more detailed summary statistics (as we saw in Coding Bootcamp and Problem Set 1).\n\n## Data Description\n\nThe data for this exercise come from the Bureau of Labor Statistics (BLS) Consumer Expenditure Survey (CES). With special permission researchers can have access to very dissaggregate data, but anyone can access their representative consumer spending data by U.S. census region (there are nine Census Regions). In this problem set we delve into that data to provide insights into how food spending varies across the nine Census regions and how food is consumed by region (at home or away from home), and then relate food expenditures to regional characteristics. \n\nThe *dataPset2.dta* file includes the following variables:\n\n|Variable Name\t|\tDescription |\t\n| :----------- | :----------------------- |\n| _region_ | U.S. census region |\n| _ncu_\t|\tNumber of consumer units (in thousands)\t|\n| _incgross_ | Income before taxes in 2018 |\n| _incnet_\t| Income after taxes in 2018 |\n| _n_\t| Number of people per consumer unit |\n| _ncars_\t| Number of Vehicles in consumer unit in 2018 |\n| _exp_\t| Average annual expenditures of consumer unit in 2018 Dollars |\n| _fahe_\t| Food at home expenditures in 2018 |\n| _fawaye_\t| Food away from home expenditures in 2018 |\n\n## Preamble\n\nUse the below code cell to load all your packages (we'll use functions in both the `haven` and `tidyverse` packages). You can also load your data here.\n\n\n```R\n\n```\n\n## Question 1\n\nFirst we would like you to become familiar with your data.\n\n(a) Please detail the following: How many US regions are in the data set? How many regions have food away from home expenditures larger than food at home expenditures? What is the average number of people per consumer unit in the data set? What is the range for the variable _Ncars_ in the data? \n\n\n\n```R\n# Write your code for part (a) here\n```\n\nWrite your answer for part (a) here\n\n(b) Construct a variable `totexp_dlr_pc` equal to total expenditures __per capita in USD__ which is equal to total expenditures by consumer unit divided by Number of people in the consumer unit. You will need to create this new variable in R. Plot a histogram of this constructed variable. What is the range of total expenditures per capita in the US in 2018?\n\n\n\n```R\n# Write your code for part (b) here\n```\n\nWrite your answer for part (b) here\n\n(c) Calculate the proportion of household expenditures spent on food. You will need to create this new variable. What is the mean? What is the median? \n\n\n```R\n# Write your code for part (c) here\n```\n\nWrite your answer for part (c) here\n\n(d) Calculate the proportion of household net income spent on food. Note that you need to first create Total Food expenditures in 2018 given the available data (call this new variable $foodExp$), and then with that create the share of net income spent on food. You will need to create this new variable in R. What is the mean? What is the median? \n\n\n```R\n# Write your code for part (d) here\n```\n\nWrite your answer for part (d) here\n\n## Question 2\n\nConsider the following two models of food expenditures and net income (where $INC$ is the net income variable in our data):\n\n\\begin{align}\nFAWAYE &= \\beta_0 + \\beta_1 INC + u~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(1)\n\\end{align}\n\n\\begin{align}\n~~~~~~~~FAHE &= \\beta_0 + \\beta_1 INC + u ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (2)~~\n\\end{align}\n\n\n(a) Estimate the two models in R with the `lm()` command. Interpret your $\\hat \\beta_1$ coefficients for both models, remembering the triplet **S**(ign), **S**(ignificance), **S**(ize), though you don't need to comment on significance in this problem set. \n\n**Make sure you run all code cells and the corresponding output appears in your notebook before submitting online.**\n\n\n```R\n# Write you code for part (a) here.\n```\n\nWrite your answer for part (a) here.\n\n(b) How well does total net income predict (i) food at home expenditures, and (ii) food away from home expenditures?\n\n\n```R\n# Write your code for part (b) here.\n```\n\nWrite your answer for part (b) here.\n\n(c) What are the predicted levels of Food Away From Home expenditures for a consumer unit with total annual income of 100,000 dollars? \n \n\n\n\n\n```R\n# Write your code for part (c) here.\n```\n\nWrite your answer for part (c) here.\n\n## Question 3\n\nYou already created Total Food expenditures in 2018 ($foodExp$) given the available data. Consider the following model of food expenditures, where *INC* is net income in the data:\n\n\\begin{align}\n\\log(foodExp)= \\beta_0 +\\beta_1\\log(INC) +u ~~~~~~~~~~~~~~(3)\n\\end{align}\n\n(a) Estimate the model, and interpret your $\\hat \\beta_1$ coefficient.\n\n\n```R\n# Write your code for part (a) here.\n```\n\nWrite your answer for part (a) here.\n\n(b) Using the results from estimating equation (3), how would you expect food expenditure to change if total income increases by 25%?\n\n\n```R\n# Write your code for part (b) here.\n```\n\nWrite your answer for part (b) here.\n\n## Question 4\n\n\nWe will now explore the role of consumer unit size in total food expenditures. \n\n\\begin{align}\n\\log(FoodExp)&=\\beta_0 +\\beta_1\\log(INC) +\\beta_2 \\log (N) +u ~~~~(4)\n\\end{align}\n\n(a) Estimate equation (4), and interpret your $\\hat \\beta_0$, $\\hat \\beta_1$ and $\\hat \\beta_2$ coefficients. \n\n\n```R\n# Write your code for part (a) here.\n```\n\nWrite your answer for part (a) here.\n\n(b) How did your estimate $\\hat\\beta_1$ change between equation (3) and equation (4)? Without performing any\ncalculations, what information does this give you about the correlation between net income and\nconsumer unit size? (Explain your reasoning in no more than 4 sentences.)\n\nWrite your answer for part (b) here.\n\n(c) Predict the expected value of food expenditure for a consumer unit with 3 members and total net\nincome of \\$90,000 using your estimates from equation (4).\n\n\n```R\n# Write your code for part (c) here.\n```\n\nWrite your answer for part (c) here.\n\n# Exercise 2. Demand for Multivitamins\n\nMany researchers have attempted to estimate important determinants of demand for vitamins. Suppose\na researcher was interested in the effect of price of a bottle of vitamins on quantity purchased of vitamins.\nOne could estimate such a regression as follows:\n\n\\begin{align}\n~~~~~~~~~~~~~~~~ Q_j = \\beta_0 + \\beta_1 Price_j + \\beta_2 Education_j + u_{ij}~~~~~~~~~~~~~~~~(1)\n\\end{align}\n\nwhere $Q_j$ corresponds to the quantity of vitamins sold in region $j$, $Education_j$ is the level of education in\nregion $j$, and $Price_j$ is the price of vitamins in region $j$.\n\n\n(a) What do you expect the sign of $\\beta_1$ to be in equation (1)? Why?\n\nWrite your answer for part (a) here.\n\n(b) List three other factors that could influence whether the quantity sold of vitamins increases.\n\nWrite your answer for part (b) here.\n\n(c) What would happen to $\\beta_1$ if you omit education from the estimation? Explain (very briefly) why.\n\nWrite your answer for part (c) here.\n\n(d) Give an example of one factor that would induce $\\beta_1$ to be biased. State the direction of the bias\nand how you determined that direction.\n\nWrite your answer for part (d) here.\n\n(e) What are the four conditions that must be satisfied for $\\beta_1$ to be unbiased? Explain whether you\nbelieve each assumption is satisfied, and why or why not (suppose we used supermarket data on the quantities and prices of multivitamins across regions to estimate $\\beta_1$)\n\nWrite your answer for part (e) here.\n\n### Submitting\n\nSave a completed version of your notebook as a pdf by \ngoing to **File > Download As > PDF Via Chrome** in the menu. You will use **PDF Via Chrome** regardless of the web browser you are on). \n\n**Important:** Make sure that all coding cells are run before submission. You can easily do this by going to **Cell > Run All** and then checking to make sure the correct output is displayed.\n", "meta": {"hexsha": "c20ededcf0221b88855f8e67a3c31f6cfa709596", "size": 20575, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Spring2020-J/ProblemSet2/ProblemSet2_2020.ipynb", "max_stars_repo_name": "sungsy12345/ENVECON-118", "max_stars_repo_head_hexsha": "b2b62f49115f37e3a3c1f13b7ac6a3550c4c0600", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-10T13:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T21:41:59.000Z", "max_issues_repo_path": "Spring2020-J/ProblemSet2/ProblemSet2_2020.ipynb", "max_issues_repo_name": "sungsy12345/ENVECON-118", "max_issues_repo_head_hexsha": "b2b62f49115f37e3a3c1f13b7ac6a3550c4c0600", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-22T17:02:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-20T14:03:54.000Z", "max_forks_repo_path": "Spring2020-J/ProblemSet2/ProblemSet2_2020.ipynb", "max_forks_repo_name": "sungsy12345/ENVECON-118", "max_forks_repo_head_hexsha": "b2b62f49115f37e3a3c1f13b7ac6a3550c4c0600", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-11-06T20:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-20T08:14:41.000Z", "avg_line_length": 28.4972299169, "max_line_length": 600, "alphanum_fraction": 0.5901336574, "converted": true, "num_tokens": 2879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.05536276222844445}} {"text": "# Лабораторая работа 4.10\n# Поляризация света. Законы Малюса и Брюстера\n\n## Выполнил: Коняхин Всеволод Владимирович, M32051\n\n## Краткие теоретические сведения\nПоперечные волны обладают особым, присущим только им, свойством, известным под\nназванием поляризация.\n\nЕсли при распространении световой волны направление колебаний электрического вектора\n𝐸⃗ бессистемно, хаотически изменяется с равной амплитудой и, следовательно, любое его\nнаправление в плоскости, перпендикулярной распространению волны, равновероятно, то такой свет\nназывают неполяризованным, или естественным. Если колебания электрического вектора\nфиксированы строго в одном направлении, свет называется линейно- или плоско-поляризованным.\nВ этом случае плоскость, образованная направлением распространения электромагнитной волны и\nнаправлением колебаний вектора напряженности электрического поля, называется плоскостью\nполяризации электромагнитной волны. \n\n**Закон Малюса:**\n\n$E_2 = E_1 \\cdot \\cos \\phi$\n\n$I_2 = I_1 \\cdot \\cos^2 \\phi$\n\nОдной из количественных характеристик поляризации является **степень поляризации $P$.**\nДля ее определения измеряется интенсивность прошедшего света при вращении поляризатора\nвокруг направления светового пучка. Определяются максимальная $I_{max}$ и минимальная $I_{min}$\nинтенсивности (соответствующие двум ортогональным ориентациям поляризатора) и вычисляется\nвеличина P по формуле:\n\n$P = \\frac{I_{max} - I_{min}}{I_{max} + I_{min}}$\n\n**Закон Брюстера:**\n\nСоответствующую зависимость в 1815 г. установил шотландец Дэвид Брюстер. Как\nпоказали опыты, отраженный луч оказывается полностью поляризованым (колебания вектора в нем\nперпендикулярны плоскости падения) в случае, когда угол между отраженным и преломленным\nлучом равен 90°. Прошедший луч поляризован частично и содержит преимущественно\nпараллельную составляющую вектора 𝐸⃗ . \n\n$R^{\\parallel} = \\left( \\frac{E_{refl}^{\\parallel}}{E_{fal}^{\\parallel}} \\right)^2 = \\frac{\\tan^2 (\\phi - \\psi)}{\\tan^2 (\\phi + \\psi)}$\n\n$R^{\\bot} = \\left( \\frac{E_{refl}^{\\bot}}{E_{fal}^{\\bot}} \\right)^2 = \\frac{\\sin^2 (\\phi - \\psi)}{\\sin^2 (\\phi + \\psi)}$\n\n$\\frac{n_2}{n_1} = \\frac{\\sin \\phi}{\\sin \\psi} = \\frac{\\sin \\phi}{\\sin(\\frac{\\pi}{2} - \\phi)} = \\frac{\\sin \\phi}{\\cos \\phi} = \\tan \\phi$\n\n$\\tan \\phi_{br} = \\frac{n_2}{n_1} = n_{21}$\n\nСоответствующий угол падения называют углом Брюстера.\n\nСтепень поляризации преломленной волны при угле падения, равном углу Брюстера,\nдостигает максимального значения, однако эта волна остается лишь частично поляризованной со\nстепенью поляризации:\n\n$P = \\frac{(n^2 - 1)^2}{2 (n^2 + 1)^2 - (n^2 - 1)^2}$\n\nДля границы воздух–стекло степень поляризации прошедшего света всего 8%. Повысить ее\nможно путем ряда последовательных отражений и преломлений. Это осуществляют с помощью так\nназываемой стопы Столетова, состоящей из нескольких одинаковых и параллельных друг другу\nпластинок, установленных под углом Брюстера к падающему свету\n\n## Цель работы \nИсследование характера поляризации лазерного излучения и\nэкспериментальная проверка законов Малюса и Брюстера.\n\n## Рабочие формулы и исходные данные\n\n### Формулы\n\n$P = \\frac{I_{max} - I_{min}}{I_{max} + I_{min}}$\n\n$I_{отн} = \\frac{I}{I_{max}}$\n\n$K_{\\parallel} = \\frac{I_{max}}{I_п}$\n\n$K_{\\bot} = \\frac{I_{min}}{I_п}$\n\n$\\tan \\phi_{br} = \\frac{n_2}{n_1} = n_{21}$\n\n$P = \\frac{(n^2 - 1)^2}{2 (n^2 + 1)^2 - (n^2 - 1)^2}$\n\n### Исходные данные\n\n$I_{o} = 1.505$ - относительная интенсивность лазера $I_{п}$, не ослабленная поляризатором\n\n$I^\\prime_{o} = 1.505$ - относительная интенсивность источника белого света, не ослабленная поляризатором\n\n$I^\\prime = 0.450$ - относительная интенсивность света, прошедшего через поляризатор\n\n$I_{max} = 0.568, I_{min} = 0.448$ - максимальное и минимальное значение интенсивности отраженного луча\n\n$\\phi_{br} = 59^{\\circ}$ - угол Брюстера\n\n\n\n## Схема установки \n\n\n1.\tВерхняя пластина\n\n2.\tСтойка с фильтрами\n\n3.\tЗащитный экран\n\n4.\tПоляризатор\n\n5.\tПоляризатор (аналог 4)\n\n6.\tБлок для измерения угла Брюстера\n\n7.\tАнализатор (аналог 4)\n\n8.\tСтойка\n\n9.\tВертикальная шкала\n\n10.\tОснование установки\n\n11.\tЭлектронный блок\n\n12.\tИндикатор измерений блока амперметра-вольтметра\n\n13.\tИндикатор режима измерений блока амперметра-вольтметра\n\n14.\tИндикатор включенного источника\n\n15.\tРегулятор накала белого осветителя\n\n16.\tКнопка переключения режима измерений блока амперметр-вольтметр\n\n17.\tКнопка включения лазера\n\n18.\tРучка установки относительной интенсивности «J/J0»\n\n19.\tКнопка переключения фотоприёмников\n\n20.\tИндикатор относительной интенсивности излучения;\n\n21.\tИндикатор включенного фотоприёмника\n\n22.\tКнопка “Сеть’\n\n23.\tОкно фотоприёмников белого осветителя\n\n24.\tОкно фотоприёмника лазерного излучения\n\n\n```python\nimport sympy\nimport scipy\nimport numpy as np\nimport pandas as pd\nfrom scipy.signal import argrelextrema\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (10,5)\n%matplotlib inline\n```\n\n## Результаты измерений и расчеты\n**Упражнение 1. Проверка Закона Малюса**\n\n$I_{o} = 1.505$ - относительная интенсивность лазера $I_{п}$, не ослабленная поляризатором\n\n$I^\\prime_{o} = 1.505$ - относительная интенсивность источника белого света, не ослабленная поляризатором\n\n$I^\\prime = 0.450$ - относительная интенсивность света, прошедшего через поляризатор\n\n**Излучение лазера**\n\n\n```python\nI_o = 1.505\nI_o_prime = 1.505\nI_prime = 0.450\n\nlazer_df = pd.DataFrame({\n '$\\phi$, градусы': [i * 10 for i in range(16)],\n '$I_1$': [0.826, 0.776, 0.671, 0.604, 0.469, 0.321, 0.206, 0.107, \n 0.036, 0.003, 0.018, 0.069, 0.176, 0.274, 0.405, 0.495],\n '$I_2$': [0.835, 0.768, 0.703, 0.6, 0.479, 0.316, 0.192, 0.11, \n 0.029, 0.004, 0.011, 0.076, 0.145, 0.263, 0.353, 0.513],\n})\n\nlazer_df['$I_{mean}$'] = (lazer_df['$I_1$'] + lazer_df['$I_2$']) / 2\n\nlazer_df\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 \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
    $\\phi$, градусы$I_1$$I_2$$I_{mean}$
    000.8260.8350.8305
    1100.7760.7680.7720
    2200.6710.7030.6870
    3300.6040.6000.6020
    4400.4690.4790.4740
    5500.3210.3160.3185
    6600.2060.1920.1990
    7700.1070.1100.1085
    8800.0360.0290.0325
    9900.0030.0040.0035
    101000.0180.0110.0145
    111100.0690.0760.0725
    121200.1760.1450.1605
    131300.2740.2630.2685
    141400.4050.3530.3790
    151500.4950.5130.5040
    \n
    \n\n\n\nгду $\\alpha$ - угол поворота анализатора, $I_1$ и $I_2$ - интенсивности луча, прошедшего\nчерез анализатор для двух экспериментов. \n$I_{mean}$ - среднее значение двух экспериментов. \n\n\n```python\ndef polarization_degree(i_max, i_min):\n degree = (i_max - i_min) / (i_max + i_min)\n return degree\n```\n\n\n```python\nprint('Степень поляризации лазерного излучения: {:.3f}'.format(polarization_degree(\n max(lazer_df['$I_{mean}$']), min(lazer_df['$I_{mean}$']))))\n```\n\n Степень поляризации лазерного излучения: 0.992\n\n\n**Найдем максимальную интенсивнность, чтобы в дальнейшем получить относителные интенсивности.**\n\n\n```python\nI_max = max(max(lazer_df['$I_1$']), max(lazer_df['$I_2$']))\nprint('I max: {}'.format(I_max))\n\nI_min = min(min(lazer_df['$I_1$']), min(lazer_df['$I_2$']))\nprint('I min: {}'.format(I_min))\n\nphi_max = 0\nprint('Phi max: {}'.format(phi_max))\n```\n\n I max: 0.835\n I min: 0.003\n Phi max: 0\n\n\n**Построим таблицу с относительными значениями:**\n\n\n```python\nlazer_rel_df = pd.DataFrame({\n '$\\phi$, градусы': [i * 10 for i in range(16)]\n})\n\nlazer_rel_df['$I_{rel1}$'] = lazer_df['$I_1$'] / I_max\nlazer_rel_df['$I_{rel2}$'] = lazer_df['$I_2$'] / I_max\nlazer_rel_df['$I_{rel}$'] = (lazer_rel_df['$I_{rel1}$'] + lazer_rel_df['$I_{rel2}$']) / 2\n\nlazer_rel_df\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 \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
    $\\phi$, градусы$I_{rel1}$$I_{rel2}$$I_{rel}$
    000.9892221.0000000.994611
    1100.9293410.9197600.924551
    2200.8035930.8419160.822754
    3300.7233530.7185630.720958
    4400.5616770.5736530.567665
    5500.3844310.3784430.381437
    6600.2467070.2299400.238323
    7700.1281440.1317370.129940
    8800.0431140.0347310.038922
    9900.0035930.0047900.004192
    101000.0215570.0131740.017365
    111100.0826350.0910180.086826
    121200.2107780.1736530.192216
    131300.3281440.3149700.321557
    141400.4850300.4227540.453892
    151500.5928140.6143710.603593
    \n
    \n\n\n\n**Построение графика зависимости нормированной интенсивности $I_{отн}$ от угла $\\phi$ поворота\nполяроида в полярных координатах; графика зависимости $\\cos^2(\\phi - \\phi_m)$ от угла $\\phi$ поворота поляроида**\n\n\n```python\nfig, ax = plt.subplots(figsize=(20, 5))\nax.set_title('Зависимость нормированной интенсивности от угла поворота')\n\nax.scatter(lazer_rel_df['$\\phi$, градусы'], lazer_rel_df['$I_{rel}$'], c='r')\nax.plot(lazer_rel_df['$\\phi$, градусы'], lazer_rel_df['$I_{rel}$'], 'r--', label='$I_{отн}$')\n\nax.scatter(lazer_rel_df['$\\phi$, градусы'], (np.cos((lazer_rel_df['$\\phi$, градусы'] - phi_max)* np.pi / 180)) ** 2, c='b')\nax.plot(lazer_rel_df['$\\phi$, градусы'], (np.cos((lazer_rel_df['$\\phi$, градусы'] - phi_max)* np.pi / 180)) ** 2, 'b--', label='$\\cos^2(\\phi - \\phi_m)$')\n\nax.legend()\n\nplt.show()\n```\n\n**Исходя из графика выше, поскольку относительная интенсивность лазерного излучения очень похожа на график $\\cos^2(\\phi - \\phi_m)$, можно утверждать, что лазерное излучение обладает линейным видом поляризации**\n\n**Найдем коэффициенты пропускания использованного поляроида для параллельной и\nперпендикулярной ориентации его плоскости пропускания**\n\n\n```python\nK_parallel = I_max / I_o\nK_bot = I_min / I_o\n\nprint('Коэффициенты: K parallel: {:.5f}, K_bot: {:.5f}'.format(K_parallel, K_bot))\n```\n\n Коэффициенты: K parallel: 0.55482, K_bot: 0.00199\n\n\n**Излучение белого света**\n\n\n```python\nlight_df = pd.DataFrame({\n '$\\phi$, градусы': [i * 10 for i in range(16)],\n '$I_1$': [0.45, 0.465, 0.478, 0.493, 0.486, 0.56, 0.49, 0.485, \n 0.483, 0.475, 0.473, 0.483, 0.49, 0.51, 0.522, 0.528],\n '$I_2$': [0.491, 0.48, 0.48, 0.482, 0.486, 0.465, 0.475, 0.466, \n 0.464, 0.46, 0.468, 0.456, 0.474, 0.491, 0.514, 0.503],\n})\n\nlight_df['$I_{mean}$'] = (light_df['$I_1$'] + light_df['$I_2$']) / 2\n\nlight_df\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 \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
    $\\phi$, градусы$I_1$$I_2$$I_{mean}$
    000.4500.4910.4705
    1100.4650.4800.4725
    2200.4780.4800.4790
    3300.4930.4820.4875
    4400.4860.4860.4860
    5500.5600.4650.5125
    6600.4900.4750.4825
    7700.4850.4660.4755
    8800.4830.4640.4735
    9900.4750.4600.4675
    101000.4730.4680.4705
    111100.4830.4560.4695
    121200.4900.4740.4820
    131300.5100.4910.5005
    141400.5220.5140.5180
    151500.5280.5030.5155
    \n
    \n\n\n\nгду $\\alpha$ - угол поворота анализатора, $I_1$ и $I_2$ - интенсивности луча белого света, прошедшего через анализатор для двух экспериментов. $I_{mean}$ - среднее значение двух экспериментов. \n\n\n```python\nprint('Степень поляризации излучения белого света: {:.3f}'.format(polarization_degree(\n max(light_df['$I_{mean}$']), min(light_df['$I_{mean}$']))))\n```\n\n Степень поляризации излучения белого света: 0.051\n\n\n**Построение зависимости $\\frac{I}{I^{\\prime}}(\\phi)$ для белого света**\n\n\n```python\nfig, ax = plt.subplots(figsize=(20, 5))\nax.set_title('Зависимость нормированной интенсивности от угла поворота')\n\nax.scatter(lazer_rel_df['$\\phi$, градусы'], lazer_rel_df['$I_{rel}$'], c='r')\nax.plot(lazer_rel_df['$\\phi$, градусы'], lazer_rel_df['$I_{rel}$'], 'r--', label='$I_{отн}$')\n\nax.scatter(light_df['$\\phi$, градусы'], light_df['$I_{mean}$'] / I_prime, c='g')\nax.plot(light_df['$\\phi$, градусы'], light_df['$I_{mean}$'] / I_prime, 'g--', label='$I / I^{\\prime} (\\phi)$')\n\n\nax.scatter(lazer_rel_df['$\\phi$, градусы'], (np.cos((lazer_rel_df['$\\phi$, градусы'] - phi_max)* np.pi / 180)) ** 2, c='b')\nax.plot(lazer_rel_df['$\\phi$, градусы'], (np.cos((lazer_rel_df['$\\phi$, градусы'] - phi_max)* np.pi / 180)) ** 2, 'b--', label='$\\cos^2(\\phi - \\phi_m)$')\n\nax.legend()\n\nplt.show()\n```\n\n**Упражнение 2. Проверка Закона Брюстера** \n\n$I_{max} = 0.568, I_{min} = 0.448$ - максимальное и минимальное значение интенсивности отраженного луча\n\n$\\phi_{br} = 59^{\\circ}$ - угол Брюстера\n\n**Экспериментальные значения:**\n\n\n```python\ndf2 = pd.DataFrame({\n '$\\phi$, градусы': [i for i in range(30, 65, 2)],\n '$I_1$': [1.076, 1.073, 1.071, 1.066, 1.063, 1.061, 1.059, 1.055, 1.051, \n 1.046, 1.038, 1.028, 1.018, 1.006, 0.988, 0.972, 0.955, 0.926],\n '$I_2$': [1.069, 1.063, 1.061, 1.058, 1.057, 1.054, 1.054, 1.051, 1.041, \n 1.043, 1.04, 1.028, 1.014, 0.999, 0.986, 0.976, 0.958, 0.926]\n})\n\nphi_br = 59\ni_max = 0.568\ni_min = 0.448\n\ndf2\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 \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
    $\\phi$, градусы$I_1$$I_2$
    0301.0761.069
    1321.0731.063
    2341.0711.061
    3361.0661.058
    4381.0631.057
    5401.0611.054
    6421.0591.054
    7441.0551.051
    8461.0511.041
    9481.0461.043
    10501.0381.040
    11521.0281.028
    12541.0181.014
    13561.0060.999
    14580.9880.986
    15600.9720.976
    16620.9550.958
    17640.9260.926
    \n
    \n\n\n\nгду $\\phi$ - угол наклона стеклянной пластинки, $I_1$ и $I_2$ - интенсивность прошедшего света в прямом и обратном направлениях, соответственно. \n\n\n```python\nn_21 = np.tan(phi_br * np.pi / 180)\nprint('Показатель преломления второй среды относительно первой: {:.3f}'.format(n_21))\n```\n\n Показатель преломления второй среды относительно первой: 1.664\n\n\n\n```python\np1 = polarization_degree(max(max(df2['$I_1$']), max(df2['$I_2$'])), min(min(df2['$I_1$']), min(df2['$I_2$'])))\nprint('Cтепень поляризации света после прохождения его через пластинку: {:.3f}'.format(p1))\n```\n\n Cтепень поляризации света после прохождения его через пластинку: 0.075\n\n\n\n```python\ndef partial_polarization(n):\n degree = (n ** 2 - 1) ** 2 / (2 * (n ** 2 + 1) ** 2 - (n ** 2 - 1) ** 2)\n return degree\n```\n\n\n```python\nprint('Cтепень поляризации света после прохождения его через пластинку теоретическая: {:.3f}'.format(partial_polarization(n_21)))\n```\n\n Cтепень поляризации света после прохождения его через пластинку теоретическая: 0.124\n\n\n\n```python\np3 = polarization_degree(i_max, i_min)\nprint('Cтепень поляризации белого света после прохождения его через пластинку: {:.3f}'.format(p3))\n```\n\n Cтепень поляризации белого света после прохождения его через пластинку: 0.118\n\n\n## Выводы и анализ результатов работы\nВ данной лабораторной работе были рассмотрены поляризация света, а также законы Малюса и Брюстера. \n\nВ первой части работы было предложено проверить закон Малюса для лазера и белого света. Поскольку графики квадрата косинуса и нормированная интенсивность лазерного излучения совпали, то можно утверждать, что лазерное излучение обладает линейной поляризацией. Были найдены коэффициенты пропускания использованного поляроида для параллельной и перпендикулярной ориентации его плоскости пропускания. Также было рассмотрено и излучение белого света: его степень поляризованности получилась меньше, поскольку изначально свет неполяризован; однако и для белого света верно, что пройдя через поляризатор, он стал линейно поляризован.\n\nВо второй части работы был вычислен показатель преломления среды по найденному углу Брюстера $n_{21} = 1.664, \\phi_{br} = 59^{\\circ}$. Были получены три числа для степени поляризации белого света через пластинкку: два экспериментальных и одно теоретическое. Эти три числа соотносятся друг с другом в пределах погрешности. \n", "meta": {"hexsha": "e39c320f9b1550342ac7c19d386f66279dcd6ba6", "size": 130983, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lab4.10/report.ipynb", "max_stars_repo_name": "sevakon/physics-labs", "max_stars_repo_head_hexsha": "2dfe206b13b41d96210f6bcf40def32e6748eceb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-05T16:45:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-28T22:34:35.000Z", "max_issues_repo_path": "lab4.10/report.ipynb", "max_issues_repo_name": "sevakon/physics-labs", "max_issues_repo_head_hexsha": "2dfe206b13b41d96210f6bcf40def32e6748eceb", "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": "lab4.10/report.ipynb", "max_forks_repo_name": "sevakon/physics-labs", "max_forks_repo_head_hexsha": "2dfe206b13b41d96210f6bcf40def32e6748eceb", "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": 100.2932618683, "max_line_length": 49728, "alphanum_fraction": 0.7932785171, "converted": true, "num_tokens": 10055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.13846178879140303, "lm_q1q2_score": 0.055358634956457806}} {"text": "\n \n \n \n \n \n\n\nPaul Maria Scheikl - Health Robotics and Automation (HERA) - Karlsruhe Institute of Technology (KIT)\n\n# Real World Example: Classifying Pigmented Lesions\nTo build an example that is more relevant to the medical field, we will now build a complete training pipeline for classifying pigment leasions in the [Skin Cancer MNIST dataset](https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000).\n\nThe dataset consists of 10015 images that show cropped images of pigmented lesions and are annotated with a diagnostic case label.\n\n\n\"*Cases include a representative collection of all important diagnostic categories in the realm of pigmented lesions: Actinic keratoses and intraepithelial carcinoma / Bowen's disease (akiec), basal cell carcinoma (bcc), benign keratosis-like lesions (solar lentigines / seborrheic keratoses and lichen-planus like keratoses, bkl), dermatofibroma (df), melanoma (mel), melanocytic nevi (nv) and vascular lesions (angiomas, angiokeratomas, pyogenic granulomas and hemorrhage, vasc).*\" [\\[ref\\]](https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000)\n\n\n \n \n \n
    \n \n \n
    \n\n\n## Data preparation\nWe have already prepared a function that reads the image file paths from a folder, as well as the labels that are stored in the csv file. The function returns a [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) which acts as in iterator, so we can use it to generate mini batches of data for our training loop. The images used for training are further scaled down to half resolution.\n\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom livelossplot import PlotLosses\nfrom pathlib import Path\nfrom tqdm.notebook import tqdm\nfrom copy import deepcopy\nfrom matplotlib import rcParams\nfrom torchsummary import summary\n\nfrom utils.data import load_dataset\nfrom utils.data import CaseTypes\n\nimage_dir = Path(\"data\") / Path(\"skin\") / Path(\"images\")\nmetadata_csv = Path(\"data\") / Path(\"skin\") / Path(\"metadata.csv\")\n\n# Network training using the GPU -> cuda or CPU -> cpu\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n# Whether to save the trained model as a file\nsave_model = False\nmodel_save_path = Path(\"models\") / Path(\"skin_cancer_prediction_model.pkl\")\n```\n\nIn contrast to our simple sine function example, we will not hold the complete data for training in memory and predict the model outputs of the complete data (called batch gradient descent).\nIn this case we will use mini batch gradient descent and calculate the gradients on mini batches of size *32* (one input to the model consists of 32 examples).\nThe gradient with regard to our loss function will be not as accurate, compared to using the complete dataset, but computation will be much faster.\n\nAlso note, that we split up the data into three separate datasets, that do not share data points.\nIn our sine example, we wanted the model to match the data as best as possible, basically memorizing the data.\nIn this case, however, we do not want the model to memorize the datapoints, otherwise we could not use it on new data. This problem of memorizing data is called [**overfitting**](https://en.wikipedia.org/wiki/Overfitting) and happens when the model has so much capacity, that it begins to interpolate the data as training goes on, rather than learning the underlying distribution of the data.\n\n
    \n \n
    [ref]\n
    \n\nWe address this problem by reserving a certain amount of data for training, another set of data points for evaluating how well the model generalizes on unseen data to stop the training before overfitting occurs, and finally the rest of the data to test the final performance of the model.\n\n* **Training Dataset**: The sample of data used to fit the model.\n* **Validation Dataset**: The sample of data used to provide an unbiased evaluation of a model fit on the training dataset while tuning model hyperparameters.\n* **Test Dataset**: The sample of data used to provide an unbiased evaluation of a final model fit on the training dataset. [ref](https://machinelearningmastery.com/difference-test-validation-datasets/)\n\n\n
    \nQuestion: Why do we need separate evaluation and testing data?\n

    \n\nBecause the evaluation results of the validation dataset will be biased towards our hyperparameter choices, because we used this data to select them.\n\n

    \n
    \n \n\n## Data Normalization\nAnother step to prepare our image dataset for the machine learning part is normalizing the data.\n\n*Data normalization is an important step which ensures that each input parameter (pixel, in this case) has a similar data distribution. This makes convergence faster while training the network. Data normalization is done by subtracting the mean from each pixel and then dividing the result by the standard deviation. The distribution of such data would resemble a Gaussian curve centered at zero.* [ref](https://becominghuman.ai/image-data-pre-processing-for-neural-networks-498289068258)\n\nWe could calculate the mean and standard deviation on a single image, but this would lead to very different data distributions on a per image basis. Imaging our dataset contains images that are either completely black or completely white. Normalizing each image independently will lead to images that are all the same.\nThis is why we have to calculate our values for mean and standard deviation of the complete dataset.\nFor RGB images, it is common to calculate mean and standard deviation for each color channel independently, so we will get three mean values and three standard deviations.\n\nFirst, lets look at some of the images in the dataset.\n\n\n```python\n# create a data loader\nimage_shape = (225, 300)\ndata_loader = load_dataset(\n image_dir,\n metadata_csv,\n batch_size=100,\n resize_image_shape=image_shape,\n do_shuffle=False,\n single_loader=True,\n num_workers=8,\n)\n\nindices = np.random.choice(list(range(len(data_loader.dataset))), 8)\nimages = [np.moveaxis(deepcopy(data_loader.dataset[i][0].numpy()), 0, -1) for i in indices]\nlabels = [data_loader.dataset[i][1] for i in indices]\ntitles = []\nfor label in labels:\n for case in CaseTypes:\n if case.id == label:\n titles.append(case.description)\n else:\n pass\n\n%matplotlib inline\n\n# figure size in inches optional\nrcParams['figure.figsize'] = 18 ,10\n\n# display images\nfig, axes = plt.subplots(4,2)\naxes = axes.flatten()\nfor i in range(8):\n axes[i].imshow(images[i]);\n axes[i].set_title(titles[i], wrap=True)\n axes[i].set_xticks([])\n axes[i].set_yticks([])\n```\n\nAs you can see, there is little contrast in the images and they are all in all mostly red.\n\n\n```python\n# placeholders for temporary values we need to calculate mead and standard deviation\npixel_sum = torch.tensor([0.0, 0.0, 0.0])\npixel_sum_squared = torch.tensor([0.0, 0.0, 0.0])\n\n# loop through the image batches in the data loader\nfor image_batch, _ in tqdm(data_loader, desc=\"Calculating...\"):\n pixel_sum += image_batch.sum(axis=[0, 2, 3])\n pixel_sum_squared += (image_batch ** 2).sum(axis=[0, 2, 3])\n\n# number of pixel in the dataset\nnum_images = len(data_loader.dataset)\ncount = num_images * image_shape[0] * image_shape[1]\n\n# mean and std\nmean = pixel_sum / count\nvar = (pixel_sum_squared / count) - (mean ** 2)\nstd = torch.sqrt(var)\n\nprint(f\"Mean: {mean.numpy()}\\nStandard Deviation: {std.numpy()}\")\n```\n\n\n Calculating...: 0%| | 0/101 [00:00.\n [HERA INFO]: Images will be normalized with:\n mean: [0.7635213 0.546128 0.57053053] and\n std: [0.1408046 0.15247564 0.1698052 ].\n [HERA INFO]: Created three DataLoaders from DataSet with batch size 32.\n [HERA INFO]: There are 7010, 1502, and 1503 data points for training, validating, and testing, respectively.\n [HERA INFO]: The image shape is (225, 300)\n [HERA INFO]: Datapoints will be shuffled after a full pass.\n\n\n## Convolutional Neural Network\nAs we have seen in the introduction, MLPs are not suited to work on images.\nWe will use a CNN as the model to classify the images.\nFor this, we will create a new class called CNN, based on a pytorch nn.Module, that consists of 4 convolutional layers, each with ReLU activation functions, a max pooling layer to reduce the feature size without introducing additional learnable parameters, and finally two additional fully connected layers.\nThe output of the last layer will be passed to a LogSoftmax function that generates log-likelihoods for each of the seven possible cases labels in the dataset.\n$$\n\\text{LogSoftmax}(x_{i}) = \\log\\left(\\frac{\\exp(x_i) }{ \\sum_j \\exp(x_j)} \\right)\n$$\n\n\n```python\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = nn.Conv2d(3, 16, 3, 2)\n self.conv2 = nn.Conv2d(16, 32, 3, 2)\n self.conv3 = nn.Conv2d(32, 64, 3, 2)\n self.conv4 = nn.Conv2d(64, 128, 3, 2)\n self.fc1 = nn.Linear(6144, 128)\n self.fc2 = nn.Linear(128, 7)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = self.conv3(x)\n x = F.relu(x)\n x = self.conv4(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\ncnn_model = CNN().to(device)\nsummary(cnn_model, (3, 225, 300))\n```\n\n ----------------------------------------------------------------\n Layer (type) Output Shape Param #\n ================================================================\n Conv2d-1 [-1, 16, 112, 149] 448\n Conv2d-2 [-1, 32, 55, 74] 4,640\n Conv2d-3 [-1, 64, 27, 36] 18,496\n Conv2d-4 [-1, 128, 13, 17] 73,856\n Linear-5 [-1, 128] 786,560\n Linear-6 [-1, 7] 903\n ================================================================\n Total params: 884,903\n Trainable params: 884,903\n Non-trainable params: 0\n ----------------------------------------------------------------\n Input size (MB): 0.77\n Forward/backward pass size (MB): 3.72\n Params size (MB): 3.38\n Estimated Total Size (MB): 7.87\n ----------------------------------------------------------------\n\n\n
    \n \n
    \n\nAs you can see, the majority of trainable parameters is part of the fully connected layers.\nWe could prevent this by introducing more convolutional layers or pooling layers to reduce the dimensionality.\nFor now, this will do.\n\n## Hyperparameters for the Training\nThe training loop for this example will also be a bit more complex that the initial sine example.\n\n### Loss Function\nThe output of our network is a list with seven elements.\nThe value of element n represents the log-likelihood of the image belonging to class n.\nSo if the image belongs to class 3 (beginning from 0), we want the neural network's output list to have its maximum value at index 3.\nThe loss function that quantifies the distance between the output of the neural network and the ground truth list of log-likelihoods in a classification problem with multiple classes is the negative log-likelihood loss (NLLLOSS).\n\nNegative log-likelihood loss is the same as cross entropy loss (aka logistic loss or multinomial logistic loss), with the difference, that our model already outputs the log probalities for each class.\n\n$$\n\\text{CrossEntropyLoss}(x, label) = -\\log\\left(\\frac{\\exp(x[label])}{\\sum_j \\exp(x[j])}\\right)\n$$\n\nSo the negative log-likelihood loss reduces to\n$$\n\\text{NLLLOSS}(prediction, label) = -prediction[label]\n$$\nwhere prediction is the list of log-likelihoods, produced by the neural network.\n\n\n\n```python\nloss_function = nn.NLLLoss().to(device)\n```\n\n\n```python\nwith torch.no_grad():\n images, labels = next(iter(data_loader))\n prediction = cnn_model(images.to(device))\n print(\"Log-likelihoods for one image: \", prediction[0].cpu())\n print(\"Ground truth label: \", labels[0])\n print(\"NLLLoss: \", loss_function(prediction[0].unsqueeze(0), labels[0].unsqueeze(0).to(device)).cpu())\n```\n\n Log-likelihoods for one image: tensor([-1.9646, -1.8996, -1.9267, -1.9468, -1.9996, -1.9540, -1.9331])\n Ground truth label: tensor(4)\n NLLLoss: tensor(1.9996)\n\n\n### Optimizer\nAt this point, we have a neural network and a loss function.\nThe next step is defining an optimizer that adapts the neural network parameters to minimize the loss over our training data.\n\nIn the last notebook, we used the SGD optimizer. In this notebook, we will use a more sofisticated optimizer: Adaptive Moment Estimation (Adam).\nIn contrast to SGD, Adam *remembers* previous gradients for each parameter, and adapts the parameter specific learning rates accordingly. \n\nThe update Rule from SGD\n$$\n\\begin{align} \n\\begin{split} \n\\theta_{t+1} = \\theta_{t}-\\gamma\\nabla L(\\theta_{t})\n = \\theta_{t}-\\gamma g_{t}\n\\end{split} \n\\end{align}\n$$\n\nchanges to Adam's update rule\n$$\n\\begin{align} \n\\begin{split}\n\\theta_{t+1} = \\theta_{t} - \\dfrac{\\gamma}{\\sqrt{\\hat{v}_t} + \\epsilon} \\hat{m}_t\n\\end{split} \n\\end{align}\n$$\n\n$\\hat{m}_t$ and $\\hat{v}_t$ are bias-corrected first and second moment estimates that scale the learning rate.\n\nThe bias-corrected first and second moment are estimated through\n\n$$\n\\begin{align} \n\\begin{split} \n\\hat{m}_t &= \\dfrac{m_t}{1 - \\beta^t_1} \\\\ \n\\hat{v}_t &= \\dfrac{v_t}{1 - \\beta^t_2} \\end{split} \n\\end{align}\n$$\n\nwith\n\n$$\n\\begin{align} \n\\begin{split} \nm_t &= \\beta_1 m_{t-1} + (1 - \\beta_1) g_t \\\\ \nv_t &= \\beta_2 v_{t-1} + (1 - \\beta_2) g_t^2 \n\\end{split} \n\\end{align}\n$$\n\n$\\beta_1$, $\\beta_2$, and $\\epsilon$ are hyperparameters of the optimizer.\n\n\nThis leads to a dynamic behavior of the optimizer that resembles a heavy ball, rolling down a curved slope under friction.\n\n
    \n \n
    [ref]\n
    \n\n\n\n\n```python\n# Learning rate for the optimizer\nlearning_rate = 0.00001\n\noptimizer = torch.optim.Adam(cnn_model.parameters(), lr=learning_rate)\n# test what happens when you use a different optimizer such as \n# optimizer = torch.optim.SGD(cnn_model.parameters(), lr=learning_rate*100, momentum=0.9)\n```\n\n### Early Stopping\nInstead of training a fixed amount of epoch, we will use a technique called early stopping, to interrrupt the training at the right time.\nWe set the maximum number of epochs to a high value and also specify an early stopping patience.\nThe early stopping patients will interrupt the training, once the validation loss has not decreased in the last n epochs. This way, we can pinpoint the epoch where our model is likely to have learned the most, without overfitting too much.\n\n
    \n \n
    [ref]\n
    \n \n\n\n```python\n# How many complete dataset passes to train\nepochs = 200\n\n# How many epochs of not decreasing validation loss to wait before stopping the training\nearly_stop_patience = 20\n```\n\n### Learning Rate Scheduler\nIf the learning rate of our scheduler is too large, we are likely to *miss* the optimum in parameter space by taking steps that are too big. If the learning rate is too small, however, training may take too long. \n\n
    \n \n
    [ref]\n
    \n \nA learning rate scheduler will take an initial learning rate and adapt the learning rate during training, based on a performance metric. In this example, we will start with a *high* learning rate, and use a scheduler, that decreases the learning rate, when the training loss plateaus. The scheduler uses a patience parameter to decide whether it is time to decrease the learning rate, similar to early stopping. \n\n \n
    \nQuestion: But isn't Adam taking care of the learning rate?\n

    \n\n Correct! In practice, though, reducing the fixed part of the learning rate sometimes helps to descend faster into a minimum.\n\n

    \n
    \n\n\n```python\n# Parameters for the learning rate scheduler:\n\n# How many epochs of not decreasing training loss to wait, before decreasing the learning rate\nlr_scheduler_patience = 8\n\n# Factor by which the learning rate will be reduced. new_lr : lr * factor.\nlr_factor = 0.1\n\nlr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer,\n verbose=True,\n factor=lr_factor,\n patience=lr_scheduler_patience\n)\n```\n\n### Initial Performance\nLet's test the initial performance of our model without any training.\n\n\n```python\nimport ipywidgets as widgets\nfrom ipywidgets import Layout\nfrom utils.training import evaluate, get_lr\n\nstart_train_bar_widget = widgets.IntProgress(\n value=0,\n min=0,\n max=len(train_data_loader),\n description='Calculating initial training loss:',\n bar_style='info', # 'success', 'info', 'warning', 'danger' or ''\n style={'bar_color': 'green', 'description_width': 'initial'},\n orientation='horizontal'\n)\n\nstart_val_bar_widget = widgets.IntProgress(\n value=0,\n min=0,\n max=len(val_data_loader),\n description='Calculating initial validation loss and accuracy:',\n bar_style='info', # 'success', 'info', 'warning', 'danger' or ''\n style={'bar_color': 'green', 'description_width': 'initial'},\n orientation='horizontal'\n)\ninitial_hbox = widgets.HBox(children=(start_train_bar_widget,start_val_bar_widget))\n\ndisplay(initial_hbox)\ninitial_train_loss, _ = evaluate(\n cnn_model=cnn_model,\n device=device,\n iterator=train_data_loader,\n criterion=loss_function,\n progress_bar=start_train_bar_widget,\n )\n\ninitial_val_loss, initial_val_acc = evaluate(\n cnn_model=cnn_model,\n device=device,\n iterator=val_data_loader,\n criterion=loss_function,\n progress_bar=start_val_bar_widget,\n )\n\nprint(\"Initial training loss: \", initial_train_loss)\nprint(\"Initial validation loss: \", initial_val_loss)\nprint(\"Initial accuracy: \", initial_val_acc)\n```\n\n\n HBox(children=(IntProgress(value=0, bar_style='info', description='Calculating initial training loss:', max=22…\n\n\n Initial training loss: 0.06110729373652827\n Initial validation loss: 0.061130413111854104\n Initial accuracy: 0.05452127659574468\n\n\n\n```python\nstyle = {'description_width': 'initial'}\n\nepoch_widget = widgets.Text(\n value=f'{0}/{epochs}',\n description='Epoch:',\n style=style,\n disabled=True\n)\n\nearly_stopping_widget = widgets.Text(\n value=f'{0}/{early_stop_patience}',\n description='Early Stopping Patience:',\n style=style,\n disabled=True,\n)\n\nlearning_rate_widget = widgets.FloatText(\n value=learning_rate,\n description='Learning Rate:',\n style=style,\n disabled=True,\n)\n\nlearning_rate_patience_widget = widgets.Text(\n value=f'{0}/{lr_scheduler_patience}',\n description='Learning Rate Patience:',\n style=style,\n disabled=True,\n)\n\ntrain_loss_widget = widgets.FloatText(\n value=initial_train_loss,\n description='Training Loss:',\n style=style,\n disabled=True,\n)\nval_loss_widget = widgets.FloatText(\n value=initial_val_loss,\n description='Validation Loss:',\n style=style,\n disabled=True\n)\nval_acc_widget = widgets.FloatText(\n value=initial_val_acc,\n description='Validation Accuracy:',\n style=style,\n disabled=True\n)\n\ntrain_bar_widget = widgets.IntProgress(\n value=0,\n min=0,\n max=len(train_data_loader),\n description='Training one epoch:',\n bar_style='info', # 'success', 'info', 'warning', 'danger' or ''\n style={'bar_color': 'green', 'description_width': 'initial'},\n orientation='horizontal'\n)\n\nval_bar_widget = widgets.IntProgress(\n value=0,\n min=0,\n max=len(val_data_loader),\n description='Validation:',\n bar_style='info', # 'success', 'info', 'warning', 'danger' or ''\n style={'bar_color': 'green', 'description_width': 'initial'},\n orientation='horizontal'\n)\n\nprogress_hbox = widgets.HBox(children=(epoch_widget,early_stopping_widget))\nlearning_rate_hbox = widgets.HBox(children=(learning_rate_widget, learning_rate_patience_widget))\nloss_hbox = widgets.HBox(children=(train_loss_widget, val_loss_widget,val_acc_widget))\nbar_hbox = widgets.HBox(children=(train_bar_widget, val_bar_widget))\n\n\nvbox = widgets.VBox(children=(progress_hbox, learning_rate_hbox, loss_hbox, bar_hbox))\n```\n\n## Actual Training of the CNN\nThe training loop in this notebook is pretty much the same as in the initial notebook.\n\n### Train\n1. Compute the outputs of the neural network for each data point in the training set.\n2. Compute the loss between predicted outputs and ground truth.\n3. Clean up the buffer variables inside the optimizer.\n4. Compute the gradients from the loss function.\n5. Perform one step in the optimizer.\n\n### Validation\n1. Compute the outputs of the neural network for each data point in the validation set.\n2. Compute the loss between predicted outputs and ground truth.\n\n### Rest\n1. Adapt the learning rate with the learning rate scheduler, if necessary.\n2. Stop the training, if the early stopping rule applies.\n\n\n```python\n# def train(cnn_model, device, iterator, optimizer, criterion, progress_bar):\n```\n\n\n```python\nfrom utils.training import train\n\n# Initialization of the train loss and the validation loss which allow to memorize the best loss obtained.\n# best_valid_loss allows the early stopping function to work.\nbest_train_loss = float('Inf')\nbest_val_loss = float('Inf')\n\n# Initialization of the counter for early stopping.\nearly_stopping = 0\n\nliveloss = PlotLosses()\nlogs = {}\nlogs['loss'] = initial_train_loss\nlogs['val_loss'] = initial_val_loss\nlogs['accuracy'] = initial_val_acc\nliveloss.update(logs)\nliveloss.send()\n\nfor epoch in range(epochs):\n \n train_loss = train(\n cnn_model=cnn_model,\n device=device,\n iterator=train_data_loader,\n optimizer=optimizer,\n criterion=loss_function,\n progress_bar=train_bar_widget,\n )\n \n val_loss, val_acc = evaluate(\n cnn_model=cnn_model,\n device=device,\n iterator=val_data_loader,\n criterion=loss_function,\n progress_bar=val_bar_widget,\n )\n \n # Pass the validation loss to the learning rate scheduler to determine,\n # whether the learning rate should be reduced\n lr_scheduler.step(val_loss)\n \n logs['loss'] = train_loss\n logs['val_loss'] = val_loss\n logs['accuracy'] = val_acc\n\n liveloss.update(logs)\n liveloss.send()\n \n epoch_widget.value = f\"{epoch+1}/{epochs}\"\n train_loss_widget.value = train_loss\n val_loss_widget.value = val_loss\n val_acc_widget.value = val_acc\n\n # Backup of the best train loss achieved\n if train_loss < best_train_loss:\n best_train_loss = train_loss\n\n # Backup of the best validation loss achieved and save the model if the valid_loss has\n # decreased (valid_loss < best_valid_loss). If not decreased, +1 to early stopping counter.\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n if save_model:\n torch.save(cnn_model, model_save_path)\n early_stopping = 0\n best_model = deepcopy(cnn_model)\n else:\n early_stopping += 1\n \n early_stopping_widget.value = f\"{early_stopping}/{early_stop_patience}\"\n learning_rate_patience_widget.value = f\"{lr_scheduler.num_bad_epochs}/{lr_scheduler_patience}\"\n\n # Lr scheduler check if training loss has decreased and if\n # it hasn't after LR_scheduler_patience of epoch, lr = lr*lr_factor\n lr_scheduler.step(train_loss)\n \n learning_rate_widget.value = get_lr(optimizer)\n\n # Early stopping :\n if early_stopping > early_stop_patience:\n print(\"Early stopping\")\n break\n\n```\n\n\n```python\ndisplay(vbox)\n```\n\n\n VBox(children=(HBox(children=(Text(value='0/200', description='Epoch:', disabled=True, style=DescriptionStyle(…\n\n\n
    \nQuestion: Why is the validation loss lower than the training loss?\n

    \n\n Because the training loss is measured during each epoch while validation loss is measured after each epoch. So during validation, the model will already have new (updated) parameter values.\n\n

    \n
    \n
    \nQuestion: What can we do?\n

    \n\n Switch the order of validation and training.\n But remember, that it does not really matter.\n It is often easier to think \"what is the validation loss after my nth training epoch?\".\n\n

    \n
    \n
    \nQuestion: How can it be, that the accuracy does not change, even though the loss decreases?\n

    \n\n Ignoring the log function (only taking the Softmax), the output of the model will be a list of probabilities (values between 0 and 1, that sum to 1).\n The accuracy is determined, by comparing the ground truth label {0..6} with the predicted label by taking the argmax of this list (index of the maximum value in the list).\n The loss, on the other hand, will be the distance between each value of the list and the ground truth value.\n \n For a classification task with two classes:\n With a ground truth label of 1, so a value list of [0.0, 1.0], a change in predicted probabilities from [0.49, 0.51] to [0.1, 0.9] drastically decreases the loss, it will not decrease the predicted class.\n\n

    \n
    \n\n## Testing the Final Model Performance\nTo get the final model performance, we need to calculate the loss and accuracy on the test data set.\n\n\n```python\ntest_bar_widget = widgets.IntProgress(\n value=0,\n min=0,\n max=len(test_data_loader),\n description='Testing:',\n bar_style='info', # 'success', 'info', 'warning', 'danger' or ''\n style={'bar_color': 'green', 'description_width': 'initial'},\n orientation='horizontal'\n)\ndisplay(test_bar_widget)\n\ntest_loss, test_acc = evaluate(\n cnn_model=best_model,\n device=device,\n iterator=test_data_loader,\n criterion=loss_function,\n progress_bar=test_bar_widget,\n)\n\nprint(\"Final testing loss: \", test_loss)\nprint(\"Final testing accuracy: \", test_acc)\n```\n\n\n IntProgress(value=0, bar_style='info', description='Testing:', max=47, style=ProgressStyle(bar_color='green', …\n\n\n Final testing loss: 0.021463156618336414\n Final testing accuracy: 0.7420212765957447\n\n\n## What's next?\n* Instead of importing the training function (`from utils.training import train`), try to implement it yourself.\n* Change the CNN model and see how the training results change. You can find a list of possible additional building blocks [here](https://pytorch.org/docs/stable/nn.html#convolution-layers).\n* Also try to change the other hyper parameters to maximize the validation accuracy.\n* Try to convert the CNN into a fully convolutional architecture, by following the [conv layer formulas](https://cs231n.github.io/convolutional-networks/#conv)\n\n
      \n
    • Volume of size \\(W_1 \\times H_1 \\times D_1\\)
    • \n
    • Requires four hyperparameters:\n
        \n
      • Number of filters \\(K\\),
      • \n
      • their spatial extent \\(F\\),
      • \n
      • the stride \\(S\\),
      • \n
      • the amount of zero padding \\(P\\).
      • \n
      \n
    • \n
    • Produces a volume of size \\(W_2 \\times H_2 \\times D_2\\) where:\n
        \n
      • \\(W_2 = (W_1 - F + 2P)/S + 1\\)
      • \n
      • \\(H_2 = (H_1 - F + 2P)/S + 1\\) (i.e. width and height are computed equally by symmetry)
      • \n
      • \\(D_2 = K\\)
      • \n
      \n
    • \n
    \n\n and the [pytorch documentation](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d). \n", "meta": {"hexsha": "48d071599ea7ff50e495ff4eb24882d0768bbfd7", "size": 449340, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Skin Cancer Classification.ipynb", "max_stars_repo_name": "Health-Robotics-and-Automation-KIT/CURAC-Academy-2021", "max_stars_repo_head_hexsha": "a2f6103c5e3aec490c30f0c956c34255eab9a8e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-24T15:00:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T15:00:08.000Z", "max_issues_repo_path": "Skin Cancer Classification.ipynb", "max_issues_repo_name": "Health-Robotics-and-Automation-KIT/CURAC-Academy-2021", "max_issues_repo_head_hexsha": "a2f6103c5e3aec490c30f0c956c34255eab9a8e6", "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": "Skin Cancer Classification.ipynb", "max_forks_repo_name": "Health-Robotics-and-Automation-KIT/CURAC-Academy-2021", "max_forks_repo_head_hexsha": "a2f6103c5e3aec490c30f0c956c34255eab9a8e6", "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": 396.9434628975, "max_line_length": 361108, "alphanum_fraction": 0.9305269951, "converted": true, "num_tokens": 7241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11596072436426733, "lm_q1q2_score": 0.05526452155461364}} {"text": "Geospatial Analysis & Visualization w/ Python\n\n# Step 0) Setup\n* To get started, we need to import all the packages we'll use.\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom matplotlib.collections import PatchCollection\n%matplotlib notebook\n\n\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"\"))\n```\n\n# Step 1) Importing our data\n* We'll load the Police Killing Data as a \"DataFrame\" using pandas\n\n\n* Then we'll convert it into a \"GeoDataFrame\" using Geopandas\n * To do this, we must assign the \"geometry\". In this case its point data, and the coordinates are in lat/long\n \n \n* Then we need to assign a Coordiante Reference System (CRS) manually\n * ESPG is a standardized code that is used to represent CRSs.\n * 'espg:4326' is for the refers to the WGS 1984 datum, which our latitude/longitude data is based in.\n * This is a CRS that is widely used by many web-based platforms because like Google Maps and Mapbox\n * The original only had addresses, not coordinates, so we used a webservice (Mapbox) to generate the coordinates of our addresses\n \n \n* Once we have the data loaded, calling .head() will give us a \"preview\" of our dataset\n\n\n```python\n# We import the Police Killings file, and set the incident ID as the index\npolice_Killings_Tabular = pd.read_csv('Data/PoliceKillings.csv',\n parse_dates=['date'],\n index_col=['id_incident']\n )\n\n# We can then convert the pandas dataframe into a geopandas \"GeodataFrame\"\npolice_Killings = gpd.GeoDataFrame(police_Killings_Tabular,\n geometry=gpd.points_from_xy(police_Killings_Tabular.longitude,\n police_Killings_Tabular.latitude\n )\n )\n\n# Now we can assign a CRS\nWGS_1984={'init' :'epsg:4326'}\npolice_Killings.crs = WGS_1984\n\n# Lets sort the incidents by date and then take a quick look.\npolice_Killings=police_Killings.sort_values(by='date')\npolice_Killings.head()\n```\n\n### Now we'll load some data from the 2016 Census\n\n* We have a tabular dataset of population data.\n\n* We'll load it using pandas\n\n\n```python\n# We'll import the tabualr census data with pandas\nCensus_Tabular = pd.read_csv('Data/Census.csv',index_col=['PRUID'])\nCensus_Tabular.head()\n```\n\n### We also have a provincial boundary shapefile\n\n* Shapefile are used to store georphric data. They already have projections and coordiantes associated with them.\n * Geopandas has similar functionality to pandas and we can use it to import shapefiles. But the read_file() method had less options, so we have to set the index manually.\n\n\n```python\n# We'll import provincial boundaries using geopandas\nProvincial_Boundaries = gpd.read_file('Data/Provincial_Boundaries.shp').set_index('PRUID')\nProvincial_Boundaries.head()\n```\n\n# Step 2) Joining our census data\n\n* This will let us map the disparity by province and do a more detailed analysis\n\n* PRUID is a \"unique identifier\" that represents the provinces.\n\n * Since both have the PRUID set as the index, we don't need to specify a join key.\n\n\n```python\nTest_Join = Provincial_Boundaries.join(Census_Tabular)\nTest_Join.head()\n```\n\n# But our join fails :(\n\n* ### Notice the NaN values.\n\n* NaN represetns missing data values\n * Lets look at the index for both files? Maybe we have a datatype missmatch?\n\n\n```python\nprint(Provincial_Boundaries.index.dtype)\nprint(Census_Tabular.index.dtype)\n```\n\n### Sure enough! The Provincial_Boundaries index is an \"object\", not an integer.\n\n* We can fix that easily and then do the join!\n * We just need to change the datatype of the Provincial_Boundaries layer.\n\n### We can assign the datatype using the .astype() function.\n\n### But datatype do we assign?\n* Hint The anser is in the cell above!!\n\n\n```python\ndtype = \nProvincial_Boundaries.index = Provincial_Boundaries.index.astype(dtype)\nProvincial_Data = Provincial_Boundaries.join(Census_Tabular)\nProvincial_Data.head()\n```\n\n# Step 3) Exploring the data\n\n### First lets make a quick map.\n\n* Our Layers need to be in the same coordinate system to match up properly on a map!\n\n* We can re-project the police_Killings layer using the .to_crs function to set the CRS to that of the Provinces\n * The provinces layer uses the Canada Lambert Conformal Conic projection (LCC). This is the standard projection used by stats canada and is ideally suited for displaying the whole of country.\n \n \n* Once both datasets are in the same coordinate system, we can make a map!\n\n\n* First we must define a plot, using the matplotlib.pyplot package. We imported this earlier as \"plt\"\n * We use the plt.subplots() to create a figure, and we can define how big we want it to be\n \n \n* Geoapandas can then use the .plot() fucntion to create a map using matplotlib.\n * We simply tell it what axis to draw the plot on with ax=\"axes\"\n * Then set a few other parameters:\n * We just want the provinces as a grey background so we can set the color\n * We want to classify killings by race, so we can set race as the column. THen we can add a legend to aid interpretation of the data\n\n\n```python\n# We can use .to_crs() to create a police killings layer with the same projection as the provinces layer.\npolice_Killings = police_Killings.to_crs(Provincial_Data.crs)\n\n# Now, we can create a figure using matplotlib (plt), first we define the figure and the size\nfig,axes=plt.subplots(\n figsize=(6,6)\n)\n\n# Now we can add the provinces using the .plot() function. We set the plotting axes and give it a grey color\ncb = Provincial_Data.plot(\n ax=axes,\n column='Total',\n cmap = 'Greys',\n edgecolor='grey',\n legend=True,\n)\n\n# Then we add the police_Killings_LCC. We'll set the column to 'race', so we can disply by race,\n# give the point markers a few more parameters, and add them to a legend\npolice_Killings.plot(\n ax=axes,\n column='race',\n edgecolor='k',\n markersize=15,\n legend=True,\n legend_kwds={'loc': 'upper right','fontsize':8}\n)\n```\n\n### And now you've made your first map with python!\n\n* But its an ugly map :(\n * It doesn't look great. This is just the quick and dirty way to look ata data\n * To make things more presentable, we'll have to be more explicit in setting up our map. But that's a task for later.\n\n\n### For now, lets move on and look at the dataset in more detail.\n\n* Pandas & Geopandas have some nice features to quickly summarize our dataset.\n\n\n\n* We can use .count() to get the total # incidents.\n * Callling .count() as is, will give us a list of all the columns, and a count for each. We can see most collumns are \"full\" but in the \"geocoding_Notes\" column, we can see that 4 points don't have coordinates associated with their address. This suggests there was an error in the data entry process. We don't need to worry about this though. \n\n\n```python\npolice_Killings.count()\n```\n\n* We can use .mean(), .min(), etc. followed by ['age'] to get some vital statistics on the age of victims.\n\n* We can use .describe() to summarize multiple attributes of the age column.\n\n\n```python\nprint('Age Distribution of Victims')\nprint()\nprint('Mean: ',\n police_Killings.mean()['age']\n )\nprint()\nprint('Standard Deviation: ',\n police_Killings.std()['age']\n )\nprint()\nprint('Youngest: ',\n police_Killings.max()['age']\n )\nprint()\nprint('Oldest: ',\n police_Killings.min()['age']\n )\n\npolice_Killings.describe()['age']\n```\n\n### We can resample our data to look for trends\n* The date column is a special type of data that allows us to resample our data by year, month, etc\n* The dataset has to be in order by date for this to work (we did this alread).\n\n\n```python\nResampled = police_Killings.set_index('date').resample('Y').count()\n\n## scipy can be used to calculate a linear regression line and print the results\nRegression_Line = stats.linregress(Resampled.index.year,Resampled['id_victim'])\nprint(Regression_Line)\n\nplt.figure(figsize=(6,6))\n\n## We can make a scatter plot of the annual killings\nplt.scatter(\n Resampled.index.year,\n Resampled['id_victim'],\n color='black',\n label='Yearly Total'\n)\n\n## Then plot he increasing trendline over it and add the slope and pvalue to the legend.\nplt.plot(\n Resampled.index.year,\n Resampled.index.year*Regression_Line[0]+Regression_Line[1],\n label='Trend Line: '+str(np.round(Regression_Line[0],3))+'\\np-value: '+str(np.round(Regression_Line[3],3)),\n color='red'\n )\n\nplt.legend()\nplt.title('Police Killings per Year in Canda')\n```\n\n### We can group our data to look for patterns too.\n\n* the .groupby() function can accept one or multple paramters to group our dataset by.\n * This allows us to create complex queries if we want.\n* We can have to follow up with .count(), .mean(), etc.\n * This tells us \"how\" to aggregate\n\n\n```python\nfig,ax = plt.subplots(figsize=(5,5))\n\n## This is a dictionary to set colors based on specific values. We're using Hex color codes here.\n## They're a common way for specifiying colors\nPie_Colors = {'None':'#FF0000',\n 'Knife':'#fecc5c',\n 'Firearm':'#ffffb2',\n 'Other weapons':'#fd8d3c'}\n\n## Group by the variable we want, summarize by count, then make our pie chart!\nArmed = police_Killings.groupby(['armed_type']).count()\nax.pie(\n Armed['id_victim'],\n labels=Armed.index,\n textprops={'fontsize': 8},\n colors=[Pie_Colors[i] for i in Armed.index],\n autopct='%1.1f%%',\n wedgeprops={\"edgecolor\":\"k\",'linewidth': 1, 'linestyle': 'dashed'}\n)\nax.set_title('Police Killings: Was the Victim Armed?')\nplt.tight_layout()\n```\n\n### Groupby allows us to create very complex queries if we want\n\n* We can search combinations of two or more variables\n\n* This retruns a record with two indexes: Department and armed type\n\n\n```python\nGroup = police_Killings.groupby(['Department','armed_type']).count()['id_victim']#.sort_values(ascending=True)\n\nprint(Group)\n```\n\n### What police departments kill the most unarmed people?\n\n* We can use the .loc command to do a search for all departments with more than one unarmed killing.\n\n* Then we sort the record, select the top 5, and plot them.\n\n\n```python\n## The unstack command allows us to turn the last index into our colum names\nForce=Group.unstack()\nForce['Total'] = Force.sum(axis=1)\nForce['Unarmed_Frac']=Force['None']/Force['Total']\n\n## .loc is the search function.\n## .sort_values() sorts our records in ascending order.\n## [-5:] grabs just the last five records\nForce = Force.loc[Force['None']>1].sort_values(by='None')[-5:]\nprint(Force)\n\nForce_Labels={'Toronto Police Service':'Toronto',\n 'RCMP':'RCMP',\n 'Vancouver Police Department':'Vancouver',\n 'Service de police de la Ville de Montreal':'Montreal',\n 'Edmonton Police Service':'Edmonton'}\n\nfig,ax=plt.subplots(figsize=(6,5))\n\nax.barh(Force.index,Force['None'],facecolor='#FF0000',edgecolor='black')\nax.set_yticklabels([Force_Labels[f] for f in Force.index.values])\nax.set_title('Unarmed Victims by Deparment (2000-2015)')\n```\n\n### We're intersted in a specific question. What's the distribution of police killings by race?\n\n\n\n```python\npolice_Killings.groupby(['race']).count()['date'].sort_values()\n```\n\n# Step 4) Normalizing our Data\n\n* The racial demographics of Canada aren't evenly split however!\n\n* We need to Normalize our data by population statistics.\n\n* Lets look at our census data again\n\n\n\n```python\nProvincial_Data[Census_Tabular.columns]\n```\n\n### The first row contains the total values for the whole country. We can use this to calculate a police killing rate.\n\n* But the Canadian Census' racial categories don't match up perfectly with the police violence dataset's racial\n* How can we work around this?\n * We have the largest three groups in the police killing set: White, Indigenous, and Black. So we can work with them as is\n * The other races make up a small portion of total killings. And we can't be entirely sure how the CBC defined their groupings. So, lets add a new category: \"Other Minorities\"\n \n* We'll do this for both the provincial boundaires and the police_Killings\n * For the police killings, we'll leave the unknow records alone\n\n\n```python\nOther_Minorities=['South Asian', 'Chinese', 'Filipino','Latin American',\n 'Arab', 'Southeast Asian', 'West Asian', 'Korean',\n'Japansese', 'Visible minority, n.i.e', 'Mixed']\nProvincial_Data['Other Minorities']=Provincial_Data[Other_Minorities].sum(axis=1)\n\nOther_Minorities=['Latin American', 'Arab', 'Other', 'South Asian', 'Asian']\npolice_Killings['race'] = police_Killings['race'].replace(to_replace=Other_Minorities,value='Other Minorities')\n\n```\n\n# From here, we can calculate the Police Killing Rate (PKR).\n\n* Dividing the total number of killings by the population gives us ...\n\n\n```python\nRaces = ['Indigenous','Black','Caucasian','Other Minorities']\nRace_Breakdown = police_Killings.groupby(['race']).count()['id_victim']\nCan_Pop = Provincial_Data[Races].sum()\n\nRacial_Rates = Race_Breakdown.T[Races]/Can_Pop\nRacial_Rates['CA. Average']=Race_Breakdown.T[Races].sum()/Can_Pop.sum()\nprint(Racial_Rates)\n# police_Killings.groupby(['race']).count()['date'].sort_values()\n```\n\n### This number isn't that meaningful though. It represents the number of killings \"per person\" over the whole study period.\n\n* Lets convert the rate to a more meaninful unit. Killings / Million Residents / Year\n\n* The date record is a \"date\" object.\n* It has some added functionality like being able to query the the year, month, day\n\n\n```python\nFirst_Year = police_Killings['date'].min().year\nLast_Year = police_Killings['date'].max().year\nprint(First_Year,Last_Year)\n```\n\n### How might we calculate our police killing rate?\n\n* What should we set as scale and duration to convert units?\n\n\n```python\nScale =\nDuration = \nrate_Conversion = Scale / Duration\n\nRacial_Rates=Racial_Rates.sort_values(ascending=True)\n\nfig, ax = plt.subplots(figsize = (5,5))\nax.barh(\n Racial_Rates.index,\n Racial_Rates.values * rate_Conversion,\n facecolor='#FF0000',\n edgecolor='black',\n linewidth=1\n)\nax.set_title('Police Killings Rates by Race in Canada')\nax.set_xlabel('Killings per Year per Million People')\nplt.tight_layout()\n```\n\n# The Police killing rates are 5x higher for Indigenous people and 4x higher for Black people than it is fo White people.\n\n* ## This is an abhorent example of systemic racism in Canadian Policing.\n\n\n# Lets look at the PKR by province.\nNow we want to normalize by provincial demographics.\n\n* We have a few more steps to go through first.\n * The police killings and census data use different abbreviations. To do a join our dataset with the census data we'll need to assign an new abbreviaton\n * We'll us a dictionary to do this\n \n \n* Then we can summarize the killings by province and join it to the Provinces_Join layer\n\n* Now we can summarize the killings by province and join it to the Provinces_Join layer\n\n\n* Note Prince Edward Island doesn't have any.\n\n\n```python\nrace_by_Province = police_Killings.groupby(['prov','race']).count()\nrace_by_Province = race_by_Province['date'].unstack()\nrace_by_Province['Total'] = race_by_Province.sum(axis=1)\n\nfor col in Races:\n Provincial_Data = Provincial_Data.join(race_by_Province[col],on='prov',rsuffix='_Killings')\n\nfor col in ['Unknown','Total']:\n Provincial_Data = Provincial_Data.join(race_by_Province[col],on='prov',rsuffix='_Killings')\nProvincial_Data\n\n# Some provines/groups don't have any records. Those are given NaN values, and need to be repalced with zeros\nProvincial_Data[[x+'_Killings' for x in Races]]=Provincial_Data[[x+'_Killings' for x in Races]].fillna(0)\nProvincial_Data['Total_Killings']=Provincial_Data['Total_Killings'].fillna(0)\nProvincial_Data[['Unknown' for x in Races]].fillna(0)\n\nProvincial_Data.head()\n```\n\n# Step 5) Calcualte and map the Police Killing Rate (PKR) on the provincial level\n* Nunavut has a huge problem. Its not a conicidence that the population is 75% Inuit.\n\n\n```python\nProvincial_Data['PKR']=(Provincial_Data['Total_Killings']/Provincial_Data['Total']*rate_Conversion)\n\nprint(Provincial_Data[['prov','PKR']].sort_values(by='PKR'))\n```\n\n### We can make a chloropleth map of this pattern.\n\n* Lets check out colorbrewer for help picking a good color scheme\n\nhttps://colorbrewer2.org/\n\n\n```python\n## We can define our own class break values, labels, and colors for the map\nbins = [-0.01,0.5,1,1.4,4,9]\nlabels = ['<0.5','0.5 - 1','1 - 1.3','3.1','7.7']\ncolors = ['#fee5d9','#fcae91','#fb6a4a','#de2d26','#FF0000']\n\n## We can use the labels and colors to create a color dictionary\nPKR_Color = {key:value for key,value in zip(labels,colors)}\n\n## The pd.cut() command will creat a new record for us containg class labels.\nProvincial_Data['PKR_Classes']=(pd.cut(Provincial_Data['PKR'],bins=bins,labels=labels)).astype('str')\n\n\nfig,ax=plt.subplots(figsize=(6,6))\n\n## To make a better map with geopandas, we have to loop through recrods and plot each class seprately\n## Then create a custom legend item for it.\n\nPatches=[]\nfor pkr_class in Provincial_Data['PKR_Classes'].unique():\n ## kwargs allows us to set multiple arguments for the plot and save them\n ## We can then used them in multiple commands\n kwargs = {'facecolor':PKR_Color[pkr_class],\n 'edgecolor':'k',\n 'label':pkr_class}\n \n Provincial_Data.loc[Provincial_Data['PKR_Classes']==pkr_class].plot(\n ax=ax,\n **kwargs\n )\n \n ## mpatches.Patch() allows us to create a custom legend item for each class\n Patches.append(mpatches.Patch(**kwargs))\n \n## We add the legend items to the legend\nax.legend(handles=Patches) \n\n## This turns off the numeric x,y labels\nax.get_xaxis().set_visible(False)\nax.get_yaxis().set_visible(False)\n\nax.set_title('Police Killings per Year per Million People')\n```\n\n# Step 6) Calculate a Police Killings Discrimination Index (PKDI):\n\n* For this, we'll compare the PKR for white people to the combined PKR of black and indigenous people\n\n* We'll use the following equations:\n\n\n\\begin{align}\n\\ PKR_{W} & = (\\frac{White Killings}{White Population}) * 1e6 / 18\\\\\n\\end{align}\n\n\\begin{align}\n\\ PKR_{BI} & = (\\frac{Black Killings + Indigenous Killings}{Black Population + Indigenous Population}) * 1e6 / 18\n\\end{align}\n\n\\begin{align}\n\\ PKDI & = PKR_{BI} - PKR_{W}\\\\\n\\end{align}\n\n## This will hightlight the disparities in police killings\n* We'll classify the data using the following scheme:\n \n * \"Low Bias\": -0.5 to 0.5 - This is the rate killings of whites. Within these ranges, differences might be due to presence or lacktherof of a certain groups \n * \"Moderate Bias\": 0.5 to 1 - Greater than the white rate, less than the national average\n * \"Severe Bias\": 1 to 3 - Greater than the national rate, less than the indigenouos rate\n * \"Extreme Bias: 3 to 10 - Greater than the national indigenous rate\n \n\n\n```python\nProvincial_Data['PKR_W']=Provincial_Data['Caucasian_Killings']/Provincial_Data['Caucasian']*rate_Conversion\nProvincial_Data['PKR_BI']=(Provincial_Data['Indigenous_Killings']+Provincial_Data['Black_Killings'])/(Provincial_Data['Indigenous']+Provincial_Data['Black'])*rate_Conversion\n\nProvincial_Data['PKDI'] = Provincial_Data['PKR_BI'] - Provincial_Data['PKR_W']\n\nProvincial_Data['PKDI']=Provincial_Data['PKDI'].fillna(0)\n\n\nbins = [-0.5,0.5,1,2,10.0]\nlabels = ['Low Bias','Moderate Bias','Severe Bias','Extreme Bias']\nProvincial_Data['PKDI_Classes']=(pd.cut(Provincial_Data['PKDI'],bins=bins,labels=labels)).astype('str')\n\nProvincial_Data.round(2)\n\n# print(Provincial_Data[['prov','PKDI','PKDI_Classes']].sort_values(by='PKDI').round(2))\n```\n\n### Lets map the patterns\n\n\n```python\nfig,ax1=plt.subplots(figsize=(5,5))\ncolors = ['#ffffb2','#fecc5c','#fd8d3c','#FF0000']\nPKDI_Color = {key:value for key,value in zip(labels,colors)}\n\nPatches = []\nfor pkdi_class in Provincial_Data['PKDI_Classes'].unique():\n kwargs = {'facecolor':PKDI_Color[pkdi_class],\n 'edgecolor':'black',\n 'linewidth':.5,\n 'label':pkdi_class}\n Provincial_Data.loc[Provincial_Data['PKDI_Classes']==pkdi_class].plot(\n ax=ax1,\n **kwargs\n )\n Patches.append(mpatches.Patch(**kwargs))\n \nax1.legend(handles=Patches,) \nax1.get_xaxis().set_visible(False)\nax1.get_yaxis().set_visible(False)\nax1.set_title('Police Killing Discrimination Index')\n```\n\n# Step 7) Save the data so we can use it in the future\n* We're going to save it as a shapefile for use with geopandas or a desktop GIS\n* We're also going to save it as a \"GeoJSON\" file. This datatype is well suited for webmapping. Which I cover in a dfferent workshp!\n\n\n```python\nProvincial_Data.to_file('Data/Provincial_Police_Violence.shp')\n```\n\n# Step 8) Putting Everything Together: Create an Infographic\n\n* Matplotlib alows us to be very specific in determining our layout with gridspec.\n\n\n* We can create a large plot and define specifically what we want.\n\n\n* We'll have two maps, showing the PKR and the PKDI on the left\n\n\n* Then we'll add some smaller plots on the right showing the annual trend, national PKR by race, and some pie charts\n\n\n* We can set our default ontsize for consistency\n\n\n```python\nSMALL_SIZE = 8\nMEDIUM_SIZE = 10\nBIGGER_SIZE = 16\n\n\nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n\n\nfig = plt.figure(figsize=(10,10))\ngs = fig.add_gridspec(100,100)\n\nPKR_Map = fig.add_subplot(gs[0:45 , 0:45])\nPKDI_Map = fig.add_subplot(gs[0:45, 55:])\n\n\n\nAnnual_Trend = fig.add_subplot(gs[47:65, 5:45])\nPKR_national = fig.add_subplot(gs[47:65, 65:])\n\nArmed_Stats = fig.add_subplot(gs[74:92, 5:45])\nDept_Stats = fig.add_subplot(gs[74:92, 65:])\n\n\nSourceStatement = fig.add_subplot(gs[93:,:])\n\nplt.subplots_adjust(left=.05, bottom=.05, right=.95, top=.95, wspace=.1, hspace=.1)\n\nfig.patch.set_facecolor([.9,.9,.9])\nplt.suptitle('Police Killings in Canada (2000-2017)')\n\n```\n\n### Now we can add things to the figure\n* First lets do the maps\n\n\n```python\n## Plot the PKR\nPatches=[]\nfor pkr_class in Provincial_Data['PKR_Classes'].unique():\n kwargs = {'facecolor':PKR_Color[pkr_class],\n 'edgecolor':'k',\n 'label':pkr_class}\n Provincial_Data.loc[Provincial_Data['PKR_Classes']==pkr_class].plot(\n ax=PKR_Map,\n **kwargs\n )\n Patches.append(mpatches.Patch(**kwargs))\nPKR_Map.legend(handles=Patches) \nPKR_Map.get_xaxis().set_visible(False)\nPKR_Map.get_yaxis().set_visible(False)\nPKR_Map.set_title('Police Killings per Year per Million People')\n\n# Plot the PKDI\nPatches = []\nfor pkdi_class in Provincial_Data['PKDI_Classes'].unique():\n kwargs = {'facecolor':PKDI_Color[pkdi_class],\n 'edgecolor':'k',\n 'label':pkdi_class}\n Provincial_Data.loc[Provincial_Data['PKDI_Classes']==pkdi_class].plot(\n ax=PKDI_Map,\n **kwargs\n )\n Patches.append(mpatches.Patch(**kwargs))\nPKDI_Map.legend(handles=Patches,) \nPKDI_Map.get_xaxis().set_visible(False)\nPKDI_Map.get_yaxis().set_visible(False)\nPKDI_Map.set_title('Police Killing Racial Discrimination Index')\n\n## Plot the annual trend\nAnnual_Trend.plot(\n Resampled.index.year,\n Resampled['id_victim'],\n color='black',\n)\nAnnual_Trend.plot(\n Resampled.index.year,\n Resampled.index.year*Regression_Line[0]+Regression_Line[1],\n label='Trend Line: '+str(np.round(Regression_Line[0],3))+'\\np-value: '+str(np.round(Regression_Line[3],3)),\n color='red'\n )\nAnnual_Trend.legend()\nAnnual_Trend.set_title('Annual Trend')\nAnnual_Trend.set_xticks([2000,2005,2010,2015])\n\n## Plot the Average PKR\nPKR_national.barh(\n Racial_Rates.index,\n Racial_Rates.values * rate_Conversion,\n facecolor='#FF0000',\n edgecolor='black',\n linewidth=1\n)\nPKR_national.set_title('Racial Disparity: National Average')\nPKR_national.set_xlabel('Killings per Year per million residents')\n\n## plot the weapon type\nArmed_Stats.pie(\n Armed['id_victim'],\n labels=Armed.index,\n colors=[Pie_Colors[i] for i in Armed.index],\n textprops={'fontsize': 8},\n autopct='%1.1f%%',\n wedgeprops={\"edgecolor\":\"k\",'linewidth': 1, 'linestyle': 'dashed'}\n)\nArmed_Stats.set_title('Was the Victim Armed?')\n\n## Plot the breakdown by department\nDept_Stats.barh(Force.index,Force['None'],facecolor='#FF0000',edgecolor='black')\nDept_Stats.set_yticklabels([Force_Labels[f] for f in Force.index.values])\nDept_Stats.set_title('Unarmed Victims by Deparment')\n\n## Add a source statement\nDescriptor = \\\n'''Infographic Created by June Skeeter. Data Soruces: The CBC \"Deadly Force (2018)\" & Stats Canada\n\nThe Police Killing Discrimination Index (PKDI) quantifies the disparitiy in police killing rates (PKR) between Black and Idigenous people and White people in Canada.\nThe PKDI is deined as: PKDI = PKR$_{Black+Indigenous}$-PKR$_{White}$'''\n\n# Descriptor = 'Kitties'\nSourceStatement.set_axis_off()\nSourceStatement.text(0, 0, \n Descriptor,\n horizontalalignment='left',\n verticalalignment='center',\n )\n\nplt.savefig('InfoGraphic.png',facecolor=fig.get_facecolor(),edgeolor='k')\n```\n\n# Updated Data for BC\n\n2013 - May 2021\n\n\n```python\n# the .read_file() function reads shapefiles\nMVan_CT = gpd.read_file('Data/CensusTracts/SimplyAnalytics_Shapefiles_2021-06-01_17_44_45_9e5629a2de473cd5362919f9edc33853.shp')\nprint(MVan_CT.crs)\nMVan_CT = MVan_CT.rename(columns={\n'VALUE0': 'Aboriginal identity, 2016',\n'VALUE1': 'Population, 2016',\n'VALUE2': 'Total visible minority population, 2016'\n })\n\nMVan_CT['NonWhitePCT'] = MVan_CT[['Aboriginal identity, 2016',\n'Total visible minority population, 2016']].sum(axis=1)/MVan_CT['Population, 2016']*100\n\n# .to_crs()changes the coordinate system\n# Provincial_Data = Provincial_Data.to_crs('EPSG:4326')\n# .to_file() saves our data to the specified format\nprint('Data Converted')\nprint(MVan_CT.NonWhitePCT.describe())\nMVan_CT.to_file(\"Data/MVan_CT.json\", driver = \"GeoJSON\")\nMVan_CT.head()\n```\n\n\n```python\n# We import the Police Killings file, and set the incident ID as the index\nBC_Tabular = pd.read_csv('Data/BC_Geocoded.csv',\n parse_dates=['date'],\n index_col=['id_incident']\n )\n\n# We can then convert the pandas dataframe into a geopandas \"GeodataFrame\"\nBC_Data = gpd.GeoDataFrame(BC_Tabular,\n geometry=gpd.points_from_xy(BC_Tabular.longitude,\n BC_Tabular.latitude\n )\n )\n\n# Now we can assign a CRS\nWGS_1984={'init' :'epsg:4326'}\nBC_Data.crs = WGS_1984\n\n# Lets sort the incidents by date and then take a quick look.\nBC_Data=BC_Data.sort_values(by='date')\nBC_Data.head()\n```\n\n# Point in Polygon Analysis\n\n\n```python\nMVan_CT['Incidents'] = 0\nfor i,row in MVan_CT.iterrows():\n pip = BC_Data.within(row['geometry'])\n if pip.sum()>0:\n# print(pip.sum())\n MVan_CT.loc[MVan_CT.index==i,'Incidents']+=pip.sum()\nprint(MVan_CT['Incidents'].describe())\n```\n\n\n```python\n\n# Now, we can create a figure using matplotlib (plt), first we define the figure and the size\nfig,axes=plt.subplots(\n figsize=(8,8)\n)\n\n# Now we can add the provinces using the .plot() function. We set the plotting axes and give it a grey color\ncb = MVan_CT.plot(\n ax=axes,\n column='Incidents',\n cmap = 'Greys',\n edgecolor='grey',\n legend=True,\n)\n\n# Then we add the police_Killings_LCC. We'll set the column to 'race', so we can disply by race,\n# give the point markers a few more parameters, and add them to a legend\nBC_Data.plot(\n ax=axes,\n edgecolor='k',\n markersize=15,\n legend_kwds={'loc': 'upper right','fontsize':8}\n)\nX_bounds = [MVan_CT.bounds.minx.min(),MVan_CT.bounds.maxx.max()]\nY_bounds = [MVan_CT.bounds.miny.min(),MVan_CT.bounds.maxy.max()]\naxes.set_ylim(Y_bounds)\naxes.set_xlim(X_bounds)\n```\n\n\n```python\nMVan_CT['Rate'] = MVan_CT['Incidents']/MVan_CT['Population, 2016']*1e4/8.5\n# Now, we can create a figure using matplotlib (plt), first we define the figure and the size\nfig,axes=plt.subplots(\n figsize=(8,8)\n)\n\n# Now we can add the provinces using the .plot() function. We set the plotting axes and give it a grey color\ncb = MVan_CT.plot(\n ax=axes,\n column='Rate',\n cmap = 'Greys',\n edgecolor='grey',\n legend=True,\n)\n\n# Then we add the police_Killings_LCC. We'll set the column to 'race', so we can disply by race,\n# give the point markers a few more parameters, and add them to a legend\nBC_Data.plot(\n ax=axes,\n edgecolor='k',\n markersize=15,\n legend_kwds={'loc': 'upper right','fontsize':8}\n)\nX_bounds = [MVan_CT.bounds.minx.min(),MVan_CT.bounds.maxx.max()]\nY_bounds = [MVan_CT.bounds.miny.min(),MVan_CT.bounds.maxy.max()]\naxes.set_ylim(Y_bounds)\naxes.set_xlim(X_bounds)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1b01026e1a74950a79df2988c4f89cce44590b99", "size": 42712, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_site/Geospatial Analysis & Visualization with Python v2.0.ipynb", "max_stars_repo_name": "ubc-library-rc/Geospatial-Analysis-Visualization-with-Python", "max_stars_repo_head_hexsha": "03ada258fa7db2976bfb562ae4e84adfe9a87a55", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-14T23:34:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T23:34:21.000Z", "max_issues_repo_path": "_site/Geospatial Analysis & Visualization with Python v2.0.ipynb", "max_issues_repo_name": "ubc-library-rc/Geospatial-Analysis-Visualization-with-Python", "max_issues_repo_head_hexsha": "03ada258fa7db2976bfb562ae4e84adfe9a87a55", "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": "_site/Geospatial Analysis & Visualization with Python v2.0.ipynb", "max_forks_repo_name": "ubc-library-rc/Geospatial-Analysis-Visualization-with-Python", "max_forks_repo_head_hexsha": "03ada258fa7db2976bfb562ae4e84adfe9a87a55", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-23T22:02:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T17:27:29.000Z", "avg_line_length": 34.3620273532, "max_line_length": 363, "alphanum_fraction": 0.5743116689, "converted": true, "num_tokens": 7766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.13477591394766722, "lm_q1q2_score": 0.054898731272601}} {"text": "\n\n# Introduccion a Colab de Google\n---\n\nColaboraty es una plataforma online de google gratuita para la ejecucion de Jupyter Notebooks https://jupyter.org/\nTiene una integracion con drive\n\nPara montar una unidad de drive diferente a la sesion actual iniciada\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/gdrive')\n%cd /gdrive/My\\ Drive/Taller\n```\n\n Mounted at /gdrive\n /gdrive/My Drive/Taller\n\n\n\n```python\n%cd \n%cd ..\ndrive.flush_and_unmount()\n```\n\n /root\n\n\nSi se monta la misma unidad, cambiar a una carpeta especifica indicando la ruta\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n%cd content/drive/MyDrive/Taller\n```\n\n Mounted at /content/drive\n\n\nObtener la ubicacion actual dentro de las carpetas del computador\n\n\n```python\n!pwd\n```\n\n /content/drive/MyDrive/Taller\n\n\nObtener los documentos dentro de la carpeta\n\n\n```python\n!ls\n```\n\n test.png\n\n\nMostrar la imagen test.png\n\nOtros comandos de la consola https://www.hostinger.co/tutoriales/linux-comandos\n\n\n```python\nfrom IPython.display import Image\nImage('test.png')\n```\n\n# Operaciones Basicas\n\n---\n\n\n\n### Suma\n\n\n```python\nO_sum = 3 + 11\nO_sum += 5\nO_sum\n```\n\n\n\n\n 19\n\n\n\n### Multiplicacion\n\n\n```python\nO_mult = 3 * 10\nO_mult *= 3\nO_mult\n```\n\n\n\n\n 90\n\n\n\n### Division\n\n\n```python\nO_div = 7 / 10\nO_div\n```\n\n\n\n\n 0.7\n\n\n\n### Exponencial\n\n\n```python\nO_exp = 2 ** 6\nO_exp\n```\n\n\n\n\n 64\n\n\n\n### Modulo\n\n\n```python\nO_mod = 20 % 3\nO_mod\n```\n\n\n\n\n 2\n\n\n\n### Cociente\n\n\n```python\nO_coci = 20 // 3\nO_coci\n```\n\n\n\n\n 6\n\n\n\n### Operaciones de comparacion\n\n\n```python\nmi_boolean = 2 == 3\nmi_boolean\n```\n\n\n\n\n False\n\n\n\n\n```python\nmi_boolean = 'hola' != \"hola\"\nmi_boolean\n```\n\n\n\n\n False\n\n\n\n\n```python\nmi_boolean = 34 < 10\nmi_boolean\n```\n\n\n\n\n False\n\n\n\n\n```python\nmi_boolean = 35 >= 35\nmi_boolean\n```\n\n\n\n\n True\n\n\n\n\n```python\nmi_boolean = 35 == 35 and 2 > 10\nmi_boolean\n```\n\n\n\n\n False\n\n\n\n\n```python\nmi_boolean = 14 <= 15 or 16 > 20\nmi_boolean\n```\n\n\n\n\n True\n\n\n\n\n```python\nmi_boolean = not 'hola' != \"hola\"\nmi_boolean\n```\n\n\n\n\n True\n\n\n\n# Variables String (alfanumerico)\n---\n\n### String\n\nSe puede usar tanto comillas dobles \" \" como comillas simples ' ' y sera interpretado como tipo string \n\n\n```python\nmensaje = 'Hola mundo'\nprint(type(mensaje))\n\nmensaje = \"Hola mundo\"\nprint(type(mensaje))\n```\n\n \n \n\n\n### Concatenar string\n\n\n```python\nmensaje += '\\nBienvenidos'\nprint(mensaje)\n```\n\n Hola mundo\n Bienvenidos\n\n\n### Replicar String\n\n\n```python\nmensaje = mensaje + '\\n'*3 + 'Hello world '*2\nprint(mensaje)\n```\n\n Hola mundo\n Bienvenidos\n \n \n Hello world Hello world \n\n\n### Obtener una entrada del usuario\n\n\n```python\nx = input()\nprint(x)\ntype(x)\n```\n\n 56\n 56\n\n\n\n\n\n str\n\n\n\n### String format\n\n\n```python\nmensaje = 'El nombre de la ciudad es {} del pais {}'.format('Bogota', 'Colombia')\nmensaje\n```\n\n\n\n\n 'El nombre de la ciudad es Bogota del pais Colombia'\n\n\n\n# Tipos de conjuntos\n---\n\n### Tuple\n\nTuple vacia\n\n\n```python\nmi_tuple = ()\nmi_tuple\n```\n\nSe pueden guardar multiple tipos de archivos en una tupla\n\n\n```python\nmi_tuple = (1, 2, 'hola')\nmi_tuple\n```\n\nSe usa los [ ] para llamar a los elementos de una tupla, iniciando desde el elemento 0 en *adelante*\n\n\n```python\nnumero1 = mi_tuple[0]\nnumero1\n```\n\nLlamar multiples elementos\n\n\n```python\nprint(mi_tuple[0:3:2])\n```\n\n### List\n\nLista vacia\n\n\n```python\nmi_lista = []\nmi_lista\n```\n\nAgregar elementos a una lista\n\n\n```python\nmi_lista.append('Hola')\nmi_lista.append('Mundo')\nmi_lista\n```\n\nLista con 3 elementos tipo string\n\n\n```python\nmi_lista = ['Andres', 'Andrea', 'Karen']\nprint(mi_lista)\nprint(len(mi_lista)) # len(list) devuelve el tamaño de una lista\nmi_lista[0]\n```\n\nLista con elemntos tipo float y string\n\n\n```python\nmi_lista = [4.5, 'hola']\nprint(type(mi_lista[0]))\nprint(type(mi_lista[1]))\nmi_lista\n```\n\n### Diccionarios\n\n\n```python\ndiccionario = {\n \"Andres\": [24, 173],\n \"Andrea\": [25, 175],\n 1: 123\n}\ndiccionario['Andres']\n```\n\n\n\n\n [24, 173]\n\n\n\n\n```python\nlista = diccionario.get(\"Andrea\")\nprint(lista, type(lista))\n```\n\n [25, 175] \n\n\n\n```python\ndiccionario[1]\n```\n\n\n\n\n 123\n\n\n\n\n```python\ndiccionario.pop(1)\n```\n\n\n\n\n 123\n\n\n\n\n```python\ndiccionario['Alex'] = [21, 124]\ndiccionario\n```\n\n\n\n\n {'Alex': [21, 124], 'Andrea': [25, 175], 'Andres': [24, 173]}\n\n\n\n\n```python\ndiccionario.clear()\n```\n\n\n```python\ndiccionario\n```\n\n\n\n\n {}\n\n\n\n# Estructuras de Control\n---\n\n### Clase booleana\n\n\n```python\nmi_boolean = True\nmi_boolean\n```\n\n\n\n\n True\n\n\n\n\n```python\nmi_boolean = not(mi_boolean)\nmi_boolean\n```\n\n\n\n\n False\n\n\n\n\n```python\nbooleano = \"Andres\" in diccionario\nbooleano\n```\n\n\n\n\n False\n\n\n\n### Declaracion If, Else y Elif\n\n\n```python\na = 3\n\nif a < 10:\n print('Menor que 10')\n```\n\n Menor que 10\n\n\n\n```python\nif a > 10:\n print('Mayor que 10')\nelse:\n print('Menor que 10')\n```\n\n Menor que 10\n\n\n\n```python\na = float(input())\n\nif a == 10:\n print('Igual que 10')\nelif a > 10:\n print('Mayor que 10')\nelse:\n print('Menor que 10')\n```\n\n 1564\n Mayor que 10\n\n\n### For\n\nSe usa in para iteral en cada uno de los elementos de una lista\n\n\n```python\nlista = [0, 1, 2, 3, 4, 5]\nfor i in lista:\n print(i)\n```\n\n 0\n 1\n 2\n 3\n 4\n 5\n\n\n\n```python\nlista = ['Andres', 'Andrea', 'Felipe']\nfor i in lista:\n print(i)\n```\n\n Andres\n Andrea\n Felipe\n\n\nUso de range\n\n\n```python\nfor i in range(0, 6, 1):\n print(i)\n```\n\n 0\n 1\n 2\n 3\n 4\n 5\n\n\n\n```python\nlista1 = [1 ,2, 3, 4, 5]\nlista2 = ['a', 'b', 'c', 'd', 'e']\nlista3 = [1.73, 1.86, 1.84, 1.62, 1.70]\n\nfor i, j, k in zip(lista1, lista2, lista3):\n print(i, j, k)\n```\n\n 1 a 1.73\n 2 b 1.86\n 3 c 1.84\n 4 d 1.62\n 5 e 1.7\n\n\nFor else, sirve para realizar acciones en caso de no ejecutarse un \"break\"\n\n\n```python\nlista1 = [1 ,2, 3, 4, 5]\nlista2 = ['a', 'b', 'c', 'd', 'e']\nlista3 = [1.73, 1.86, 1.84, 1.62, 1.70]\nnumero = 3\n\nfor i, j, k in zip(lista1, lista2, lista3):\n print(i, j, k)\n if numero <= 1:\n break\n numero -= 1\nelse:\n print('Todos los elementos fueron impresos')\n```\n\n 1 a 1.73\n 2 b 1.86\n 3 c 1.84\n\n\n### While\n\n\n```python\nprint('hola')\n```\n\n hola\n\n\n\n```python\nprint('funciona?')\n```\n\n funciona?\n\n\n# Debugging en Jupyter Notebook\n\n\n### Debug despues de un error\n\n\n```python\na = 14\nb = 5\nb -= (a + 1)/3\n\nDivision = a / b\nDivision\n```\n\n\n```python\n%debug\n```\n\n### Debugging y breakpoints\n\nPara ejecutar el codigo paso a paso creamos una funcion Code_debug y usamos la libreria de debug de Ipython\n\n\n```python\ndef Code_debug():\n from IPython.core.debugger import set_trace\n \n set_trace() # Se crea un breakpoint\n\n a = 14\n b = 5\n b -= (a + 1)/3\n\n Division = a / b\n \nCode_debug()\n```\n\n### Debugging a funciones\n\n\n```python\nfrom IPython.core.debugger import set_trace\n\ndef Funcion1(a=1):\n set_trace()\n\n b = a ** 10\n c = a / b\n\n return c\nFuncion1()\n```\n\n# Bibliotecas Numpy y Sympy\n\n### Funciones\n\n\n```python\nimport numpy as np \n\ndef f(x):\n return np.sqrt(x + 2)\n\nx = np.array([-2, -1, 0, 2, 4, 6]) # Creando el vector de valores de x\ny = f(x)\nlist(zip(x, y))\n```\n\n### Derivadas\n\n\n```python\nfrom sympy import Derivative, diff, simplify, Symbol\n\nx = Symbol('x') # Creando el simbolo x.\nfx = (2*x + 1)*(x**3 + 2)\ndx = Derivative(fx, x).doit()\ndx\n```\n\n\n```python\n# simplificando los resultados\nsimplify(dx)\n```\n\n\n```python\n# Derivada de segundo orden con el 3er argumento.\nDerivative(fx, x, 2).doit()\n```\n\n\n```python\n# Calculando derivada de (3x +1) / (2x)\nfx = (3*x + 1) / (2*x)\ndx = Derivative(fx, x).doit()\nsimplify(dx)\n```\n\n\n```python\n# la función diff nos da directamente el resultado\nsimplify(diff(fx, x))\n```\n\n\n```python\n# con el metodo subs sustituimos el valor de x \n# para obtener el resultado numérico. Ej x = 1.\ndiff(fx, x).subs(x, 1)\n```\n\n### Integrales\n\n\n```python\nfrom sympy import Integral, integrate\n\nfx = x**3 - 6*x\ndx = Integral(fx, x).doit()\ndx\n```\n\n\n```python\n# la función integrate nos da el mismo resultado\nintegrate(fx, x)\n```\n\n\n```python\n# Calculando integral definida para [0, 3]\nIntegral(fx, (x, 0, 3)).doit()\n```\n", "meta": {"hexsha": "05b5a311b0b8d10ddf1adfdd6470288d7061eabc", "size": 179968, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "TallerPython.ipynb", "max_stars_repo_name": "Wijuva/Programacion_Basica_Plazi", "max_stars_repo_head_hexsha": "ac219fdc22daf580d9165af1a2802333bc6dba1c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-04T12:23:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T00:30:06.000Z", "max_issues_repo_path": "TallerPython.ipynb", "max_issues_repo_name": "Wijuva/Programacion_Basica_Plazi", "max_issues_repo_head_hexsha": "ac219fdc22daf580d9165af1a2802333bc6dba1c", "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": "TallerPython.ipynb", "max_forks_repo_name": "Wijuva/Programacion_Basica_Plazi", "max_forks_repo_head_hexsha": "ac219fdc22daf580d9165af1a2802333bc6dba1c", "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": 87.1515738499, "max_line_length": 135466, "alphanum_fraction": 0.8196734975, "converted": true, "num_tokens": 2721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.18242552602881165, "lm_q1q2_score": 0.054863670439195475}} {"text": "# Tutorial 3: Synapses and Networks\n\n## Neuronal connectivity\n\nNeurons are connected at specific sites called **synapses**. Usually, the axon of a **presynaptic** neuron will make contact with the dendrite (or soma) of a **postsynaptic** in what's called a **chemical synapse**: **neurotransmitters** are transferred via the tiny gap between the two neurons (**synaptic cleft**) thanks to biochemical processes. This generates a change in membrane potential at the postsynaptic site, called **postsynaptic potential**. **Electrical synapses**, also known as **gap junctions**, can also be present -- in this case, specialized proteins make a direct electrical connection between neurons. [1]\n\n
    \n\n
    from [2]
    \n\nIn this tutorial we will connect two or more neurons in NEST to create our first neuronal networks. First, we will learn the basic commands following [3] and [4], and then apply these to a well-known balanced network known as the **Brunel network**. By the end of this tutorial, you should be able to understand that a network's stability and activity behavior is deeply influenced by its parametrization.\n\n### Sources:\n\n>[1] Wulfram Gerstner and Werner M. Kistler, \"Spiking Neuron Models\". Cambridge University Press, 2002\n\n>[2] Peter Dayan and L. F. Abbot, \"Theoretical Neuroscience: Computational and Mathematical Modeling of Neural Systems\". The MIT Press, 2001\n\n>[3] [PyNEST tutorial: Part 2, Populations of Neurons](https://nest-simulator.readthedocs.io/en/latest/tutorials/pynest_tutorial/part_2_populations_of_neurons.html)\n\n>[4] [PyNEST tutorial: Part 3, Connecting Networks with Synapses](https://nest-simulator.readthedocs.io/en/latest/tutorials/pynest_tutorial/part_3_connecting_networks_with_synapses.html)\n\n## Introduction: synapses in NEST\n\nAll synapse types included in NEST can be found in the following link:\n\n>[5] [NEST Docs: All synapse models](https://nest-simulator.readthedocs.io/en/latest/models/synapses.html)\n\nAlternatively, you can verify all synapse models present in NEST using the following command:\n\n\n```python\nimport nest\nnest.Models('synapses')\n```\n\n\n\n\n ('bernoulli_synapse',\n 'bernoulli_synapse_lbl',\n 'clopath_synapse',\n 'clopath_synapse_lbl',\n 'cont_delay_synapse',\n 'cont_delay_synapse_hpc',\n 'cont_delay_synapse_lbl',\n 'diffusion_connection',\n 'diffusion_connection_lbl',\n 'gap_junction',\n 'gap_junction_lbl',\n 'ht_synapse',\n 'ht_synapse_hpc',\n 'ht_synapse_lbl',\n 'quantal_stp_synapse',\n 'quantal_stp_synapse_hpc',\n 'quantal_stp_synapse_lbl',\n 'rate_connection_delayed',\n 'rate_connection_delayed_lbl',\n 'rate_connection_instantaneous',\n 'rate_connection_instantaneous_lbl',\n 'static_synapse',\n 'static_synapse_hom_w',\n 'static_synapse_hom_w_hpc',\n 'static_synapse_hom_w_lbl',\n 'static_synapse_hpc',\n 'static_synapse_lbl',\n 'stdp_dopamine_synapse',\n 'stdp_dopamine_synapse_hpc',\n 'stdp_dopamine_synapse_lbl',\n 'stdp_facetshw_synapse_hom',\n 'stdp_facetshw_synapse_hom_hpc',\n 'stdp_facetshw_synapse_hom_lbl',\n 'stdp_pl_synapse_hom',\n 'stdp_pl_synapse_hom_hpc',\n 'stdp_pl_synapse_hom_lbl',\n 'stdp_synapse',\n 'stdp_synapse_hom',\n 'stdp_synapse_hom_hpc',\n 'stdp_synapse_hom_lbl',\n 'stdp_synapse_hpc',\n 'stdp_synapse_lbl',\n 'stdp_triplet_synapse',\n 'stdp_triplet_synapse_hpc',\n 'stdp_triplet_synapse_lbl',\n 'tsodyks2_synapse',\n 'tsodyks2_synapse_hpc',\n 'tsodyks2_synapse_lbl',\n 'tsodyks_synapse',\n 'tsodyks_synapse_hom',\n 'tsodyks_synapse_hom_hpc',\n 'tsodyks_synapse_hom_lbl',\n 'tsodyks_synapse_hpc',\n 'tsodyks_synapse_lbl',\n 'vogels_sprekeler_synapse',\n 'vogels_sprekeler_synapse_hpc',\n 'vogels_sprekeler_synapse_lbl')\n\n\n\n## Synapse types\n\nThe simplest synapse type is the `static_synapse`. In this case, the **synaptic weight**, a measure of how strong is the influence of the presynaptic neuron on the postsynaptic neuron, is static, i.e. does not change over time. The synaptic transmission, however, is not instantaneous, and hence a **synaptic delay** is defined as the time between the presynaptic neuron activation (**action potential**) and the moment the postsynaptic potential is generated.\n\nIn NEST, we can check the default values for all parameters using the `GetDefaults` function:\n\n\n```python\nnest.GetDefaults('static_synapse')\n```\n\n\n\n\n {'delay': 1.0,\n 'has_delay': True,\n 'num_connections': 0,\n 'receptor_type': 0,\n 'requires_symmetric': False,\n 'sizeof': 32,\n 'synapse_model': ,\n 'weight': 1.0,\n 'weight_recorder': -1}\n\n\n\nBiological synapses, however, are constantly being created, destroyed and modified. Many models have been created to describe all of these processes. On synaptic modification, one of the most common models is the **spike-time dependent plasticity**. In this example, the synaptic weight changes according to the temporal order between pre and postsynaptic spike times.\n\nIn NEST, the most common STDP mechanisms are implemented in `stdp_synapse`. The change for **normalized** synaptic weights is described by\n\n\\begin{equation}\n \\Delta w = \\begin{cases} - \\lambda f_{-}(w) \\times K_-(\\Delta t) & \\text{if $\\Delta t \\leq 0$,} \\\\\n \\lambda f_{+}(w) \\times K_+(\\Delta t) & \\text{if $\\Delta t > 0$,} \\end{cases}\n\\end{equation}\n\nwhere $\\Delta t \\equiv t_{post} - t_{pre}$ and the temporal filter is defined as $K_{(+,-)}(\\Delta t) = \\exp(-|\\Delta t| / \\tau_{(+,-)})$. The update functions\n\n\\begin{equation}\n f_{+}(w) = (1-w)^{\\mu_{+}} \\text{ and } f_{-}(w) = \\alpha w^{\\mu_{-}}\n\\end{equation}\n\ncreate **synaptic potentiation** (stronger weights) when **causal spiking** is detected ($\\Delta t > 0$), otherwise generating **synaptic depression** (weaker weights). This rule is also known as **temporally asymmetric Hebbian plasticity** and has been thoroughly studied under different parametrizations:\n\n| STDP Type | Parametrization | Ref. |\n|---------------------|----------------------------------|------|\n| multiplicative STDP | $\\mu_{+}=\\mu_{-}=1.0$ | [7] |\n| additive STDP | $\\mu_{+}=\\mu_{-}=0.0$ | [8] |\n| Guetig STDP | $\\mu_{+}=\\mu_{-}=[0.0, 1.0]$ | [6] |\n| van Rossum STDP | $\\mu_{+}=0.0, \\mu_{-} = 1.0$ | [9] |\n\n### Sources:\n\n> [6] Guetig et al. (2003). Learning input correlations through nonlinear temporally asymmetric hebbian plasticity. Journal of Neuroscience, 23:3697-3714 DOI: https://doi.org/10.1523/JNEUROSCI.23-09-03697.2003\n\n> [7] Rubin J, Lee D, Sompolinsky H (2001). Equilibrium properties of temporally asymmetric Hebbian plasticity. Physical Review Letters, 86:364-367. DOI: https://doi.org/10.1103/PhysRevLett.86.364\n\n> [8] Song S, Miller KD, Abbott LF (2000). Competitive Hebbian learning through spike-timing-dependent synaptic plasticity. Nature Neuroscience 3(9):919-926. DOI: https://doi.org/10.1038/78829\n\n> [9] van Rossum MCW, Bi G-Q, Turrigiano GG (2000). Stable Hebbian learning from spike timing-dependent plasticity. Journal of Neuroscience, 20(23):8812-8821. DOI: https://doi.org/10.1523/JNEUROSCI.20-23-08812.2000\n\nAgain, we can check the default values for all parameters of `stdp_synapse` using the `GetDefaults` function:\n\n\n```python\nnest.GetDefaults('stdp_synapse')\n```\n\n\n\n\n {'lambda': 0.01,\n 'alpha': 1.0,\n 'delay': 1.0,\n 'has_delay': True,\n 'mu_minus': 1.0,\n 'mu_plus': 1.0,\n 'num_connections': 0,\n 'receptor_type': 0,\n 'requires_symmetric': False,\n 'sizeof': 96,\n 'synapse_model': ,\n 'tau_plus': 20.0,\n 'weight': 1.0,\n 'weight_recorder': -1,\n 'Wmax': 100.0}\n\n\n\nYou may have noticed that `tau_minus` is absent from the above list. For STDP synaptic models, the time constant of the depressing window of STDP is exceptionally a parameter of the **post-synaptic neuron**.\n\n\n```python\nnest.Create(\"iaf_psc_alpha\", params={\"tau_minus\": 30.0})\n```\n\n\n\n\n (1,)\n\n\n\nTo change the default value of an **accessible** parameter, we can use the function `SetDefaults`. \n\nNote that *only some parameters listed by `GetDefaults` are changeable*. Please verify the details of the synapse type you want to use beforehand. [[5]](https://nest-simulator.readthedocs.io/en/latest/models/synapses.html)\n\n\n```python\nnest.SetDefaults(\"stdp_synapse\",{\"tau_plus\": 15.0})\n```\n\nCustomized variants of a synapse model can be created using `CopyModel()`, and can be used anywhere that a built-in model name can be used. \n\n\n```python\nnest.CopyModel(\"stdp_synapse\",\"layer1_stdp_synapse\",{\"Wmax\": 90.0})\n```\n\nWhen connecting multiple neurons, connectivity rules can be defined. Besides simple set-ups like `one_to_one` and `all_to_all`, sparse methods like `fixed_indegree`, `fixed_outdegree`, `fixed_total_number` and `pairwise_bernoulli` are also available. Please check [[3]](https://nest-simulator.readthedocs.io/en/latest/tutorials/pynest_tutorial/part_2_populations_of_neurons.html) to learn more details about creating and connecting neuron populations.\n\n\n```python\nepop1 = nest.Create(\"iaf_psc_delta\", 10, params={\"tau_m\": 30.0})\nepop2 = nest.Create(\"iaf_psc_delta\", 10)\nK = 5\n\nconn_dict = {\"rule\": \"fixed_indegree\", \"indegree\": K}\nsyn_dict = {\"model\": \"stdp_synapse\", \"alpha\": 1.0}\nnest.Connect(epop1, epop2, conn_dict, syn_dict)\n```\n\nSynaptic parameters can also be randomly distributed by assigning a dictionary to the parameter. This should contain the target distribution and its optional parameters, as listed below:\n\n| Distributions | Keys |\n|---------------|------------------|\n| `normal` | `mu`, `sigma` |\n| `lognormal` | `mu`, `sigma` |\n| `uniform` | `low`, `high` |\n| `uniform_int` | `low`, `high` |\n| `binomial` | `n`, `p` |\n| `exponential` | `lambda` |\n| `gamma` | `order`, `scale` |\n| `poisson` | `lambda` |\n\n\n```python\nneuron = nest.Create(\"iaf_psc_alpha\")\n\nalpha_min = 0.1\nalpha_max = 2.\nw_min = 0.5\nw_max = 5.\n\nsyn_dict = {\"model\": \"stdp_synapse\",\n \"alpha\": {\"distribution\": \"uniform\", \"low\": alpha_min, \"high\": alpha_max},\n \"weight\": {\"distribution\": \"uniform\", \"low\": w_min, \"high\": w_max},\n \"delay\": 1.0}\nnest.Connect(epop1, neuron, \"all_to_all\", syn_dict)\n```\n\nSynapse information can be retrieved from its origin, target and synapse model using `GetConnections()`:\n\n\n```python\nnest.GetConnections(epop1, target=epop2, synapse_model=\"stdp_synapse\")\n```\n\n\n\n\n (array('l', [2, 14, 0, 14, 0]),\n array('l', [2, 14, 0, 14, 1]),\n array('l', [2, 21, 0, 14, 3]),\n array('l', [2, 19, 0, 14, 4]),\n array('l', [2, 18, 0, 14, 5]),\n array('l', [2, 17, 0, 14, 6]),\n array('l', [2, 18, 0, 14, 7]),\n array('l', [3, 20, 0, 14, 8]),\n array('l', [3, 17, 0, 14, 10]),\n array('l', [3, 20, 0, 14, 11]),\n array('l', [3, 12, 0, 14, 12]),\n array('l', [3, 21, 0, 14, 13]),\n array('l', [3, 20, 0, 14, 14]),\n array('l', [4, 13, 0, 14, 15]),\n array('l', [4, 21, 0, 14, 16]),\n array('l', [4, 15, 0, 14, 17]),\n array('l', [4, 13, 0, 14, 18]),\n array('l', [4, 13, 0, 14, 19]),\n array('l', [4, 18, 0, 14, 20]),\n array('l', [4, 17, 0, 14, 21]),\n array('l', [4, 14, 0, 14, 22]),\n array('l', [4, 12, 0, 14, 23]),\n array('l', [4, 19, 0, 14, 24]),\n array('l', [4, 12, 0, 14, 25]),\n array('l', [4, 17, 0, 14, 26]),\n array('l', [4, 13, 0, 14, 27]),\n array('l', [5, 17, 0, 14, 29]),\n array('l', [5, 16, 0, 14, 30]),\n array('l', [5, 20, 0, 14, 31]),\n array('l', [5, 15, 0, 14, 32]),\n array('l', [6, 16, 0, 14, 34]),\n array('l', [6, 16, 0, 14, 36]),\n array('l', [7, 20, 0, 14, 37]),\n array('l', [7, 16, 0, 14, 39]),\n array('l', [7, 14, 0, 14, 40]),\n array('l', [8, 14, 0, 14, 41]),\n array('l', [8, 18, 0, 14, 42]),\n array('l', [8, 15, 0, 14, 44]),\n array('l', [8, 19, 0, 14, 45]),\n array('l', [9, 21, 0, 14, 46]),\n array('l', [9, 15, 0, 14, 48]),\n array('l', [9, 13, 0, 14, 49]),\n array('l', [9, 12, 0, 14, 50]),\n array('l', [9, 16, 0, 14, 51]),\n array('l', [9, 18, 0, 14, 52]),\n array('l', [10, 15, 0, 14, 53]),\n array('l', [10, 12, 0, 14, 54]),\n array('l', [11, 21, 0, 14, 56]),\n array('l', [11, 19, 0, 14, 57]),\n array('l', [11, 19, 0, 14, 58]))\n\n\n\nWe can then extract the data using `GetStatus()`. Specific information can be retrieved by providing a list of desired parameters.\n\n\n```python\nconns = nest.GetConnections(epop1, synapse_model=\"stdp_synapse\")\nconn_vals = nest.GetStatus(conns, [\"target\",\"weight\"])\n```\n\n---\n\n## Example: connecting two neurons\n\nIn this example, we will create and connect two neurons, A and B. Neuron A is of type `iaf_psc_delta` and receives external current $I_e = 376.0 pA$. This current is sufficient to elicit a spike every $\\approx$ 50ms. Neuron B is solely connected to neuron A and hence can only spike if the input from A is strong enough. Let's observe how B can be influenced by A.\n\nFirst, verify the activity of neuron A running the block of code below.\n\n\n```python\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# reset kernel for new example\n\nnest.ResetKernel()\n\nneuron_A = nest.Create(\"iaf_psc_delta\", 1, {\"I_e\": 376.0})\n\nmultimeter_A = nest.Create(\"multimeter\", params={\"withtime\": True, \"record_from\":[\"V_m\"]})\nspikedetector_A = nest.Create(\"spike_detector\", params={\"withgid\": True, \"withtime\": True})\n\nnest.Connect(multimeter_A, neuron_A)\nnest.Connect(neuron_A, spikedetector_A)\n\nnest.Simulate(300.0)\n\n# plot membrane potential and spiking activity\n\nplt.rcParams['figure.dpi'] = 300\nfig, ax = plt.subplots(2, 1, sharex=True, sharey=False)\n\nmultimeter_A_readout = nest.GetStatus(multimeter_A)[0]\nV_A = multimeter_A_readout[\"events\"][\"V_m\"]\nt_A = multimeter_A_readout[\"events\"][\"times\"]\n\nspikedetector_A_readout = nest.GetStatus(spikedetector_A, keys=\"events\")[0]\nevent_A = spikedetector_A_readout[\"senders\"]\nte_A = spikedetector_A_readout[\"times\"]\n\nax[0].set_ylabel('V (mV)')\n\nax[0].plot(t_A, V_A, color=\"tab:blue\", label=\"A\")\nax[0].legend() \n\nax[1].set_xlabel('time (ms)')\nax[1].set_ylabel('Spike times')\nax[1].plot(te_A, event_A, \".\")\n\nax[1].set_yticks([1])\nax[1].set_yticklabels([\"A\"])\n\nplt.show()\n```\n\nNow let's create neuron B as `iaf_psc_delta` with no external current:\n\n\n```python\nneuron_B = nest.Create(\"iaf_psc_delta\", 1, {\"I_e\": 0.0})\n\nmultimeter_B = nest.Create(\"multimeter\", params={\"withtime\": True, \"record_from\":[\"V_m\"]})\nspikedetector_B = nest.Create(\"spike_detector\", params={\"withgid\": True, \"withtime\": True})\n\nnest.Connect(multimeter_B, neuron_B)\nnest.Connect(neuron_B, spikedetector_B)\n```\n\nWe'll use the function below to easily plot the activity of the two neurons at the same time:\n\n\n```python\ndef plot2neurons(multimeter_A, multimeter_B, spikedetector_A, spikedetector_B):\n multimeter_A_readout = nest.GetStatus(multimeter_A)[0]\n V_A = multimeter_A_readout[\"events\"][\"V_m\"]\n t_A = multimeter_A_readout[\"events\"][\"times\"]\n\n multimeter_B_readout = nest.GetStatus(multimeter_B)[0]\n V_B = multimeter_B_readout[\"events\"][\"V_m\"]\n t_B = multimeter_B_readout[\"events\"][\"times\"]\n \n spikedetector_A_readout = nest.GetStatus(spikedetector_A, keys=\"events\")[0]\n event_A = spikedetector_A_readout[\"senders\"]\n te_A = spikedetector_A_readout[\"times\"]\n\n spikedetector_B_readout = nest.GetStatus(spikedetector_B, keys=\"events\")[0]\n event_B = spikedetector_B_readout[\"senders\"]\n te_B = spikedetector_B_readout[\"times\"] \n\n plt.rcParams['figure.dpi'] = 300\n fig, ax = plt.subplots(2, 1, sharex=True, sharey=False) \n \n ax[0].set_ylabel('V (mV)')\n \n ax[0].plot(t_A, V_A, color=\"tab:blue\", label=\"A\")\n ax[0].plot(t_B, V_B, color=\"tab:orange\", label=\"B\")\n ax[0].legend()\n \n ax[1].set_ylim(0,5)\n ax[1].set_yticks([1,4])\n ax[1].set_yticklabels([\"A\",\"B\"])\n ax[1].set_xlabel('time (ms)')\n ax[1].set_ylabel('Spike times')\n\n ax[1].plot(te_A, event_A, \".\", color=\"tab:blue\")\n ax[1].plot(te_B, event_B, \".\", color=\"tab:orange\")\n\n plt.show()\n```\n\n\n```python\nnest.Simulate(300.0)\nplot2neurons(multimeter_A, multimeter_B, spikedetector_A, spikedetector_B)\n```\n\nNeuron B is still inactive. We need to connect both neurons:\n\n\n```python\nnest.Connect(neuron_A, neuron_B, {\"rule\": \"one_to_one\"}, {\"model\": \"static_synapse\"})\n\nnest.Simulate(300.0)\nplot2neurons(multimeter_A, multimeter_B, spikedetector_A, spikedetector_B)\n```\n\n### Suggest at least 3 alterations we can make in this example to elicit spiking activity from B.\n\nRun the code below and check if B spikes using the spike time raster (bottommost graph). \n\nAdditionally, check what happens if the neuron model is different: for example, change `iaf_psc_delta` to `hh_psc_alpha`.\n\nFinally, connect B to A reciprocally and check their dynamics. How can you describe their behavior?\n\n\n```python\nnest.ResetKernel()\n\nneuron_A = nest.Create(\"iaf_psc_delta\", 1, {\"I_e\": 376.0})\n\nmultimeter_A = nest.Create(\"multimeter\", params={\"withtime\": True, \"record_from\":[\"V_m\"]})\nspikedetector_A = nest.Create(\"spike_detector\", params={\"withgid\": True, \"withtime\": True})\n\nnest.Connect(multimeter_A, neuron_A)\nnest.Connect(neuron_A, spikedetector_A)\n\nneuron_B = nest.Create(\"iaf_psc_delta\", 1, {\"I_e\": 0.0})\n\nmultimeter_B = nest.Create(\"multimeter\", params={\"withtime\": True, \"record_from\":[\"V_m\"]})\nspikedetector_B = nest.Create(\"spike_detector\", params={\"withgid\": True, \"withtime\": True})\n\nnest.Connect(multimeter_B, neuron_B)\nnest.Connect(neuron_B, spikedetector_B)\n\nnest.Connect(neuron_A, neuron_B, {\"rule\": \"one_to_one\"}, {\"model\": \"static_synapse\", \"weight\": 1.})\n\nnest.Simulate(300.0)\nplot2neurons(multimeter_A, multimeter_B, spikedetector_A, spikedetector_B)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1fd13fef12432deb3a5c42fc4d7c996b9ded4e6e", "size": 469188, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorial-3_Synapses-and-Networks/Synapses.ipynb", "max_stars_repo_name": "oist-ncbc/skill-pill-plus", "max_stars_repo_head_hexsha": "698002772cb045e2b8d92c4a850f35f6d82a782b", "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": "Tutorial-3_Synapses-and-Networks/Synapses.ipynb", "max_issues_repo_name": "oist-ncbc/skill-pill-plus", "max_issues_repo_head_hexsha": "698002772cb045e2b8d92c4a850f35f6d82a782b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-08T04:21:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-08T04:21:01.000Z", "max_forks_repo_path": "Tutorial-3_Synapses-and-Networks/Synapses.ipynb", "max_forks_repo_name": "oist-ncbc/skill-pill-plus", "max_forks_repo_head_hexsha": "698002772cb045e2b8d92c4a850f35f6d82a782b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-13T13:11:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-13T13:11:30.000Z", "avg_line_length": 565.286746988, "max_line_length": 130572, "alphanum_fraction": 0.9431741647, "converted": true, "num_tokens": 5583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.12940272487671914, "lm_q1q2_score": 0.05467324913606892}} {"text": "# Advanced free energy analyses with SOMD\n\nIn this notebook we will explore advanced analysis techniques for alchemical free enregy calculations, using Sire tool `analyse_freenrg mbar`. \nInitially, you will learn how to correctly interpret phase space overlap matrix. Following, advanced commands will be shown to enhance the mbar analysis.\n\nThe notebook forms part of the CCPBio-Sim workshop **Alchemical Free Energy Simulation Analysis with analyse_freenrg** run on the 11th of April 2018 at the University of Bristol.\n\n*Author: Anotnia Mey & Stefano Bosisio \nEmail: antonia.mey@ed.ac.uk*\n\n**Reading time of the document: xx mins**\n\n## Overlap matrix\n\n\n```python\n%pylab inline\nimport glob\nimport seaborn as sbn\nsbn.set_style(\"ticks\")\nsbn.set_context(\"notebook\", font_scale = 2)\n```\n\n### The overlap matrix\n\ncan be used to look at the phase space overlap of neighbouring lambdas. \nBy adding the flag `--overlap` this matrix will be automatically computed and added to the output file. \n\nSo let's look at the overlap matrix for a simulation of a host-guest system, shown in figure, obtained by running 16 $\\lambda$ windows of 8 ns length each. \nThis time we will write an output file called `good_overlap.dat`\n\n\n\n\n\n\n```python\n%%capture run_info_good\n#Let's run the analysis again with the keyword --overlap\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i good_overlap/lambda-*/simfile.dat -o good_overlap.dat --subsampling --overlap\n```\n\n\n```python\n#A helper function to read the overlap matrix from file\ndef get_overlp_matrix(filename, lambda_val ):\n fh = open (filename, 'r')\n lines = fh.readlines()\n fh.close()\n count = 0\n matrix = []\n for line in lines:\n if line.startswith('#Overlap'):\n matrix = lines[(count+1):(count+1+lambda_vals)]\n break\n count = count+1 \n for i in range(len(matrix)):\n temp = matrix[i].strip().split(' ')\n float_temp = [float(j) for j in temp]\n matrix[i] = float_temp\n matrix =np.array(matrix)\n return matrix\n```\n\n\n```python\n#an exercise could be add the lambda_vals in the function above\ngood_overlap = get_overlp_matrix('good_overlap.dat',16)\n\n```\n\n### Plotting the overlap matrix\nThe plotting library has a nice advanced heat map feature that allows you to not only plot a pictorial image of a matrix or heatmap but also add the numercal values making it easier to read the plot\n\n\n```python\nfig = figure(figsize=(12,12))\nax = sbn.heatmap(good_overlap, annot=True, fmt='.2f', linewidths=.5, annot_kws={\"size\": 12})\nax.set_xlabel(r'$\\lambda$ index')\nax.set_ylabel(r'$\\lambda$ index')\nax.set_title('Good overlap matrix')\n```\n\n### Example of a bad overlap matrix\nBelow we have the same simulation as before, but reducing the number of lambda windows from 11 to 6. What do you observe in terms of the overlap matrix?\n\nBelowe we have the same simulation as before, but the number of $\\lambda$ windows was reduced from 16 to 10. What do you observe in terms of the overlap matrix? \nRepeat the procedure above and create a file called `bad_overlap.dat`\n\n\n```python\n%%capture run_info_bad\n#Let's run the analysis again with the keyword --overlap\n\n```\n\n\n```python\nbad_overlap = get_overlp_matrix('bad_overlap.dat',10)\n```\n\n\n```python\nfig = figure(figsize=(12,12))\nax = sbn.heatmap(good_overlap, annot=True, fmt='.2f', linewidths=.5, annot_kws={\"size\": 12})\nax.set_xlabel(r'$\\lambda$ index')\nax.set_ylabel(r'$\\lambda$ index')\nax.set_title('Bad overlap matrix')\n```\n\n### Advanced tasks\n\nAs an advanced task we are going to deal with mbar command `subsampling` and `discard`. The former option performs a subsamplin operation over all the samles data, written in the `simfile.dat` files. The second choice, `discard`, will discard a number of frames from the beginning of the simulation. This is beneficial for our estimation, as in the very first frames the system is usually equilibrating, giving rise to noise to the final free energy calculation. \n\nWe are going to study a host-guest system, similar to the one shown before. To compute the binding free energy, the following thermodynamic cycle is adopted:\n\nInitially, a `discharging` step is performed, where ligand's charges are turned off both in solvated and bound phases. Following, a `vanishing` step is done, by switching off ligand's Lennard Jones terms, in order to have a fully decouple molecule. \nThe final free energy of binding is computed, by summing up the contribution of each leg of the cycle, as:\n\\begin{equation}\n\\Delta G_\\mathrm{bind} = (\\Delta G^\\mathrm{solv}_\\mathrm{elec} + \\Delta G^\\mathrm{solv}_\\mathrm{vdW}) - (\\Delta G^\\mathrm{host}_\\mathrm{elec} + \\Delta G^\\mathrm{host}_\\mathrm{vdW} ) \n\\end{equation}\n\nTry to perform these steps:\n1. Compute the discharging and vanishing free energy for the solvated and bound phase using the standard `analyse_freenrg mbar` command. Thus, retrieve the binding free energy using the equation above\n2. Compute the discharging and vanishing free energy by adding the option `--subsampling` and discarding the first 500 frames (`discard 500`). What do you notice? What is happening to TI? and MBAR? What is the final binding free energy?\n3. What conclusions can you draw from the previous points?\n\n\n\n```python\n#1. Compute the discharging and vanishing free energy for the solvated and bound phase:\n#bound phase -discharging\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/bound/run001/discharge/output/lambda-*/simfile.dat -o bound_discharge.dat\n#bound phase -vanishing\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/bound/run001/vanish/output/lambda-*/simfile.dat -o bound_vanish.dat\n#solvated phase -discharging\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/free/run001/discharge/output/lambda-*/simfile.dat -o free_discharge.dat\n#solvated phase -vanishing\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/free/run001/vanish/output/lambda-*/simfile.dat -o free_vanish.dat\n\n```\n\n\n```python\n#helper function to extract DG from the freenrg_analysis generated files. \ndef get_free_energy(ifile):\n reader = open(ifile,\"r\").readlines()\n mbar = float(reader[-3].split(\",\")[0])\n ti = float(reader[-1].split()[0])\n return mbar, ti\n```\n\n\n```python\n#Extract the free energy changes from the output files\nbound_discharge_mbar, bound_discharge_ti = get_free_energy('bound_discharge.dat')\nbound_vanish_mbar,bound_vanish_ti = get_free_energy('bound_vanish.dat')\n\nfree_discharge_mbar,free_discharge_ti = get_free_energy('free_discharge.dat')\nfree_vanish_mbar, free_vanish_ti = get_free_energy('free_vanish.dat')\n\n#Compute the free energy change in the bound and water phase for mbar\nDG_bound_mbar =\nDG_free_mbar = \n#Compute the free energy change in the bound and water phase for TI\nDG_bound_ti = \nDG_free_ti = \n\n\n#Thus, using the equation above, compute the estimation of binding free energy using mbar and TI\nDG_bind_mbar = DG_free_mbar - DG_bound_mbar \nDG_bind_ti = \n\n#What is the binding free energy with MBAR? and with TI?\n\n```\n\n\n```python\n#3. Try to re run using the --discard option. What do you notice?\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/bound/run001/discharge/output/lambda-*/simfile.dat -o bound_discharge.dat --subsampling --discard 500\n#bound phase -vanishing\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/bound/run001/vanish/output/lambda-*/simfile.dat -o bound_vanish.dat --subsampling --discard 500\n#solvated phase -discharging \n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/free/run001/discharge/output/lambda-*/simfile.dat -o free_discharge.dat --subsampling --discard 500\n#solvated phase -vanishing\n!~/sire_2018/sire.app/bin/analyse_freenrg mbar -i subsampling/free/run001/vanish/output/lambda-*/simfile.dat -o free_vanish.dat --subsampling --discard 500\n\n\n```\n\n\n```python\n#Extract the free enery change from the output files\nbound_discharge_mbar, bound_discharge_ti = get_free_energy('bound_discharge.dat')\nbound_vanish_mbar,bound_vanish_ti = get_free_energy('bound_vanish.dat')\n\nfree_discharge_mbar,free_discharge_ti = get_free_energy('free_discharge.dat')\nfree_vanish_mbar, free_vanish_ti = get_free_energy('free_vanish.dat')\n\n#Compute the free energy change in the bound and water phase for mbar\nDG_bound_mbar =\nDG_free_mbar = \n#Compute the free energy change in the bound and water phase for TI\nDG_bound_ti = \nDG_free_ti =\n\n\n#Thus, using the equation above, compute the estimation of binding free energy using mbar and TI\nDG_bind_mbar = \nDG_bind_ti = \n\n#What is the binding free energy with MBAR? and with TI?\n\n```\n\nThe experimental standard binding free energy $\\Delta G^\\circ_\\mathrm{bind}$ is 7.08 $\\pm$ 0.01 kcal$\\cdot$mol$^{-1}$.\nAlthough our predictions are quite far apart, the subsampling and discard show an improvement of about 1 kcal$\\cdot$mol$^{-1}$ on the final MBAR free energy estimation. On the other side, TI fails to correctly predict the binding in this case. This is due to the noise present along the simulation, which greatly influences the free energy gradients values, thus the final free energy integration. Such a behaviour does not exist in MBAR, which is always consistent for all the evaluation process.\nFinally, it is worth to mention that this is just the first step toward accurate predictions. What w ehave obtained here is just a binding free energy $\\Delta G_\\mathrm{bind}$ which cannot be compared to the experimental value. Indeed, we are missing the definition of a standard state for the simulation, thus a standard state correction term for the free energy evaluation. Additionally, we should consider also Lennard Jones corrections and electrostatic finite size artefacts correction, which can remarkably improve the final free energy estimation.\n\n\n\n\nCongratulations you have finished this tutorial! Time for a coffee or tea break :-)\n", "meta": {"hexsha": "83dc2931a92e0bf5496d3ae034d2492ce2bfd29f", "size": 13886, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Exercises/07_things_gone_wrong/Exercise.ipynb", "max_stars_repo_name": "michellab/CCP-BioSim-Workshop", "max_stars_repo_head_hexsha": "d94108514eaf7f5201f56ebd8574c0bb39fa1a38", "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": "Exercises/07_things_gone_wrong/Exercise.ipynb", "max_issues_repo_name": "michellab/CCP-BioSim-Workshop", "max_issues_repo_head_hexsha": "d94108514eaf7f5201f56ebd8574c0bb39fa1a38", "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": "Exercises/07_things_gone_wrong/Exercise.ipynb", "max_forks_repo_name": "michellab/CCP-BioSim-Workshop", "max_forks_repo_head_hexsha": "d94108514eaf7f5201f56ebd8574c0bb39fa1a38", "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": 40.3662790698, "max_line_length": 562, "alphanum_fraction": 0.6427336886, "converted": true, "num_tokens": 2535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.13296422989056964, "lm_q1q2_score": 0.05466304204579944}} {"text": "# Kerja Gaya Gesek\n\nMarshanda Tiana Sarjito\n10219066\nmrshndtianasarjito@gmail.com\nhttps://github.com/MarshandaTiana\n\nKerja yang dilakukan oleh gaya gesek merupakan bentuk kerja yang tidak diharapkan karena energi yang dikeluarkan, biasanya dalam bentuk panas atau bunyi yang dilepas ke lingkungan, tidak dapat dimanfaatkan lagi oleh sistem sehingga energi sistem berkurang.\n\n## Gerak Benda di Atas Lantai Mendatar Kasar\n\nSistem yang ditinjau adalah suatu benda yang bergerak di atas lantai mendatar kasar. Benda diberi kecepatan awal tertentu dan bergerak melambat sampai berhenti karena adanya gaya gesek kinetis antara benda dan lantai kasar.\n\n### Parameter \n\nBeberapa parameter yang digunakan adalah seperti pada tabel berikut ini.\n\nTabel 1. Simbol beserta satuan dan artinya\n\nSimbol | Satuan | Arti\n:-: | :-: | :-\n$t$ | s | waktu\n$v_0$ | m/s | kecepatan awal\n$x_0$ | m | posisi awal\n$v$ | m/s | kecepatan saat $t$\n$x$ | m | posisi saat $t$\n$a$ | m/s$^2$ | percepatan\n$\\mu_k$ | - | koefisien gesek kinetis\n$f_k$ | N | gaya gesek kinetis\n$m$ | kg | massa benda\n$F$ | N | total gaya yang bekerja\n$N$ | N | gaya normal\n$w$ | N | gaya gravitasi\n\nSimbol-simbol pada Tabel 1 akan diberi nilai kemudian saat diimplementasikan dalam program.\n\n## Persamaan \n\nPersamaan-persamaan yang akan digunakan adalah seperti dicantumkan pada bagian ini.\n\n### Kinematika\n\nHubungan antara antara kecepatan $v$, kecepatan awal $v_0$\n, percepatan $a$, dan waktu $t$ diberikan oleh\n\n\\begin{equation}\\label{eqn1}\\tag{1}\nv = v_0 + at\n\\end{equation}\n\nPosisi benda $x$ bergantung pada posisi awal $x_0$, kecepatan awal \n$v_0$, percepatan $a$, dan waktu $t$ melalui hubungan\n\n\\begin{equation}\\label{eqn2}\\tag{2}\nx = x_0 + v_0t + \\frac{1}{2}at^2\n\\end{equation}\n\nSelain kedua persamaan sebelumnya, terdapat pula persamaan berikut\n\n\\begin{equation}\\label{eqn3}\\tag{3}\nv^2 = v_0^2 + 2a(x-x_0)\n\\end{equation}\n\nyang menghubungkan kecepatan $v$ dengan kecepatan awal $v_0$, percepatan $a$, dan jarak yang ditempuh $x-x_0$.\n\n### Dinamika\n\nHukum Newton I menyatakan bahwa benda yang semula diam akan tetap diam dan yang semula bergerak dengan kecepatan tetap akan tetap bergerak dengan kecepatan tetap bila tidak ada gaya yang bekerja pada benda atau jumlah gaya-gaya yang bekerja sama dengan nol\n\n\\begin{equation}\\label{eqn4}\\tag{4}\n\\sum F = 0\n\\end{equation}\n\nBila ada gaya yang bekerja pada benda bermassa $m$ atau jumlah gaya-gaya tidak nol\n\n\\begin{equation}\\label{eqn5}\\tag{5}\n\\sum F = ma\n\\end{equation}\n\nmaka keadaan gerak benda akan berubah melalui percepatan $a$, dengan $m$ > 0 dan $a \\neq 0$\n\n### Usaha\n\nUsaha oleh suatu gaya $F$ dengan posisi awal $x_0$ dan posisi akhir $x$ dapat diperoleh melalui\n\n\\begin{equation}\\label{eqn6}\\tag{6}\nW = \\int_{x_0}^{x} F dx\n\\end{equation}\n\natau dengan \n\n\\begin{equation}\\label{eqn7}\\tag{7}\nW = \\Delta K\n\\end{equation}\n\ndengan $K$ adalah energi kinetik. Persamaan \\eqref{eqn7} akan memberikan gaya oleh semua gaya. Dengan demikian bila $F$ adalah satu-satunya gaya yang bekerja pada benda, maka persamaan ini akan menjadi Persamaan \\eqref{eqn6}\n\n## Sistem\n\nIlustrasi sistem perlu diberikan agar dapat terbayangan dan memudahkan penyelesaian masalah. Selain itu juga perlu disajikan diagram gaya-gaya yang bekerja pada benda.\n\n### Ilustrasi \n\nSistem yang benda bermassa $m$ bergerak di atas lantai kasar dapat digambarkan seperti berikut ini.\n\n\n```python\n%%html\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n image/svg+xml\n \n \n \n \n \n v0\n \n \n \n \n v = 0\n μk > 0\n m\n \n g\n x0\n x\n \n\n\n
    \n\nGambar 1. Sistem benda bermassa $m$ begerak di atas lantai\nmendatar kasar dengan koefisien gesek kinetis $\\mu_k$.\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 image/svg+xml\n \n \n \n \n \n v0\n \n \n \n \n v = 0\n μk > 0\n m\n \n g\n x0\n x\n \n\n\n
    \n\nGambar 1. Sistem benda bermassa $m$ begerak di atas lantai\nmendatar kasar dengan koefisien gesek kinetis $\\mu_k$.\n\n\n\nKeadaan akhir benda, yaitu saat kecepatan $v=0$ diberikan pada bagian kanan Gambar 1 dengan warna abu-abu.\n\n### Diagram Gaya\n\nDiagram gaya-gaya yang berja pada benda perlu dibuat berdasarkan informasi dari Gambar 1 dan Tabel 1, yang diberikan berikut ini.\n\n\n```python\n%%html\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n image/svg+xml\n \n \n \n \n \n N\n v\n \n w\n \n g\n \n \n \n \n \n \n fk\n \n\n\n
    \n\nGambar 2. Diagram gaya-gaya yang bekerja pada benda\nbermassa $m$.\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 image/svg+xml\n \n \n \n \n \n N\n v\n \n w\n \n g\n \n \n \n \n \n \n fk\n \n\n\n
    \n\nGambar 2. Diagram gaya-gaya yang bekerja pada benda\nbermassa $m$.\n\n\n\nTerlihat bahwa pada arah $y$ terdapat gaya normal $N$ dan gaya gravitasi $w$, sedangkan pada arah $x$ hanya terdapat gaya gesek kinetis $f_k$ yang melawan arah gerak benda. Arah gerak benda diberikan oleh arah kecepatan $v$.\n\n## Metode Numerik\n\nIntegrasi suatu fungsi $f(x)$ berbentuk \n\n\\begin{equation}\\label{eqn8}\\tag{8}\nA = \\int_{a}^{b} f(x) dx\n\\end{equation}\n\ndapat didekati dengan \n\n\\begin{equation}\\label{eqn9}\\tag{9}\nA \\approx \\sum_{i=0}^{N} f [\\frac{1}{2}(x_i+x_{i+1} )]\\Delta x \n\\end{equation}\n\nyang dikenal sebagai metode persegi titik tengah, dimana \n\n\\begin{equation}\\label{eqn10}\\tag{10}\n\\Delta x = \\frac{b-a}{N}\n\\end{equation}\n\ndengan $N$ adalah jumlah partisi. Variabel $x_i$ pada Persamaan \\eqref{eqn9} diberikan oleh \n\n\\begin{equation}\\label{eqn11}\\tag{11}\nx_i = a + i\\Delta x\n\\end{equation}\n\ndengan $i = 0,...,N$.\n\n### Penyelesaian\n\nPenerapan 1, 2, 3, 4, dan 5 pada gambar 2 akan menghasilkan\n\n\\begin{equation}\\label{eqn12}\\tag{12}\nf_k = \\mu_kmg\n\\end{equation}\n\ndan usahanya adalah \n\n\\begin{equation}\\label{eqn13}\\tag{13}\nW = \\int_{x_0}^{x} f_k dx\n = \\int_{x_0}^{x} \\mu_kmg dx\n = mg\\int_{x_0}^{x} \\mu_k dx\n\\end{equation}\n\ndengan koefisien gesek statisnya dapat merupakan fungsi dari posisi $\\mu_k = \\mu_k(x)$\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.ion()\n\n# set integral lower and upper bounds\na = 0\nb = 1\n\n# generate x\nx = [1, 2, 3, 4, 5]\n\n# generate y from numerical integration\ny = [1, 2, 3, 5, 6]\n\n## plot results\nfig, ax = plt.subplots()\nax.scatter(x, y)\nax.set_xlabel(\"$x - x^0$\")\nax.set_ylabel(\"y\")\n\nfrom IPython import display\nfrom IPython.core.display import HTML\nHTML('''\n
    \nGambar 3. Kurva antara usaha $W$ dan jarak tempuh $x - x_0$.\n
    \n''')\n```\n\n## Diskusi \n\nBerdasarkan Gambar 3 dapat dijelaskan bahwa dengan $\\mu_k=\\mu_k(x)$ maka kurva $W(x)$ tidak lagi linier karena dipengaruhi oleh sejauh mana perhitungan kerja dilakukan. \n\n## Kesimpulan \n\nPerhitungan kerja dengan $\\mu_k=\\mu_k(x)$ telah dapat dilakukan \n\n## Referensi\n\nJ. A. C. Martins, J. T. Oden, F. M. F. Simões, \"A study of static and kinetic friction\", International Journal of Engineerting Science, vol 28, no 1, p 29-92, 1990, url https://doi.org/10.1016/0020-7225(90)90014-A.\n\nCarl Rod Nave, \"Friction\", HyperPhysics, 2017, url http://hyperphysics.phy-astr.gsu.edu/hbase/frict.html#fri [20220419].\n\nWikipedia contributors, \"Friction\", Wikipedia, The Free Encyclopedia, 12 April 2022, 00:33 UTC, url https://en.wikipedia.org/w/index.php?oldid=1082223658 [20220419].\n\nTia Ghose, Ailsa Harvey, \"What is friction?\", Live Science, 8 Feb 2022, url https://www.livescience.com/37161-what-is-friction.html [20220419].\n\n\n```python\n\n```\n", "meta": {"hexsha": "3f2c8dbb3a6238318f549a8680e54463eb3e1532", "size": 77489, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignments/05/10219066/Assignment 5 fiskommm.ipynb", "max_stars_repo_name": "MarshandaTiana/fi3201-01-2021-2", "max_stars_repo_head_hexsha": "d1317f788a9542eccd167ef869545174c8a51cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-18T22:29:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T22:29:24.000Z", "max_issues_repo_path": "assignments/05/10219066/Assignment 5 fiskommm.ipynb", "max_issues_repo_name": "MarshandaTiana/fi3201-01-2021-2", "max_issues_repo_head_hexsha": "d1317f788a9542eccd167ef869545174c8a51cf5", "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": "assignments/05/10219066/Assignment 5 fiskommm.ipynb", "max_forks_repo_name": "MarshandaTiana/fi3201-01-2021-2", "max_forks_repo_head_hexsha": "d1317f788a9542eccd167ef869545174c8a51cf5", "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": 45.8243642815, "max_line_length": 5504, "alphanum_fraction": 0.5284233891, "converted": true, "num_tokens": 17129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.310694383214554, "lm_q2_score": 0.17553806931030444, "lm_q1q2_score": 0.05453869217503867}} {"text": "# Python Programming\n\n**What is Python?** source: [python.org](https://www.python.org/doc/essays/blurb/)\n\nPython is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.\n\nOften, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.\n\n**What is Python capable of?***\n\nLong answer short: everything. Most often Python is used for web developments and prototyping, using frameworks such as [Flask](http://flask.palletsprojects.com/en/1.1.x/) and [Django](https://www.djangoproject.com/). Because of its simplicity, it is also popularly used in data science, both in industry and in academia.\n\n\nIn this lab, we mainly cover the following python programming topics:\n\n
      \n
    • data types
    • \n
    • built-in data structure
    • \n
    • I/O in Python
    • \n
    • loops in Python
    • \n
    • function and class
    • \n
    \n\n## Data Types\n\n\n```python\n# integer\na = 1\nprint('I am an integer:', a)\n```\n\n\n```python\n# float -> decimal numbers\na = 1.0\nprint('I am a float:', a)\n```\n\n\n```python\n# strings -> an array of characteristics\na = \"GOTO Chicago Fall 2019\"\nprint('I am a string:', a)\n```\n\n\n```python\n# boolean -> binary\na = True\nprint('I am a binary:', a)\n```\n\n**Data Type Conversion**\n\n\n```python\n# integer to float\na = 1\nprint('I was an integer:', a, ', but now I am a float:', float(a))\n```\n\n\n```python\n# float to integer\na = 1.0\nprint('I was a float:', a, ', but now I am an integer:', int(a))\n```\n\n\n```python\n# string to integer/float\na = '1.0'\nprint('I was a string: \"'+ a +'\", but now I am a number:', eval(a))\n```\n\n\n```python\n# integer/float to string\na = 1.0\nprint('I was a number:', a, ', but now I am a string:', str(a))\n```\n\nAdditional material for reading if interested: [source](https://www.geeksforgeeks.org/type-conversion-python/)\n\n## Data Structures\n\n\n```python\n# list -> mutable\na = [1, 2, 3, 'a', 'b', 'c']\nprint('I am a list:', a)\n```\n\n\n```python\n# tuple -> immutable\na = (1, 2, 3, 'a', 'b', 'c')\nprint('I am a tuple:', a)\n```\n\n\n```python\n# dictionary\na = {'1': 'a', 2: 'b', 'c': 3}\nprint('I am a dictionary:', a)\n```\n\n**List**\n\nList is mutable, meaning after a list is defined, you can alter the values stored in it. **Tuple** is not mutable, meaning once it's defined, you can't change the values. Let's focus on the list for now.\n\n\n```python\na = [1, 2, 3]\n```\n\n\n```python\n# select an item\na[0]\n```\n\n\n```python\n# select a range of items\na[0:2]\n```\n\n\n```python\n# add an item\n# method 1: append to the end of the list\na.append(4)\na\n```\n\n\n```python\n# method 2: insert into a specific position\na.insert(2, 10)\na\n```\n\n\n```python\n# remove an item\n# method 1: pop the last item in the list\na.pop()\n```\n\n\n```python\na\n```\n\n\n```python\n# method 2: remove a specific position\na.pop(2)\n```\n\n\n```python\na\n```\n\n\n```python\n# method 3: remove a specific value\na.remove(3)\n```\n\n\n```python\na\n```\n\n**Dictionary**\n\n\n```python\n# initiate an empty dictionary\na = dict()\na\n```\n\n\n```python\n# add an item\n# dictionary[key_name]= value_name\na['my_key'] = 'my_value'\na['my_key_2'] = 'my_value_2'\na\n```\n\n\n```python\n# select a value based on key\na['my_key']\n```\n\n\n```python\n# remove an item\n# method 1: pop the item added last\na.popitem()\n```\n\n\n```python\na\n```\n\n\n```python\n# method 2: pop the key\na.pop('my_key')\n```\n\n\n```python\na\n```\n\n**Substring**\n\n\n```python\na = 'I am a string.'\n```\n\n\n```python\n# select a sub string out of the main string\na[:5]\n```\n\n## Input/Output (I/O) in Python\n\nImagine you're reading a book, what are the steps for you to finish the process of reading a book? It should all include three steps,\n\n
      \n
    1. Open the book
    2. \n
    3. Read the book
    4. \n
    5. Close the book
    6. \n
    \n\nSimilar in Python, to read a text file from your local, you need to open a the file, read the content, and close the file. Here is how to do it.\n\n**Step-by-Step Version**\n\n\n```python\n# open the file\npath = './data/dummy.txt'\nfile = open(path, 'r')\n```\n\n`r` denotes read only mode.\n\n\n```python\n# read the content\ncontent = file.read()\n```\n\n\n```python\nprint(content)\n```\n\n\n```python\n# close the file\nfile.close()\n```\n\nNow you can work with the content in `content` variable\n\n\n```python\ncontent\n```\n\n\n```python\n# split() is a built-in method with Python's string datatype that splits a string using the sub-string \n# specified; if nothing is specified, it splits by a single space by default\ncontent.split('\\n')\n```\n\n**Question:** What is the output data structure of the split method?\n\n**\"All-in-One\" or The Clean Version**\n\n\n```python\n# \"with\" method takes care of closing the file so you don't have to worry about that\nwith open('./data/dummy.txt', 'r') as file:\n content2 = file.read()\n```\n\n\n```python\ncontent2\n```\n\nThough you may have heard about tools like `Pandas` and `Numpy` that take care of I/O for you, knowing how to correctly read files using native Python is also important because data come in different formats.\n\n## Loops in Python\n\nGiven that you are already a developer, this section is just to show you how to write for and while loops in Python.\n\n\n**For Loop**\n\n\n```python\nmy_list = [1, 2, 3, '4', '5', '7', True]\n```\n\n\n```python\nfor item in my_list: # loop through the list\n if isinstance(item, str): # if the item is a string\n print(item, 'is a string.')\n else:\n print(item, 'is not a string.')\n```\n\n**While Loop**\n\n\n```python\ni = 0\nwhile i < len(my_list):\n item = my_list[i]\n if isinstance(item, str): # if the item is a string\n print(item, 'is a string.')\n else:\n print(item, 'is not a string.')\n i += 1\n```\n\n**Break and Continue**\n\n`break`: it breaks out of a for loop and continue the code\n\n`continue`: it skips the rest of the code in the current loop and moves onto the next iteration\n\n\n```python\nfor item in my_list:\n if not isinstance(item, str):\n continue\n print('this is not a string.. this line is not even executed at all')\n else:\n print(item)\n```\n\n**Q&A:** What happens if we swap out `continue` with `break`?\n\n## Function and Class\n\nA `function` is a set of python instructions/statements that take in inputs, do things to them, and output the results out. Note: This is the standard function definition, and not all functions need to take in inputs and/or returns output.\n\nA `class` is a code template that creates objects and it contains one or more functions. If you have experience in Java, it is just like the Java class.\n\n\n```python\n# function example\ndef my_function(a_input): # define a function\n output = str(a_input) + ' is the input' # do something to the input\n return output # return output\n```\n\n\n```python\nmy_function(5)\n```\n\n\n```python\n# class example\nclass my_class(object):\n \"\"\"i am a doc string :) \"\"\"\n \n def __init__(self, input_str=None):\n \"\"\"I am the first function to be called when a new object is initiated\"\"\"\n self.input_str = str(input_str)\n self.output_str = None\n \n def do_something(self):\n \"\"\"I am a separate method that does something in this class\n Note that I don't have to return anything here\n \"\"\"\n self.output_str = self.input_str + ' is the input'\n \n def give_me_output(self):\n return self.output_str\n```\n\n\n```python\nnew_instance = my_class(5) # at this step, __init__ is called\n```\n\n\n```python\nnew_instance.do_something() # here, do_something() is called\n```\n\n\n```python\nnew_instance.give_me_output() # here, give_me_output() is called\n```\n\nFinally, if you care about code styling a lot, which you should, feel free to check out PEP 8 Python coding styling standards [here](https://www.python.org/dev/peps/pep-0008/).\n\n**Exercise**\n\nIf time permits, try build a calculator that does the following in Python.\n
      \n
    • Addition
    • \n
    • Subtraction
    • \n
    • Multiplication
    • \n
    • Division
    • \n
    \n\n\n```python\nclass MyCalculator(object):\n \"\"\"insert your doc string here\"\"\"\n \n def __init__(self):\n pass\n \n def add(self):\n pass\n \n def subtract(self):\n pass\n \n def multiply(self):\n pass\n \n def divide(self):\n pass\n```\n\n# Statistics\n\nWhew, I'm sure the Python section bored you out a little. Let's learn something more fun.\n\n\n\nLet's first use Python's `random` module to generate 1,000,000 random numbers.\n\n\n```python\nimport random\nrandom.seed(1234) \n# by setting a seed, you can ensure every time you run this block of code, the output is the same\n\ndataset = [random.random() for _ in range(1_000_000)] \n# underscore means that variable is not important to store\n\nimport statistics # let's import this for later\n```\n\n\n```python\nlen(dataset)\n```\n\n\n```python\ndataset[:5]\n```\n\n**Arithmetic Mean a.k.a. Average**\n\n\n```python\ndef average(arr):\n return sum(arr) / len(arr)\n```\n\n\n```python\nmean = average(dataset)\n```\n\n\n```python\nmean\n```\n\n\n```python\n# validate\nstatistics.mean(dataset)\n```\n\n**Median**\n\n\n```python\ndef median(arr):\n arr = sorted(arr)\n median_index = int(len(arr) / 2)\n if len(arr) % 2 == 0: # if the list has even number of elements\n median = average([arr[median_index], arr[median_index-1]])\n else:\n median = arr[median_index]\n return median\n```\n\n\n```python\nmedian(dataset)\n```\n\n\n```python\n# validate\nstatistics.median(dataset)\n```\n\n**Variance**\n\n\n```python\ndef variance(arr):\n mean = average(arr) # note that I am using the average() function here\n variance = sum(\n map(lambda i: (i-mean)**2, arr)\n ) / (len(arr) - 1)\n return variance\n```\n\n`map` operation \"maps\" a function to every element of a collection passed in the second section.\n\n`lambda` is a Python way to explicitly define small-scale function anonymously; see more [here](https://realpython.com/python-lambda/)\n\n\n```python\nvariance(dataset)\n```\n\n\n```python\n# validate\nstatistics.variance(dataset)\n```\n\n**Standard Deviation**\n\n\n```python\ndef stdv(arr):\n var = variance(arr)\n standard_deviation = var ** 0.5\n return standard_deviation\n```\n\n\n```python\nstdv(dataset)\n```\n\n\n```python\n# validate\nstatistics.stdev(dataset)\n```\n\nOk... I got the math now, but what do all of these mean???????\n\n\n\n\n\nNomral distribution is a bell-curve shaped distribution, where `mean` equals to `median`. In addition, it is estimated that \n\n
      \n
    • 68% of the data fall between +/-1 standard deviation>
    • \n
    • 95% of the data fall between +/-2 standard deviation>
    • \n
    • 99% of the data fall between +/-3 standard deviation>
    • \n
    \n\nTo calculate how far the value is away from the sample mean, `z-score` is calculated which we do not cover today. Read more about `z-score` [here](https://www.investopedia.com/terms/z/zscore.asp).\n\n## Let's Make It A Bit More Complicated\n\nWe've been focusing on one variable. Let's now look into the descriptive statistics of two variables.\n\nAssuming we have two variables, `X` and `Y`, we can calculate the same descriptive statistics above for both of them such that\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    Average \n \\begin{equation}\n \\bar{X} = \\frac{\\displaystyle\\sum_{i=1}^n x_i}{n}\n \\end{equation}\n \n \\begin{equation}\n \\bar{Y} = \\frac{\\displaystyle\\sum_{i=1}^n y_i}{n}\n \\end{equation}\n
    Variance \n \\begin{equation}\n Var(X) = \\sigma_x^2 = \\frac{\\displaystyle\\sum_{i=1}^{n}(x_i - \\bar{X})^2} {n-1}\n \\end{equation}\n \n \\begin{equation}\n Var(Y) = \\sigma_y^2 = \\frac{\\displaystyle\\sum_{i=1}^{n}(y_i - \\bar{Y})^2} {n-1}\n \\end{equation}\n
    Standard Deviation \n \\begin{equation}\n Stdev(X) = \\sqrt{Var(X)}\n \\end{equation}\n \n \\begin{equation}\n Stdev(Y) = \\sqrt{Var(Y)}\n \\end{equation}\n
    \n\n**Covariance**\n\nCovariance is a measure of how much two random variables vary together.\n\n\\begin{equation}\n cov_{x,y}=\\frac{\\displaystyle\\sum_{i=1}^{N}(x_{i}-\\bar{x})(y_{i}-\\bar{y})}{N-1}\n\\end{equation}\n\nIf the covariance is positive, it tells us that the two variables are positively related, and vice versa. However, covariance does not have a upper nor lower limit, thus we cannot compare the magnitude of inter-variable relationship.\n\n**Correlation**\n\nCorrelation coefficients are used to measure how strong the relationship is between two variables. There are several types of correlation coefficients and Pearson's Correlation is commonly used in describing linear relations.\n\n\\begin{equation}\n cor_{x,y} = \\frac{cov_{x, y}}{\\sigma_x\\sigma_y}\n\\end{equation}\n\n\n```python\n# Let's generate two random variables with the same size\nimport numpy as np\n# numpy (Numerical Python) is a very popular data science tool (https://numpy.org/)\n\nx = np.random.random(1_000_000)\ny = np.random.random(1_000_000)\n```\n\n\n```python\nlen(x), len(y)\n```\n\n\n```python\nx[:5]\n```\n\n\n```python\n# Let's calculate covariance\nnp.cov(x, y)\n```\n\nThe output above is known as `variance-covariance matrix`, where the diagonal represents the variance of each variable, and the other positions represents the covariance of different variable pairs, such that\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    XY
    XVar(X)Cov(X, Y)
    YCov(X, Y)Var(Y)
    \n\n**Note:** Cov(X, X) is equal to Var(X)\n\n\n```python\n# Let's calculate correlation\nnp.corrcoef(x, y)\n```\n\nThe output above is known as `correlation matrix`, where the diagonal represents the correlation of the variable with itself, and the other positions represents the correlation of different variable pairs, such that\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    XY
    XCorr(X, X)Corr(X, Y)
    YCorr(X, Y)Corr(Y, Y)
    \n\n**Note:** Corr(X, X) is 1 -> A variable is perfectly postiively correlated with itself.\n\n# Recap\n\nIn this session, we've covered\n\n
      \n
    1. Basic Python programming
    2. \n
    3. Statistics for single variable
    4. \n
    5. Descriptive statistics for two variables
    6. \n
    \n\nYou should be able to\n
      \n
    1. Complete the Calculator exercise
    2. \n
    3. Explain what descriptive statistics are appropriate for sing variable
    4. \n
    5. Interpret the implications of descriptive statistics
    6. \n
    7. Explain the difference between covariance and correlation
    8. \n
    9. Interpret Pearson's Correlation Coefficient
    10. \n
        \n\n\n```python\n\n```\n", "meta": {"hexsha": "83ee77e657b26589b9a3b0a760e78c7064bc683e", "size": 31271, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "labs/lab-1-python-and-statistics.ipynb", "max_stars_repo_name": "ilmstudios/GOTO19-MC-Data-Science", "max_stars_repo_head_hexsha": "44f04b1f330bca73c14dd8f7c8cbcc01fba10082", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-13T18:01:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T17:32:49.000Z", "max_issues_repo_path": "labs/lab-1-python-and-statistics.ipynb", "max_issues_repo_name": "ilmstudios/GOTO19-MC-Data-Science", "max_issues_repo_head_hexsha": "44f04b1f330bca73c14dd8f7c8cbcc01fba10082", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-11-13T21:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T20:28:25.000Z", "max_forks_repo_path": "labs/lab-1-python-and-statistics.ipynb", "max_forks_repo_name": "ilmstudios/GOTO19-MC-Data-Science", "max_forks_repo_head_hexsha": "44f04b1f330bca73c14dd8f7c8cbcc01fba10082", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-13T18:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-13T18:01:48.000Z", "avg_line_length": 24.4687010955, "max_line_length": 891, "alphanum_fraction": 0.5153017172, "converted": true, "num_tokens": 4397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.1732882123335211, "lm_q1q2_score": 0.05442125974905359}} {"text": "

        Dinámica

        \n

        Capítulo 2: Cinemática y Cinética de partículas

        \n

        Movimiento curvilíneo

        \n

        2021/02

        \n

        MEDELLÍN - COLOMBIA

        \n\n\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***Docente:*** Carlos Alberto Álvarez Henao, I.C. D.Sc.\n\n***e-mail:*** carlosalvarezh@gmail.com\n\n***skype:*** carlos.alberto.alvarez.henao\n\n***Linkedin:*** https://www.linkedin.com/in/carlosalvarez5/\n\n***github:*** https://github.com/carlosalvarezh/Dinamica\n\n***Herramienta:*** [Jupyter](http://jupyter.org/)\n\n***Kernel:*** Python 3.9\n\n\n***\n\n

        Tabla de Contenidos

        \n\n\n

        \n \n

        \n\n\n\n\n## Movimiento curvilíneo General\n\n### Definición\n\nEl [movimiento curvilíneo](https://en.wikipedia.org/wiki/Curvilinear_motion) es aquél que se describe cuando una partícula se desplaza a lo largo de una trayectoria curva ([parabólico](https://en.wikipedia.org/wiki/Projectile_motion), [oscilatorio](https://en.wikipedia.org/wiki/Oscillation) o [circular](https://en.wikipedia.org/wiki/Circular_motion)). Se emplearán los conceptos de [análisis vectorial](https://en.wikipedia.org/wiki/Vector_calculus) para describir la posición, velocidad y aceleración de la partícula en las tres dimensiones espaciales. En este capítulo se considerarán también tres tipos de [sistemas de coordenadas](https://en.wikipedia.org/wiki/Coordinate_system) usadas frecuentemente en el análisis de este tipo de movimiento.\n\n\n### Posición\n\n

        \n \n

        \n\n\n\nSea una partícula situada en un punto de una curva espacial definida por la función de trayectoria $s(t)$. El vector de posición $\\vec{\\boldsymbol{r}} = \\vec{\\boldsymbol{r}}(t)$ designará la posición de la partícula, medida con respecto a un punto fijo $O$. Tanto la magnitud como la dirección de este vector cambiarán a medida que la partícula se mueve a lo largo de la curva.\n\n### Desplazamiento\n\n

        \n \n

        \n\n\n\nSi durante un breve intervalo $\\Delta t$ la partícula se mueve una distancia $\\Delta s$ a lo largo de la curva a una nueva posición, definida por $\\vec{\\boldsymbol{r'}} = \\vec{\\boldsymbol{r}} +\\Delta \\vec{\\boldsymbol{r}}$, el desplazamiento $\\Delta \\vec{\\boldsymbol{r}}$ representará el cambio de posición de la partícula y se determina mediante la resta vectorial $\\Delta \\vec{\\boldsymbol{r}}= \\vec{\\boldsymbol{r'}} - \\vec{\\boldsymbol{r}}$.\n\n### Velocidad\n\n

        \n \n

        \n\n\n\nDurante el tiempo $\\Delta t$, la velocidad promedio de la partícula es\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{v}}_{prom}=\\frac{\\Delta \\vec{\\boldsymbol{r}}}{\\Delta t}\n\\label{eq:Ec2_1} \\tag{2.1}\n\\end{equation*}\n\nLa *velocidad instantánea* se determina cuando $\\Delta t \\rightarrow 0$, entonces, la dirección de $\\Delta \\vec{\\boldsymbol{r}}$ tiende a la *tangente* a la curva y,\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{v}}=\\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta \\vec{\\boldsymbol{r}}}{\\Delta t}=\\frac{d{\\boldsymbol{r}}}{dt}\n\\label{eq:Ec2_2} \\tag{2.2}\n\\end{equation*}\n\nComo $\\Delta \\vec{\\boldsymbol{r}}$ será tangente a la curva, la dirección de $\\vec{\\boldsymbol{v}}$ también es tangente a la curva. La magnitud de $\\vec{\\boldsymbol{v}}$, conocida como la rapidez, se obtiene al tener en cuenta que la longitud del segmento de línea recta $\\Delta \\vec{\\boldsymbol{r}}$ tiende la longitud de arco $\\Delta s$ a medida que $\\Delta t \\rightarrow 0$, tenemos \n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{v}}=\\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta \\vec{\\boldsymbol{r}}}{\\Delta t}=\\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta s}{\\Delta t}=\\frac{ds}{dt}\n\\label{eq:Ec2_3} \\tag{2.3}\n\\end{equation*}\n\n\n### Aceleración\n\n

        \n \n

        \n\n\n\nSi la velocidad de la partícula es $\\vec{\\boldsymbol{v}}$ en el instante $t$ y $\\vec{\\boldsymbol{v'}}=\\vec{\\boldsymbol{v}}+\\Delta \\vec{\\boldsymbol{v}}$ en el instante $t + \\Delta t$, entonces la aceleración promedio de la partícula durante el intervalo $\\Delta t$ es\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{a}}_{prom}=\\frac{\\Delta \\vec{\\boldsymbol{v}}}{\\Delta t}\n\\label{eq:Ec2_4} \\tag{2.4}\n\\end{equation*}\n\nPara estudiar la tasa de cambio en el tiempo, los dos vectores de velocidad en la figura anterior se trazan en la siguiente figura\n\n

        \n \n

        \n\n\n\nde modo que sus colas queden en el punto fijo $O'$ y sus cabezas de punta de flecha toquen puntos situados en la curva. Esta curva se llama [hodógrafa](https://en.wikipedia.org/wiki/Hodograph) y describe el lugar geométrico de puntos para la cabeza de punta de flecha del vector de velocidad, así como la trayectoria $s$ describe el lugar geométrico de puntos para la cabeza de punta de flecha del vector de posición.\n\nLa *aceleración instantánea* se determina cuando $\\Delta t \\rightarrow 0$, entonces, en el límite $\\Delta \\vec{\\boldsymbol{v}}$ la tangente tenderá a la *hodógrafa* y por lo tanto\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{a}}=\\lim \\limits_{\\Delta t \\to 0} \\frac{\\Delta \\vec{\\boldsymbol{v}}}{\\Delta t}=\\frac{d{\\boldsymbol{v}}}{dt}\n\\label{eq:Ec2_5} \\tag{2.5}\n\\end{equation*}\n\neste resultado también puede ser escrito en función del vector posición $\\vec{\\boldsymbol{r}}$ de la siguiente manera\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{a}}=\\frac{d^2{\\boldsymbol{r}}}{dt^2}\n\\label{eq:Ec2_6} \\tag{2.6}\n\\end{equation*}\n\n### Comentarios al movimiento curvilíneo general\n\n- Por definición de la derivada, $\\vec{\\boldsymbol{a}}$ actúa tangente a la hodógrafa, \n\n

        \n \n

        \n\n\n\ny, en general no es tangente a la trayectoria del movimiento.\n\n

        \n \n

        \n\n\n\n\n- Tanto $\\Delta \\vec{\\boldsymbol{v}}$ como $\\vec{\\boldsymbol{a}}$, deben responder el cambio tanto de magnitud como de dirección de la velocidad $\\vec{\\boldsymbol{v}}$ a medida que la partícula se mueve de un punto al siguiente a lo largo de la trayectoria. \n\n\n- Para que la partícula siga cualquier trayectoria curva, el cambio direccional siempre *“cambia”* el vector de velocidad hacia el *“interior”* o *“lado cóncavo”* de la trayectoria, y por consiguiente a no puede permanecer tangente a la trayectoria. \n\n\n- En conclusión, $\\vec{\\boldsymbol{v}}$ siempre es tangente a la trayectoria y $\\vec{\\boldsymbol{a}}$ siempre es tangente a la hodógrafa.\n\n## Movimiento curvilíneo: Componente rectangulares\n\nEl movimiento curvilíneo también se puede expresar en función de las coordenadas $x$, $y$, $z$ que cubren su trayectoria.\n\n### Posición\n\n

        \n \n

        \n\n\n\nSi la partícula está en el punto $(x, y, z)$ de la trayectoria curva $s$, entonces su posición se definirá por el vector:\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{r}}=x\\vec{\\boldsymbol{i}}+y\\vec{\\boldsymbol{j}}+z\\vec{\\boldsymbol{k}}\n\\label{eq:Ec2_7} \\tag{2.7}\n\\end{equation*}\n\n***Comentarios:***\n\n- Cuando la partícula se mueve, las compontes del vector $\\vec{\\boldsymbol{r}}$ se representan en función del tiempo, es decir, $x(t), y(t), z(t)$. Por lo que $\\vec{\\boldsymbol{r}}=\\vec{\\boldsymbol{r}}(t)$\n\n\n- La magnitud de $\\vec{\\boldsymbol{r}}$ estará dada por la [norma euclideana](https://en.wikipedia.org/wiki/Euclidean_space#Euclidean_norm):\n\n\n\\begin{equation*}\nr=\\sqrt{x^2+y^2+z^2}\n\\label{eq:Ec2_8} \\tag{2.8}\n\\end{equation*}\n\n- La dirección del vector $\\vec{\\boldsymbol{r}}$ se determina a través del [vector unitario](https://en.wikipedia.org/wiki/Unit_vector):\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{u}}_r=\\frac{\\vec{\\boldsymbol{r}}}{r}\n\\label{eq:Ec2_9} \\tag{2.9}\n\\end{equation*}\n\n\n### Velocidad\n\n

        \n \n

        \n\n\n\nDerivando el vector posición respecto al tiempo, se obtendrá el vector velocidad:\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{v}}=\\frac{d\\vec{\\boldsymbol{r}}}{dt}=\\frac{d}{dt}(x\\vec{\\boldsymbol{i}})+\\frac{d}{dt}(y\\vec{\\boldsymbol{j}})+\\frac{d}{dt}(z\\vec{\\boldsymbol{k}})\n\\label{eq:Ec2_10} \\tag{2.10}\n\\end{equation*}\n\n***Comentarios:***\n\n- Tener en cuenta que al derivar es necesario derivar tanto la magnitud como la dirección en cada componente, es decir:\n\n\n\\begin{equation*}\n\\begin{aligned}\n\\frac{d}{dt}(x\\vec{\\boldsymbol{i}})=\\frac{dx}{dt}\\vec{\\boldsymbol{i}}+x\\frac{d\\vec{\\boldsymbol{i}}}{dt} \\\\\n\\frac{d}{dt}(y\\vec{\\boldsymbol{j}})=\\frac{dy}{dt}\\vec{\\boldsymbol{j}}+y\\frac{d\\vec{\\boldsymbol{j}}}{dt} \\\\\n\\frac{d}{dt}(z\\vec{\\boldsymbol{k}})=\\frac{dz}{dt}\\vec{\\boldsymbol{k}}+z\\frac{d\\vec{\\boldsymbol{k}}}{dt} \n\\end{aligned}\n\\label{eq:Ec2_11} \\tag{2.11}\n\\end{equation*}\n\n- El segundo término del lado derecho en cada una de las ecuaciones anteriores será cero si el marco de referencia es fijo, por lo que la dirección y magnitud de $\\vec{\\boldsymbol{i}}$ no cambia con el tiempo.\n\n\n- Es usual representar el vector velocidad también como:\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{v}}=\\frac{d\\vec{\\boldsymbol{r}}}{dt}=v_x\\vec{\\boldsymbol{i}}+v_y\\vec{\\boldsymbol{j}}+v_z\\vec{\\boldsymbol{k}}\n\\label{eq:Ec2_12} \\tag{2.12}\n\\end{equation*}\n\n- O usando la notación \"punto\" que representa las primeras derivadas de $x=x(t)$, $y=y(t)$, $z=z(t)$: $v_x=\\dot{x}$, $v_y=\\dot{y}$, $v_z=\\dot{z}$\n\n\n- La magnitud de la velocidad es a su vez:\n\n\n\\begin{equation*}\nv=\\sqrt{v_x^2+v_y^2+v_z^2}\n\\label{eq:Ec2_13} \\tag{2.13}\n\\end{equation*}\n\n\n- y el vector unitario, que especifica su dirección y es tangente a la trayectoria, está dado por:\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{u}}_v=\\frac{\\vec{\\boldsymbol{v}}}{v}\n\\label{eq:Ec2_14} \\tag{2.14}\n\\end{equation*}\n\n\n### Aceleración\n\n

        \n \n

        \n\n\n\nSacando la primera derivada del vector velocidad respecto al tiempo (o la segunda derivada del vector posición), se obtiene el vector aceleración:\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{a}}=\\frac{d\\vec{\\boldsymbol{v}}}{dt}=a_x\\vec{\\boldsymbol{i}}+a_y\\vec{\\boldsymbol{j}}+a_z\\vec{\\boldsymbol{k}}\n\\label{eq:Ec2_15} \\tag{2.15}\n\\end{equation*}\n\n***Comentarios:***\n\n- Usando la notación \"punto\": \n\n\n\\begin{equation*}\n\\begin{aligned}\na_x=\\dot{v}_x=\\ddot{x} \\\\\na_y=\\dot{v}_y=\\ddot{y} \\\\\na_z=\\dot{v}_z=\\ddot{z}\n\\end{aligned}\n\\label{eq:Ec2_16} \\tag{2.16}\n\\end{equation*}\n\n\n- La magnitud de la aceleración estará dada por,\n\n\n\\begin{equation*}\na=\\sqrt{a_x^2+a_y^2+a_z^2}\n\\label{eq:Ec2_17} \\tag{2.17}\n\\end{equation*}\n\n- el vector unitario, está dado por:\n\n\n\\begin{equation*}\n\\vec{\\boldsymbol{u}}_a=\\frac{\\vec{\\boldsymbol{a}}}{a}\n\\label{eq:Ec2_18} \\tag{2.18}\n\\end{equation*}\n\nComo la aceleración representa el cambio tanto de la magnitud como de la dirección de la velocidad, en geneeral, no es tangente a la trayectoria.\n\n### Ejemplos movimiento curvilínea componentes rectangulares\n\n#### Globo atmosférico\n\n \n \n\n\n\n
        \n\n\n\n

        En cualquier instante $x=(8t)pies$, donde $t$ está en segundos, define la posición horizontal del globo atmosférico de la figura. Si la ecuación de la trayectoria es $y = x^2/10$, determina la magnitud y dirección de la velocidad y la aceleración cuando $t = 2 s$.

        \n
        \n\n***Solución analítica:***\n\n- ***Velocidad:*** \n\nLa componente de la velocidad en la dirección $x$ se obtiene como:\n\n$$v_x=\\dot{x}=\\frac{d}{dt}(8t)=8 pies/s \\rightarrow$$\n\nPara determinar la componente de la velocidad en la dirección $y$ es necesario emplear la [regla de la cadena](https://en.wikipedia.org/wiki/Chain_rule) vista en cálculo\n\n$$v_y=\\dot{y}=\\frac{d}{dt}(x^2/10)=2x\\dot{x}/10=2(16)(8)/10=25.6pies/s \\uparrow$$\n\nen $t=2s$, la magnitud de la velocidad es:\n\n$$v=\\sqrt{(8 pies/s)^2+(25.6pies/s)^2}=26.8 pies/s$$\n\nPara determinar la dirección, se debe tener presente que ésta se calcula como el ángulo respecto al eje $x$ y es tangente a la trayectoria. \n\n

        \n \n

        \n\n\n\n$$\\theta_v=tan^{-1}\\frac{v_y}{v_x}=tan^{-1}\\frac{25.6}{8}=72.6^\\circ$$\n\n\n- ***Aceleración:***\n\nProcediendo de la misma forma que para la velocidad, se empleará la Regla de la Cadena para determinar las componentes de la aceleración\n\n$$a_x=\\dot{v}_x=\\frac{d}{dt}(8)=0$$\n$$a_y=\\dot{v}_y=\\frac{d}{dt}(2x\\dot{x}/10)=2(\\dot{x})\\dot{x}/10+2x\\ddot{x}/10$$\n\n\\begin{equation*}\n\\begin{aligned}\na_y &=\\dot{v}_y=\\frac{d}{dt}(2x\\dot{x}/10)=2(\\dot{x})\\dot{x}/10+2x\\ddot{x}/10 \\\\\n &=2(8)^2/10+2(16)(0)=12.8pies/s^2 \\uparrow\n\\end{aligned}\n\\end{equation*}\n\nla magnitud estaría dada por\n\n$$a=\\sqrt{(0)^2+(12.8)^2}=12.8 pies/s^2$$\n\ny su dirección\n\n$$\\theta_a=tan^{-1}\\frac{12.8}{0}=90^\\circ$$\n\n***Solución computacional***\n\n\n```python\nfrom sympy import *\nt = symbols('t')\ninit_printing(use_latex='mathjax')\n```\n\nPara el cálculo de las componentes de la velocidad tanto en la dirección $x$ como $y$ se procederá de la siguiente forma. \n\n- Se crean las funciones de la posición y la trayectoria\n\n\n```python\n# Ecuación de la posición x en un instante t\nx = 8 * t\n\n# Ecuación de la trayectoria\ny = x**2 / 10\n```\n\n- La velocidad es la derivada del espacio, para cada una de sus componentes, respecto al tiempo\n\n\n```python\n# Cálculo de la velocidad en la dirección x\nvx = diff(x,t)\nvx\n```\n\n\n\n\n$\\displaystyle 8$\n\n\n\n\n```python\n# Evaluación de la velocidad en x cuando t = 2 (en este caso es una constante)\nvx = vx.subs(t,2)\nvx\n```\n\n\n\n\n$\\displaystyle 8$\n\n\n\n\n```python\n# calculo de la velocidad en la dirección x, y evaluación en t=2 en una misma línea de código\nvx = diff(x,t).subs(t,2)\nvx\n```\n\n\n\n\n$\\displaystyle 8$\n\n\n\n\n```python\n# Cálculo de la velocidad en la dirección y\nvy = diff(y,t)\nvy\n```\n\n\n\n\n$\\displaystyle \\frac{64 t}{5}$\n\n\n\n\n```python\n# Evaluación de la velocidad en y cuando t = 2 y representación en punto flotante (Numerical)\nvy = N(vy.subs(t,2))\nvy\n```\n\n\n\n\n$\\displaystyle 25.6$\n\n\n\n- Se cacula la magnitud euclideana\n\n\n```python\nmagVel = sqrt(vx**2 + vy**2).evalf(3)\nmagVel\n```\n\n\n\n\n$\\displaystyle 26.8$\n\n\n\n\n```python\nmagVel = N(sqrt(vx**2 + vy**2),3)\nmagVel\n```\n\n\n\n\n$\\displaystyle 26.8$\n\n\n\n- Para el cálculo de la dirección hay qué tener en cuenta que los valores resultantes de los cálculos numéricos se expresan en [radianes](https://es.wikipedia.org/wiki/Radi%C3%A1n). Por lo que es necesario convertirlos a grados mediante la fórmula\n\n$$x[grad] = x [rad] \\times \\frac{180}{\\pi}$$\n\n\n```python\ntheta = N(atan(vy / vx) * 180 / pi, 3)\ntheta\n```\n\n\n\n\n$\\displaystyle 72.6$\n\n\n\nSe deja como ejercicio al estudiante el desarrollo del punto que corresponde a la aceleración\n", "meta": {"hexsha": "b87b96f53a52ad521f80754d39fe2260c22b8696", "size": 32881, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "C02_CinematicaCineticaParticulas_MovCurvilineo.ipynb", "max_stars_repo_name": "carlosalvarezh/Dinamica", "max_stars_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "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": "C02_CinematicaCineticaParticulas_MovCurvilineo.ipynb", "max_issues_repo_name": "carlosalvarezh/Dinamica", "max_issues_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "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": "C02_CinematicaCineticaParticulas_MovCurvilineo.ipynb", "max_forks_repo_name": "carlosalvarezh/Dinamica", "max_forks_repo_head_hexsha": "c6696cd3292416b5d91e52af3e7928686b707847", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-28T18:47:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T18:47:37.000Z", "avg_line_length": 36.0933040615, "max_line_length": 2531, "alphanum_fraction": 0.5738268301, "converted": true, "num_tokens": 6654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220179564702847, "lm_q2_score": 0.15405756269148546, "lm_q1q2_score": 0.05425935021294584}} {"text": "\n\n## Machine Translation\nA sequence-to-sequence model is a model that takes a sequence of items and outputs another sequence of items using two networks that are trained end-to-end. This is perfect for machine translation since input sequences are directly related to output sequences. We will looking at preparing a dataset for Machine Translation task and implementing a seq2seq model. We will be using the parallel corpus available from [here](ftp://ftp.monash.edu/pub/nihongo/examples.utf.gz) \n\n### Concepts covered here:\n- Encoder-Decoder architecture: We will be using a encoder to encode input sequences from one language in a latent space and use the encoding to generate words in the target language one token at a time. The encoder and the decoder are an RNNs. \n\n- Attention: We will be looking at the attention mechanism described in [Bahdanau et al., 2015](https://arxiv.org/pdf/1409.0473.pdf). We will explore the theory, the intuition behind it and how to move from theory and intuition to implementation.\n\n\n```\n%matplotlib inline\nfrom pathlib import Path\nimport re,string\nimport numpy as np\nfrom google.colab import files\n```\n\n\n```\n!mkdir data\n```\n\n\n```\npath = Path('data')\n```\n\nWe will need to download the translation corpus and install a tokenizer for Japanese text.\n\n\n```\n#get corpus\n#!wget ftp://ftp.monash.edu/pub/nihongo/examples.utf.gz\n#decompress it and move it to data folder\n#!gunzip examples.utf.gz\n#!mv examples.utf data/\n#install dependencies for mecab tokenizer\n#!sudo apt install swig\n#!sudo apt install mecab\n#!sudo apt install libmecab-dev\n#!sudo apt install mecab-ipadic-utf8\n#!sudo pip3 install mecab-python3\n```\n\n\n```\ncorpus = (path/'examples.utf').open().readlines()\ncorpus[:5]\n```\n\n\n\n\n ['A: ムーリエルは20歳になりました。\\tMuiriel is 20 now.#ID=1282_4707\\n',\n 'B: は 二十歳(はたち){20歳} になる[01]{になりました}\\n',\n 'A: すぐに戻ります。\\tI will be back soon.#ID=1284_4709\\n',\n 'B: 直ぐに{すぐに} 戻る{戻ります}\\n',\n 'A: すぐに諦めて昼寝をするかも知れない。\\tI may give up soon and just nap instead.#ID=1300_4727\\n']\n\n\n\n\n```\ndef make_corpus(corpus_path):\n corpus = corpus_path.open().readlines()\n en,ja = [],[]\n pat = r'#ID.+\\n'\n for c in corpus:\n if 'A: ' in c:\n clean_c = c.replace('A: ','')\n res = re.search(pat,clean_c)\n clean_c = clean_c.replace(res.group(0),'').split('\\t')\n ja.append(clean_c[0])\n en.append(clean_c[1])\n return en,ja\n```\n\n\n```\nen, ja = make_corpus(path/'examples.utf')\nen[:2],ja[:2]\n```\n\n\n\n\n (['Muiriel is 20 now.', 'I will be back soon.'],\n ['ムーリエルは20歳になりました。', 'すぐに戻ります。'])\n\n\n\n\n```\nimport MeCab\n```\n\n\n```\ntagger = MeCab.Tagger('-Owakati')\n\ndef ja_tokenizer(text):\n result = tagger.parse(text)\n words = result.split()\n if len(words) ==0: return []\n if words[-1] == '\\n':return words[:-1]\n return words\n```\n\n\n```\nja_tokenizer(ja[0])\n```\n\n\n\n\n ['ムーリエル', 'は', '2', '0', '歳', 'に', 'なり', 'まし', 'た', '。']\n\n\n\n\n```\nimport spacy\nfrom spacy.symbols import ORTH\n```\n\n\n```\nen_tok = spacy.load('en')\n```\n\n\n```\ndef en_tokenizer(text):\n text = text.lower()\n return [t.text for t in en_tok.tokenizer(text)]\n```\n\n\n```\nen_tokenizer(en[0])\n```\n\n\n\n\n ['muiriel', 'is', '20', 'now', '.']\n\n\n\n\n```\nen_toks = [en_tokenizer(text) for text in en]\nja_toks = [ja_tokenizer(text) for text in ja]\nen_toks[:2], ja_toks[:2]\n```\n\n\n\n\n ([['muiriel', 'is', '20', 'now', '.'],\n ['i', 'will', 'be', 'back', 'soon', '.']],\n [['ムーリエル', 'は', '2', '0', '歳', 'に', 'なり', 'まし', 'た', '。'],\n ['すぐ', 'に', '戻り', 'ます', '。']])\n\n\n\n\n```\nlen(en_toks), len(ja_toks)\n```\n\n\n\n\n (149785, 149785)\n\n\n\n\n```\nfrom collections import Counter,defaultdict\n```\n\n\n```\ndef numericalize_tok(tokens, max_vocab=50000, min_freq=0, unk_tok=\"xxunk\", pad_tok=\"xxpad\", bos_tok=\"xxbos\", eos_tok=\"xxeos\"):\n if isinstance(tokens, str):\n raise ValueError(\"Expected to receive a list of tokens. Received a string instead\")\n if isinstance(tokens[0], list):\n tokens = [p for o in tokens for p in o]\n freq = Counter(tokens)\n int2tok = [o for o,c in freq.most_common(max_vocab) if c>min_freq]\n unk_id = 3\n int2tok.insert(0, bos_tok)\n int2tok.insert(1, pad_tok)\n int2tok.insert(2, eos_tok)\n int2tok.insert(unk_id, unk_tok)\n tok2int = defaultdict(lambda:unk_id, {v:k for k,v in enumerate(int2tok)})\n return int2tok, tok2int\n```\n\n\n```\nint2j,j2int = numericalize_tok(ja_toks)\nint2en,en2int = numericalize_tok(en_toks)\n```\n\n\n```\nlen(int2j), len(int2en)\n```\n\n\n\n\n (31813, 21393)\n\n\n\n\n```\nimport pickle\n```\n\n\n```\npickle.dump(int2j,(path/'int2j.pkl').open('wb'))\npickle.dump(int2en,(path/'int2en.pkl').open('wb'))\n```\n\n\n```\nint2j = pickle.load((path/'int2j.pkl').open('rb'))\nint2en = pickle.load((path/'int2en.pkl').open('rb'))\nj2int = defaultdict(lambda:3, {v:k for k,v in enumerate(int2j)})\nen2int = defaultdict(lambda:3, {v:k for k,v in enumerate(int2en)})\n```\n\n\n```\nlen(int2j), len(int2en)\n```\n\n\n\n\n (12677, 9290)\n\n\n\n\n```\nj_ids = np.array([[0]+[j2int[o] for o in sent]+[2] for sent in ja_toks])\nen_ids = np.array([[0]+[en2int[o] for o in sent]+[2] for sent in en_toks])\nlen(j_ids),len(en_ids), j_ids[10],en_ids[10]\n```\n\n\n\n\n (149785,\n 149785,\n [0,\n 48,\n 6,\n 4891,\n 5,\n 109,\n 11,\n 143,\n 10,\n 83,\n 8,\n 57,\n 86,\n 1798,\n 7,\n 2146,\n 232,\n 255,\n 47,\n 36,\n 4,\n 2],\n [0, 114, 2251, 107, 38, 97, 85, 2649, 77, 28, 356, 4, 2])\n\n\n\n\n```\nnp.random.seed(42)\n```\n\n\n```\ntrn_keep = np.random.rand(len(en_ids))>0.1\nen_trn,j_trn = en_ids[trn_keep],j_ids[trn_keep]\nen_val,j_val = en_ids[~trn_keep],j_ids[~trn_keep]\nlen(en_trn),len(en_val)\n```\n\n\n\n\n (134774, 15011)\n\n\n\n\n```\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.autograd.variable import Variable\nfrom torch.utils.data import Dataset,DataLoader\n```\n\n\n```\nfrom numpy import array as A\n```\n\n\n```\nclass Seq2SeqDataset(Dataset):\n def __init__(self, x, y): self.x,self.y = x,y\n def __getitem__(self, idx): return A(self.x[idx]), A(self.y[idx])\n def __len__(self): return len(self.x)\n```\n\n\n```\ntrn_ds = Seq2SeqDataset(en_trn,j_trn)\nval_ds = Seq2SeqDataset(en_val,j_val)\n\nbs = 120\n\ntrn_dl = DataLoader(trn_ds,batch_size=bs,shuffle=True)\nval_dl = DataLoader(val_ds,batch_size=bs)\n```\n\n\n```\nx, y = next(iter(val_dl))\nx.size(), y.size()\n```\n\n\n\n\n (torch.Size([120, 25]), torch.Size([120, 25]))\n\n\n\n\n```\nfrom keras.preprocessing.sequence import pad_sequences\n```\n\n\n```\nenlen_90 = int(np.percentile([len(o) for o in en_ids], 99))\njalen_90 = int(np.percentile([len(o) for o in j_ids], 99))\nenlen_90,jalen_90\n```\n\n\n\n\n (25, 29)\n\n\n\n\n```\nj_ids = pad_sequences(j_ids, maxlen=29, dtype='int32', padding='post', truncating='post', value=1)\nen_ids = pad_sequences(en_ids, maxlen=25, dtype='int32', padding='post', truncating='post', value=1)\n```\n\n\n```\ntrn_keep = np.random.rand(len(en_ids))>0.1\nen_trn,j_trn = en_ids[trn_keep],j_ids[trn_keep]\nen_val,j_val = en_ids[~trn_keep],j_ids[~trn_keep]\nlen(en_trn),len(en_val)\n```\n\n\n\n\n (134746, 15039)\n\n\n\n\n```\ntrn_ds = Seq2SeqDataset(en_trn,j_trn)\nval_ds = Seq2SeqDataset(en_val,j_val)\n\nbs = 120\n\ntrn_dl = DataLoader(trn_ds,batch_size=bs,shuffle=True)\nval_dl = DataLoader(val_ds,batch_size=bs)\n```\n\n\n```\nx, y = next(iter(val_dl))\nx.size(), y.size()\n```\n\n\n\n\n (torch.Size([120, 25]), torch.Size([120, 29]))\n\n\n\n\n```\n## load fasttext vectors\n#code from here:https://github.com/facebookresearch/fastText/blob/master/docs/crawl-vectors.md\nimport io\ndef load_vectors(fname):\n fin = io.open(fname, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n header = fin.readline().split()\n n, d = int(header[0]), int(header[1])\n data = {}\n for line in fin:\n tokens = line.rstrip().split(' ')\n data[tokens[0]] = np.array(tokens[1:], dtype=float)\n return data, int(n), int(d)\n```\n\n\n```\n# get word vectors\n!wget https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec.zip\n!wget https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.ja.300.vec.gz\n!unzip wiki-news-300d-1M.vec.zip\n!gunzip cc.ja.300.vec.gz\n!mv wiki-news-300d-1M.vec data/\n!mv cc.ja.300.vec data/\n```\n\n --2019-03-15 09:27:27-- https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec.zip\n Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.20.22.166, 104.20.6.166, 2606:4700:10::6814:6a6, ...\n Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.20.22.166|:443... connected.\n HTTP request sent, awaiting response... 200 OK\n Length: 681808098 (650M) [application/zip]\n Saving to: ‘wiki-news-300d-1M.vec.zip’\n \n wiki-news-300d-1M.v 100%[===================>] 650.22M 30.1MB/s in 22s \n \n 2019-03-15 09:27:49 (29.4 MB/s) - ‘wiki-news-300d-1M.vec.zip’ saved [681808098/681808098]\n \n --2019-03-15 09:27:51-- https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.ja.300.vec.gz\n Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.20.22.166, 104.20.6.166, 2606:4700:10::6814:6a6, ...\n Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.20.22.166|:443... connected.\n HTTP request sent, awaiting response... 200 OK\n Length: 1279641604 (1.2G) [binary/octet-stream]\n Saving to: ‘cc.ja.300.vec.gz’\n \n cc.ja.300.vec.gz 100%[===================>] 1.19G 30.1MB/s in 41s \n \n 2019-03-15 09:28:32 (29.9 MB/s) - ‘cc.ja.300.vec.gz’ saved [1279641604/1279641604]\n \n Archive: wiki-news-300d-1M.vec.zip\n inflating: wiki-news-300d-1M.vec \n\n\n\n```\nen_vecs,_,dim_en_vec = load_vectors('data/wiki-news-300d-1M.vec')\nj_vecs,_,dim_j_vec = load_vectors('data/cc.ja.300.vec')\n```\n\n\n```\ndef create_emb(vecs, itos, em_sz):\n emb = nn.Embedding(len(itos), em_sz, padding_idx=1)\n if vecs is None: return emb\n wgts = emb.weight.data\n miss = []\n for i,w in enumerate(itos):\n try: wgts[i] = torch.from_numpy(vecs[w])\n except: miss.append(w)\n print('Number of unknowns in data: {}'.format(len(miss)))\n return emb\n \n```\n\n\n```\ndef V(tensor,req_grad=True):\n if torch.cuda.is_available():return Variable(tensor.cuda())\n else: return Variable(tensor)\n```\n\n### RNN Visualization\n\n[RNN Visualization](http://jalammar.github.io/images/RNN_1.mp4)\n\n### Seq2Seq Architecture\n> ...a multilayered Long Short-Term Memory (LSTM) to map the input sequence to a vector of a fixed dimensionality, and then another deep LSTM to decode the target sequence from the vector. \n\n[Sutskever et al., 2014](https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf)\n\n\n\nImage:[from here](https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html)\n\n\n```\nclass Seq2Seq(nn.Module):\n def __init__(self,int2en,int2j,em_sz,j_vecs=None,en_vecs=None,nh=128,out_sl=25,dropf=1,nl=2):\n super().__init__()\n #encoder\n self.nl,self.nh,self.em_sz,self.out_sl = nl,nh,em_sz,out_sl\n self.emb_enc = create_emb(en_vecs,int2en,em_sz)\n self.emb_drop = nn.Dropout(0.15*dropf)\n self.encoder = nn.GRU(em_sz,nh,num_layers=nl,dropout=0.25*dropf, bidirectional=True)\n #decoder\n self.emb_dec = create_emb(j_vecs,int2j,em_sz)\n self.decoder = nn.GRU(em_sz,nh*2,num_layers=nl,dropout=0.25*dropf)\n self.out_drop = nn.Dropout(0.35*dropf)\n self.out = nn.Linear(nh*2,len(int2j))\n \n def forward(self,inp,y=None):\n sl, bs = inp.size()\n emb_in = self.emb_drop(self.emb_enc(inp))\n h_n = self.initHidden(bs)\n enc_out, h_n = self.encoder(emb_in,h_n)\n h_n = h_n.view(2,2,bs,-1).permute(0,2,1,3).contiguous().view(self.nl,bs,-1)\n \n dec_inp = V(torch.zeros(bs).long())\n res = []\n for i in range(self.out_sl):\n dec_emb = self.emb_dec(dec_inp)\n outp,h_n = self.decoder(dec_emb.unsqueeze(0),h_n)\n outp = F.log_softmax(self.out(self.out_drop(outp[0])),dim=-1)\n res.append(outp)\n dec_inp = outp.data.max(1)[1]\n if (dec_inp==1).all(): break\n return torch.stack(res)\n \n def initHidden(self,bs):\n return V(torch.zeros([self.nl*2,bs,self.nh]))\n```\n\n### Why Bidirectional Encoder\n> Finally, we found that reversing the order of the words in all source sentences (butnot target sentences) improved the LSTM’s performance markedly, because doing so introduced many short term dependencies between the source and the targetsentence which made the optimization problem easier.\n\n[Sutskever et al., 2014](https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf)\n\nInput and output sequences may not directly map to each other so preserving information from both passes of the input sequence will help learn how tokens relate to each other. For example in a translation task, subject and object can be in opposite positions depending on the language structure.\n\n\n```\nseq2seq = Seq2Seq(int2en,int2j,300,en_vecs=None,j_vecs=None)\nseq2seq.cuda()\n```\n\n\n\n\n Seq2Seq(\n (emb_enc): Embedding(21393, 300, padding_idx=1)\n (emb_drop): Dropout(p=0.15)\n (encoder): GRU(300, 128, num_layers=2, dropout=0.25, bidirectional=True)\n (emb_dec): Embedding(31813, 300, padding_idx=1)\n (decoder): GRU(300, 256, num_layers=2, dropout=0.25)\n (out_drop): Dropout(p=0.35)\n (out): Linear(in_features=256, out_features=31813, bias=True)\n )\n\n\n\n\n```\nout = seq2seq(V(x.transpose(1,0).long()))\nout.size()\n```\n\n\n\n\n torch.Size([25, 120, 31813])\n\n\n\nLoss Function: We will use Cross Entropy Loss as we are trying to classify ot the correct words. Cross entropy loss can be simplified to: \n\n`cross_entropy = sum(-log(y_pred) for y_pred in y_preds)`\n\nwhere `y_pred` is the likelihood of the target class predicted by the model. This is a good loss function for classification because if the likelihood of the correct class is low, the loss value goes up and if it is high, the loss value goes down.\n\n\n```\ndef seq2seq_loss(input, target):\n sl,bs = target.size()\n sl_in,bs_in,nc = input.size()\n if sl>sl_in: input = F.pad(input, (0,0,0,0,0,sl-sl_in))\n input = input[:sl]\n return F.cross_entropy(input.view(-1,nc), target.view(-1))\n```\n\n\n```\nseq2seq_loss(out,V(y.transpose(1,0).long()))\n```\n\n\n\n\n tensor(10.3560, device='cuda:0', grad_fn=)\n\n\n\n\n```\ndef step(x, y, epoch, m, crit, opt, clip=None):\n output = m(x, y)\n if isinstance(output,tuple): output = output[0]\n opt.zero_grad()\n loss = crit(output, y)\n loss.backward()\n if clip:\n nn.utils.clip_grad_norm_(m.parameters(), clip)\n opt.step()\n return loss.data.item()\n```\n\n\n```\nfrom tqdm import tqdm\n```\n\n\n```\ndef train(trn_dl,val_dl,model,crit,opt,epochs=10,clip=None):\n for epoch in range(epochs):\n loss_val = loss_trn = 0\n with tqdm(total=len(trn_dl)) as pbar:\n model.train()\n for i, ds in enumerate(trn_dl):\n x, y = ds\n #if isinstance(x,tuple): x = x[0]\n x, y = x.transpose(1,0), y.transpose(1,0)\n loss = step(V(x.long()),V(y.long()),epoch,model,crit,opt)\n loss_trn += loss\n pbar.update()\n model.eval()\n for i, ds in enumerate(val_dl):\n with torch.no_grad():\n x, y = ds\n #if isinstance(x,tuple): x = x[0]\n x, y = x.transpose(1,0), y.transpose(1,0)\n out = model(V(x.long()))\n if isinstance(out,tuple): out = out[0]\n loss_val+= crit(out, V(y.long()))\n #loss_val +=loss\n print(f'Epoch: {epoch} trn loss: {loss_trn/len(trn_dl)} val loss: {loss_val/len(val_dl)}')\n```\n\n\n```\nfrom torch import optim\n```\n\n\n```\nopt = optim.Adam(seq2seq.parameters(),lr=3e-3,betas=(0.7,0.8))\n```\n\n\n```\ntrain(trn_dl,val_dl,seq2seq,seq2seq_loss,opt,epochs=10)\n```\n\n 100%|██████████| 1124/1124 [02:40<00:00, 7.02it/s]\n 0%| | 1/1124 [00:00<03:05, 6.06it/s]\n\n Epoch: 0 trn loss: 4.750732962983359 val loss: 4.082951068878174\n\n\n 100%|██████████| 1124/1124 [02:52<00:00, 6.51it/s]\n 0%| | 1/1124 [00:00<03:11, 5.86it/s]\n\n Epoch: 1 trn loss: 3.5997307712073003 val loss: 3.3246185779571533\n\n\n 100%|██████████| 1124/1124 [02:55<00:00, 6.39it/s]\n 0%| | 1/1124 [00:00<03:04, 6.08it/s]\n\n Epoch: 2 trn loss: 3.1077632744965604 val loss: 3.4751904010772705\n\n\n 100%|██████████| 1124/1124 [02:57<00:00, 6.34it/s]\n 0%| | 1/1124 [00:00<02:50, 6.60it/s]\n\n Epoch: 3 trn loss: 2.8518904808153036 val loss: 3.94274640083313\n\n\n 100%|██████████| 1124/1124 [02:58<00:00, 6.30it/s]\n 0%| | 1/1124 [00:00<03:06, 6.01it/s]\n\n Epoch: 4 trn loss: 2.7045018161743135 val loss: 2.766321897506714\n\n\n 100%|██████████| 1124/1124 [02:58<00:00, 6.29it/s]\n 0%| | 1/1124 [00:00<03:06, 6.01it/s]\n\n Epoch: 5 trn loss: 2.5743112220458713 val loss: 2.752124071121216\n\n\n 100%|██████████| 1124/1124 [02:58<00:00, 6.28it/s]\n 0%| | 1/1124 [00:00<03:04, 6.08it/s]\n\n Epoch: 6 trn loss: 2.5332621384769998 val loss: 2.935807228088379\n\n\n 100%|██████████| 1124/1124 [02:59<00:00, 6.27it/s]\n 0%| | 1/1124 [00:00<03:03, 6.11it/s]\n\n Epoch: 7 trn loss: 2.500852593323514 val loss: 3.133931875228882\n\n\n 100%|██████████| 1124/1124 [02:59<00:00, 6.99it/s]\n 0%| | 1/1124 [00:00<03:04, 6.10it/s]\n\n Epoch: 8 trn loss: 2.458315055141245 val loss: 2.8610451221466064\n\n\n 100%|██████████| 1124/1124 [02:59<00:00, 6.26it/s]\n\n\n Epoch: 9 trn loss: 2.456163497369909 val loss: 3.016350269317627\n\n\n\n```\ndef produce_out(val_dl, model,int2en,int2j,interval=(20,30)):\n model.eval()\n x,y = next(iter(val_dl))\n x, y = x.transpose(1,0), y.transpose(1,0)\n probs = seq2seq(V(x.long()))\n if isinstance(probs,tuple): probs = probs[0] \n preds = A(probs.max(2)[1].cpu())\n for i in range(interval[0],interval[1]):\n print(' '.join([int2en[o] for o in x[:,i] if o not in [0,1,2]]))\n print(''.join([int2j[o] for o in y[:,i] if o not in [0,1,2]]))\n print(''.join([int2j[o] for o in preds[:,i] if o not in [0,1,2]]))\n print()\n```\n\n\n```\nproduce_out(trn_dl,seq2seq,int2en,int2j)\n```\n\n the flower garden needs watering .\n その花壇は水をやる必要がある。\n その花は庭がががが。\n \n country life is very peaceful in comparison with city life .\n 田舎での生活は、都会生活と比較してとても穏やかだ。\n 国ののはははのののににに。。\n \n you are beautifully dressed .\n あなたはとても美しいドレスを着ていらっしゃいますね。\n あなたははなををててている。\n \n it 's quite all right .\n 全くかまいません。\n それはですだ。\n \n the president put off visiting japan .\n 大統領は訪日を延期しました。\n 大統領は日本にををしたた\n \n he has two brothers , one lives in osaka and the other in kobe .\n 彼には兄弟が二人いて、一人は大阪で、もう一人は神戸で暮らしている。\n 彼はは2人2人ががが、人人でで。。\n \n a famous architect built this house .\n 有名な建築家がこの家を建てた。\n そのな家家家家家家をたた。\n \n i could not but think that he had died .\n 彼は死んでしまったと考えざるを得なかった。\n 私は彼たたたはははたた。\n \n i enjoyed watching the easter parade .\n 私は復活祭のパレードを見て楽しんだ。\n 私はそのをを見を見を見。。\n \n i will not allow you to be ill - treated .\n 君が虐待されているのを放ってはいられない。\n 私は病気にににににない。。。\n \n\n\n\n```\ntorch.save(seq2seq.state_dict(),open(path/'translate_seq2seq.pth','wb'))\n```\n\n\n```\nseq2seq.load_state_dict(torch.load('translate_seq2seq.pth', map_location=lambda storage, loc: storage))\n```\n\n### Seq2Seq w/ Attention\nA critical and apparent disadvantage of this fixed-length context vector design is incapability of remembering long sentences. Often it has forgotten the first part once it completes processing the whole input. The attention mechanism was born [Bahdanau et al., 2015](https://arxiv.org/pdf/1409.0473.pdf) to resolve this problem.\n\nGiven the following vectors:\n\\begin{align}\n\\boldsymbol{x} = \\{x_1,x_2,x_3,\\ldots,x_n\\} \\\\\n\\boldsymbol{y} = \\{y_1,y_2,y_3,\\ldots,y_m\\} \\\\\n\\end{align}\nThe hidden state from the Bidir encoder is given by:\n\\begin{align}\n\\boldsymbol{h}_i = [\\overrightarrow{\\boldsymbol{h}}_i^\\top; \\overleftarrow{\\boldsymbol{h}}_i^\\top]^\\top, i=1,\\dots,n \\\\\n\\end{align}\n\nThe hidden state from the decoder at time $t$ is given by: $s_t$\n\nThe score for at time $t$:\n\n\\begin{aligned}\n\\text{score}(\\boldsymbol{s}_t, \\boldsymbol{h}_i) = \\mathbf{v}_a^\\top \\tanh(\\mathbf{W}_a[\\boldsymbol{s}_t; \\boldsymbol{h}_i])\n\\end{aligned}\n\nwhere both $v_a$ and $W_a$ are weight matrices to be learned in the alignment model.\n\n\\begin{aligned}\n\\mathbf{c}_t &= \\sum_{i=1}^n \\alpha_{t,i} \\boldsymbol{h}_i & \\small{\\text{; Context vector for output }y_t}\\\\\n\\alpha_{t,i} &= \\text{align}(y_t, x_i) & \\small{\\text{; How well two words }y_t\\text{ and }x_i\\text{ are aligned.}}\\\\\n&= \\frac{\\exp(\\text{score}(\\boldsymbol{s}_{t-1}, \\boldsymbol{h}_i))}{\\sum_{i'=1}^n \\exp(\\text{score}(\\boldsymbol{s}_{t-1}, \\boldsymbol{h}_{i'}))} & \\small{\\text{; Softmax of some predefined alignment score.}}.\n\\end{aligned}\n\nEquations borrowed from [here](https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html)\n\n\n\n[Attention Visualization](http://jalammar.github.io/images/attention_process.mp4)\n\n\n```\nimport math,random\n\ndef rand_t(*sz): return torch.randn(sz)/math.sqrt(sz[0])\ndef rand_p(*sz): return nn.Parameter(rand_t(*sz))\n```\n\n\n```\nclass Seq2SeqAttention(nn.Module):\n def __init__(self,int2en,int2j,em_sz,j_vecs=None,en_vecs=None,nh=128,out_sl=25,dropf=1,nl=2):\n super().__init__()\n #encoder\n self.nl,self.nh,self.em_sz,self.out_sl = nl,nh,em_sz,out_sl\n self.emb_enc = create_emb(en_vecs,int2en,em_sz)\n self.emb_drop = nn.Dropout(0.15*dropf)\n self.encoder = nn.GRU(em_sz,nh,num_layers=nl,dropout=0.25*dropf, bidirectional=True)\n #decoder\n self.emb_dec = create_emb(j_vecs,int2j,em_sz)\n self.decoder = nn.GRU(em_sz,nh*2,num_layers=nl,dropout=0.25*dropf)\n self.out_drop = nn.Dropout(0.35*dropf)\n self.out = nn.Linear(nh*2,len(int2j))\n #attention layer\n self.W1 = rand_p(nh*2, nh*2) #parameter\n self.l2 = nn.Linear(nh*2, nh*2)\n self.l3 = nn.Linear(em_sz+nh*2, em_sz)\n self.V = rand_p(nh*2) #parameter\n \n def forward(self,inp,y=None):\n sl, bs = inp.size()\n emb_in = self.emb_drop(self.emb_enc(inp))\n h_n = self.initHidden(bs)\n enc_out, h_n = self.encoder(emb_in,h_n)\n h_n = h_n.view(2,2,bs,-1).permute(0,2,1,3).contiguous().view(self.nl,bs,-1)\n \n dec_inp = V(torch.zeros(bs).long())\n res,attns = [], []\n #multiply by parameter\n w1e = enc_out @ self.W1\n for i in range(self.out_sl):\n #linear layer \n w2h = self.l2(h_n[-1])\n #non-linear activation to calculate score\n u = torch.tanh(w1e + w2h)\n #softmax to make them into probs\n a = F.softmax(u @ self.V, 0)\n attns.append(a)\n #multiply each vector by scores and then add them up\n Xa = (a.unsqueeze(2) * enc_out).sum(0)\n dec_emb = self.emb_dec(dec_inp)\n #linear layer to reduce dimensions\n wgt_enc = self.l3(torch.cat([dec_emb, Xa], 1))\n outp,h_n = self.decoder(wgt_enc.unsqueeze(0),h_n)\n outp = F.log_softmax(self.out(self.out_drop(outp[0])),dim=-1)\n res.append(outp)\n dec_inp = outp.data.max(1)[1]\n if (random.random() > 0.5) and y is not None: dec_inp=y[i] \n if (dec_inp==1).all(): break\n return torch.stack(res),attns\n \n def initHidden(self,bs):\n return V(torch.zeros([self.nl*2,bs,self.nh]))\n```\n\n\n```\nseq2seq = Seq2SeqAttention(int2en,int2j,300,en_vecs=None,j_vecs=None)\nseq2seq.cuda()\n```\n\n\n\n\n Seq2SeqAttention(\n (emb_enc): Embedding(21393, 300, padding_idx=1)\n (emb_drop): Dropout(p=0.15)\n (encoder): GRU(300, 128, num_layers=2, dropout=0.25, bidirectional=True)\n (emb_dec): Embedding(31813, 300, padding_idx=1)\n (decoder): GRU(300, 256, num_layers=2, dropout=0.25)\n (out_drop): Dropout(p=0.35)\n (out): Linear(in_features=256, out_features=31813, bias=True)\n (l2): Linear(in_features=256, out_features=256, bias=True)\n (l3): Linear(in_features=556, out_features=300, bias=True)\n )\n\n\n\n\n```\nopt = optim.Adam(seq2seq.parameters(),lr=3e-3,betas=(0.7,0.8))\n```\n\n\n```\ntrain(trn_dl,val_dl,seq2seq,seq2seq_loss,opt,epochs=10)\n```\n\n 100%|██████████| 1124/1124 [03:21<00:00, 6.28it/s]\n 0%| | 1/1124 [00:00<03:27, 5.42it/s]\n\n Epoch: 0 trn loss: 2.797933133683595 val loss: 4.138897895812988\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.24it/s]\n 0%| | 1/1124 [00:00<03:32, 5.28it/s]\n\n Epoch: 1 trn loss: 2.16145394790215 val loss: 2.8873095512390137\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.17it/s]\n 0%| | 1/1124 [00:00<03:29, 5.35it/s]\n\n Epoch: 2 trn loss: 2.0703822573733075 val loss: 3.0309219360351562\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.07it/s]\n 0%| | 1/1124 [00:00<03:28, 5.38it/s]\n\n Epoch: 3 trn loss: 2.07098806148322 val loss: 2.844566822052002\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.07it/s]\n 0%| | 1/1124 [00:00<03:28, 5.38it/s]\n\n Epoch: 4 trn loss: 2.088127380906475 val loss: 2.8696582317352295\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.26it/s]\n 0%| | 1/1124 [00:00<03:29, 5.36it/s]\n\n Epoch: 5 trn loss: 2.093448414603162 val loss: 2.7895729541778564\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.12it/s]\n 0%| | 1/1124 [00:00<03:29, 5.37it/s]\n\n Epoch: 6 trn loss: 2.1055155513125383 val loss: 2.9072670936584473\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 5.45it/s]\n 0%| | 1/1124 [00:00<03:30, 5.34it/s]\n\n Epoch: 7 trn loss: 2.11192792569191 val loss: 2.7808303833007812\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.23it/s]\n 0%| | 1/1124 [00:00<03:29, 5.37it/s]\n\n Epoch: 8 trn loss: 2.116793169139543 val loss: 2.8389084339141846\n\n\n 100%|██████████| 1124/1124 [03:26<00:00, 6.13it/s]\n\n\n Epoch: 9 trn loss: 2.1336968614325404 val loss: 2.8806753158569336\n\n\n\n```\nproduce_out(trn_dl,seq2seq,int2en,int2j)\n```\n\n mingle your joys sometimes with your earnest occupation .\n ときに君の喜びと君の真剣な職業とを交流せしめよ。\n あなたの仕事をはにはををする。\n \n a tunnel has been bored through the mountain .\n 山を掘り抜いてトンネルが造られた。\n そのはは山ののをた。\n \n please refrain from smoking .\n どうぞタバコを控えてください。\n タバコをタバコをください。\n \n i am poor at tennis .\n 私はテニスが下手だ。\n 私はテニスがテニスが。\n \n i still owe my brother the ten dollars that he lent me last week .\n 先週弟が貸してくれた10ドル、借りたままだ。\n 私は私ののののののののを1週間、ていた。\n \n there is a rumor that she got married .\n 彼女が結婚したといううわさがある。\n 彼女は結婚結婚した。\n \n he tried to appeal .\n 彼は訴えようとした。\n 彼はうとした。\n \n day is breaking .\n 夜が明けかけてきた。\n 日は日日。\n \n though she looks like his older sister , the fact is that she is his mother .\n 彼女は彼の姉のように見えるが、実は母親なのだ。\n 彼女は彼の妹に、て、、は、彼の。\n \n his failure in business left him penniless .\n 彼は事業に失敗して一文なしになった。\n 彼の失敗は失敗したのは失敗した。\n \n\n\n\n```\ntorch.save(seq2seq.state_dict(),open('translate_seq2seq_attention.pth','wb'))\n```\n\n\n```\nseq2seq.load_state_dict(torch.load('translate_seq2seq_attention.pth', map_location=lambda storage, loc: storage))\n```\n\n\n```\nout, atts = seq2seq(x.long().cuda())\n```\n\n\n```\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\nimport matplotlib.ticker as ticker\n```\n\n\n```\ntorch.stack(atts).size()\n```\n\n\n\n\n torch.Size([25, 120, 25])\n\n\n\n\n```\nplt.matshow(torch.stack(atts)[:,5,:].detach().cpu().numpy())\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "8e898101196e435acd16032e71ba6f4d00a519b6", "size": 71419, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/translate_colab.ipynb", "max_stars_repo_name": "jacekwachowiak/Seq2Seq-Workshop", "max_stars_repo_head_hexsha": "fe9cc20ed6c99a36435dc63a45c7bbce1e63aef6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-21T16:22:57.000Z", "max_issues_repo_path": "notebooks/translate_colab.ipynb", "max_issues_repo_name": "jacekwachowiak/Seq2Seq-Workshop", "max_issues_repo_head_hexsha": "fe9cc20ed6c99a36435dc63a45c7bbce1e63aef6", "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": "notebooks/translate_colab.ipynb", "max_forks_repo_name": "jacekwachowiak/Seq2Seq-Workshop", "max_forks_repo_head_hexsha": "fe9cc20ed6c99a36435dc63a45c7bbce1e63aef6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-03-16T03:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-29T21:36:47.000Z", "avg_line_length": 32.199729486, "max_line_length": 4680, "alphanum_fraction": 0.4737394811, "converted": true, "num_tokens": 9746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.05425934397094298}} {"text": "```python\nimport numpy as np\nimport scipy.special as sci\nimport matplotlib.pyplot as plt\nfrom scipy import stats # linregress\nimport pandas as pd\nfrom IPython.display import Latex\n```\n\n## Lecture 10: Reactive Mass Transport\n\n_(The contents presented in this section were re-developed principally by Dr. P. K. Yadav. The original contents are from Prof. Rudolf Liedl)_\n\n---\n\nThe last lecture dealt with the conservative transport processes and quantified the mass flow and flux emanating from those processes. The effects of these processes were evaluated as an isolated processes and as joint transport process. \n\n\nThe last lecture dealt with the conservative transport processes and quantified the mass flow and flux emanating from those processes. The effects of these processes were evaluated as an isolated processes and as joint transport process. \n\n```{admonition} Last lecture important conclusions\n> $J_{adv}>J_{dis}>>J_{diff}$ is normal aquifers. \n> $J_{diff}$ may only be useful as an individual processes in special aquifers, e.g., clayey aquifers. \n> In general aquifers, hydrodynamic dispersion $J_{hyd} = J_{dis} + J_{diff}$ is used in the analysis of solute transport process. \n```\n \nFinally, the last chapter introduced _Concentration Profile_ $(C-t)$ and _Breakthrough Curve_ $(C-x)$ to visually evaluate solute transport in aquifers using _Concentration_ $(C)$, a process output, as a function of _time_ $(t)$ and _space_ $(x)$. \n\nFinally, the last chapter introduced _Concentration Profile_ $(C-t)$ and _Breakthrough Curve_ $(C-x)$ to visually evaluate solute transport in aquifers using _Concentration_ $(C)$, a process output, as a function of _time_ $(t)$ and _space_ $(x)$. \n\nThis section focuses on the _reactive transport processes,_ which as already discussed involves the transport of solute with _reaction_ processes. This course being an introductory groundwater course, _sorption_ and _degradation_ are the only two reaction types introduced and combined with the conservative transport processes- _advection_ and _dispersion_. Eventully, the section evaluates the joint action of conservative transport and reactive processes limiting to 1-D scenario. \n\nThe section will, however, first deal with 3-D effects of dispersive process, which is more important to quantify the reactive processes.\n\n## Dispersive Mass Flow in 3-D\n\nIn the last section we saw that concentration gradient $\\frac{\\Delta C}{\\Delta L}$ drives dispersive and diffusive solute transport process. \n\n\nHowever, in the natural aquifers $\\frac{\\Delta C}{\\Delta L}$ is normally varying with space $(x,y,z)$ and time $(t)$. Therefore, a differential operator $\\big(\\frac{\\mathrm{d}}{\\mathrm{d} x}\\big)$ is more suitable representation of gradient than the difference operator $\\frac{\\Delta C}{\\Delta x}$. The differential operator also generalizes the gradient case.\n\nConsidering the differential operator, the diffusive mass flow and diffusive mass flux (= mass flow per unit area) in 1D is then expressed as:\n\n\n$$\nJ_{diff} = - n_e \\cdot A \\cdot D_p \\cdot \\frac{\\mathrm{d} C}{\\mathrm{d}x} \n$$\n\nand \n$$\nj_{diff} = - n_e \\cdot D_p \\cdot \\frac{\\mathrm{d} C}{\\mathrm{d}x} \n$$\n\nLikewise, the dispersive mass flow and dispersive mass flux (1-D) is:\n\n$$\nJ_{disp, h} = - n_e \\cdot A \\cdot D_{disp} \\cdot \\frac{\\mathrm{d} C}{\\mathrm{d}x} \n$$\n\n$$\nj_{disp, h} = - n_e \\cdot D_{disp} \\cdot \\frac{\\mathrm{d} C}{\\mathrm{d}x} \n$$\n\nThe examples of these relations are presented in last section (@Alex pls. link)\n\n\n### 3-D concentration Gradient\n\nThe concentration gradient $\\frac{\\mathrm{d}C}{\\mathrm{d}x}$ for 1-D solute transport problems is uni-directional, i.e, direction is fixed, and thus only the magnitude of the gradient is the important factor. However in higher dimensions, 2-D or 3-D, solute transport problems, the _direction_ of gradient along with it's _magnitude_ in that direction has to be specified. Thus, for higher dimension solute transport problems, the _concentration gradient_ becomes **concentration vector**, i.e., a quantity providing both magnitude and direction. \n\nThus, the representation of concentration gradient in Cartesian coordinate in 2-D and 3-D is:\n\n$$\n\\mathrm{grad}C = \\nabla C= \\begin{pmatrix}\n\\frac{\\partial C}{\\partial x}\\\\\n\\frac{\\partial C}{\\partial y}\n\\end{pmatrix}\n$$\n\nand\n\n$$\n\\mathrm{grad} C = \\nabla C= \\begin{pmatrix}\n\\frac{\\partial C}{\\partial x}\\\\\n\\frac{\\partial C}{\\partial y}\\\\\n\\frac{\\partial C}{\\partial z}\n\\end{pmatrix}\n$$\n\nThe $\\nabla$, the inverted Delta symbol, is called the **del** or **nabla** operator. The vector **grad$C$** in the above relations points in the direction of the _steepest increase_ of $C$. However, for the **Hydrogeologists**, the concentration gradients as well the grad$C$ points to the _steepest decrease_ of $C$. \n\n**@Anne/Sophie - can we try to find a simple example finding grad$C$ in 2-D/3-D**\n\n### Isotropic and Anisotropic Dispersion\n\nCorresponding the expression for the concentration gradient at higher dimensions, the expression for mass flow and flux becomes:\n\n$$\nJ_{disp,\\, h} = \\begin{pmatrix}\nJ_{disp,\\, hx}\\\\\nJ_{disp,\\, hy}\\\\\nJ_{disp,\\, hz}\n\\end{pmatrix}\n$$\nand the 3-D mass flux is:\n\n$$\nj_{disp,\\, h} = \\begin{pmatrix}\nj_{disp,\\, hx}\\\\\nj_{disp,\\, hy}\\\\\nj_{disp,\\, hz}\n\\end{pmatrix}\n$$\n\nThe subscript in ${{disp, h}}$ refers to _hydrodynamic dispersion_ which is sum of _mechanical dispersion_ and _diffusion_. Likewise, the subscript ${{disp,\\, hx}}$, ${{disp,\\, hy}}$ and ${{disp,\\, hz}}$ refers to dispersion components along the Cartesian coordinates. The corresponding mass flow and mass flux in the higher dimension is then:\n\n$$\nJ_{disp,\\, h} = - n_e \\cdot A \\cdot D_{hyd} \\cdot \\text{grad}C\n$$\n\nand\n\n### Isotropic and Anisotropic Dispersion\n\nCorresponding the expression for the concentration gradient at higher dimensions, the expression for mass flow and flux becomes:\n\n$$\nJ_{disp,\\, h} = \\begin{pmatrix}\nJ_{disp,\\, hx}\\\\\nJ_{disp,\\, hy}\\\\\nJ_{disp,\\, hz}\n\\end{pmatrix}\n$$\nand the 3-D mass flux is:\n\n$$\nj_{disp,\\, h} = \\begin{pmatrix}\nj_{disp,\\, hx}\\\\\nj_{disp,\\, hy}\\\\\nj_{disp,\\, hz}\n\\end{pmatrix}\n$$\n\nThe subscript in ${{disp,\\, h}}$ refers to _hydrodynamic dispersion_ which is sum of _mechanical dispersion_ and _diffusion_. Likewise, the subscript ${{disp,\\, hx}}$, ${{disp,\\, hy}}$ and ${{disp,\\, hz}}$ refers to dispersion components along the Cartesian coordinates. The corresponding mass flow and mass flux in the higher dimension is then:\n\n$$\nJ_{disp,\\, h} = - n_e \\cdot A \\cdot D_{hyd} \\cdot \\text{grad}C\n$$\n\nand\n\n$$\nj_{disp,\\, h} = - n_e \\cdot A \\cdot D_{hyd} \\cdot \\text{grad}C\n$$\n\nThe **isotropic dispersion**, rather an _exceptional,_ the $D_{hyd}$ in this case is:\n\n$$\nD_{hyd} = \\alpha \\cdot |v| + n_e \\cdot D \n$$\nwhere, $D$ is direction independent dispersion coefficient and $\\alpha$ $[L]$ is dispersivity, which in:\n\n**heterogeneous aquifer**: $\\alpha = \\alpha(x,y,z)$ and in \n\n**homogeneous aquifer**: $\\alpha = \\text{constant}$ \n\n\n\n\n\nFor more practical cases and in normal aquifers, the 2-D and 3-D the dispersion for solute transport is _direction dependent,_ i.e. **anisotropic**. Hence the $D_{hyd}$ is not an scalar quantity but a _matrix (tensor),_ which relates the concentration gradient (vector) to the dispersive mass flow (vector). However, if the princopal axes of the dispersion tensor $D_{hyd}$ is made to coincide with the axes of a Cartesian coordinate system _and_ the groundwater flow is considered uniform along the $x-$axis, the dispersive mass flux can be obtained from\n\n$$\n\\begin{pmatrix} J_x \\\\ j_y \\\\ j_z \\end{pmatrix} =\n\\begin{pmatrix} \\alpha_L \\cdot v_x + n_e \\cdot D & 0 & 0 \\\\\n0 & \\alpha_{Th} \\cdot v_x + n_e \\cdot D & 0\\\\\n0 & 0 & \\alpha_{Tv} \\cdot v_x + n_e \\cdot D\n\\end{pmatrix}\n\\cdot\n\\begin{pmatrix} \\frac{\\partial C}{\\partial x} \\\\ \\frac{\\partial C}{\\partial y} \\\\ \\frac{\\partial C}{\\partial z} \\end{pmatrix} \n$$\n\nwith $\\alpha_L$, $\\alpha_{Th}$ and $\\alpha_{Tv}$ are longitudinal dispersivity, horizontal transverse dispversity and vertical transverse dispersivity, respectively. The statistical analysis of dispersivity data shows that $\\alpha_{L}>\\alpha_{Th}>\\alpha_{Tv}$ and the values differ by roughly an order of magnitude. This, however, is just a rule of thumb.\n\n@Anne/@Sophie can you find a very simple numerical example for caculating dispersivity or something that explains the above relation.\n\n\n```python\n# Analytical solution from Bear (1976) - Line source, 1st-type input and infinte plane\n\n# Input (values can be changed)\nCo = 1 # mg/L, input concentration \nDx = 3 # m, Dispersion in x direction \nDy = Dx/10 # m\nv = 0.05 # m/d\nQ = 10 # m^3/d\n\n## domain dimension and descritization (values can be changed)\nxmin = -100; xmax= 101 \nymin = 0.1; ymax = 11\n[x, y] = np.meshgrid(np.linspace(xmin, xmax, 1000), np.linspace(ymin, ymax, 100)) # mesh\n\n# Bear (1976) solution Implementation \n#\"k0: Modified Bessel function of second type and zero Order\"\n\nterm1 = (Co*Q)/(2*np.pi* np.sqrt(Dx*Dy))\nterm2 = (x*v)/(2*Dx)\nargs = (v**2*x**2)/(4*Dx**2) + (v**2*y**2)/(4*Dx*Dy)\nsol = term1*np.exp(term2)*sci.k0(args)\n\n# plots\nfig, ax = plt.subplots()\nCS = ax.contour(x,y,sol, cmap='flag')\nax.clabel(CS, inline=1, fontsize= 10)\nCB = fig.colorbar(CS, shrink=0.8, extend='both')\n```\n\n## Equilibrium Sorption ##\n\n---\n\nA reactive transport system can include a single reactive process, e.g., degradation, or combination of several multiple reactive processes, e.g. degradation and sorption. The inclusion of the reactive process(es) in the transport studies are site specific. The important to note is that an inclusion of a reactive process increases the complexity of transport problem.\n\nIn this course we limit ourselves with the following two types of reaction processes:\n\n**1. Sorption**\n\n**2. Degradation**\n\nAcid-base reaction, precipitation-dissolution reaction, organic combustion etc. are among the reactions type that can be part of the reactive process individually or in any combination. \n\nAlso an important distinction is the rate or speed of the reaction. One distinguishes between time-dependent reaction (kinetics) or time-independent reactions (steady-state or equilibrium). Special reaction rates such as instantaneous reaction (extremely fast reaction) can also be part of the reaction process in the transport system.\n\n\n\n\n### Sorption Basics\n\n**Sorption** is a rather a general term used to indicate both **adsorption** and **absorption**. But in this course the _sorption_ refers to only _adsorption._\n\n**Adsorption** can be more formally defined as the process of accumulation of dissolved chemicals on the surface of a solid, e.g., accumulation of a chemicals dissolved in groundwater on the surface of the aquifer material.\n\nThe figure below clarifies the _adsorption_ process. \n\n\n\nIn the figure _chemical in solution_ (the circular objects) more often called **solute** in the water is found to attach is the solid surface. The figure presents the following two important terms part of the adsorption process:\n\n> **Adsorbent**: The solid onto which the chemicals are attached. More formally, _adsorbents_ provide adsorption sites for solutes.\n\n> **Adsorbate**: These are solutes that are attached on the _adsorbent._ \n\nBased on the figure, _adsorption_ can be considered as a partition process that divides the chemical originally present in water between adsorbent and water. \n\nQuite often adsorption is a reversible process, i.e., adsorbed chemicals can get back to water phase. This process is called **desorption**. \n\nSpeaking about _equilibrium,_ this is reached when\n\n> _adsorption rate_ $\\rightleftharpoons $ _desorption rate_\n\nAdsorption in groundwater is often a rapid process. Although sorption kinetics can be important, the description in this introductory level course is limited to equilibrium sorption. Thus, we learn next to quantify equilibrium sorption. \n\n\n\n\n### Adsorption Isotherms\n\nThe adsorption process that has reached equilibrium can be relatively easily quantified with the use of empirical models called **isotherms**. These models are often simple algebraic equation that relates solute concentrations partitioned between the adsorbate and adsorbent at constant temperature. More than 15 different _isotherm_ models can be found in the literature. However, in groundwater reactive transport studies the following three are the two most commonly used isotherms:\n\n1. **Henry or Linear isotherm**
        \n2. **Freundlich isotherm** \n\nFor quantification, laboratory based experiments are performed using solids from subsurface and chemicals of interest. The laboratory observations are then graphically fitted with empirical isotherm models to quantify adsorption properties. Figure below shows isotherms that are particularly observed in groundwater transport studies. As can be observed in the figure sorption coefficient ($K$) is the common quantities obtained from isotherm models. \n\n\n\n### Henry Isotherm\n\nThe **Henry isotherm** (Henry, 1803) is based on the idea of a _linear_ relationship between the solute concentration **$C$** and the _adsorbate:adsorbent_ mass ratio $C_a$. Henry isotherm is quite often also called _linear isotherm_ or the $K_d$ model. Mathematically, the Henry isotherm is:\n\n$$\nC_a = K_d \\cdot C\n$$\n\nwith\n\n$C$ = solute concentration [ML$^{-3}$]
        \n$C_a$ = mass ratio adsorbate:adsorbent [M:M]
        \n$K_d$ = distribution or partitioning coefficient [L$^3$M$^{-1}$].\n\nOften symbols $C_s$ or $s$ are used instead of $C_a$. \n\nThe Henry model has been most widely used in groundwater transport studies. This is largely because of the simplicity (see equation) of the model and it's applicability in representing adsorption process more generally observed in groundwater studies. $K_d$, the partitioning coefficient, is particularly used in groundwater transport studies. It is equal to the slope of the Henry isotherm. \n\n\n```python\n# Example of Henry isotherm (Source: Fetter et al. 2018)\n\n# Following sorption data are available:\n\nC = np.array([7, 15, 174, 249, 362]) # ug/L, Eq. concentration \nCa = np.array([2, 4, 33, 50, 70]) # ug/g, Eq. sorbed mass \n\n# linear- fit y = m*x+c\n\nslope, intercept, r_value, p_value, std_err = stats.linregress(C, Ca)\nprint(\"slope: %f intercept: %f R-squared: %f\" % (slope, intercept, r_value**2))\nfit_line = slope*C + intercept\n\n#plot\n\nplt.scatter(C, Ca, label= \"Original data\") # data plot\nplt.plot(C, fit_line, color = \"red\", label = \"fit-line\")\nplt.legend(); plt.xlabel(r\"Equilibrium Aqueous Concentration, $C$ ($\\mu$g/L) \")\nplt.ylabel(r\"Mass sorbed per unit absorbent weight, $C_a$ ($\\mu$g/g) \"); \nplt.text(0, 50, '$C_a=%0.5s C + %0.5s$'%(slope, intercept), fontsize=10)\nplt.text(0, 40, '$R^2=%0.5s $'%(r_value**2), fontsize=10)\n\n# Output\n\nLatex(\"The required partition coefficient = slope, $K_{d}$= %0.5s L/g \" % slope)\n```\n\n### Freundlich Isotherm\n\n**Freundlich isotherm** (Freundlich, 1907) is a more general isotherm. It is based on the idea of a power law, i.e., includes also the non-linear behaviour, relating the solute concentration $C$ to the adsorbate:adsorbent mass ration $C_a$. The isotherm is mathematically given as\n\n$$\nC_a = K_{Fr} \\cdot C^N\n$$\n\nwith\n\n$C$ = solute concentration [ML$^{-3}$]
        \n$C_a$ = mass ratio adsorbate:adsorbent [M:M]
        \n$n$ = Freundlich exponent [-]
        \n$K_{Fr}$ = Freundlich partitioning coefficient [(M:M)/(M/L$^3)^n$].\n\nThe Freundlich isotherm equation can be easily linearized by applying logarithmic transformation of the equation, which gives\n\n\\begin{eqnarray}\n\\log C_a = \\log K_{Fr} + n\\cdot \\log C \n\\end{eqnarray}\n\nThe above equation resembles the straight line equation $y = b + a \\cdot x b$, in which $b\\equiv \\log K_{Fr}$ is the intercept and $a\\equiv n$ the slope. Thus, from fitting the adsoprtion experimental results with the above equation, both $n$ and $K_{Fr}$ can be obtained.\n\n\n\n```python\n# Example of Freundlich isotherm\n\n# Following sorption data are available:\n\nCf= np.array([23.6, 6.67, 3.26, 0.322, 0.169, 0.114]) # mg/L, Eq. concentration \nCaf = np.array([737, 450, 318, 121, 85.2, 75.8]) # mg/g, Eq. sorbed mass \n\nlogCf = np.log10(Cf) # log10 transformation of data\nlogCaf = np.log10(Caf)\n\n# fitting: y = mx +c\nslope, intercept, r_value, p_value, std_err = stats.linregress(logCf, logCaf)\nprint(\"slope: %f intercept: %f R-squared: %f\" % (slope, intercept, r_value**2))\nfit_line = slope*logCf + intercept\n\n# plots\nplt.figure(figsize=(10,4))\n\nplt.subplot(121)\nplt.plot(Cf, Caf, \"*--\", label= \"Original data\")\nplt.legend(); plt.xlabel(r\"Eq. Aq. Conc., $C$ ($mg$g/L) \"); \nplt.ylabel(r\"Mass sorbed/absorbent weight, $C_a$ ($mg$g/g) \"); \n\nplt.subplot(122)\nplt.scatter(logCf, logCaf, label=\"Log transformed data\") \nplt.plot(logCf, fit_line, color=\"red\", label= \"linear fit line\")\nplt.legend(); plt.xlabel(r\"Eq. Aq. Conc., $\\log C$ ($mg$g/L) \"); \nplt.ylabel(r\"Mass sorbed/absorbent weight, $\\log C_a$ ($mg$/g) \"); \nplt.text(-1, 2.6, '$C_a=%0.5s C + %0.5s$'%(slope, intercept), fontsize=10)\nplt.text(-1, 2.5, '$R^2=%0.5s $'%(r_value**2), fontsize=10)\nplt.subplots_adjust(wspace=0.35)\n\nLatex(\"$K_{Fr}$ = %0.5s (mg/g)$^{1/n}$(mg/L) and $n$ = %0.4s\" % (10**intercept, slope))\n```\n\n### Retardation Factor (for Henry Isotherm)\n\nThe net effect of adsorption is the retarded movement of solute in comparison to the average flow of the groundwater. The term **Retardation Factor** $(R)$ is defined that quantifies the retarded movement of solute. The formulation of $R$ is based on the type of isotherm. For Henry isotherm $R$ can be straightforwardly calculated with the help of a mass budget. \n\nFor this purpose, an aquifer volume $V$ with the effective porosity $n_e$ is considered (see fig. below)\n\n\n\nThe steps involved are:\n\n- Total volume: $V$\n- Water volume: $n_e \\cdot V$\n- Mass of dissolved chemical: $n_e \\cdot V \\cdot C$\n- Volume of solid: $(1-n_e)\\cdot V$\n- Density of solid material: $\\rho$\n- Mass of solid: $\\rho \\cdot(1-n_e)\\cdot V$\n- Mass of adsorbate: $\\rho \\cdot(1-n_e)\\cdot V\\cdot C_a$ = $(1-n_e)\\cdot\\rho \\cdot V \\cdot K_d \\cdot C$\n- Total mass: $n_e\\cdot V \\cdot C + (1-n_e)\\cdot\\rho \\cdot V\\cdot K_d \\cdot C = n_e \\cdot R \\cdot V \\cdot C$
        \nwith _Retardation factor_ $$R = 1 + \\frac{1-n_e}{n_e}\\cdot \\rho \\cdot K_d$$\n\nThe expression for $R$ can be further modified by using bulk density $\\rho_b$ $= (1-n_e)\\cdot \\rho$ = mass of solid/total volume. This leads to\n\n$$\nR = 1+\\frac{\\rho_b}{n_e} \\cdot K_d\n$$\n\nAs can be observed from the equation, $R = 1$ when there is no adsorption, i.e., when $K_d= 0$.\n\n\n@ Anne @ Sophie pls. provide a very short numerical example on R\n\n## Degradation\n\n**Degradation** leads to alteration or transformation of chemical structure of chemicals. This contrasts to adsorption in which chemical structure is not altered. In adsorption (or desorption) the original chemical is partitioned between the solid particles and water. It is _degradation_ that eventually lead to removal of the _original_ chemical from the groundwater. The transformation of original chemical, due to degradation, results to so-called _daughter products (metabolites)._ The new chemical(s) can make groundwater more suitable (decrease contamination) or further contaminate it. \n\nIn groundwater studies, degradation can appear as:\n\n- **Radioactive decay**\n- **Microbial degradation (bio-degradation)**\n- **Chemical degradation**\n\nThere are several approaches to quantify degradation process. \nA common aspect to most of them is the assumption of _time-dependency_ (or _Kinetics_ ).\n\n\n### $n^{th}$ - Order Degradation Kinetics\n\nThe general equation for the degradation kinetics is:\n\n$$\n\\frac{\\text{d}C}{\\text{d} t} = - \\lambda \\cdot C^n\n$$\n\nwith $t$ = time [t]
        \n$C$ = solute concentration [ML$^{-3}$]
        \n$n$ = order of the degradation kinetics [ - ] ($n\\geq 0)$
        \n$\\lambda$ = degradation rate constant [(ML$^{-3})^{(1-n)}$T$^{-1}$].\n\nConsidering the initial concentration (or input concentration) $C_0$, the solutions of the kinetics equation are:\n\n$$\nC(t) = C_0\\cdot e^{-\\lambda \\cdot t} \\: \\: \\: \\text{if }\\: n = 1 \n$$\n\nand\n\n$$\nC(t) = [C_0^{1-n} - (1-n)\\cdot \\lambda t]^{\\frac{1}{1-n}} \\:\\:\\: \\text{if }\\: n\\neq 1 \n$$\n\nThe **half life** $(T_{1/2})$, which is the time span elapsing until the initial concentration $C_0$ is reduced by half, is an important time-scale in the degradation analysis. $T_{1/2}$ is $C_0$ dependent in nearly all cases with an exception for 1$^\\text{st}$- order degradation kinetics. 0$^{th}$-order and the 1$^\\text{st}$- order degradation kinetics are most commonly observed in groundwater studies. The $(T_{1/2})$ of these orders are:\n\n$$\nT_{1/2} = \\frac{C_0}{2\\cdot \\lambda} \\:\\:\\: \\text{for } \\:0^{\\text{th}}\\text{-order} \n$$\n\n$$\nT_{1/2} = \\frac{\\ln 2}{\\lambda} \\:\\:\\: \\text{for } \\:1^{\\text{st}}\\text{-order} \n$$\n\nAs can be observed above $T_{1/2}$ is independent of concentration for the 1$^{\\text{st}}$-order degradation kinetics. \n\nAnother important properties of the degradation kinetics is that for $n\\geq 1$ the solute concentration _asymptotically_ approaches zero, whereas for $n<1$, the solute concentration actually reaches zero\n\n\n```python\n# behaviour of degradation kinetics\n\n#input - you may change the values\nCo = 1 # mg/L, initial concentration\nla = 0.003 # unit is order dependent. For n=1, 1/t\n\n# main equation\nZ_order = lambda t: Co* np.exp(-la*t) # for n = 0\nF_order = lambda t: Co-la*t # for n = 1\n\n# simulation for t\nt = np.linspace(1,1000, 1000) # 1000 time units\nZ_results = Z_order(t)\nF_results = F_order(t)\n\n# plots\nplt.figure(figsize=(10,4))\n\n# n = 1\nplt.subplot(121)\nplt.plot(t, Z_results)\nplt.ylim(0, Co); plt.xlim(0)\nplt.text(400, Co*0.8, r\"$C(t) = C_0 \\cdot e^{-\\lambda \\cdot t} $\", fontsize = 12) \nplt.text (400, Co*0.9, r\"1$^{st}$-order kinetics\", color = \"red\", fontsize = 12)\nplt.text(0, Co/2, r\"$T_{1/2}= \\frac{\\ln 2}{\\lambda}$\", color= \"red\", fontsize=14)\nplt.xlabel(\"Time, t (days)\"); plt.ylabel(r\"Concentration, $C(t)$ (mg/L)\")\n\n# n = 0\nplt.subplot(122)\nplt.plot(t, F_results)\nplt.ylim(0, Co); plt.xlim(0)\nplt.text(400, Co*0.8, r\"$C(t) = C_0 \\cdot-\\lambda \\cdot t} $\", fontsize = 12)\nplt.text (400, Co*0.9, r\"0$^{th}$-order kinetics\", color = \"red\", fontsize = 12)\nplt.text(0, Co/2, r\"$T_{1/2}= \\frac{C_0}{2\\cdot \\lambda}$\", color= \"red\", fontsize=14) \nplt.xlabel(\"Time, t (days)\"); plt.ylabel(r\"Concentration, $C(t)$ (mg/L)\")\n\nplt.subplots_adjust(wspace=0.35)\n```\n\n### Radioactive decay\n\nRadioactive decay is degradation of a chemical due to radiation. The radioactive decay is limited to radioactive chemicals such as Cobalt, Cesium, Iodine. This decay obeys the 1$^\\text{st}$- order degradation kinetics and therefore the half-life is $T_{1/2} = \\frac{\\ln 2}{\\lambda}$. $T_{1/2}$ is characteristic property of radioactive chemicals and it can be used to compute degradation rate ($\\lambda$). \n\n\n\n\n```python\n# Example of Radioactive decaly\n\n#experimental results\n\nt = [0, 1, 2, 5, 10, 20, 28 ] # yr, time\nCo_60 = [10, 8.76, 7.68, 5.17, 2.68, 0.72, 0.25] # mg/L, Cobalt 60 conc.\nSo_90 = [10, 9.76, 9.52, 8.84, 7.81, 6.10, 5] # mg/L, Strontium 90 Conc.\n\nz_list = list(zip(t, Co_60, So_90))\n\nCols= [\"time (a)\", \"Cobalt 60 (mg/L)\", \"Strontium 90 (mg/L)\"]\ndf = pd.DataFrame(z_list, columns=Cols)\nprint(df)\n\n# computing\nTH_Co60 = 28 # yr, Half life of Cobalt 60\nTH_St90 = 5.26 # yr, Half life of Strontium 90\nla_Co60 = np.log(2)/TH_Co60 # 1/yr, degradation rate of Cobalt 60\nla_St90 = np.log(2)/TH_St90 # 1/yr, degradation rate of Strontium 90\n\n# visualize\nplt.plot(t, Co_60, \"o--\", label = \"Cobalt 60\") \nplt.plot(t, So_90, \"v--\", label= \"Strontium 90\")\nplt.xlabel(\"Time (years)\"); plt.ylabel(\"Concentration (mg/L)\")\nplt.legend();\n\nLatex(\"The degradation rate ($\\lambda$) for Cobalt 60 = %0.5s 1/y and for Strontium 90 = %0.5s 1/y\" % (la_Co60, la_St90))\n```\n\n## Joint Action of Conservative and Reactive Transport (1D)\n\n### Concentration Profile\n\nFigure below presents the joint action of conservative transport with equilibrium sorption (linear isotherm) and degradation. The figure shows the solute concentration $C$ (in water) at the same time-levels for various combinations of acting processes.\n\n\n\nThe figure can be explained in the following way:\n\n(A): The solute is initially present at constant concentration in a limited area.\n\n(B): Solute spreads only due to advection. Due to absence of dispersion there is no (1D) spreading effect.\n\n(C): Inclusion of dispersion process causes spread of concentration. As retardation is absence the front centreline remains unchanged\n\n(D): The inclusion of retardation ($R$) with advection and dispersion leads to removal of chemicals from water and as well the retarded movement of the chemical front.\n\n(E): The inclusion of retardation along with degradation and conservative transport process leads to high removal of chemical from water.\n\n\n\n\n### Breakthrough Curve\n\nBreakthrough curves provide a _time-dependent_ spread of chemicals in the groundwater. The inclusion of multiple processes are normally solved using numerical models. Analytical models are available for limited processes and simplified problems. A 1-D analytical solution by Kinzelbach (1987) provide a transient (time-dependent) solution of reactive transport problem with inclusion of equilibrium linear sorption represented by retardation $(R)$, first-order degradation rate $(\\lambda)$ and the conservative transport quantities - dispersion $(D)$ and advection. The solution is given as:\n\n\n$$\nC(x,t) = C_0 \\cdot \\exp(-\\lambda\\cdot t)\\bigg(1- \\frac{1}{2}\\text{erfc}\\bigg(\\frac{R\\cdot x - v\\cdot t}{2\\cdot\\sqrt{D\\cdot R \\cdot t}}\\bigg) - \\frac{1}{2}\\exp\\bigg(\\frac{v\\cdot x}{D}\\bigg)\\text{erfc}\\bigg(\\frac{R\\cdot x + v\\cdot t}{2\\cdot\\sqrt{D\\cdot R \\cdot t}}\\bigg) \n$$\n\nwith $C_0$ = input/source concentration [ML$^{-3}$]
        \n$t$ = time [T]
        \n$v$ = groundwater flow velocity [LT$^{-1}$]
        \nerfc() = represents the complementary error function [See here for details](https://en.wikipedia.org/wiki/Error_function). erfc() can be easily computed using Python Scipy special function library.\n\n\n```python\n# Breakthrough curve using Kinzelbach (1987) analytical solution Main function\n\n# The main function - you may change the value of C_o, lam, R, Dx, v, x\n# C_o = input concentration, mg/L \n# lam = 0 # 1/d, degradation rate, 1/d \n# R = retardation factor, ()\n# Dx = dispersion coeff. along x, m^2/d\n# v = groundwater velocity, m/d\n# x = position where C is to be measured, m\n\ndef Cx(t, C_o= 1, lam = 0, R=1, Dx=1, v= 10, x = 20):\n sterm = C_o*np.exp(-lam*t)\n erf_ag1 = (R*x-v*t)/(2*np.sqrt(Dx*R*t)) \n erf_ag2 = (R*x+v*t)/(2*np.sqrt(Dx*R*t)) \n \n C = sterm*(1-(0.5*sci.erfc(erf_ag1)-0.5*np.exp((v*x)/Dx)*sci.erfc(erf_ag2)))\n return C \n\n```\n\n\n```python\n# Computing Case 1: Conservative process- R = 1, Lambda = 0\nt1 = np.linspace(1e-5,50,1000) # times, d\nC1 = Cx(t1, C_o= 1, lam = 0, R=1, Dx=1, v= 1, x = 20)\n\n# Computing Case 2: Conservative system + Retardation - R = 2, Lambda = 0\nt2 = np.linspace(1e-5,50,1000) # times, d\nC2 = Cx(t2, C_o= 1, lam = 0, R=2, Dx=1, v= 1, x = 20)\n\n# Computing Case 3: Conservative system + Retardation + degradation - R = 2, Lambda = 0.004\nt3 = np.linspace(1e-5,50,1000) # times, d\nC3 = Cx(t3, C_o= 1, lam = 0.004, R=2, Dx=1, v= 1, x = 20)\n\n# plots - this should be adjusted as required \n\nplt.figure(figsize=(9, 6))\n\nplt.plot(t1, C1, label=\"Conservative transport\")\nplt.plot(t2, C2, label = \"Reactive transport with sorption\")\nplt.plot(t3, C3, label = \"Reactive transport with sorption and degradation rate\")\nplt.legend(loc= 3); plt.xlim(0), plt.ylim(0)\nplt.xlabel(\"time (d)\"); plt.ylabel(r\"Concentration, $C$ (mg/L)\")\nplt.text(5, 0.2, r\"$x= 20$ m\") \n```\n\n### Mass (Re-)Distribution During Injection / Extraction\n\n**Consider a scenario**: \n\nWater is _injected_ into a certain portion of an aquifer with total volume $V$, bulk density $\\rho_b$ and effective porosity $n_e$. Assume that the injected water contains a chemical of total mass $M$, which is adsorbed by the aquifer materials under equilibrium conditions according to Henry isotherm (quantified by $K_d$$).\n\nBases on the assumption of sorption equilibrium, the total mass $M$ of the chemical is instantaneously(!) split up into a dissolved and a sorbed part. In such case, the mass distribution can be computed as follows (with $R$ = retardation factor, $\\rho_b$\n= bulk density):\n\n\\begin{align}\nM &= n_e \\cdot V \\cdot C + V\\cdot\\rho_b \\cdot C_a \\\\ \n&= n_e \\cdot V \\cdot C + V \\cdot \\rho_b \\cdot K_d \\cdot C\\\\ \n&= n_e \\cdot (1 + \\rho_b \\cdot K_d/n_e) \\cdot V \\cdot C\\\\\n&= n_e \\cdot R \\cdot V \\cdot C\n\\end{align}\n\nIn which,\n\n$n_e \\cdot V \\cdot C$ = dissolved mass
        \n\n$V\\cdot\\rho_b \\cdot C_a$ = mass of adsorbate\n\nFor the dissolved mass we thus have $n_e \\cdot V \\cdot C = M/R$ and consequently the mass of adsorbate is:
        \n$V\\cdot\\rho_b \\cdot C_a = M- M/R = (1-1/R)\\cdot M$\n\nThe same approach can be adopted for the **extraction** scenarios, i.e. equilibrium desorption.\n\n\n\n\n\n\n", "meta": {"hexsha": "866cb305554b08c904b082476802b09812074e84", "size": 211358, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "contents/transport/lecture_10/.ipynb_checkpoints/22_reactive-checkpoint.ipynb", "max_stars_repo_name": "prabhasyadav/iGW-I", "max_stars_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "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": "contents/transport/lecture_10/.ipynb_checkpoints/22_reactive-checkpoint.ipynb", "max_issues_repo_name": "prabhasyadav/iGW-I", "max_issues_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "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": "contents/transport/lecture_10/.ipynb_checkpoints/22_reactive-checkpoint.ipynb", "max_forks_repo_name": "prabhasyadav/iGW-I", "max_forks_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "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": 200.3393364929, "max_line_length": 42656, "alphanum_fraction": 0.8881991692, "converted": true, "num_tokens": 8504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.16667541089705434, "lm_q1q2_score": 0.054042068352520595}} {"text": "```julia\n\"\"\"Tutorial: Second-Order Moller--Plesset Perturbation Theory (MP2)\"\"\"\n\n__author__ = [\"D. Menendez\", \"Dominic A. Sirianni\"]\n__credit__ = [\"D. Menendez\", \"Dominic A. Sirianni\", \"Daniel G. A. Smith\"]\n\n__copyright__ = \"(c) 2014-2020, The Psi4Julia Developers\"\n__license__ = \"BSD-3-Clause\"\n__date__ = \"2020-07-30\"\n```\n\n\n\n\n \"2020-07-30\"\n\n\n\n# Second-Order Moller-Plesset Perturbation Theory (MP2)\n\nMoller-Plesset perturbation theory [also referred to as many-body perturbation theory (MBPT)] is an adaptation of the more general Rayleigh-Schrodinger perturbation theory (RSPT), applied to problems in molecular electronic structure theory. This tutorial will provide a brief overview of both RSPT and MBPT, before walking through an implementation of second-order Moller-Plesset perturbation theory (specifically referred to as MP2) which uses conventional, 4-index ERIs. \n\n### I. Overview of Rayleigh-Schrodinger Perturbation Theory\nGiven the Hamiltonian operator $\\hat{H}$ for a system, perturbation theory solves the Schrodinger equation for that system by rewriting $\\hat{H}$ as\n\n\\begin{equation}\n\\hat{H} = \\hat{H}{}^{(0)} + \\lambda\\hat{V},\n\\tag{[Szabo:1996], pp. 322, Eqn. 6.3}\n\\end{equation}\n\nwere $\\hat{H}{}^{(0)}$ is the Hamiltonian operator corresponding to a solved problem which resembles $\\hat{H}$, and $\\hat{V}$ is the *perturbation* operator, defined as $\\hat{V} = \\hat{H} - \\hat{H}{}^{(0)}$. Then the Schrodinger equation for the system becomes \n\n\\begin{equation}\n\\hat{H}\\mid\\Psi_n\\rangle = (\\hat{H}{}^{(0)} + \\lambda\\hat{V})\\mid\\Psi_n\\rangle = E_n\\mid\\Psi_n\\rangle.\n\\tag{[Szabo:1996], pp. 322, Eqn. 6.2}\n\\end{equation}\n\nThe energies $E_n$ and wavefunctions $\\mid\\Psi_n\\rangle$ will both be functions of $\\lambda$; they can therefore be written as a Taylor series expansion about $\\lambda = 0$ ([Szabo:1996], pp. 322, Eqns. 6.4a & 6.4b):\n\n\\begin{align}\nE_n &= E_n^{(0)} + \\lambda E_n^{(1)} + \\lambda^2E_n^{(2)} + \\ldots;\\tag{[Szabo:1996], pp. 322, Eqn. 6.4a}\\\\\n\\mid\\Psi_n\\rangle &= \\mid\\Psi_n^{(0)}\\rangle + \\lambda\\mid\\Psi_n^{(1)}\\rangle + \\lambda^2\\mid\\Psi_n^{(2)}\\rangle + \\ldots,\\tag{[Szabo:1996], pp. 322, Eqn. 6.4b}\\\\\n\\end{align}\n\nin practice, these perturbation expansions may be truncated to a given power of $\\lambda$. Substituting the perturbation series above back into the Schrodinger equation yields\n\n\\begin{equation*}\n(\\hat{H}{}^{(0)} + \\lambda\\hat{V})(\\mid\\Psi_n^{(0)}\\rangle + \\lambda\\mid\\Psi_n^{(1)}\\rangle + \\lambda^2\\mid\\Psi_n^{(2)}\\rangle + \\ldots) = (E_n^{(0)} + \\lambda E_n^{(1)} + \\lambda^2E_n^{(2)} + \\ldots)(\\mid\\Psi_n^{(0)}\\rangle + \\lambda\\mid\\Psi_n^{(1)}\\rangle + \\lambda^2\\mid\\Psi_n^{(2)}\\rangle + \\ldots),\n\\end{equation*}\n\nwhich by equating powers of $\\lambda$ ([Szabo:1996], pp. 323, Eqns. 6.7a-6.7d) gives expressions for the $E_n^{(i)}$and $\\mid\\Psi_n^{(i)}\\rangle$. Note that for $\\lambda^0$, $E_n^{(0)}$ and $\\mid\\Psi_n^{(0)}\\rangle$ are known, as they are the solution to the zeroth-order problem $\\hat{H}{}^{(0)}$. For $\\lambda^1$ and $\\lambda^2$, the expressions for $E_n^{(1)}$ and $E_n^{(2)}$ are given by\n\n\\begin{align}\n\\lambda^1:\\;\\;\\;\\;E_n^{(1)} &= \\langle\\Psi_n^{(0)}\\mid\\hat{V}\\mid\\Psi_n^{(0)}\\rangle,\\tag{[Szabo:1996], pp. 323, Eqn. 6.8b}\\\\\n\\lambda^2:\\;\\;\\;\\;E_n^{(2)} &= \\sum_{\\mu\\neq n}\\frac{\\mid\\langle\\Psi_{n}^{(0)}\\mid\\hat{V}\\mid\\Psi_{\\mu}^{(0)}\\rangle\\mid^2}{E_n^{(0)} - E_{\\mu}^{(0)}}\\tag{[Szabo:1996], pp. 324, Eqn. 6.12}\\\\\n\\end{align}\n\n\n### II. Overview of Moller-Plesset Perturbation Theory\n\nThe exact electronic Hamiltonian for an N-electron molecule with a given atomic configuration is (in atomic units):\n\n\\begin{equation}\n\\hat{H}_{elec} = \\sum_i\\hat{h}(i) + \\sum_{i Import statements & Global Options <==\nusing PyCall: pyimport\npsi4 = pyimport(\"psi4\")\nnp = pyimport(\"numpy\") # used only to cast to Psi4 arrays\nusing TensorOperations: @tensor\n\npsi4.set_memory(Int(2e9))\nnumpy_memory = 2\npsi4.core.set_output_file(\"output.dat\", false)\n```\n\n \n Memory set to 1.863 GiB by Python driver.\n\n\nNext, we can define our molecule and Psi4 options. Notice that we are using `scf_type pk` to indicate that we wish to use conventional, full 4-index ERIs, and that we have specified `mp2_type conv` so that the MP2 algorithm we check against also uses the conventional ERIs.\n\n\n```julia\n# ==> Molecule & Psi4 Options Definitions <==\nmol = psi4.geometry(\"\"\"\nO\nH 1 1.1\nH 1 1.1 2 104\nsymmetry c1\n\"\"\")\n\n\npsi4.set_options(Dict(\"basis\" => \"6-31g\",\n \"scf_type\" => \"pk\",\n \"mp2_type\" => \"conv\",\n \"e_convergence\" => 1e-8,\n \"d_convergence\" => 1e-8))\n```\n\nSince MP2 is a perturbation on the zeroth-order Hartree-Fock description of a molecular system, all of the relevant information (Fock matrix, orbitals, orbital energies) about the system can be computed using any Hartree-Fock program. We could use the RHF program that we wrote in tutorial 3a, but we could just as easily use Psi4 to do our dirty work. In the cell below, use Psi4 to compute the RHF energy and wavefunction, and store them using the `return_wfn=True` keyword argument to `psi4.energy()`:\n\n\n```julia\n# Get the SCF wavefunction & energies\nscf_e, scf_wfn = psi4.energy(\"scf\", return_wfn=true)\n```\n\n\n\n\n (-75.95252904632221, PyObject )\n\n\n\nIn the expression for $E_0^{(2)}$, the two summations are over occupied and virtual indices, respectively. Therefore, we'll need to get the number of occupied orbitals and the total number of orbitals. Additionally, we must obtain the MO energy eigenvalues; again since the sums are over occupied and virtual orbitals, it is good to separate the occupied orbital energies from the virtual orbital energies. From the SCF wavefunction you generated above, get the number of doubly occupied orbitals, number of molecular orbitals, and MO energies:\n\n\n```julia\n# ==> Get orbital information & energy eigenvalues <==\n# Number of Occupied orbitals & MOs\nndocc = scf_wfn.nalpha()\nnmo = scf_wfn.nmo()\n\n# Get orbital energies, cast into NumPy array, and separate occupied & virtual\neps = np.asarray(scf_wfn.epsilon_a())\ne_ij = eps[1:ndocc]\ne_ab = eps[ndocc+1:end];\n```\n\nUnlike the orbital information, Psi4 does not return the ERIs when it does a computation. Fortunately, however, we can just build them again using the `psi4.core.MintsHelper()` class. Recall that these integrals will be generated in the AO basis; before using them in the $E_0^{(2)}$ expression, we must transform them into the MO basis. To do this, we first need to obtain the orbital coefficient matrix, **C**. In the cell below, generate the ERIs for our molecule, get **C** from the SCF wavefunction, and obtain occupied- and virtual-orbital slices of **C** for future use. \n\n\n```julia\n# ==> ERIs <==\n# Create instance of MintsHelper class\nmints = psi4.core.MintsHelper(scf_wfn.basisset())\n\n# Memory check for ERI tensor\nI_size = nmo^4 * 8.e-9\nprintln(\"\\nSize of the ERI tensor will be $I_size GB.\")\nmemory_footprint = I_size * 1.5\nif I_size > numpy_memory\n psi4.core.clean()\n throw(OutOfMemoryError(\"Estimated memory utilization ($memory_footprint GB) exceeds \" * \n \"allotted memory limit of $numpy_memory GB.\"))\nend\n\n# Build ERI Tensor\nI = np.asarray(mints.ao_eri())\n\n# Get MO coefficients from SCF wavefunction\nC = np.asarray(scf_wfn.Ca())\nCocc = C[:, 1:ndocc]\nCvirt = C[:, ndocc+1:end];\n```\n\n \n Size of the ERI tensor will be 0.00022848800000000003 GB.\n\n\nIn order to transform the four-index integrals from the AO to the MO basis, we must perform the following contraction:\n\n$$(i\\,a\\mid j\\,b) = C_{\\mu i}C_{\\nu a}(\\mu\\,\\nu\\mid|\\,\\lambda\\,\\sigma)C_{\\lambda j}C_{\\sigma b}$$\n\nAgain, here we are using $i,\\,j$ as occupied orbital indices and $a,\\, b$ as virtual orbital indices. We could carry out the above contraction all in one step using either `@tensor` or explicit loops:\n\n~~~julia\n# Naive Algorithm for ERI Transformation\n@tensor I_mo[i,a,j,b] := Cocc[p,i] * Cvirt[q,a] * I[p,q,r,s] * Cocc[r,j] * Cvirt[s,b]\n~~~\n\nNotice that the transformation from AO index to occupied (virtual) MO index requires only the occupied (virtual) block of the **C** matrix; this allows for computational savings in large basis sets, where the virtual space can be very large. This algorithm, while efficient with `@tensor`, has horrendous scaling if the search of an optimal contraction fails. We will enforce a better contraction. Examining the contraction more closely, we see that there are 8 unique indices, and thus the step above scales as ${\\cal O}(N^8)$. With this algorithm, a twofold increase of the number of MO's would result in $2^8 = 256\\times$ expense to perform. We can, however, refactor the above contraction such that\n\n$$(i\\,a\\mid j\\,b) = \\left[C_{\\mu i}\\left[C_{\\nu a}\\left[C_{\\lambda j}\\left[C_{\\sigma b}(\\mu\\,\\nu\\mid|\\,\\lambda\\,\\sigma)\\right]\\right]\\right]\\right],$$\n\nwhere we have now written the transfomation as four ${\\cal O}(N^5)$ steps instead of one ${\\cal O}(N^8)$ step. This is a savings of $\\frac{4}{n^3}$, and is responsible for the feasibility of the MP2 method for application to any but very small systems and/or basis sets. We may carry out the above ${\\cal O}(N^5)$ algorithm by carrying out one index transformation at a time, and storing the result in a temporary array. In the cell below, transform the ERIs from the AO to MO basis, using our smarter algorithm:\n\n\n```julia\n# ==> Transform I -> I_mo @ O(N⁵) <==\nI_mo = @tensor begin\n I_mo[i,q,r,s] := Cocc[p,i] * I[p,q,r,s]\n I_mo[i,a,r,s] := Cvirt[q,a] * I_mo[i,q,r,s]\n I_mo[i,a,j,s] := I_mo[i,a,r,s] * Cocc[r,j]\n I_mo[i,a,j,b] := I_mo[i,a,j,s] * Cvirt[s,b]\nend\nnothing\n```\n\nWe note here that we can use infrastructure in Psi4 to carry out the above integral transformation; this entails obtaining the occupied and virtual blocks of **C** Psi4-side, and then using the built-in `MintsHelper` function `MintsHelper.mo_eri()` to transform the integrals. Just to check your work above, execute the next cell to see this tech in action:\n\n\n```julia\n# ==> Compare our Imo to MintsHelper <==\nCo = scf_wfn.Ca_subset(\"AO\",\"OCC\")\nCv = scf_wfn.Ca_subset(\"AO\",\"VIR\")\nMO = np.asarray(mints.mo_eri(Co, Cv, Co, Cv))\nprintln(\"Do our transformed ERIs match Psi4's? \", np.allclose(I_mo, np.asarray(MO)))\n```\n\n Do our transformed ERIs match Psi4's? true\n\n\nNow we have all the pieces needed to compute $E_0^{(2)}$. This could be done by writing explicit loops over occupied and virtual indices Julia side, e.g.,\n\n\n```julia\n# Compute SS & OS MP2 Correlation\nmp2_corr = let mp2_ss_corr = 0.0, mp2_os_corr = 0.0\n nvirt = nmo - ndocc\n for i in 1:ndocc, a in 1:nvirt, j in 1:ndocc, b in 1:nvirt\n numerator = I_mo[i,a,j,b] * (I_mo[i, a, j, b] - I_mo[i, b, j, a])\n mp2_ss_corr += numerator / (e_ij[i] + e_ij[j] - e_ab[a] - e_ab[b])\n mp2_os_corr += I_mo[i,a,j,b]^2 / (e_ij[i] + e_ij[j] - e_ab[a] - e_ab[b])\n end\n mp2_ss_corr + mp2_os_corr\nend\n\n# Total MP2 Energy\nMP2_E = scf_e + mp2_corr\n\n# ==> Compare to Psi4 <==\npsi4.compare_values(psi4.energy(\"mp2\"), MP2_E, 6, \"MP2 Energy\")\n```\n\n \tMP2 Energy........................................................PASSED\n\n\n\n\n\n true\n\n\n\nIn this method it is very clear what is going on and is easy to program. Julia has the distinct advantage loops are as fast as the same block written in a compiled language like C, C++, or Fortran. \n\nHowever, we will provide an alternative formulation using tensor contractions. It should be clear how to contract the four-index integrals $(i\\,a\\mid j\\,b)$ and $(i\\,a\\mid j\\,b)$ with one another, but what about the energy eigenvalues $\\epsilon$? We can use a Julia trick called *broadcasting* to construct a four-index array of all possible energy denominators, which can then be contracted with the full I_mo arrays. To do this, we'll use the function `reshape()`:\n~~~julia\n# Prepare 4d energy denominator array\ne_denom = reshape(e_ij, 1, 1, 1, :) # Diagonal of 4d array are occupied orbital energies\ne_denom -= reshape(e_ab', 1, 1, :) # all combinations of (e_ij - e_ab)\ne_denom += e_ij # all combinations of [(e_ij - e_ab) + e_ij]\ne_denom -= e_ab' # All combinations of full denominator\ne_denom = premutedims(e_denom, (1,2,4,3)) # permute 3rd and 4th dims to have (nocc,nvirt,nocc,nvirt) shape\ne_denom = inv.(e_denom) # Take reciprocal for contracting with numerator\n~~~\nIn the cell below, compute the energy denominator using `reshape()` and contract this array with the four-index ERIs to compute the same-spin and opposite-spin MP2 correction using `sum()`. Then, add these quantities to the SCF energy computed above to obtain the total MP2 energy.\n\nHint: For the opposite-spin correlation, use `permutedims()` to obtain the correct ordering of the indices in the exchange integral.\n\n\n```julia\n#using Einsum: @einsum\n# ==> Compute MP2 Correlation & MP2 Energy <==\n# Compute energy denominator array\ne_denom = reshape(e_ij,1,1,1,:) .- reshape(e_ab',1,1,:) .+ (e_ij .- e_ab')\ne_denom = permutedims(e_denom, (1,2,4,3)) # 3 ↔ 4\ne_denom = inv.(e_denom)\n\n# check\n#using Test\n#nvirt = nmo - ndocc\n#for i in 1:ndocc, a in 1:nvirt, j in 1:ndocc, b in 1:nvirt\n# @test e_denom[i,a,j,b] ≈ 1 / (e_ij[i] + e_ij[j] - e_ab[a] - e_ab[b])\n#end\n\n# Compute SS & OS MP2 Correlation with sum()\nbctd_mp2_os_corr = sum(I_mo .* I_mo .* e_denom)\nI_mo_swap = permutedims(I_mo,(3,2,1,4)) # 1 ↔ 3\nbctd_mp2_ss_corr = sum(I_mo .* (I_mo .- I_mo_swap) .* e_denom)\n\n# Compare broadcasted and loop MP2\n@assert bctd_mp2_os_corr + bctd_mp2_ss_corr ≈ mp2_corr\n\n# Total MP2 Energy\nMP2_E = scf_e + bctd_mp2_os_corr + bctd_mp2_ss_corr\n```\n\n\n\n\n -76.09464888642944\n\n\n\n\n```julia\n# ==> Compare to Psi4 <==\npsi4.compare_values(psi4.energy(\"mp2\"), MP2_E, 6, \"MP2 Energy\")\n```\n\n \tMP2 Energy........................................................PASSED\n\n\n\n\n\n true\n\n\n\n## References\n\n1. Original paper: \"Note on an Approximation Treatment for Many-Electron Systems\"\n\t> [[Moller:1934:618](https://journals.aps.org/pr/abstract/10.1103/PhysRev.46.618)] C. Møller and M. S. Plesset, *Phys. Rev.* **46**, 618 (1934)\n2. The Laplace-transformation in MP theory: \"Minimax approximation for the decomposition of energy denominators in Laplace-transformed Møller–Plesset perturbation theories\"\n > [[Takasuka:2008:044112](http://aip.scitation.org/doi/10.1063/1.2958921)] A. Takatsuka, T. Siichiro, and W. Hackbusch, *J. Phys. Chem.*, **129**, 044112 (2008)\n3. Equations taken from:\n\t> [[Szabo:1996](https://books.google.com/books?id=KQ3DAgAAQBAJ&printsec=frontcover&dq=szabo+%26+ostlund&hl=en&sa=X&ved=0ahUKEwiYhv6A8YjUAhXLSCYKHdH5AJ4Q6AEIJjAA#v=onepage&q=szabo%20%26%20ostlund&f=false)] A. Szabo and N. S. Ostlund, *Modern Quantum Chemistry: Introduction to Advanced Electronic Structure Theory*. Courier Corporation, 1996.\n4. Algorithms taken from:\n\t> [Crawford:prog] T. D. Crawford, \"The Second-Order Møller–Plesset Perturbation Theory (MP2) Energy.\" Accessed via the web at http://github.com/CrawfordGroup/ProgrammingProjects.\n", "meta": {"hexsha": "30cb7130365dd16606342fd953cb87fe65a98e00", "size": 27131, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorials/05_Moller-Plesset/5a_conventional-mp2.ipynb", "max_stars_repo_name": "zyth0s/psi4julia", "max_stars_repo_head_hexsha": "beb0384028f1a3654b8a2f8690b7db5bd9c24b86", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-02-13T22:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-17T07:34:10.000Z", "max_issues_repo_path": "Tutorials/05_Moller-Plesset/5a_conventional-mp2.ipynb", "max_issues_repo_name": "zyth0s/psi4julia", "max_issues_repo_head_hexsha": "beb0384028f1a3654b8a2f8690b7db5bd9c24b86", "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": "Tutorials/05_Moller-Plesset/5a_conventional-mp2.ipynb", "max_forks_repo_name": "zyth0s/psi4julia", "max_forks_repo_head_hexsha": "beb0384028f1a3654b8a2f8690b7db5bd9c24b86", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7121495327, "max_line_length": 1015, "alphanum_fraction": 0.5901367439, "converted": true, "num_tokens": 6452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.13477591742295678, "lm_q1q2_score": 0.05388498067708348}} {"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(examples:the_brachistochrone)=\n# The Brachistochrone\n\n```{admonition} Things you'll learn through this example\n- How to define a basic Dymos ODE system.\n- How to test the partials of your ODE system.\n- Adding a Trajectory object with a single Phase to an OpenMDAO Problem.\n- Imposing boundary conditions on states with simple bounds via `fix_initial` and `fix_final`.\n- Using the Phase.interpolate` method to set a linear guess for state and control values across the Phase.\n- Checking the validity of the result through explicit simulation via the `Trajectory.simulate` method.\n```\n\nThe brachistochrone is one of the most well-known optimal control problems.\nIt was originally posed as a challenge by Johann Bernoulli.\n\n```{admonition} The brachistochrone problem\n_Given two points A and B in a vertical plane, find the path AMB\ndown which a movable point M must by virtue of its weight fall from\nA to B in the shortest possible time._\n\n- Johann Bernoulli, Acta Eruditorum, June 1696\n```\n\nWe seek to find the optimal shape of a wire between two points (A and B) such that a bead sliding\nwithout friction along the wire moves from point A to point B in minimum time.\n\n\n```python\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import FancyArrowPatch, Arc\n\nLW = 2\n\nfig, ax = plt.subplots(1, 1, figsize=(5, 5))\nax.axis('off')\n\nax.set_xlim(-1, 11)\nax.set_ylim(-1, 11)\n\ncircle = plt.Circle((0, 10), radius=0.1, fc='k')\nax.add_patch(circle)\nplt.text(0.2, 10.2, 'A')\n\ncircle = plt.Circle((10, 5), radius=0.1, fc='k')\nax.add_patch(circle)\nplt.text(10.2, 5.2, 'B')\n\n# Choose a to suite, compute b\na = 0.1\nb = -0.5 - 10*a\nc = 10\n\ndef y_wire(x):\n return a*x**2 + b*x + c, 2*a*x + b\n\nx = np.linspace(0, 10, 100)\ny, _ = y_wire(x)\nplt.plot(x, y, 'b-')\n\n# Add the bead to the wire\nx = 3\ny, dy_dx = y_wire(x)\nplt.plot(x, y, 'ro', ms=10)\n\n# Draw and label the gravity vector\ngvec = FancyArrowPatch((x, y), (x, y-2), arrowstyle='->', mutation_scale=10, linewidth=LW, color='k')\nlv_line = plt.Line2D((x, x), (y, y-2), visible=False) # Local vertical\nax.add_patch(gvec)\nplt.text(x - 0.5, y-1, 'g')\n\n# Draw and label the velocity vector\ndx = 2\ndy = dy_dx * dx\nvvec = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10, linewidth=LW, color='k')\nax.add_patch(vvec)\nplt.text(x+dx-0.25, y+dy-0.25, 'v')\n\n# Draw angle theta\nvvec_line = plt.Line2D((x, x+dx), (y, y+dy), visible=False)\n# angle_plot = get_angle_plot(lv_line, vvec_line, color='k', origin=(x, y), radius=3)\n# ax.add_patch(angle_plot)\nax.text(x+0.25, y-1.25, r'$\\theta$')\n\n# Draw the axes\nx = 0\ny = 2\ndx = 5\ndy = 0\nxhat = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10, linewidth=LW, color='k')\nax.add_patch(xhat)\nplt.text(x+dx/2.0-0.5, y+dy/2.0-0.5, 'x')\n\ndx = 0\ndy = 5\nyhat = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10, linewidth=LW, color='k')\nax.add_patch(yhat)\nplt.text(x+dx/2.0-0.5, y+dy/2.0-0.5, 'y')\n\nplt.ylim(1, 11)\nplt.xlim(-0.5, 10.5)\n\nplt.savefig('brachistochrone_fbd.png')\n\nplt.show()\n```\n\n## State variables\n\nIn this implementation, three _state_ variables are used to define the configuration of the system at any given instant in time.\n\n- **x**: The horizontal position of the particle at an instant in time.\n- **y**: The vertical position of the particle at an instant in time.\n- **v**: The speed of the particle at an instant in time.\n\n## System dynamics\n\nFrom the free-body diagram above, the evolution of the state variables is given by the following ordinary differential equations (ODE).\n\n\\begin{align}\n \\frac{d x}{d t} &= v \\sin(\\theta) \\\\\n \\frac{d y}{d t} &= -v \\cos(\\theta) \\\\\n \\frac{d v}{d t} &= g \\cos(\\theta)\n\\end{align}\n\n## Control variables\n\nThis system has a single control variable.\n\n- **$\\theta$**: The angle between the gravity vector and the tangent to the curve at the current instant in time.\n\n## The initial and final conditions\n\nIn this case, starting point **A** is given as _(0, 10)_.\nThe point moving along the curve will begin there with zero initial velocity.\n\nThe initial conditions are:\n\n\\begin{align}\n x_0 &= 0 \\\\\n y_0 &= 10 \\\\\n v_0 &= 0\n\\end{align}\n\nThe end point **B** is given as _(10, 5)_.\nThe point will end there, but the velocity at that point is not constrained.\n\nThe final conditions are:\n\n\\begin{align}\n x_f &= 10 \\\\\n y_f &= 5 \\\\\n v_f &= \\mathrm{free}\n\\end{align}\n\n## Defining the ODE as an OpenMDAO System\n\nIn Dymos, the ODE is an OpenMDAO System (a Component, or a Group of components).\nThe following ExplicitComponent computes the state rates for the brachistochrone problem.\n\nMore detail on the workings of an ExplicitComponent can be found in the OpenMDAO documentation. In summary:\n\n- **initialize**: Called at setup, and used to define options for the component. **ALL** Dymos ODE components should have the property `num_nodes`, which defines the number of points at which the outputs are simultaneously computed.\n- **setup**: Used to add inputs and outputs to the component, and declare which outputs (and indices of outputs) are dependent on each of the inputs.\n- **compute**: Used to compute the outputs, given the inputs.\n- **compute_partials**: Used to compute the derivatives of the outputs w.r.t. each of the inputs analytically. This method may be omitted if finite difference or complex-step approximations are used, though analytic is recommended.\n\n\n```python\nimport numpy as np\nimport openmdao.api as om\n\n\nclass BrachistochroneODE(om.ExplicitComponent):\n\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n self.options.declare('static_gravity', types=(bool,), default=False,\n desc='If True, treat gravity as a static (scalar) input, rather than '\n 'having different values at each node.')\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), desc='velocity', units='m/s')\n\n if self.options['static_gravity']:\n self.add_input('g', val=9.80665, desc='grav. acceleration', units='m/s/s',\n tags=['dymos.static_target'])\n else:\n self.add_input('g', val=9.80665 * np.ones(nn), desc='grav. acceleration', units='m/s/s')\n\n self.add_input('theta', val=np.ones(nn), desc='angle of wire', units='rad')\n\n self.add_output('xdot', val=np.zeros(nn), desc='velocity component in x', units='m/s',\n tags=['dymos.state_rate_source:x', 'dymos.state_units:m'])\n\n self.add_output('ydot', val=np.zeros(nn), desc='velocity component in y', units='m/s',\n tags=['dymos.state_rate_source:y', 'dymos.state_units:m'])\n\n self.add_output('vdot', val=np.zeros(nn), desc='acceleration magnitude', units='m/s**2',\n tags=['dymos.state_rate_source:v', 'dymos.state_units:m/s'])\n\n self.add_output('check', val=np.zeros(nn), desc='check solution: v/sin(theta) = constant',\n units='m/s')\n\n # Setup partials\n arange = np.arange(self.options['num_nodes'])\n self.declare_partials(of='vdot', wrt='theta', rows=arange, cols=arange)\n\n self.declare_partials(of='xdot', wrt='v', rows=arange, cols=arange)\n self.declare_partials(of='xdot', wrt='theta', rows=arange, cols=arange)\n\n self.declare_partials(of='ydot', wrt='v', rows=arange, cols=arange)\n self.declare_partials(of='ydot', wrt='theta', rows=arange, cols=arange)\n\n self.declare_partials(of='check', wrt='v', rows=arange, cols=arange)\n self.declare_partials(of='check', wrt='theta', rows=arange, cols=arange)\n\n if self.options['static_gravity']:\n c = np.zeros(self.options['num_nodes'])\n self.declare_partials(of='vdot', wrt='g', rows=arange, cols=c)\n else:\n self.declare_partials(of='vdot', wrt='g', rows=arange, cols=arange)\n\n def compute(self, inputs, outputs):\n theta = inputs['theta']\n cos_theta = np.cos(theta)\n sin_theta = np.sin(theta)\n g = inputs['g']\n v = inputs['v']\n\n outputs['vdot'] = g * cos_theta\n outputs['xdot'] = v * sin_theta\n outputs['ydot'] = -v * cos_theta\n outputs['check'] = v / sin_theta\n\n def compute_partials(self, inputs, partials):\n theta = inputs['theta']\n cos_theta = np.cos(theta)\n sin_theta = np.sin(theta)\n g = inputs['g']\n v = inputs['v']\n\n partials['vdot', 'g'] = cos_theta\n partials['vdot', 'theta'] = -g * sin_theta\n\n partials['xdot', 'v'] = sin_theta\n partials['xdot', 'theta'] = v * cos_theta\n\n partials['ydot', 'v'] = -cos_theta\n partials['ydot', 'theta'] = v * sin_theta\n\n partials['check', 'v'] = 1 / sin_theta\n partials['check', 'theta'] = -v * cos_theta / sin_theta ** 2\n```\n\n```{admonition} \"Things to note about the ODE system\"\n- There is no input for the position states ($x$ and $y$). The dynamics aren't functions of these states, so they aren't needed as inputs.\n- While $g$ is an input to the system, since it will never change throughout the trajectory, it can be an option on the system. This way we don't have to define any partials w.r.t. $g$.\n- The output `check` is an _auxiliary_ output, not a rate of the state variables. In this case, optimal control theory tells us that `check` should be constant throughout the trajectory, so it's a useful output from the ODE.\n```\n\n## Testing the ODE\n\nNow that the ODE system is defined, it is strongly recommended to test the analytic partials before using it in optimization.\nIf the partials are incorrect, then the optimization will almost certainly fail.\nFortunately, OpenMDAO makes testing derivatives easy with the `check_partials` method.\nThe `assert_check_partials` method in `openmdao.utils.assert_utils` can be used in test frameworks to verify the correctness of the partial derivatives in a model.\n\nThe following is a test method which creates a new OpenMDAO problem whose model contains the ODE class.\nThe problem is setup with the `force_alloc_complex=True` argument to enable complex-step approximation of the derivatives.\nComplex step typically produces derivative approximations with an error on the order of 1.0E-16, as opposed to ~1.0E-6 for forward finite difference approximations.\n\n\n```python\nimport numpy as np\nimport openmdao.api as om\n\nnum_nodes = 5\n\np = om.Problem(model=om.Group())\n\nivc = p.model.add_subsystem('vars', om.IndepVarComp())\nivc.add_output('v', shape=(num_nodes,), units='m/s')\nivc.add_output('theta', shape=(num_nodes,), units='deg')\n\np.model.add_subsystem('ode', BrachistochroneODE(num_nodes=num_nodes))\n\np.model.connect('vars.v', 'ode.v')\np.model.connect('vars.theta', 'ode.theta')\n\np.setup(force_alloc_complex=True)\n\np.set_val('vars.v', 10*np.random.random(num_nodes))\np.set_val('vars.theta', 10*np.random.uniform(1, 179, num_nodes))\n\np.run_model()\ncpd = p.check_partials(method='cs', compact_print=True)\n```\n\n\n```python\nfrom dymos.utils.testing_utils import assert_check_partials\n\nassert_check_partials(cpd)\n```\n\n## Solving the problem with Legendre-Gauss-Lobatto collocation in Dymos\n\nThe following script fully defines the brachistochrone problem with Dymos and solves it. In this section we'll walk through each step.\n\n\n```python\nimport openmdao.api as om\nimport dymos as dm\nfrom dymos.examples.plotting import plot_results\nfrom dymos.examples.brachistochrone import BrachistochroneODE\nimport matplotlib.pyplot as plt\n\n#\n# Initialize the Problem and the optimization driver\n#\np = om.Problem(model=om.Group())\np.driver = om.ScipyOptimizeDriver()\np.driver.declare_coloring()\n\n#\n# Create a trajectory and add a phase to it\n#\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\nphase = traj.add_phase('phase0',\n dm.Phase(ode_class=BrachistochroneODE,\n transcription=dm.GaussLobatto(num_segments=10)))\n\n#\n# Set the variables\n#\nphase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n\nphase.add_state('x', fix_initial=True, fix_final=True)\n\nphase.add_state('y', fix_initial=True, fix_final=True)\n\nphase.add_state('v', fix_initial=True, fix_final=False)\n\nphase.add_control('theta', continuity=True, rate_continuity=True,\n units='deg', lower=0.01, upper=179.9)\n\nphase.add_parameter('g', units='m/s**2', val=9.80665)\n\n#\n# Minimize time at the end of the phase\n#\nphase.add_objective('time', loc='final', scaler=10)\n\np.model.linear_solver = om.DirectSolver()\n\n#\n# Setup the Problem\n#\np.setup()\n\n#\n# Set the initial values\n#\np['traj.phase0.t_initial'] = 0.0\np['traj.phase0.t_duration'] = 2.0\n\np.set_val('traj.phase0.states:x', phase.interp('x', ys=[0, 10]))\np.set_val('traj.phase0.states:y', phase.interp('y', ys=[10, 5]))\np.set_val('traj.phase0.states:v', phase.interp('v', ys=[0, 9.9]))\np.set_val('traj.phase0.controls:theta', phase.interp('theta', ys=[5, 100.5]))\n\n#\n# Solve for the optimal trajectory\n#\ndm.run_problem(p)\n\n# Check the results\nprint(p.get_val('traj.phase0.timeseries.time')[-1])\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-3)\n```\n\n\n```python\n# Generate the explicitly simulated trajectory\nexp_out = traj.simulate()\n\nplot_results([('traj.phase0.timeseries.states:x', 'traj.phase0.timeseries.states:y',\n 'x (m)', 'y (m)'),\n ('traj.phase0.timeseries.time', 'traj.phase0.timeseries.controls:theta',\n 'time (s)', 'theta (deg)')],\n title='Brachistochrone Solution\\nHigh-Order Gauss-Lobatto Method',\n p_sol=p, p_sim=exp_out)\n\nplt.show()\n```\n\n(examples:brachistochrone:explicit_shooting)=\n## Solving the problem with single shooting in Dymos\n\nThe following script fully defines the brachistochrone problem with Dymos and solves it using a single explicit shooting method.\n\nThe code is nearly identical to that using the collocation approach.\nKey differences are shown when defining the transcription, specifying how to constraint the final state values of `x` and `y` states, and providing initial guesses for all states.\n\n\n```python\nimport openmdao.api as om\nimport dymos as dm\nfrom dymos.examples.plotting import plot_results\nfrom dymos.examples.brachistochrone import BrachistochroneODE\nimport matplotlib.pyplot as plt\n\n#\n# Initialize the Problem and the optimization driver\n#\np = om.Problem(model=om.Group())\np.driver = om.ScipyOptimizeDriver()\n\n# We'll try to use coloring, but OpenMDAO will tell us that it provides no benefit.\np.driver.declare_coloring()\n\n#\n# Create a trajectory and add a phase to it\n#\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\nphase = traj.add_phase('phase0',\n dm.Phase(ode_class=BrachistochroneODE,\n transcription=dm.ExplicitShooting(num_segments=10,\n num_steps_per_segment=10,\n method='rk4')))\n\n#\n# Set the variables\n#\nphase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n\n# Note, we cannot use fix_final=True with the shooting method\n# because the final value of the states are \n# not design variables in the transcribed optimization problem.\nphase.add_state('x', fix_initial=True)\n\nphase.add_state('y', fix_initial=True)\n\nphase.add_state('v', fix_initial=True)\n\nphase.add_control('theta', continuity=True, rate_continuity=True,\n units='deg', lower=0.01, upper=179.9)\n\nphase.add_parameter('g', units='m/s**2', val=9.80665)\n\n#\n# Minimize time at the end of the phase\n#\nphase.add_objective('time', loc='final', scaler=10)\n\n#\n# Add boundary constraints for x and y since we could not use `fix_final=True` \n#\nphase.add_boundary_constraint('x', loc='final', equals=10)\nphase.add_boundary_constraint('y', loc='final', equals=5)\n\np.model.linear_solver = om.DirectSolver()\n\n#\n# Setup the Problem\n#\np.setup()\n\n#\n# Set the initial values\n#\np['traj.phase0.t_initial'] = 0.0\np['traj.phase0.t_duration'] = 2.0\n\n# Only the initial values of the states are design variables,\n# so the phase interp method is not used on states.\np.set_val('traj.phase0.states:x', 0.0)\np.set_val('traj.phase0.states:y', 10.0)\np.set_val('traj.phase0.states:v', 0.0)\np.set_val('traj.phase0.controls:theta', phase.interp('theta', ys=[5, 100.5]))\n\n#\n# Solve for the optimal trajectory\n#\ndm.run_problem(p)\n\n# Check the results\nprint(p.get_val('traj.phase0.timeseries.time')[-1])\n```\n\n\n```python\nassert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-3)\n```\n\n\n```python\nplot_results([('traj.phase0.timeseries.states:x', 'traj.phase0.timeseries.states:y',\n 'x (m)', 'y (m)'),\n ('traj.phase0.timeseries.time', 'traj.phase0.timeseries.controls:theta',\n 'time (s)', 'theta (deg)')],\n title='Brachistochrone Solution\\nExplicit Shooting Method',\n p_sol=p)\n\nplt.show()\n```\n\nNote that the shooting methods provide timeseries values at the start and end of each segment.\nDue to plans to enable variable step integration in the future, Dymos cannot provide outputs for each individual step since the number of steps will not be known when setting up the problem.\n\nBecause control values and rates may not be continuous across segment bounds, depending on the settings used, there may be discontinuities in ODE outputs and therefore timeseries values are provided on each side of each segment boundary.\n", "meta": {"hexsha": "9d0ce3aeecf3d26624f80858d97e8da3591b6ce1", "size": 25628, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/examples/brachistochrone/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/brachistochrone/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/brachistochrone/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": 37.1420289855, "max_line_length": 243, "alphanum_fraction": 0.5621195567, "converted": true, "num_tokens": 5007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.14804720179063333, "lm_q1q2_score": 0.05373657521334857}} {"text": "```\n#hide\n#skip\n! [ -e /content ] && pip install -Uqq self-supervised\n```\n\n\n```\n#default_exp vision.supcon\n```\n\n# SupCon\n\n> **SupCon**: [Supervised Contrastive Learning](https://arxiv.org/pdf/2004.11362.pdf)\n\n\n```\n#export\n_all_ = ['UnsupMethod']\n```\n\n\n```\n#export\nfrom fastai.vision.all import *\nfrom self_supervised.augmentations import *\nfrom self_supervised.layers import *\n```\n\n## Algorithm\n\n#### SupCon\n\n\n\nSupCon introduces a generalized form for contrastive losses, and shows that self-supervised loss from SimCLR, N-Pair loss and triplet margin loss are special cases. In this repo, we leverage this general form and formalize a loss that can transition from self-supervised contrastive loss to supervised contrastive loss:\n\n$$\n\\begin{equation} \n\\begin{split}\n\\mathcal{L} & = \\hspace{30mm} \\mathcal{L}^{unsup} \\hspace{16mm}+ \\hspace{30mm} \\lambda\\mathcal{L}^{sup} \\\\\n \\\\\n & = - \\sum_{i \\in I} \\log \\frac{\\exp \\left(\\boldsymbol{z}_{i} \\cdot \\boldsymbol{z}_{j(i)} / \\tau\\right)}{\\sum_{a \\in A(i)} \\exp \\left(\\boldsymbol{z}_{i} \\cdot \\boldsymbol{z}_{a} / \\tau\\right)} + \\lambda \\sum_{i \\in I} \\frac{-1}{|P(i)|} \\sum_{p \\in P(i)} \\log \\frac{\\exp \\left(\\boldsymbol{z}_{i} \\cdot \\boldsymbol{z}_{p} / \\tau\\right)}{\\sum_{a \\in A(i)} \\exp \\left(\\boldsymbol{z}_{i} \\cdot \\boldsymbol{z}_{a} / \\tau\\right)}\n\\end{split}\n\\end{equation}\n$$\n\n\nWe use supervised signal as regularization which has an associated weight $\\lambda$, this allows to pretrain with a dataset mixed with labelled and unlabelled data. This regularization can help to learn more generic features which in turn can help with the downstream task. In `SupCon` callback you can choose to use all samples (`UnsupMethod.All`) for unsupervised loss or only use the ones doesn't have a label (`UnsupMethod.All`). Supervised loss will use the samples with labels.\n\nTherefore, positive samples come form two disjoint categories:\n \n (1) Other view of the anchor sample after augmentation (self-supervised case)\n (2) All views of the samples that have the same class id with anchor, including the other view of the same sample (supervised case)\n \n \n \n*Note that self-supervised and unsupervised are used interchangably in this context*\n\nSimCLR model consists of an `encoder` and a `projector (MLP)` layer. The definition of this module is fairly simple as below.\n\n\n```\n#export\nclass SupConModel(Module):\n \"Compute predictions of concatenated xi and xj\" \n def __init__(self,encoder,projector): self.encoder,self.projector = encoder,projector\n def forward(self,x): return self.projector(self.encoder(x))\n```\n\nInstead of directly using `SupConModel` by passing both an `encoder` and a `projector`, `create_simclr_model` function can be used by minimally passing a predefined `encoder` and the expected input channels.\n\n\n```\n#export\ndef create_supcon_model(encoder, hidden_size=256, projection_size=128, bn=False, nlayers=2):\n \"Create SupCon model\"\n n_in = in_channels(encoder)\n with torch.no_grad(): representation = encoder(torch.randn((2,n_in,128,128)))\n projector = create_mlp_module(representation.size(1), hidden_size, projection_size, bn=bn, nlayers=nlayers) \n apply_init(projector)\n return SupConModel(encoder, projector)\n```\n\nYou can use `self_supervised.layers` module to create an encoder. It supports all **timm** and **fastai** models available out of the box.\n\nWe define number of input channels with `n_in`, projector/mlp's hidden size with `hidden_size`, projector/mlp's final projection size with `projection_size` and projector/mlp's number of layers with `nlayers`.\n\n\n```\nencoder = create_encoder(\"tf_efficientnet_b0_ns\", n_in=3, pretrained=False, pool_type=PoolingType.CatAvgMax)\nmodel = create_supcon_model(encoder, hidden_size=2048, projection_size=128, nlayers=2)\nout = model(torch.randn((2,3,224,224))); out.shape\n```\n\n\n\n\n torch.Size([2, 128])\n\n\n\n## SupCon Callback\n\nThe following parameters can be passed;\n\n- **aug_pipelines** list of augmentation pipelines List[Pipeline] created using functions from `self_supervised.augmentations` module. Each `Pipeline` should be set to `split_idx=0`. You can simply use `get_supcon_aug_pipelines` utility to get aug_pipelines.\n- **temp** temperature scaling for cross entropy loss (defaults to paper's best value)\n\nSupCon algorithm uses 2 views of a given image, and `SupCon` callback expects a list of 2 augmentation pipelines in `aug_pipelines`.\n\nYou can simply use helper function `get_supcon_aug_pipelines()` which will allow augmentation related arguments such as size, rotate, jitter...and will return a list of 2 pipelines, which then can be passed to the callback. This function uses `get_multi_aug_pipelines` which then `get_batch_augs`. For more information you may refer to `self_supervised.augmentations` module.\n\nAlso, you may choose to pass your own list of aug_pipelines which needs to be List[Pipeline, Pipeline] where Pipeline(..., split_idx=0). Here, `split_idx=0` forces augmentations to be applied in training mode.\n\n\n```\n#export\n@delegates(get_multi_aug_pipelines)\ndef get_supcon_aug_pipelines(size, **kwargs): return get_multi_aug_pipelines(n=2, size=size, **kwargs)\n```\n\n\n```\naug_pipelines = get_supcon_aug_pipelines(size=28, rotate=False, jitter=False, bw=False, blur=False, stats=None, cuda=False)\naug_pipelines\n```\n\n\n\n\n [Pipeline: RandomResizedCrop -> RandomHorizontalFlip,\n Pipeline: RandomResizedCrop -> RandomHorizontalFlip]\n\n\n\n\n```\n#export\nmk_class('UnsupMethod', **{o:o.lower() for o in ['All', 'Only']},\n doc=\"Whether to use all (sup+unsup) or only unsup data in a batch for unsup loss\") \n```\n\n\n```\n#export\nclass SupCon(Callback):\n order,run_valid = 9,True\n def __init__(self, aug_pipelines, unsup_class_id, unsup_method=UnsupMethod.All, \n reg_lambda=1.,\n temp=0.07, \n print_augs=False):\n assert_aug_pipelines(aug_pipelines)\n self.aug1, self.aug2 = aug_pipelines\n if print_augs: print(self.aug1), print(self.aug2)\n store_attr('unsup_class_id,unsup_method,reg_lambda,temp')\n \n \n def before_fit(self): \n self.learn.loss_func = self.lf\n \n \n def before_batch(self):\n xi,xj = self.aug1(self.x), self.aug2(self.x)\n self.learn.xb = (torch.cat([xi, xj]),)\n \n \n def _remove_diag(self, x):\n bs = x.shape[0]\n return x[~torch.eye(bs).bool()].reshape(bs,bs-1) \n \n \n def unsup_lf(self, pred, yb):\n \"Self-Supervised contrasitve loss with all or only unlabelled batch samples\"\n targ = torch.cat([yb,yb])\n unsup_mask = (targ == self.unsup_class_id)\n if self.unsup_method == UnsupMethod.All:\n pass\n elif self.unsup_method == UnsupMethod.Only:\n pred = pred[unsup_mask]\n else:\n raise Exception(f\"{self.unsup_method} is not a valid UnsupMethod\")\n \n if len(pred) == 0: return 0\n \n pred = F.normalize(pred, dim=1)\n bs = pred.shape[0]\n targ = torch.arange(bs, device=pred.device).roll(bs//2)\n sim = self._remove_diag(pred @ pred.T) / self.temp\n targ = self._remove_diag(torch.eye(targ.shape[0], device=pred.device)[targ]).nonzero()[:,-1]\n return F.cross_entropy(sim, targ)\n \n \n def sup_lf(self, pred, yb):\n \"Supervised contrasitve loss with labelled batch samples\"\n targ = torch.cat([yb,yb])\n unsup_mask = (targ == self.unsup_class_id)\n pred = pred[~unsup_mask]\n targ = targ[~unsup_mask]\n \n if len(pred) == 0: return 0\n \n # exclude anchor from loss calc\n ohe_labels = (targ[...,None] == targ[None, ...]).float()\n pred = F.normalize(pred, dim=1)\n sim = self._remove_diag(pred @ pred.T) / self.temp\n targ = self._remove_diag(ohe_labels)\n\n return (F.cross_entropy(sim, targ, reduction='none')/targ.sum(1)).mean()\n \n \n def lf(self, pred, *yb):\n unsup_loss = self.unsup_lf(pred, *yb)\n sup_loss = self.sup_lf(pred, *yb)\n return unsup_loss + self.reg_lambda*sup_loss\n \n \n @torch.no_grad()\n def show(self, n=1):\n bs = self.learn.x.size(0)//2\n x1,x2 = self.learn.x[:bs], self.learn.x[bs:] \n idxs = np.random.choice(range(bs),n,False)\n x1 = self.aug1.decode(x1[idxs].to('cpu').clone()).clamp(0,1)\n x2 = self.aug2.decode(x2[idxs].to('cpu').clone()).clamp(0,1)\n images = []\n for i in range(n): images += [x1[i],x2[i]] \n return show_batch(x1[0], None, images, max_n=len(images), nrows=n)\n```\n\n### Tests\n\n\n```\n# No unsupervised, all samples are labelled, but use all for unsup loss\nsupcon = SupCon([Pipeline([],0),Pipeline([],0)], unsup_class_id=0, unsup_method=\"all\")\nyb = torch.tensor([1,1,2,2])\npred = torch.randn((yb.shape[0]*2,128))\n```\n\n\n```\nloss1 = supcon.unsup_lf(pred, yb)\nnll = -(supcon._remove_diag(F.normalize(pred) @ F.normalize(pred).T)/supcon.temp).log_softmax(1)\nloss2 = torch.mean(tensor([nll[i,idx] for i, idx in enumerate([3,4,5,6,0,1,2,3])]))\nassert torch.isclose(loss1,loss2)\n```\n\n\n```\nloss1 = supcon.sup_lf(pred, yb)\nnll = -(supcon._remove_diag(F.normalize(pred) @ F.normalize(pred).T)/supcon.temp).log_softmax(1)\nohe = supcon._remove_diag(tensor([[1,1,0,0,1,1,0,0],\n [1,1,0,0,1,1,0,0],\n [0,0,1,1,0,0,1,1],\n [0,0,1,1,0,0,1,1],\n [1,1,0,0,1,1,0,0],\n [1,1,0,0,1,1,0,0],\n [0,0,1,1,0,0,1,1],\n [0,0,1,1,0,0,1,1]]))\nloss2 = (tensor([(row[idxs.bool()].sum()/idxs.sum()) for row, idxs in zip(nll, ohe)])).mean()\nassert torch.isclose(loss1, loss2)\n```\n\n\n```\n# No unsupervised, all samples are labelled, use only unlabelled for unsup loss\nsupcon = SupCon([Pipeline([],0),Pipeline([],0)], unsup_class_id=0, unsup_method=\"only\")\nyb = torch.tensor([1,1,2,2])\npred = torch.randn((yb.shape[0]*2,128))\n```\n\n\n```\nloss1 = supcon.unsup_lf(pred, yb)\nassert loss1 == 0\n```\n\n\n```\nloss1 = supcon.sup_lf(pred, yb)\nnll = -(supcon._remove_diag(F.normalize(pred) @ F.normalize(pred).T)/supcon.temp).log_softmax(1)\nohe = supcon._remove_diag(tensor([[1,1,0,0,1,1,0,0],\n [1,1,0,0,1,1,0,0],\n [0,0,1,1,0,0,1,1],\n [0,0,1,1,0,0,1,1],\n [1,1,0,0,1,1,0,0],\n [1,1,0,0,1,1,0,0],\n [0,0,1,1,0,0,1,1],\n [0,0,1,1,0,0,1,1]]))\nloss2 = (tensor([(row[idxs.bool()].sum()/idxs.sum()) for row, idxs in zip(nll, ohe)])).mean()\nassert torch.isclose(loss1,loss2)\n```\n\n\n```\n# All samples are unlabelled, but use all for unsup loss\nyb = torch.tensor([0,0,0,0])\npred = torch.randn((yb.shape[0]*2,128))\n```\n\n\n```\nsupcon = SupCon([Pipeline([],0),Pipeline([],0)], unsup_class_id=0, unsup_method=\"all\")\nloss1 = supcon.unsup_lf(pred, yb)\nsupcon = SupCon([Pipeline([],0),Pipeline([],0)], unsup_class_id=0, unsup_method=\"only\")\nloss2 = supcon.unsup_lf(pred, yb)\nnll = -(supcon._remove_diag(F.normalize(pred) @ F.normalize(pred).T)/supcon.temp).log_softmax(1)\nloss3 = torch.mean(tensor([nll[i,idx] for i, idx in enumerate([3,4,5,6,0,1,2,3])]))\nassert torch.isclose(loss1, loss2) and torch.isclose(loss2, loss3)\n```\n\n\n```\nloss1 = supcon.sup_lf(pred, yb)\nassert loss1 == 0\n```\n\n\n```\n# Mixed samples, but use all for unsup loss\nyb = torch.tensor([1,1,2,0])\npred = torch.randn((yb.shape[0]*2,128))\nsupcon = SupCon([Pipeline([],0),Pipeline([],0)], unsup_class_id=0, unsup_method=\"all\")\n```\n\n\n```\nloss1 = supcon.unsup_lf(pred, yb)\nnll = -(supcon._remove_diag(F.normalize(pred) @ F.normalize(pred).T)/supcon.temp).log_softmax(1)\nloss2 = torch.mean(tensor([nll[i,idx] for i, idx in enumerate([3,4,5,6,0,1,2,3])]))\nassert torch.isclose(loss1, loss2)\n```\n\n\n```\nsupcon = SupCon([Pipeline([],0),Pipeline([],0)], unsup_class_id=0, unsup_method=\"only\")\nloss1 = supcon.unsup_lf(pred, yb)\nassert loss1 == 0 # log(1) -> 0, there is no negative sample\n```\n\n\n```\nloss1 = supcon.sup_lf(pred, yb)\ntarg = torch.cat([yb,yb])\nunsup_mask = (targ == supcon.unsup_class_id)\npred = pred[~unsup_mask]\nnll = -(supcon._remove_diag(F.normalize(pred) @ F.normalize(pred).T)/supcon.temp).log_softmax(1)\nohe = supcon._remove_diag(tensor([[1,1,0,1,1,0],\n [1,1,0,1,1,0],\n [0,0,1,0,0,1],\n [1,1,0,1,1,0],\n [1,1,0,1,1,0],\n [0,0,1,0,0,1]]))\n\nloss2 = (tensor([(row[idxs.bool()].sum()/idxs.sum()) for row, idxs in zip(nll, ohe)])).mean()\nassert torch.isclose(loss1, loss2)\n```\n\n## SupConMOCO Callback [Experimental]\n\nThe following parameters can be passed;\n\n- **aug_pipelines** list of augmentation pipelines List[Pipeline] created using functions from `self_supervised.augmentations` module. Each `Pipeline` should be set to `split_idx=0`. You can simply use `get_supcon_aug_pipelines` utility to get aug_pipelines.\n- **temp** temperature scaling for cross entropy loss (defaults to paper's best value)\n\nSupCon algorithm uses 2 views of a given image, and `SupCon` callback expects a list of 2 augmentation pipelines in `aug_pipelines`.\n\nYou can simply use helper function `get_supcon_aug_pipelines()` which will allow augmentation related arguments such as size, rotate, jitter...and will return a list of 2 pipelines, which then can be passed to the callback. This function uses `get_multi_aug_pipelines` which then `get_batch_augs`. For more information you may refer to `self_supervised.augmentations` module.\n\nAlso, you may choose to pass your own list of aug_pipelines which needs to be List[Pipeline, Pipeline] where Pipeline(..., split_idx=0). Here, `split_idx=0` forces augmentations to be applied in training mode.\n\n\n```\n#export\nclass SupConMOCO(Callback):\n order,run_valid = 9,True\n def __init__(self, aug_pipelines, unsup_class_id, unsup_method=UnsupMethod.All, \n K=4096,\n m=0.999,\n reg_lambda=1.,\n temp=0.07, \n print_augs=False):\n assert_aug_pipelines(aug_pipelines)\n self.aug1, self.aug2 = aug_pipelines\n if print_augs: print(self.aug1), print(self.aug2)\n store_attr('unsup_class_id,unsup_method,K,m,reg_lambda,temp')\n \n \n def before_fit(self): \n \"Create key encoder and init queue\"\n if (not hasattr(self, \"encoder_k\")) and (not hasattr(self, \"queue\")):\n # init key encoder\n self.encoder_k = deepcopy(self.learn.model).to(self.dls.device)\n for param_k in self.encoder_k.parameters(): param_k.requires_grad = False\n \n # init queue\n nf = self.learn.model.projector[-1].out_features\n self.emb_queue = torch.randn(self.K, nf).to(self.dls.device)\n self.emb_queue = nn.functional.normalize(self.emb_queue, dim=1)\n self.label_queue = torch.zeros(self.K).to(self.dls.device) + self.unsup_class_id\n self.queue_ptr = 0\n else: \n warnings.warn(\"Key encoder and queue are already defined, keeping them.\")\n \n self.learn.loss_func = self.lf\n \n \n def before_batch(self):\n \"Generate query and key for the current batch\"\n q_img,k_img = self.aug1(self.x), self.aug2(self.x.clone())\n self.learn.xb = (q_img,)\n with torch.no_grad(): \n self.encoder_k.eval()\n self.learn.yb = (F.normalize(self.encoder_k(k_img)), self.y) # query and labels\n \n \n @torch.no_grad()\n def _momentum_update_key_encoder(self):\n for param_q, param_k in zip(self.learn.model.parameters(), self.encoder_k.parameters()):\n param_k.data = param_k.data * self.m + param_q.data * (1. - self.m)\n \n \n @torch.no_grad()\n def _dequeue_and_enqueue(self):\n bs = self.x.size(0)\n key_embs, key_labels = self.yb\n assert self.K % bs == 0 # for simplicity\n self.emb_queue[self.queue_ptr:self.queue_ptr+bs, :] = key_embs\n self.label_queue[self.queue_ptr:self.queue_ptr+bs] = key_labels\n self.queue_ptr = (self.queue_ptr + bs) % self.K # move pointer\n\n \n def unsup_lf(self, pred, key_embs, key_labels):\n \"Self-Supervised contrasitve loss with all or only unlabelled batch samples\"\n query_embs = F.normalize(pred, dim=1) \n queue_embs, queue_labels = self.emb_queue, self.label_queue\n \n if self.unsup_method == UnsupMethod.All:\n key_embs = torch.cat([key_embs, queue_embs])\n \n elif self.unsup_method == UnsupMethod.Only:\n query_embs = query_embs[(key_labels == self.unsup_class_id)]\n key_embs = key_embs[(key_labels == self.unsup_class_id)]\n queue_embs = queue_embs[(queue_labels == self.unsup_class_id)]\n \n key_embs = torch.cat([key_embs, queue_embs])\n \n else:\n raise Exception(f\"{self.unsup_method} is not a valid UnsupMethod\")\n \n if len(query_embs) == 0: return 0\n \n labels = torch.arange(len(query_embs), device=pred.device)\n sim = query_embs @ key_embs.T / self.temp\n return F.cross_entropy(sim, labels)\n \n \n def sup_lf(self, pred, key_embs, key_labels):\n \"Supervised contrasitve loss with labelled batch samples\"\n query_embs = F.normalize(pred, dim=1)\n queue_embs, queue_labels = self.emb_queue, self.label_queue\n \n query_embs = query_embs[(key_labels != self.unsup_class_id)]\n key_embs = key_embs[(key_labels != self.unsup_class_id)]\n queue_embs = queue_embs[(queue_labels != self.unsup_class_id)]\n \n key_embs = torch.cat([key_embs, queue_embs])\n \n key_labels = key_labels[(key_labels != self.unsup_class_id)]\n queue_labels = queue_labels[(queue_labels != self.unsup_class_id)]\n \n labels = torch.cat([key_labels, queue_labels])\n \n if len(query_embs) == 0: return 0\n \n # exclude anchor from loss calc\n ohe_labels = (key_labels[...,None] == labels[None, ...]).float()\n sim = query_embs @ key_embs.T / self.temp\n return (F.cross_entropy(sim, ohe_labels, reduction='none')/ohe_labels.sum(1)).mean()\n \n \n def lf(self, pred, *yb):\n unsup_loss = self.unsup_lf(pred, *yb)\n sup_loss = self.sup_lf(pred, *yb)\n return unsup_loss + self.reg_lambda*sup_loss\n \n \n def after_step(self):\n \"Update momentum (key) encoder and queue\"\n self._momentum_update_key_encoder()\n self._dequeue_and_enqueue()\n \n \n @torch.no_grad()\n def show(self, n=1):\n bs = self.learn.x.size(0)//2\n x1,x2 = self.learn.x[:bs], self.learn.x[bs:] \n idxs = np.random.choice(range(bs),n,False)\n x1 = self.aug1.decode(x1[idxs].to('cpu').clone()).clamp(0,1)\n x2 = self.aug2.decode(x2[idxs].to('cpu').clone()).clamp(0,1)\n images = []\n for i in range(n): images += [x1[i],x2[i]] \n return show_batch(x1[0], None, images, max_n=len(images), nrows=n)\n```\n\n### Tests\n\n\n```\nfrom fastai.test_utils import *\n```\n\n\n```\nclass ContrastiveModel(Module):\n def __init__(self): \n self.encoder = nn.Parameter(tensor([1.]))\n self.projector = nn.Linear(1,5, bias=False)\n self.projector.weight.data.zero_()\n self.projector.weight.data += 1\n self.projector = nn.Sequential(self.projector)\n \n def forward(self, x): return self.projector(x*self.encoder)\n```\n\n\n```\n# No unsupervised, all samples are labelled, but use all for unsup loss\nsupcon = SupConMOCO([Pipeline([noop],0),Pipeline([noop],0)], unsup_class_id=0, unsup_method=\"all\", K=8, m=0.999, reg_lambda=1.0, temp=0.07)\nyb = torch.tensor([1,1,2,2])\npred = torch.randn((yb.shape[0]*2,128))\n```\n\n\n```\nlearner = synth_learner(cbs=supcon, data=synth_dbunch(a=0,b=0,bs=4), model=ContrastiveModel())\n```\n\n\n```\nlearner.sup_con_moco.aug1, learner.sup_con_moco.aug2\n```\n\n\n\n\n (Pipeline: , Pipeline: )\n\n\n\n\n```\nlearner.sup_con_moco.__dict__['__stored_args__']\n```\n\n\n\n\n {'unsup_class_id': 0,\n 'unsup_method': 'all',\n 'K': 8,\n 'm': 0.999,\n 'reg_lambda': 1.0,\n 'temp': 0.07}\n\n\n\n\n```\nlearner('before_fit')\n```\n\n\n```\nassert learner.sup_con_moco.emb_queue.shape == (8,5)\nassert torch.all(learner.sup_con_moco.label_queue == torch.zeros(8))\nassert not any(list(o.requires_grad for o in learner.sup_con_moco.encoder_k.parameters()))\nassert torch.all(learner.sup_con_moco.encoder_k.projector[0].weight == 1)\n```\n\n\n```\nb = tensor([1,1,-1,1]).reshape(-1,1),tensor([1,1,2,2])\nlearner._split(b)\nlearner('before_batch')\n```\n\n\n```\nkey_embs, labels = learner.sup_con_moco.yb\nassert torch.equal(F.normalize(learner.sup_con_moco.encoder_k(b[0])), key_embs)\nassert torch.equal(labels, b[1])\n```\n\n\n```\nlearner.model.encoder.data += 0.1 # pseudo param update 1.0 -> 1.1\nlearner.model.projector[0].weight.data += 0.1 # pseudo param update 1.0 -> 1.1\n```\n\n\n```\nlearner('after_step')\n```\n\n\n```\nassert torch.equal(learner.sup_con_moco.emb_queue[:4], key_embs)\n```\n\n\n```\nnewval = 1*supcon.m + 1.1*(1-supcon.m)\nassert torch.all(learner.sup_con_moco.encoder_k.encoder.data == newval) and torch.all(learner.sup_con_moco.encoder_k.projector[0].weight.data==newval)\n```\n\n\n```\nb = tensor([-1,-1,1,-1]).reshape(-1,1),tensor([1,1,2,2])\nlearner._split(b)\nlearner('before_batch')\n```\n\n\n```\nkey_embs, labels = learner.sup_con_moco.yb\nassert torch.equal(F.normalize(learner.sup_con_moco.encoder_k(b[0])), key_embs)\nassert torch.equal(labels, b[1])\n```\n\n\n```\nlearner('after_step')\n```\n\n\n```\nassert torch.equal(learner.sup_con_moco.emb_queue[-4:], key_embs)\nassert torch.equal(learner.sup_con_moco.label_queue, tensor([1,1,2,2,1,1,2,2]).float())\n```\n\n\n```\nnewval = newval*supcon.m + 1.1*(1-supcon.m)\nassert torch.all(learner.sup_con_moco.encoder_k.encoder.data == newval) and torch.all(learner.sup_con_moco.encoder_k.projector[0].weight.data==newval)\n```\n\n\n```\npred = F.normalize(learner.model(learner.x))\nloss1 = learner.sup_con_moco.unsup_lf(pred, *learner.yb)\nkey_embs, labels = learner.yb\nlogits = pred @ torch.cat([key_embs,learner.sup_con_moco.emb_queue]).T / learner.sup_con_moco.temp\nloss2 = F.cross_entropy(logits, tensor([0,1,2,3]))\nassert loss1 == loss2\n```\n\n\n```\nlearner.sup_con_moco.unsup_method = UnsupMethod.Only\nlearner.sup_con_moco.unsup_class_id = 1\nloss1 = learner.sup_con_moco.unsup_lf(pred, *learner.yb)\nlogits = pred[labels==1] @ torch.cat([key_embs[labels==1],learner.sup_con_moco.emb_queue[learner.sup_con_moco.label_queue==1]]).T / learner.sup_con_moco.temp\nloss2 = F.cross_entropy(logits, tensor([0,1]))\nassert loss1 == loss2\n```\n\n\n```\nlearner.sup_con_moco.unsup_class_id = 0\npred = F.normalize(learner.model(learner.x))\nloss1 = learner.sup_con_moco.sup_lf(pred, *learner.yb)\nlogits = pred @ torch.cat([key_embs,learner.sup_con_moco.emb_queue]).T / learner.sup_con_moco.temp\nohe_labels = tensor([[1., 1., 0, 0, 1., 1., 0, 0, 1., 1., 0, 0],\n [1., 1., 0, 0, 1., 1., 0, 0, 1., 1., 0, 0],\n [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,],\n [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]])\nloss2 = (F.cross_entropy(logits, ohe_labels, reduction='none') / ohe_labels.sum(1)).mean()\nassert loss1 == loss2\n```\n\n\n```\nlearner.sup_con_moco.unsup_class_id = 2\npred = F.normalize(learner.model(learner.x))\nloss1 = learner.sup_con_moco.sup_lf(pred, *learner.yb)\nlogits = pred[labels != 2] @ torch.cat([key_embs[labels != 2],learner.sup_con_moco.emb_queue[learner.sup_con_moco.label_queue != 2]]).T / learner.sup_con_moco.temp\nohe_labels = tensor([[1., 1., 1., 1., 1., 1.],\n [1., 1., 1., 1., 1., 1.]])\nloss2 = (F.cross_entropy(logits, ohe_labels, reduction='none') / ohe_labels.sum(1)).mean()\nassert loss1 == loss2\n```\n\n\n```\nkey_embs, labels = learner.yb\nlearner.sup_con_moco.unsup_class_id = 3\nlearner.xb = (torch.cat([learner.x, tensor([[0]])]),)\nkey_embs, labels = torch.cat([learner.y[0], learner.y[0][:1]]), torch.cat([learner.y[1], tensor([3])])\nlearner.yb = (key_embs, labels)\npred = F.normalize(learner.model(learner.x))\nloss1 = learner.sup_con_moco.sup_lf(pred, *learner.yb)\nlogits = pred[labels != 3] @ torch.cat([key_embs[labels != 3],learner.sup_con_moco.emb_queue[learner.sup_con_moco.label_queue != 3]]).T / learner.sup_con_moco.temp\nohe_labels = tensor([[1., 1., 0, 0, 1., 1., 0, 0, 1., 1., 0, 0],\n [1., 1., 0, 0, 1., 1., 0, 0, 1., 1., 0, 0],\n [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,],\n [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]])\nloss2 = (F.cross_entropy(logits, ohe_labels, reduction='none') / ohe_labels.sum(1)).mean()\nassert loss1 == loss2\n```\n\n\n```\nkey_embs, labels = learner.yb\nlearner.sup_con_moco.unsup_class_id = 3\n\nlearner.xb = (torch.cat([learner.x[:2],tensor([[0]]), learner.x[2:]]),)\nkey_embs, labels = torch.cat([learner.y[0][:2], learner.y[0][:1], learner.y[0][2:]]), torch.cat([learner.y[1][:2], tensor([3]), learner.y[1][2:]])\n\nlearner.yb = (key_embs, labels)\npred = F.normalize(learner.model(learner.x))\n\nloss1 = learner.sup_con_moco.sup_lf(pred, *learner.yb)\nlogits = pred[labels != 3] @ torch.cat([key_embs[labels != 3],learner.sup_con_moco.emb_queue[learner.sup_con_moco.label_queue != 3]]).T / learner.sup_con_moco.temp\nohe_labels = tensor([[1., 1., 0, 0, 1., 1., 0, 0, 1., 1., 0, 0],\n [1., 1., 0, 0, 1., 1., 0, 0, 1., 1., 0, 0],\n [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,],\n [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]])\nloss2 = (F.cross_entropy(logits, ohe_labels, reduction='none') / ohe_labels.sum(1)).mean()\nassert loss1 == loss2\n```\n\n### Example Usage\n\n\n```\npath = untar_data(URLs.IMAGEWANG_160)\nitems = get_image_files(path)\n```\n\n\n```\nitems = np.random.choice(items, size=1000)\n```\n\n\n```\ntds = Datasets(items, [[PILImage.create, ToTensor, RandomResizedCrop(112, min_scale=1.)],\n [parent_label, Categorize()]], splits=RandomSplitter()(items))\ndls = tds.dataloaders(bs=5, after_item=[ToTensor(), IntToFloatTensor()], device='cpu')\n```\n\n\n```\nunsup_class_id = dls.vocab.o2i['unsup']\n```\n\n\n```\nfastai_encoder = create_encoder('xresnet18', n_in=3, pretrained=False)\nmodel = create_supcon_model(fastai_encoder, hidden_size=2048, projection_size=128)\naug_pipelines = get_supcon_aug_pipelines(size=28, rotate=False, jitter=False, bw=False, blur=False, stats=None, cuda=False)\nlearn = Learner(dls, model, cbs=[SupCon(aug_pipelines, \n unsup_class_id,\n unsup_method=UnsupMethod.All, reg_lambda=1.0, temp=0.07,\n print_augs=True),ShortEpochCallback(0.001)])\n```\n\n Pipeline: RandomResizedCrop -> RandomHorizontalFlip\n Pipeline: RandomResizedCrop -> RandomHorizontalFlip\n\n\nAlso, with `show_one()` method you can inspect data augmentations as a sanity check. You can use existing augmentation functions from `augmentations` module.\n\n\n```\nb = dls.one_batch()\nlearn._split(b)\nlearn('before_batch')\naxes = learn.sup_con.show(n=5)\n```\n\n\n```\nlearn.fit(1)\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
        epochtrain_lossvalid_losstime
        000:02
        \n\n\n\n```\nlearn.recorder.losses\n```\n\n\n\n\n [TensorCategory(1.7556)]\n\n\n\n\n```\nfastai_encoder = create_encoder('xresnet18', n_in=3, pretrained=False)\nmodel = create_supcon_model(fastai_encoder, hidden_size=2048, projection_size=128)\naug_pipelines = get_supcon_aug_pipelines(size=28, rotate=False, jitter=False, bw=False, blur=False, stats=None, cuda=False)\nlearn = Learner(dls, model, cbs=[SupConMOCO(aug_pipelines, \n unsup_class_id,\n unsup_method=UnsupMethod.All, K=25, reg_lambda=1.0, temp=0.07,\n print_augs=True),ShortEpochCallback(0.001)])\n```\n\n Pipeline: RandomResizedCrop -> RandomHorizontalFlip\n Pipeline: RandomResizedCrop -> RandomHorizontalFlip\n\n\n\n```\nlearn.fit(1)\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
        epochtrain_lossvalid_losstime
        000:06
        \n\n\n## Export -\n\n\n```\n#hide\nfrom nbdev.export import notebook2script\nnotebook2script()\n```\n\n Converted 01 - augmentations.ipynb.\n Converted 02 - layers.ipynb.\n Converted 03 - distributed.ipynb.\n Converted 10 - simclr.ipynb.\n Converted 11 - moco.ipynb.\n Converted 12 - byol.ipynb.\n Converted 13 - swav.ipynb.\n Converted 14 - barlow_twins.ipynb.\n Converted 15 - dino.ipynb.\n Converted 16 - supcon.ipynb.\n Converted 20 - clip.ipynb.\n Converted 21 - clip-moco.ipynb.\n Converted 70 - vision.metrics.ipynb.\n Converted 90 - models.vision_transformer.ipynb.\n Converted index.ipynb.\n\n\n\n```\n\n```\n", "meta": {"hexsha": "ddb2f8acd597250c15095c49872fe08ffd716364", "size": 91336, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nbs/16 - supcon.ipynb", "max_stars_repo_name": "jimmiemunyi/self_supervised", "max_stars_repo_head_hexsha": "360df7f1fa06b0ab1e2abe2e1ea6e2230b073a12", "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": "nbs/16 - supcon.ipynb", "max_issues_repo_name": "jimmiemunyi/self_supervised", "max_issues_repo_head_hexsha": "360df7f1fa06b0ab1e2abe2e1ea6e2230b073a12", "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": "nbs/16 - supcon.ipynb", "max_forks_repo_name": "jimmiemunyi/self_supervised", "max_forks_repo_head_hexsha": "360df7f1fa06b0ab1e2abe2e1ea6e2230b073a12", "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": 67.2577319588, "max_line_length": 45316, "alphanum_fraction": 0.7491131646, "converted": true, "num_tokens": 8882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1097057753333734, "lm_q1q2_score": 0.053567508463341594}} {"text": "Sveučilište u Zagrebu
        \nFakultet elektrotehnike i računarstva\n\n# Strojno učenje\n\nhttp://www.fer.unizg.hr/predmet/su\n\nAk. god. 2015./2016.\n\n# Bilježnica 8: Stroj potpornih vektora (SVM)\n\n(c) 2015 Jan Šnajder\n\nVerzija: 0.3 (2015-12-11)\n\n\n```python\nimport scipy as sp\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport pandas as pd\n%pylab inline\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n### Sadržaj:\n\n* Uvod\n\n* Problem maksimalne margine\n\n* Optimizacija uz ograničenja\n\n* Metoda Lagrangeovih multiplikatora\n\n* Dualna formulacija problema maksimalne margine\n\n* Meka margina\n\n* Gubitak zglobnice\n\n* Jezgreni trik\n\n* Mercerove jezgre\n\n* Optimizacija hiperparametara\n\n\n# Uvod\n\n\n* Vrlo učinkovit **diskriminativan model**\n\n\n* Podsjetnik: Algoritam strojnog učenja definiran je \n 1. modelom\n * pogreškom\n * optimizacijskim postupkom\n \n \n* Model:\n \n$$\n h(\\mathbf{x}) = \\mathbf{w}^\\intercal\\boldsymbol{\\phi}(\\mathbf{x})\n$$\n\n\n* Dakle, to je poopćeni linearan model bez aktivacijske funkcije $f$\n\n\n* Gornja definicija modela je tzv. **primarna formulacija**\n\n\n* Postoji i **dualna formulacija**:\n * Umjesto da značajke novog primjera množimo težinama $\\mathbf{w}$, možemo za novi primjer izračunati koliko je sličan primjerima iz skupa za učenje i na temelju toga odrediti klasifikaciju\n * Model efektivno postaje **neparametarski**!\n \n \n* U dualnoj formulaciji možemo iskoristiti tzv. **jezgreni trik**, koji nam omogućava jeftino preslikavanje primjera u prostor više dimenzije (a time i nelinearnost modela)\n * SVM je jedna vrsta tzv. **jezgrenog stroja** (engl. *kernel machine*)\n\n\n* Model je jednostavan, no definicija pogreške i optimizacijskog postupka su nešto složeniji\n\n\n* Osnovna ideja: primjere dviju klasa razdvojiti tako da je prostor između njih što veći $\\Rightarrow$ tzv. **maksimalna margina**\n\n\n* Opravdanje: generalizacija će biti najbolja onda kada granicu između klasa povućemo točno po sredini margine\n\n\n* Do sada smo optimizacijski problem definirali tako da smo\n * krenuli od log-izglednosti pa izveli MLE (naivan Bayes)\n * krenuli od funkcije gubitka pa izveli funkciju pogreške (linearna regresija) i napravili analitičku minimizaciju\n * krenuli od funkcije pogreške pa izveli funkciju gubitka (logistička regresija, perceptron) i iskoristili je za gradijentni spust\n \n \n* Kod SVM-a, krenut ćemo odmah od onoga što u konačnici želimo dobiti: maksimalnu marginu $\\Rightarrow$ to je ono što SVM optimizira\n\n\n* Ići ćemo \"klasičnim pristupom\": formalizirati to kao problem **kvadratnog programiranja**\n\n\n* Naknadno ćemo iz toga izvesti funkciju gubitka (i funkciju pogreške), ali samo radi usporedbe s drugim algoritmima\n\n\n> **Sinopsis:**\n> \n> * Prvo ćemo se fokusirati na **linearan model** i **linearno odvojive probleme** (tvrda granica)\n * Matematika: Lagrangeovi multiplikatori\n> \n> * Zatim ćemo proširiti **linearan model** tako da može raditi s **linearno neodvojivim problemima** (meka granica)\n> \n> * Na kraju ćemo proširiti na **nelinearan model** (jezgreni trik)\n> * Matematika: Mercerove jezgre\n\n# Problem maksimalne margine\n\n* Model:\n$$\nh(\\mathbf{x}) = \\mathbf{w}^\\intercal x + w_0\n$$\n\n\n* Oznake primjera za učenje: $y\\in\\{-1,+1\\}$\n\n\n* Granica između klasa: hiperravnina $h(\\mathbf{x})=0$\n\n\n* Predikcija klase: $y=\\mathrm{sgn}(h(\\mathbf{x}))$\n\n\n* Pretpostavimo da su primjeri iz $\\mathcal{D}$ **linearno odvojivi**\n\n\n* Onda postoji $\\mathbf{w}$ i $w_0$ takvi da\n$$\n\\begin{align*}\nh(\\mathbf{x}^{(i)}) \\geq 0 & \\quad\\text{za svaki $y^{(i)}=+1$}\\\\\nh(\\mathbf{x}^{(i)}) < 0 & \\quad\\text{za svaki $y^{(i)}=-1$}\\\\\n\\end{align*}\n$$\n\n\n* Kraće, postoje $\\mathbf{w}$ i $w_0$ takvi da\n$$\n\\forall(\\mathbf{x}^{(i)},y^{(i)}) \\in \\mathcal{D}.\\ y^{(i)}h(\\mathbf{x}^{(i)})\\geq 0\n$$\n\n\n* Postoji beskonačno mnogo rješenja za $\\mathbf{w}$ i $w_0$ (prostor inačica je beskonačan)\n\n\n* No nas zanima rješenje **maksimalne margine** $\\Rightarrow$ induktivna pristranost preferencijom\n\n\n* **Margina = udaljenost hiperravnine do najbližeg primjera**\n\n\n* Ako maksimiziramo marginu, onda će hiperravnina prolaziti točno na pola puta između dva primjera\n\n\n#### Formulacija optimizacijskog problema\n\n\n* Predznačena udaljenost primjera od hiperravnine je\n\n$$\nd = \\frac{h(\\mathbf{x})}{\\|\\mathbf{w}\\|}\n$$\n\n\n* Nas zanimaju samo hiperravnine koje ispravno klasificiraju primjere. U tom slučaju **apsolutna** udaljenost primjera do hiperravnine je:\n\n$$\n\\frac{y^{(i)}h(\\mathbf{x})}{\\|\\mathbf{w}\\|} = \n\\frac{y^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0)}{\\|\\mathbf{w}\\|}\n$$\n\n\n* Po definiciji, margina je udaljenost hiperravnine do najbližeg primjera:\n\n$$\n\\frac{1}{\\|\\mathbf{w}\\|}\\mathrm{min}_i\\big\\{y^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x} + w_0)\\big\\}\n$$\n\n\n* Tu udaljenost želimo maksimizirati:\n\n$$\n\\mathrm{argmax}_{\\mathbf{w},w_0}\\Big\\{\\frac{1}{\\|\\mathbf{w}\\|}\\mathrm{min}_i\\big\\{y^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x} + w_0)\\big\\}\\Big\\}\n$$\n\n\n* Ako je $\\mathcal{D}$ linearno odvojiv, onda postoji samo jedna takva margina\n\n#### Pojednostavljenje optimizacijskog problema\n\n\n* Gornji problem teško je riješiti izravno (min unutar max)\n\n\n* Vektor $(\\mathbf{w},w_0)$ možemo pomnožiti s proizvoljnom konstantom, a da to ne utječe na udaljenosti između primjera i hiperravnine:\n\n$$\nd=\\frac{h(\\mathbf{x})}{\\|\\mathbf{w}\\|}=\n\\frac{\\color{red}{\\alpha}\\mathbf{w}^\\intercal\\mathbf{x}+\\color{red}{\\alpha}w_0}{\\|\\color{red}{\\alpha}\\mathbf{w}\\|}=\n\\frac{\\color{red}{\\alpha}(\\mathbf{w}^\\intercal\\mathbf{x}+w_0)}{\\color{red}{\\alpha}\\|\\mathbf{w}\\|}=\n\\frac{\\mathbf{w}^\\intercal\\mathbf{x}+w_0}{\\|\\mathbf{w}\\|}\n$$\n\n\n* Kako bismo pojednostavili problem, možemo definirati da za primjer $\\mathbf{x}^{(i)}$ koji je najbliži margini vrijedi\n\n$$\ny^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x}+w_0)=1\n$$\n\n\n* Svi ostali primjeri jednako su blizu margine ili su od nje još udaljeniji:\n\n$$\ny^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0) \\geq 1, \\qquad i=1,\\dots,N\n$$\n\n\n* Za primjere za koje $y^{(i)}h(\\mathbf{x})=1$ kažemo da su ograničenja **aktivna**, dok su za ostale primjere ograničenja neaktivna \n * (Primjeri za koje su ograničenja aktivna zovemo potpornim vektorima, ali o tome više kasnije)\n\n\n* Uvijek će postojati barem **dva** aktivna ograničenja\n\n\n* [Skica: maksimalna margina]\n\n\n* Dakle, umjesto\n$$\n\\mathrm{argmax}_{\\mathbf{w},w_0}\\Big\\{\\frac{1}{\\|\\mathbf{w}\\|}\\underbrace{\\mathrm{min}_i\\big\\{y^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x} + w_0)\\big\\}}_{=1}\\Big\\}\n$$\nmi sada maksimiziramo\n$$\n\\mathrm{argmax}_{\\mathbf{w},w_0}\\frac{1}{\\|\\mathbf{w}\\|}\n$$\nuz ograničenja\n$$\ny^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0) \\geq 1, \\qquad i=1,\\dots,N\n$$\n\n\n* Maksimizator od $\\frac{1}{\\|\\mathbf{w}\\|}$ ekvivalentan je minimizatoru od $\\|\\mathbf{w}\\|=\\sqrt{\\mathbf{w}^\\intercal\\mathbf{w}}$, a taj je ekvivalentan minimizatoru od $\\|\\mathbf{w}\\|^2$. Još ćemo pomnožiti s $\\frac{1}{2}$ radi kasnije matematičke jednostavnosti\n\n\n* Konačna formulacija optimizacijskog problema maksimalne margine:\n\n> $\\mathrm{argmin}_{\\mathbf{w},w_0}\\frac{1}{2}\\|\\mathbf{w}\\|^2$\n\n> tako da $\\quad y^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0) \\geq 1, \\quad i=1,\\dots,N$\n\n\n* Naš optimizacijski problem sveo se na ciljnu funkciju koju želimo optimirati i ograničenja koja pritom moramo poštovati: tipičan problem **konveksne optimizacije uz ograničenja**, točnije **kvadratnog programiranja**\n * \"Programiranje\" = matematičko programiranje = (matematička) optimizacija\n\n# Optimizacija uz ograničenja\n\n\n* Optimizacijski problem $\\Rightarrow$ Optimizacija uz ograničenja $\\Rightarrow$ Konveksni optimizacijski problem $\\Rightarrow$ Kvadratno programiranje\n\n\n* Optimizacijski problem uz ograničenja (standardni oblik):\n\n$$\n\\begin{align*}\n\\text{minimizirati} &\\quad f(\\mathbf{x})\\\\\n\\text{uz ograničenja} &\\quad g_i(\\mathbf{x})\\leq0,\\quad i=1,\\dots,m\\\\\n&\\quad h_i(\\mathbf{x}) = 0,\\quad i=1,\\dots,p\n\\end{align*}\n$$\n\n\n* $f : \\mathbb{R}^n\\to\\mathbb{R}$ je **ciljna funkcija** (engl. *objective function*\n* $h_i : \\mathbb{R}^n\\to\\mathbb{R}$ su **ograničenja\njednakosti** (engl. *equality constraints*)\n* $g_i:\\mathbb{R}^n\\to\\mathbb{R}$ su **ograničenja nejednakosti** (engl. *inequality constraints*)\n\n\n* **NB:** Sva ograničenja (ne)jednakosti mogu se se svesti na standardni oblik\n\n\n* Tražimo minimum koji zadovoljava sva ograničenja\n* Točke koje zadovoljavaju rješenja zovemo **ostvarivim\ntočkama** (engl. *feasible points*)\n\n\n* Konveksni optimizacijski problem:\n\n$$\n\\begin{align*}\n\\text{minimizirati} &\\quad f(\\mathbf{x})\\ \\color{red}{\\text{$\\Rightarrow$ konveksna}}\\\\\n\\text{uz ograničenja} &\\quad g_i(\\mathbf{x})\\leq0,\\quad i=1,\\dots,m\\\\\n&\\quad \\mathbf{a}_i^\\intercal\\mathbf{x} - b_i = 0,\\quad i=1,\\dots,p\n\\end{align*}\n$$\n\n* Kvadratni program:\n\n$$\n\\begin{align*}\n\\text{minimizirati} &\\quad \\frac{1}{2}\\mathbf{x}^\\intercal P\\mathbf{x} + \\mathbf{q}^\\intercal\\mathbf{x} + r\\ \\color{red} {\\text{$\\Rightarrow$ kvadratna funkcija}}\\\\\n\\text{uz ograničenja} &\\quad G\\mathbf{x}\\leq\\mathbf{h}\\\\\n&\\quad A\\mathbf{x}=\\mathbf{b}\\\\\n\\end{align*}\n$$\n\n# Metoda Lagrangeovih multiplikatora\n\n* Kvadratni program može se riješiti metodom **Langrangeovih multiplikatora**\n \n\n* Lagrangeovi multiplikatori mogu se koristiti općenito za optimizaciju s ograničenjima (problem ne mora biti konveksan)\n\n\n* Ideja: preformulirati ograničen problem tako da se u ciljnu funkciju ugrade ograničenja\n\n\n* Alternative: **metode unutarnje točke** (engl. *interior-point methods*, *barrier methods*) ili **metode s kaznom** (engl. *penalty methods*)\n\n\n\n#### Lagrangeova funkcija\n\n* **Lagrangeova funkcija** izravno ugrađuje ograničenja u ciljnu funkciju\n\n\n* [Skica ideje]\n\n\n* Početni problem:\n\n\\begin{align*}\n\\text{minimizirati} &\\quad f(\\mathbf{x})\\\\\n\\text{uz ograničenja} &\\quad g_i(\\mathbf{x})\\leq0,\\quad i=1,\\dots,m\\\\\n &\\quad h_i(\\mathbf{x}) = 0,\\quad i=1,\\dots,p\n\\end{align*}\n\n\n* Lagrangeova funkcija:\n\n$$\n\\begin{equation}\nL(\\mathbf{x},\\color{red}{\\boldsymbol\\alpha},\\color{red}{\\boldsymbol\\beta}) = f(\\mathbf{x}) + \\sum_{i=1}^m\\color{red}{\\alpha_i} g(\\mathbf{x}) + \\sum_{i=1}^p\\color{red}{\\beta_i}\nh(\\mathbf{x})\n\\end{equation}\n$$\n\n* Dobili smo neograničeni problem optimizacije: rješenje izvornoga ograničenog problema jest točka koja mimimizira $\\mathbf{x}$ i maksimizira $\\boldsymbol\\alpha$ (sedlo)\n\n\n* Vrijednosti $\\alpha_i$ i $\\beta_i$ su **Lagrangeovi multiplikatori** (množitelji) za ograničenja nejednakosti odnosno jednakosti\n\n\n* Za vrijednosti $\\alpha_i$ vrijede takozvani **Karush-Kuhn-Tuckerovi (KKT)** uvjeti:\n\n$$\n\\begin{align}\n\\alpha_i &\\geq 0,\\quad i=1,\\dots,m\\\\\n\\alpha_i g_i(\\mathbf{x}) &= 0,\\quad i=1,\\dots,m\n\\end{align}\n$$\n\n\n#### Lagrangeova dualnost\n\n\n* Načelo dualnosti u teoriji optimizacije:\n * **Primarni problem** (engl. *primal problem*): minimizacija funkcije $f(\\mathbf{x})$\n * **Dualni problem**: nalaženje donje granice primarnog problema (\"minimum ne može biti manji od $\\mathbf{x}$\")\n\n\n* [Skica: primal-dual sedlo]\n\n\n* Općenito, rješenja primarnog i dualnog problema se ne preklapaju već postoji **dualni procjep**\n\n\n* Uz određene uvjete, kod konveksne optimizacije dualni procjep jednak je nuli $\\Rightarrow$ **jaka dualnost**\n\n\n* To znači da je rješenje dualnog problema ujedno i rješenje primarnog problema\n\n\n* Dakle, ako nam je tako pogodnije, možemo rješavati dualni problem umjesto primarnog\n\n\n* U nastavku promatramo Lagrangeovu dualnost\n\n\n* Lagrangeova funkcija (BSO: samo s ograničenjima jednakosti):\n\n$$\nL(\\mathbf{x},\\boldsymbol\\alpha) = f(\\mathbf{x}) + \\sum_i\\alpha_i h_i(\\mathbf{x})\n$$\n\n\n* To je fukcija od $\\mathbf{x}$ (**primarne varijable**) i $\\boldsymbol\\alpha$ (**dualne varijable**)\n\n\n* Optimum:\n$$\nL(\\mathbf{x}^*,\\boldsymbol\\alpha^*) = \\min_{\\mathbf{x},\\boldsymbol\\alpha} L(\\mathbf{x},\\boldsymbol\\alpha)\n$$\n\n\n* Vrijednost za $\\mathbf{x}^*$ nalazimo rješavanjem sustava:\n\n$$\n\\begin{equation}\n\\nabla f(\\mathbf{x}) + \\nabla \\sum_i\\alpha_i h_i(\\mathbf{x}) = 0\n\\end{equation}\n$$\n\n\n* To rješenje ne mora dovesti do uklanjanja dualnih varijabli! Općenito, dobit ćemo rješenje koje minimizira $\\mathbf{x}$ za neki zadani $\\boldsymbol\\alpha$:\n$$\n\\tilde{L}(\\boldsymbol\\alpha)= \\min_{\\mathbf{x}}L(\\mathbf{x},\\boldsymbol\\alpha) = \\min_{\\mathbf{x}}\\Big(f(\\mathbf{x}) + \\sum_i\n\\alpha_i h(\\mathbf{x})\\Big)\n$$\n$\\Rightarrow$ **Dualna Lagrangeova funkcija**\n\n\n* Sigurno vrijedi:\n$$\n\\tilde{L}(\\boldsymbol\\alpha) \\leq L(\\mathbf{x}^*,\\boldsymbol\\alpha)\n$$\n$\\Rightarrow$ Dualna Lagrangeova funkcija je **donja ograda** primarnog problema\n\n\n* U točki $\\boldsymbol\\alpha^*$ vrijedi $\\tilde{L}(\\boldsymbol\\alpha^*)=L(\\mathbf{x}^*,\\boldsymbol\\alpha^*)$\n\n\n* Kako bismo pronašli $\\boldsymbol\\alpha^*$, moramo maksimizirati\ndonju ogradu, tj. riješiti sljedeći konveksni problem:\n\n$$\n\\begin{align*}\n\\text{maksimizirati} &\\quad \\tilde{L}(\\boldsymbol\\alpha)\\\\\n\\text{uz ograničenja} &\\quad \\alpha_i\\geq 0,\\quad i=1,\\dots,p\n\\end{align*}\n$$\n\n\n* **NB:** minimizacija ciljne funkcije $\\Leftrightarrow$ maksimizacija dualne funkcije\n\n# Dualna formulacija problema maksimalne margine\n\n\n* Optimizacijski problem maksimalne margine:\n\n> $\\mathrm{argmin}_{\\mathbf{w},w_0}\\frac{1}{2}\\|\\mathbf{w}\\|^2$\n\n> tako da $\\quad y^{(i)}(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0) \\geq 1, \\quad i=1,\\dots,N$\n\n\n* Odgovarajuća Lagrangeova funkcija:\n\n$$\nL(\\mathbf{w},w_0,\\color{red}{\\boldsymbol\\alpha})=\\frac{1}{2}\\|\\mathbf{w}\\|^2 -\n\\sum_{i=1}^N\\color{red}{\\alpha_i}\\Big\\{y^{(i)}\\big(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0\\big)-1\\Big\\}\n$$\n\n\n* $\\color{red}{\\boldsymbol\\alpha=(\\alpha_1,\\dots,\\alpha_N)}$ je vektor Lagrangeovih multiplikatora, po jedan za svako ograničenje\n\n\n* Prelazimo na **dualnu formulaciju** problema jer je ta formulacija jednostavnija (optimirat ćemo samo po $\\boldsymbol\\alpha$, a postoje i neke druge prednosti)\n\n\n* Minimizator $(\\mathbf{w}^*, w_0^*)$: deriviranje po $\\mathbf{w}$ odnosno $w_0$ i izjednačavanje s nulom:\n$$\n\\begin{align}\n\\mathbf{w} &= \\sum_{i=1}^N \\alpha_i y^{(i)}\\mathbf{x}^{(i)}\\\\\n0 &= \\sum_{i=1}^N\\alpha_i y^{(i)}\n\\end{align}\n$$\n\n\n* Dualna Lagrangeova funkcija:\n\n$$\n\\begin{align*}\n\\tilde{L}(\\boldsymbol\\alpha) &=\n\\frac{1}{2}\\|\\mathbf{w}\\|^2 -\\sum_{i=1}^N\\alpha_i\\Big\\{y^{(i)}\\big(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0\\big)-1\\Big\\}\\\\\n&= \n\\frac{1}{2}\\|\\mathbf{w}\\|^2\n-\\sum_{i=1}^N\\alpha_i y^{(i)}\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}\n\\color{gray}{\\underbrace{-w_0 \\sum_{i=1}^N\\alpha_iy^{(i)}}_{=0}} + \n\\sum_{i=1}^N\\alpha_i\\\\\n&= \\nonumber\n\\frac{1}{2}\\sum_{i=1}^N\\alpha_i y^{(i)}(\\mathbf{x}^{(i)})^\\intercal\\sum_{j=1}^N\\alpha_j y^{(j)}\\mathbf{x}^{(j)}\n-\n\\sum_{i=1}^N\\alpha_i y^{(i)}(\\mathbf{x}^{(i)})^\\intercal\\sum_{j=1}^N\\alpha_j y^{(j)}\\mathbf{x}^{(j)}\n+ \\sum_{i=1}^N\\alpha_i\\\\\n&= \n\\sum_{i=1}^N\\alpha_i - \n\\frac{1}{2}\\sum_{i=1}^N\n\\sum_{j=1}^N\n\\alpha_i\n\\alpha_j\ny^{(i)}\ny^{(j)}\n(\\mathbf{x}^{(i)})^\\intercal\n\\mathbf{x}^{(j)}\n\\end{align*}\n$$\n\n* Dobili smo **dualni optimizacijski problem**:\n\n> **Maksimizirati** izraz\n> \\begin{align}\n\\sum_{i=1}^N\\alpha_i - \n\\frac{1}{2}\\sum_{i=1}^N\n\\sum_{j=1}^N\n\\alpha_i\n\\alpha_j\ny^{(i)}\ny^{(j)}\n(\\mathbf{x}^{(i)})^\\intercal\n\\mathbf{x}^{(j)}\n\\end{align}\n> tako da:\n> \\begin{align*}\n\\alpha_i &\\geq 0,\\quad i=1,\\dots,N \\\\ \n\\sum_{i=1}^N\\alpha_i y^{(i)} &= 0\n\\end{align*}\n\n* Također vrijedi KKT-uvjet:\n$$\n\\alpha_i\\big(y^{(i)} h(\\mathbf{x}^{(i)})-1\\big) = 0\n$$\n\n\n* Ovo je i dalje problem kvadratnog programiranja, međutim broj varijabli se promijenio\n * Primarni problem: $n+1$ varijabli\n * Dualni problem: $N$ varijabli\n \n \n* Dakle, prijelaz u dualni problem se računalno isplati ako $N\\ll n$\n \n \n* Općenito, složenost kvadratnog programiranja od $n$ varijabli je $\\mathcal{O}(n^3)$\n * Posebni algoritmi su efikasniji: **slijedna minimalna optimizacija (SMO)** ima $\\mathcal{O}(n^2)$\n\n#### Model\n\n* Već smo izračunali:\n$$\n\\begin{align}\n\\mathbf{w} &= \\sum_{i=1}^N \\alpha_i y^{(i)}\\mathbf{x}^{(i)}\n\\end{align}\n$$\n\n\n* Uvrštavanjem:\n$$\n\\begin{equation}\nh(\\mathbf{x})=\n\\underbrace{\\mathbf{w}^\\intercal\\mathbf{x}+w_0}_{\\text{Primarno}} = \n\\underbrace{\\sum_{i=1}^N \\alpha_i y^{(i)}\\mathbf{x}^\\intercal\\mathbf{x}^{(i)} + w_0}_{\\text{Dualno}}\n\\end{equation}\n$$\n\n\n* Kako bismo klasificirali primjer $\\mathbf{x}$, računamo skalarni produkt između $\\mathbf{x}$ i svih primjera $\\mathbf{x}^{(i)}$ iz skupa $\\mathcal{D}$, pomnožen s težinom $\\alpha_i$ i predznakom $\\mathcal{y}^(i)$\n\n\n* Računanje skalarnog produkta $\\mathbf{x}^\\intercal\\mathbf{x}^{(i)}$ je zapravo računanje sličnosti između vektora $\\mathbf{x}$ i $\\mathbf{x}^{(i)}$, budući da:\n$$\n\\mathbf{x}^\\intercal\\mathbf{y} = \\sum_{i=1}^n x_i y_i\n$$\n(produkt će biti to veći što se vektori podudaraju u više komponenenata)\n\n\n* Dakle, umjesto da pohranjujemo težine $\\mathbf{w}$, trebamo pohraniti primjere i njihove oznake\n * Umjesto $h(\\mathbf{x}|\\mathbf{w})$ imamo $h(\\mathbf{x}|\\boldsymbol\\alpha,\\mathcal{D})$\n \n \n* Složenost modela sada ovisi o broju primjera $\\Rightarrow$ **neparametarski model**\n\n\n* Zaključak: ako se trenira tako da se rješava primarni problem, SVM je parametarski model, a ako se rješava dualni problem, onda je neparametarski \n\n\n\n#### Potporni vektori\n\n* Iz KKT-uvjeta\n$$\n\\alpha_i\\big(y^{(i)} h(\\mathbf{x}^{(i)})-1\\big) = 0\n$$\nslijedi da za svaki primjer $\\mathbf{x}^{(i)}$ iz $\\mathcal{D}$ vrijedi \n$$\n\\alpha_i=0\n$$\nili \n$$\ny^{(i)}h(\\mathbf{x}^{(i)})=1\n$$\n\n\n* To znači da je se u izrazu za model pojavljuju samo vektori koji leže točno na ravnini maksimalne margine $\\Rightarrow$ **potporni vektori** (engl. *support vectors*)\n\n\n* Svi ostali vektori za koje $\\alpha_i=0$ uopće ne utječu na izlaz modela i možemo ih zanemariti kada radimo predikciju\n\n\n* Alternativni pogled: hiperravnina (u primarnom problemu) definirana je linearnom kombinacijom potpornih vektora (u dualnom problemu)\n\n\n```python\nseven_X = sp.array([[2,1], [2,3], [1,2], [3,2], [5,2], [5,4], [6,3]])\nseven_y = sp.array([1, 1, 1, 1, -1, -1, -1])\n```\n\n\n```python\nplot_problem(seven_X, seven_y)\n```\n\n\n```python\nfrom sklearn.svm import SVC\n\nsvc = SVC(kernel='linear')\nsvc.fit(seven_X, seven_y)\n```\n\n\n\n\n SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,\n kernel='linear', max_iter=-1, probability=False, random_state=None,\n shrinking=True, tol=0.001, verbose=False)\n\n\n\n\n```python\nplot_problem(seven_X, seven_y, svc.predict)\n```\n\n\n```python\nsvc.predict(sp.array([1, 1]))\n```\n\n\n\n\n array([1])\n\n\n\n\n```python\nsvc.predict(sp.array([6, 1]))\n```\n\n\n\n\n array([-1])\n\n\n\n\n```python\nsvc.predict(sp.array([3.5, 2]))\n```\n\n\n\n\n array([1])\n\n\n\n\n```python\nsvc.decision_function(seven_X)\n```\n\n\n\n\n array([[ 1.99980469],\n [ 1.99921875],\n [ 2.99921875],\n [ 0.99980469],\n [-0.99960937],\n [-1.00019531],\n [-1.99960938]])\n\n\n\n\n```python\nsvc.support_\n```\n\n\n\n\n array([4, 5, 3], dtype=int32)\n\n\n\n\n```python\nsvc.dual_coef_\n```\n\n\n\n\n array([[ 4.99707031e-01, 1.46484375e-04, -4.99853516e-01]])\n\n\n\n**NB:** Koeficijenti iz `dual_coef_` ne odgovaraju vrijednostima $\\alpha_i$ već vrijednostima $-\\alpha_i y^{(i)}$\n\n\n```python\nsvc.support_vectors_\n```\n\n\n\n\n array([[ 5., 2.],\n [ 5., 4.],\n [ 3., 2.]])\n\n\n\n#### Rekonstrukcija primarnog problema\n\n* Nakon što je model naučen, možemo rekonstruirati primarne varijable, odnosno težine $\\mathbf{w}$ i $w_0$\n\n\n* Težine $\\mathbf{w}$:\n$$\n\\begin{align}\n\\mathbf{w} &= \\sum_{i=1}^N \\alpha_i y^{(i)}\\mathbf{x}^{(i)}\n\\end{align}\n$$\n\n\n* Pomak $w_0$: za potporne vektore $\\mathbf{x}^{(i)}\\in S$ vrijedi\n\n$$\n\\begin{align*}\ny^{(i)} h(\\mathbf{x}) &= 1\\\\ \ny^{(i)} \\Big(\\sum_{j\\in S} \\alpha_j y^{(j)}(\\mathbf{x}^{(i)})^\\intercal\\mathbf{x}^{(j)} + w_0\\Big) &= y^{(i)} y^{(i)}\\\\\nw_0 &= y^{(i)} - \\sum_{j\\in S} \\alpha_j y^{(j)}(\\mathbf{x}^{(i)})^\\intercal\\mathbf{x}^{(j)}\\\\\n\\end{align*}\n$$\n\n\n* $w_0$ možemo izračunati na temelju jednog primjera $\\mathbf{x}^{(i)}$. Međutim, radi numeričke stabilnosti, bolje je uprosječiti izračun nad svim potpornim vektorima:\n\n\n$$\nw_0 = \\frac{1}{|S|}\\sum_{i\\in S} \\Big( y^{(i)} - \\sum_{j\\in S} \\alpha_j y^{(j)}(\\mathbf{x}^{(i)})^\\intercal\\mathbf{x}^{(j)}\\Big)\n$$\n\n\n\n```python\ndef w(X, y, dc, sv):\n s = 0\n for alpha, i in zip(dc, sv):\n s += -alpha * X[i]\n return s\n \ndef w0(X, y, dc, sv):\n s = 0\n for i in sv:\n r = 0\n for alpha, j in zip(dc, sv) :\n r += -alpha * sp.dot(X[i], X[j])\n s += y[i] - r\n return s / float(len(sv))\n```\n\n\n```python\nw(seven_X, seven_y, svc.dual_coef_[0], svc.support_)\n```\n\n\n\n\n array([ -9.99707031e-01, -2.92968750e-04])\n\n\n\n\n```python\nsvc.coef_\n```\n\n\n\n\n array([[ -9.99707031e-01, -2.92968750e-04]])\n\n\n\n\n```python\nw0(seven_X, seven_y, svc.dual_coef_[0], svc.support_)\n```\n\n\n\n\n 3.9995117187499982\n\n\n\n\n```python\nsvc.intercept_\n```\n\n\n\n\n array([ 3.99951172])\n\n\n\n\n```python\ndef h_primal(x, w, w0):\n return sp.dot(w, x) + w0\n\ndef h_dual(x, X, y, dc, sv):\n xs = [ -alpha * sp.dot(x, X[i]) for alpha, i in zip(dc, sv) ]\n return sum(xs) + w0(X, y, dc, sv)\n```\n\n\n```python\nsvc.decision_function(seven_X)\n```\n\n\n\n\n array([[ 1.99980469],\n [ 1.99921875],\n [ 2.99921875],\n [ 0.99980469],\n [-0.99960937],\n [-1.00019531],\n [-1.99960938]])\n\n\n\n\n```python\nmap(lambda x: h_primal(x ,svc.coef_, svc.intercept_), seven_X)\n```\n\n\n\n\n [array([ 1.99980469]),\n array([ 1.99921875]),\n array([ 2.99921875]),\n array([ 0.99980469]),\n array([-0.99960938]),\n array([-1.00019531]),\n array([-1.99960938])]\n\n\n\n\n```python\nmap(lambda x: h_dual(x, seven_X, seven_y, svc.dual_coef_[0], svc.support_), seven_X)\n```\n\n\n\n\n [1.9998046874999988,\n 1.9992187499999989,\n 2.999218749999998,\n 0.99980468749999929,\n -0.99960937500000036,\n -1.0001953124999989,\n -1.9996093750000021]\n\n\n\n#### Je li ovo jedini način za treniranje SVM-a?\n\n* Nije. Mogli smo ostati na primarnom problemu, i riješiti ga npr. stohastičkim gradijentnim spustom uz penalizaciju (algoritam *Pegasos*)\n\n\n* Postoji niz SVM solvera \n * https://cseweb.ucsd.edu/~akmenon/ResearchExam.pdf\n * https://mitpress.mit.edu/sites/default/files/titles/content/9780262026253_sch_0001.pdf\n \n\n* Međutim, prednost dualne formulacije je da omogućava **jezgreni trik**\n\n# Meka margina\n\n$$\n\\begin{align}\ny^{(i)}\\big(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0\\big) \\geq 1 - \\xi_i, \\quad i=1,\\dots,N\n\\end{align}\n$$\n\n$$\n\\xi_i \\geq 0, i=1,\\dots,N\n$$\n\n* Ciljna funkcija:\n\n$$\n\\begin{equation}\n\\frac{1}{2}\\|\\mathbf{w}\\|^2+ C\\sum_{i=1}^N\\xi_i\n\\end{equation}\n$$\n\n> $$\n\\mathrm{argmin}_{\\mathbf{w},w_0}\n\\Big\\{\\frac{1}{2}\\|\\mathbf{w}\\|^2+ C\\sum_{i=1}^N\\xi_i \\Big\\}\n$$\n> Uz ograničenja:\n> $$\n\\begin{align*}\ny^{(i)}\\big(\\mathbf{w}^\\intercal\\mathbf{x}^{(i)}+w_0\\big) &\\geq 1 - \\xi_i, \\quad& i=1,\\dots,N\\\\\n\\xi_i&\\geq 0, & i=1,\\dots,N\\\\\n\\end{align*}\n$$\n\n* Pripadna Lagrangeova funkcija:\n\n$$\nL(\\mathbf{w}, w_0,\\boldsymbol\\xi,\\color{red}{\\boldsymbol\\alpha},\\color{red}{\\boldsymbol\\beta})=\n\\frac{1}{2}\\|\\mathbf{w}\\|^2+ C\\sum_{i=1}^N \\xi_i\n- \\sum_{i=1}^N\\color{red}{\\alpha_i}\\big(y^{(i)} h(\\mathbf{x})-1 + \\xi_i\\big)\n- \\sum_{i=1}^N\\color{red}{\\beta_i}\\xi_i\n$$\n\n\n* Minimizacija po $\\mathbf{w}$, $w_0$ i $\\xi_i$:\n\n$$\n\\begin{align*}\n\\mathbf{w} &= \\sum_{i=1}^N \\alpha_i y^{(i)}\\mathbf{x}^{(i)}\\\\\n\\sum_{i=1}^N\\alpha_i y^{(i)} &= 0\\\\\n\\alpha_i &= C - \\beta_i\n\\end{align*}\n$$\n\n* Dualna Lagrangeova funkcija:\n\n$$\n\\tilde{L}(\\boldsymbol\\alpha) = \n\\begin{align}\n\\sum_{i=1}^N\\alpha_i - \n\\frac{1}{2}\\sum_{i=1}^N\n\\sum_{j=1}^N\n\\alpha_i\n\\alpha_j\ny^{(i)}\ny^{(j)}\n(\\mathbf{x}^{(i)})^\\intercal\n\\mathbf{x}^{(j)}\n\\end{align}\n$$\n\n* Dualni optimizacijski problem:\n\n> **Maksimizirati** izraz\n> \\begin{align}\n\\sum_{i=1}^N\\alpha_i - \n\\frac{1}{2}\\sum_{i=1}^N\n\\sum_{j=1}^N\n\\alpha_i\n\\alpha_j\ny^{(i)}\ny^{(j)}\n(\\mathbf{x}^{(i)})^\\intercal\n\\mathbf{x}^{(j)}\n\\end{align}\n> tako da:\n> \\begin{align*}\n0 \\leq \\alpha_i &\\leq C,\\quad i=1,\\dots,N \\\\ \n\\sum_{i=1}^N\\alpha_i y^{(i)} &= 0, \\quad i=1,\\dots,N\n\\end{align*}\n\n\n\n```python\nX1, y1 = sp.append(seven_X, [[3,3]], axis=0), sp.append(seven_y, -1)\nX2, y2 = sp.append(seven_X, [[2,2]], axis=0), sp.append(seven_y, -1)\n```\n\n\n```python\ndef predict(model,x) : \n #h = sp.dot(model.coef_,x)+model.intercept_\n h = model.decision_function(x)\n if h >= -1 and h <= 1 : return 0.5\n else : return max(-1,min(1,h))\n return h\n```\n\n\n```python\nfrom sklearn.metrics import hinge_loss\n\nfor C in [1e-2,1,1e2] :\n svc = SVC(C=C,kernel='linear')\n svc.fit(X1,y1)\n plot_problem(X1,y1,lambda x: predict(svc,x)); show()\n print svc.support_vectors_\n print \"margin = \", 2/sp.linalg.norm(svc.coef_)\n print \"loss = \", hinge_loss(y1,svc.decision_function(X1))\n```\n\n\n```python\nfor C in [1e-2, 1, 1e2] :\n svc = SVC(C=C, kernel='linear')\n svc.fit(X2, y2)\n plot_problem(X2, y2, lambda x: predict(svc,x)); show()\n print svc.support_vectors_\n print \"margin = \", 2/sp.linalg.norm(svc.coef_)\n print \"loss = \", hinge_loss(y1,svc.decision_function(X2))\n```\n\n# Gubitak zglobnice\n\nTODO (v. skriptu)\n\n# Jezgreni trik\n\nTODO (v. skriptu)\n\n# Mercerove jezgre\n\n\n\nTODO (v. skriptu)\n\n# Optimizacija hiperparametara\n\nTODO (v. skriptu)\n\n# Sažetak\n\nTODO\n\n\n```python\ndef plot_problem(X, y, h=None, surfaces=True) :\n '''\n Plots a two-dimensional labeled dataset (X,y) and, if function h(x) is given, \n the decision boundaries (surfaces=False) or decision surfaces (surfaces=True)\n '''\n assert X.shape[1] == 2, \"Dataset is not two-dimensional\"\n if h!=None : \n # Create a mesh to plot in\n r = 0.02 # mesh resolution\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, r),\n np.arange(y_min, y_max, r))\n XX=np.c_[xx.ravel(), yy.ravel()]\n try:\n Z_test = h(XX)\n if shape(Z_test) == () :\n # h returns a scalar when applied to a matrix; map explicitly\n Z = sp.array(map(h,XX))\n else :\n Z = Z_test\n except ValueError:\n # can't apply to a matrix; map explicitly\n Z = sp.array(map(h,XX))\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n if surfaces :\n plt.contourf(xx, yy, Z, cmap=plt.cm.Pastel1)\n else :\n plt.contour(xx, yy, Z)\n # Plot the dataset\n scatter(X[:,0],X[:,1],c=y, cmap=plt.cm.Paired,marker='o',s=50);\n```\n", "meta": {"hexsha": "27806b6399c95f282a3a9c2383e60e6bfdce4d84", "size": 109960, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/SU-2015-8-SVM.ipynb", "max_stars_repo_name": "jsnajder/StrojnoUcenje", "max_stars_repo_head_hexsha": "5c7da3558095541018ab908857857ea629d4e1cd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2015-11-01T15:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T20:39:38.000Z", "max_issues_repo_path": "notebooks/SU-2015-8-SVM.ipynb", "max_issues_repo_name": "jsnajder/StrojnoUcenje", "max_issues_repo_head_hexsha": "5c7da3558095541018ab908857857ea629d4e1cd", "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": "notebooks/SU-2015-8-SVM.ipynb", "max_forks_repo_name": "jsnajder/StrojnoUcenje", "max_forks_repo_head_hexsha": "5c7da3558095541018ab908857857ea629d4e1cd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-12-15T11:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T10:22:58.000Z", "avg_line_length": 66.3608931804, "max_line_length": 9716, "alphanum_fraction": 0.762922881, "converted": true, "num_tokens": 10524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.1276526220030806, "lm_q1q2_score": 0.053447760155716985}} {"text": "\n\n# Fizeau and Sansbury\n> \"Here we begin analysis of Fizeau's classical sawtooth experiment (1849) with Sansbury's proposed setup. While Fizeau studies a saw tooth wheel in uniform motion on the order of twenty rotations per second, Sansbury's setup can be interpreted as either the same wheel in nonuniform motion, or a wheel with variable saw tooth length in uniform motion. We argue that Sansbury's predictions could be tested if Fizeau's wheel could increase it's angular velocity from 20 revolutions per second, to 80 revolutions or 160 revolutions per second. \"\n\n- toc: false\n- branch: master\n- badges: false\n- comments: true\n- author: JHM\n- categories: [fizeau, sansbury, c, SR]\n\n\nAs described in previous posts, our critical [essay](https://github.com/jhmartel/SR/) on foundations in SR is basically stable and readable. Here we begin to elaborate on the concluding section, which briefly mentions Ralph Sansbury's proposed experiment. Sansbury's experiment is this. We take $c$ the speed of light as equal to $1$ foot per nanosecond $[\\mu s]=10^{-8}$ seconds.\n\n# Sansbury's Experiment\n\nWe quote from Sansbury's [paper](http://www.naturalphilosophy.org/pdf/abstracts/abstracts_5955.pdf) and his book [\"Faster than Light\"](https://www.amazon.ca/Faster-Than-Light-Relativity-Reconsidered-ebook/dp/B00LQT8056). \n\n__(Case 1)__ _A $15$ nanosecond light pulse from a laser was sent to a light detector, $30$ feet away. When the light pulse was blocked at the photodiode during the time of emission, but unblocked at the expected time of arrival, $31.2$ nanoseconds after the beginning of the time of emission, for $15$ nanosecond duration, little light was received. (A little more than the $4mV$ noise on the oscilloscope). This process was repeated thousands of times per second._\n\n__(Case 2)__ _When the light was unblocked at the photodiode during the time of emission ($15$ nanoseconds) but blocked after the beginning of the time of emission, during the expected time of arrival for $15$ nanoseconds, twice as much light was received ($8mV$). This process was repeated thousands of times per second._\n\nSansbury's conclusion? That _this indicated that light is not a moving wave or photon, but rather the cumulative effect of instantaneous forces at a distance. That is, undetectable oscillations of charge can occur in the atomic nuclei of the photodiode that spill over as detectable oscillations of electrons after a delay._\n\nSansbury found the equipment necessary for the experiment too expensive to rent for an extended period of time, and he was possibly not a sufficient expert in calibrating the equipment. So Sansbury's experiment appears to have not been sufficiently investigated, and we would argue that the experiment has neither been reproduced nor properly reviewed. Thus we turn to the classical Fizeau experiment, and consider its similarities to Sansbury's setup.\n\n# Fizeau's Saw Tooth Experiment (1849)\n\nNow Sansbury's apparatus has some similarity with Fizeau's sawtooth apparatus, as used circa 1849 to prove some of the first sensible measurements of luminal velocity. \n\n[Here](https://skullsinthestars.com/2008/03/31/fizeaus-experiment-the-original-paper/) is a blog which inlcudes a transcription of Fizeau's original 1849 paper in Comptes Rendus.\n\n[Here](https://youtu.be/7CUE1Bpz4hM) is an interesting youtube video en francais sur la mesure de Fizeau. Around the 4-5 minute mark is the most interesting. While the speed of the wheel is increased, the received light signal becomes increasingly erratic and intermittent, until a sufficiently high speed of rotation is achieved and the received light signal becomes eventually null and _no light is received_. \n\n[Here](https://physics.stackexchange.com/questions/315812/why-does-the-fizeau-measurement-of-the-speed-of-light-use-a-sawtoothed-gear-inst) is a useful physics stackexchange answer. \n\n# Sansbury vs. Fizeau\n\nNow Fizeau's original setup is a type of Sansbury test where the wheel is in uniform motion. Sansbury's setup involves either a wheel in _nonuniform_ motion, or equivalently a wheel in uniform motion with a nonuniform sawtooth distribution.\n\nWe remark that Fizeau was historically looking to estimate the luminal velocity $c$. Sansbury's experiment assumes $c$ as given, estimated at $1$ foot per nanosecond. Sansbury's goal is to distinguish light propagation from particle model, and his setup is meant to test whether light is even something that travels at all. \n\nLet's review the basic math of Fizeau's apparatus, it's very simple. No matter how we setup the mirrors, we suppose light has some total travel time. In Fizeau's original setup, light travelled a total path of $\\approx 16 km$. With an expected speed of light $c=3\\times 10^8 km$, then the expected travel time is \n\n\\begin{equation}\n\\frac{16 \\times 10^3 [m]}{3 \\times 10^8 [m]/[sec]}=5.333\\ldots \\times 10^{-5} [sec].\\end{equation} \n\nNow consider the wheel with angular velocity $\\omega$ having units of $[degrees]/[sec]$ and having a toothlength equal to $1/720$ degrees. The time required to turn one toothlength is therefore $\\frac{1/720}{\\omega}=\\frac{1}{720 \\omega} [sec]$. Thus we find that the expected travel time is equal to the time to rotate one toothlength if the following equality holds $$\\frac{16 \\times 10^3 }{3 \\times 10^8} = \\frac{1}{720 \\omega}, $$ which implies $$\\omega \\approx 26 ~~~\\frac{[rotations]}{[sec]}.$$\n\n\nSansbury's __(Case 1)__ could be realized if the wheel was allowed to rotate nonuniformly, i.e. if the wheel could be accelerated in \"impulses\" something closer to the actual discrete motions of a clock. For example, if the wheel is initially opened at the time of emission, then immediately rotated one saw tooth length (to the closed position) during the expected time of travel, and just prior to the expected time of arrival is rotated another tooth length (to the open position), then Fizeau would predict that the receiver would observe a strong light source. However Sansbury predicts that the receiver would observe rather a very weak signal. Notice here we require the wheel to move twice as fast as Fizeau's angular velocity. In otherwords the wheel must rotate two complete tooth lengths before the estimated arrival time.\n\nSansbury's __(Case 2)__ could be realized if the wheel was rotating _nonuniformly_. For example, if we keep the wheel fixed during the expected time of flight of the light particle, and turn the wheel one complete toothlength at the expected time of arrival, then Sansbury would predict a relatively strong signal would be received. Fizeau and the particle model would however predict no light would be received, since in the model it would be blocked by the sawtooth at the expected time of arrival.\n\nN.B. Fizeau's conception of the sawtooth wheel is _classical_. But what happens if we retrospectively apply the SR methodology to the experiment, what results are obtained? It appears that SR has a null effect on the entire experiment, i.e. returns the same results as the classical case. While the sawteeth lengths are contracting in SR, this effects the circumference of the wheel but not the angular velocity. Thus Fizeau experiment appears insensitive to any Lorentz SR effects and an experiment which cannot prove SR in contrast to the classical mechanics.\n\nWe do not require mathematics at this stage, but rather to perform an experiment. However there is an intersting math aspect to the question, \"How to keep a nonuniform wheel in uniform motion?\". \n\nFizeau's original wheel was materially balanced: the distribution of teeth was equidistant and regular. The centre of mass corresponded with the axis of rotation. \n\nBut if we begin to study nonuniform wheels, then the behaviour becomes more difficult depending on, say, whether the centre of mass coincides with the axis of rotation.\n\nSome comparisons between Fizeau and Sansbury:\n\n1. Fizeau's involves several reflecting mirrors (beam splitters). Therefore there is more interaction involved in Fizeau's setup than with Sansbury's. For Fizeau's is a type of two-way trip of light, where the source and receiver are space-coincident. But Sansbury's is a one-way trip, requiring some electronics at the receiver namely a photodiode, to measure the amount of electrons released by the light emission.\n\n2. If the phase of Fizeau's wheel could be controlled, then we could compare the behaviour of the experiment when the wheels differ by one saw tooth length. The trouble in Fizeau is that, because the source and receiver coincide, it's evident that no light is emitted when the phase is shifted one tooth length. Sansbury's experiment however does emphatically require the apparatus to be _open_ at the moment of emission. \n\n# Faster Fizeau Wheels\n\nWe could test some of Sansbury's ideas if we could increase the angular velocity of the Fizeau wheel by factor of $4$, i.e. we need a wheel of roughly $100$ revolutions per second instead of $20$ revolutions per second. \n\nGiven such a revolution speed, then we could change the sawtooth pattern of the wheels, having some that are $1/4$ closed, $1/2$ closed, and $3/4$ closed wheels. For example, we could have the alternating sawtooth $$\\ldots 0101010101 \\ldots$$ or we could have $$\\ldots 001100110011 \\ldots$$ both of which are $1/2$ closed but having different patterns. And these patterns would have different predictions depending on the photon model or Sansbury's cumulative action-at-a-distance. Likewise it would be interesting to compare the predictions given a wheel having a $1/4$-closed sawtooth pattern $$\\ldots 0001000100010001 \\ldots$$ versus a $3/4$-closed pattern $$ \\ldots 0111011101110111\\ldots.$$\n\nIf we could get the Fizeau wheel to spin $200$ revolutions per second, then we could test the theories according to $8$-periodic patterns, i.e. with sawtooth patterns being $1/8, 2/8$, $\\ldots$, $7/8$ths closed. \n\nIf we could build a larger wheel with more teeth, say, $1440$ teeth, then $2880$ teeth, then basic gear ratio would increase the speed of the initial _pinion_ wheel by factor of $\\times 2$, $\\times 4$, etc..\n\nThe heuristics by which we can determine reasonable revolutions per second depends probably on some energy estimates and would require smaller and smaller radii. \n\n[To be continued...]\n\n\n", "meta": {"hexsha": "b0fb8283ac6f597debbbf94b68e058a232865f0e", "size": 12533, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2022-04-29-FizeauSansbury.ipynb", "max_stars_repo_name": "jhmartel/0x", "max_stars_repo_head_hexsha": "9e72b419651608d619cd9c2fba53048049099fb9", "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/2022-04-29-FizeauSansbury.ipynb", "max_issues_repo_name": "jhmartel/0x", "max_issues_repo_head_hexsha": "9e72b419651608d619cd9c2fba53048049099fb9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-11T22:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T18:40:36.000Z", "max_forks_repo_path": "_notebooks/2022-04-29-FizeauSansbury.ipynb", "max_forks_repo_name": "jhmartel/0x", "max_forks_repo_head_hexsha": "9e72b419651608d619cd9c2fba53048049099fb9", "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": 93.5298507463, "max_line_length": 848, "alphanum_fraction": 0.6991941275, "converted": true, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.1441488530327406, "lm_q1q2_score": 0.05336756570624991}} {"text": "```python\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom IPython.display import Image \nfrom astropy.cosmology import WMAP9 as cosmo\nfrom astropy import constants as const\n\nfrom causticpy import *\nfrom functions_caustic import to_xyz_coordinates, linear_angle, data_query_id\n```\n\n У нас имеются таблицы с данными каталогов:\n- **SDSS (glist_s)**, \n- **2MRS (glist_2)**.\n \n**SDSS** - *Sloan Digital Sky Survey* с англ. — «Слоуновский цифровой небесный обзор») — проект широкомасштабного исследования многоспектральных изображений и спектров красного смещения звёзд и галактик при помощи 2,5-метрового широкоугольного телескопа в обсерватории Апачи-Пойнт в штате Нью-Мексико. Проект назван в честь фонда Альфреда Слоуна.\n\nИсследования начались в 2000 году, в ходе работы проекта было проведено картографирование более 35 % небесной сферы с фотометрическими наблюдениями порядка 500 миллионов объектов и получением спектров более чем для 3 миллионов объектов. Среднее значение красного смещения по изображениям галактик составило 0.1; для ярких красных галактик вплоть до z=0,4, для квазаров до z=5. Наблюдения в рамках обзора способствовали обнаружению квазаров со сдвигом более 6.\n\nПроект делится на несколько фаз: SDSS-I (2000—2005), SDSS-II (2005—2008), SDSS-III (2008—2014), SDSS-IV (2014—2020). Собранные в ходе обзоров данные публикуются в виде отдельных релизов (Data Release), последний из них, DR13 опубликован в августе 2016 года.\n\n**2MASS Redshift Survey** - aims to map the distribution of galaxies and dark matter in the local universe, out to a mean redshift of z = 0.03 (roughly equivalent to 115 Mpc or 370 million light-years). It is based on galaxy selection in the near infra-red from the *Two Micron All-Sky Survey* (**2MASS**). 2MASS has now mapped all of the sky in the near infra-red J, H and K-bands. This photometric survey is complete and fully available to the public (IRSA). The 2MASS extended source catalog (XSC) includes roughly half a million galaxies to a limiting K magnitude of K=13.5 mag. 2MRS ultimately aims to determine the redshifts of all galaxies in the XSC to a magnitude of K=12.2 mag (about 100,000 galaxies) and to within 5 deg of the Galactic plane. The second phase of 2MRS is now complete, providing an all-sky survey of 45,000 galaxies with redshifts to a limiting magnitude of K=11.75 mag. It is the densest sampled all-sky redshift survey to date and its selection in the near infra-red reduces the impact of the zone of avoidance (where the plane of our own Galaxy obscures extragalactic objects). 2MRS provides complementary redshift information to deeper surveys like SDSS and the 2dFRGS which cover much smaller fractions of the sky. It improves on the IRAS redshift survey IRAS PSCz which was not able to distinguish galaxies in regions of high density (ie. clusters).\n\n\n```python\nImage(\"projections.png\") \n```\n\nВ астрофизике принято рассматривать небесные объекты в проекции на небесную сферу. \n\nПредполагается, что наблюдатель располагается в вершине угла $a$.\nна рисунке обозначено:\n\n$O$ - центр некоторого скопления,\n\n$A_0$ - некоторая галактика из скопления,\n\n$r_0$ - вектор, соединяющий глаз наблюдателя и центр скопления $O$,\n\n$r_1$ - вектор, соединяющий глаз наблюдателя и объект $A_0$,\n\n$P$ - плоскость построенная таким образом, что она перпендикулярна вектору $r_0$ и проходит через центр скопления $O$,\n\n$A$ - точка пересечения луча, идущего из глаза наблюдателя через объект $А_0$ с плоскостью $P$,\n\n$H$ - перпендикуляр, опущенный из из $A_0$ на плоскость $H$,\n\n$a$ - линейный угол между векторами $r_0$ и $r_1$,\n\nкрасные отрезки $OA(OH)$ - проекции на плоскость Р.\n\n###### Так как наблюдения проводятся из одной точки, то интересующая нас проекция - центральная. \n\nПоскольку данные об углах right ascention (RAJ2000) и declination (DEJ2000) указаны в градусах, а вычислениях мы будем пользоваться радианами, то с помощью формулы перейдем от одних единиц измерения к другим:\n\n\\begin{equation}\n\\alpha_{rad} = \\pi \\frac{\\alpha_{grad}}{180}\n\\end{equation}\n\nЧерез данные об углах наклонения (DEC=DEJ2000) и вознесения (RA=RAJ2000) вычисляются координаты соответствующего объекта на единичной сфере:\n\n \\begin{equation}\n\\left\\{ \\begin{array}{ll}\n x = \\cos(DEC)\\cos(RA) \\\\\n y = \\cos(DEC)\\sin(RA)\\\\\n z = \\sin(DEC)\n\\end{array} \\right.\n\\end{equation}\n\nДалее необходимо вычислить длинну проекции $OA$ для каждой галактики из соответствующего скопления по всем скоплениям с помощью формулы: \n\n\\begin{equation}\n r_{pr} = r_0 \\tan(a),\n\\end{equation}\n\nгде угол $а$ - линейный угол между лучами, соединяющими наблюдателя с галактикой в скоплении и наблюдателя с центром скопления. Зная углы наклонения (DEC=DEJ2000) и вознесения (RA=RAJ2000), можно вычислить тангенс угла $а$:\n\n \\begin{equation}\n\\left\\{ \\begin{array}{ll}\n x = \\cos(DEC)\\cos(RA) \\\\\n y = \\cos(DEC)\\sin(RA)\\\\\n z = \\sin(DEC)\n\\end{array} \\right.\n\\end{equation}\n\n\\begin{equation}\n\\cos(a) = x_{centr}x_{gal} + y_{centr}y_{gal}+z_{centr}z_{gal}\n\\end{equation}\n\n\\begin{equation}\n\\tan(a) = \\frac{\\sqrt{1-\\cos^2(a)}}{\\cos(a)}\n\\end{equation}\n\nВведем используемые в дальнейшем исследовании космологические постоянные:\n\nСкорости галактик в скоплении относительно центра этого скопления высчитывались с помощью формулы: \n\n\\begin{equation}\n v = c * (z_{gal} - z_{cent})\n\\end{equation}\n\nОтметим, что все эти скорости могут вычислены только вдоль луча зрения (line-of-sight) на основании измерений красного смещения (red shift) $z$ рассматриваемого объекта. Поперечные скорости определить сложно, так как время съемки телескопом данного участка неба по сравнению с перемещением объекта по небесной сфере ничтожно мало, а потому увидеть какие-то видимые измения в положении объекта на небе пока не представляется возможным.\n\nДалее воспользуемся программой 'Caustic mass estimator for astrophysical systems', взятой с репозитория Dan Gifford на GitHub http://github.com/giffordw . Данная программа позволяет на основе данных об углах RA, DEC и красного смещения z строить каустические кривые для скоплений галактик. Программный код основывается на методах, описанных в статьях:\n- A.Diafferio. Mass estimation in the outer regions of galaxy clusters. 1999.\n- Gifford et al. A Systematic Analysis of Caustic Methods for Galaxy Cluster Masses. 2013.\n- Gifford & Miller. Velocity Anisotropy and Shape Bias in the Caustic Technique. 2013.\n\nКаустики - это некие кривые в фазовой плоскости (r,v), которые разделяют эту плоскость на несколько сегметов: центральный, нижний и верхний. Из взаимного положения галактик в коплении и соответствующих каустик на фазовой плоскости можно судить о будующем этого скопления. Например, если галактики лежат вне центральной области, ограниченной каустиками, то можно заключить, что данная галактика в будущем покинет это скопление.\n\n\n```python\nC = const.c.to('km/s') #300000 # km/s - скорость света в вакууме\n# Mpc = 3.086e+19 # km - мегапарсек\n```\n\n\n```python\ndata = pd.read_csv('glist_2.csv')\n```\n\n\n```python\ndata.info()\n```\n\n \n RangeIndex: 1200 entries, 0 to 1199\n Data columns (total 21 columns):\n iGalID 1200 non-null int64\n iGrID 1200 non-null int64\n Name 1200 non-null object\n RAJ2000_gal 1200 non-null float64\n DEJ2000_gal 1200 non-null float64\n z_gal 1200 non-null float64\n logMstar_gal 425 non-null float64\n RAJ2000_group 1200 non-null float64\n DEJ2000_group 1200 non-null float64\n z_group 1200 non-null float64\n logLtot 1200 non-null float64\n logLobs 1200 non-null float64\n logMtot 1200 non-null float64\n logMstar_group 1165 non-null float64\n NMstar 1200 non-null int64\n logMdyn 1200 non-null float64\n sigma 1200 non-null float64\n Rad 1200 non-null float64\n angRad 1200 non-null float64\n DL 1200 non-null float64\n Ntot 1200 non-null int64\n dtypes: float64(16), int64(4), object(1)\n memory usage: 197.0+ KB\n\n\n\n```python\n# !pip install scikit-image\n```\n\n\n```python\niGrID = data['iGrID'].unique()[0:1]\n```\n\n\n```python\n# data.columns\n```\n\n\n```python\ndata_query = data_query_id(data, iGrID[0], 'iGrID')\ngalaxydata = data_query.to_numpy()\n```\n\n\n```python\nc = Caustic()\ngood_flag = c.run_caustic(galaxydata, \n clus_ra=galaxydata[:,3].mean(),\n clus_dec=galaxydata[:,4].mean(),\n clus_z=galaxydata[:,5].mean())#, r200=0.743, clus_ra=195.095, clus_dec=19.131,clus_z=0.063)\n```\n\n DATA SET SIZE 43\n Pre_r200= 0.35374227608257586\n Calculating Density w/Mirrored Data\n Vdisp from galaxies= 118.4137724813458\n Combined Vdisp= 118.4137724813458\n Calculating initial surface\n complete\n r200 estimate: 0.2338076934627482\n M200 estimate: 1550714469573.0642\n\n\n\n```python\ndata_query.columns\n```\n\n\n\n\n Index(['RAJ2000_gal', 'DEJ2000_gal', 'z_gal', 'RAJ2000_group', 'DEJ2000_group',\n 'z_group', 'iGrID', 'DL', 'r_pr', 'v'],\n dtype='object')\n\n\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(7,5))\nx_max = data_query['r_pr'].max()\ny_max = abs(data_query['v']).max()\nx = data_query['r_pr']\ny = data_query['v'] \nax.scatter(x, y, c=data_query['iGrID'], marker='*')\nax.plot(c.x_range, c.caustic_profile, c='red')\nax.plot(c.x_range, -c.caustic_profile, c='red')\nax.plot(c.r,c.v,'o', c='black')\nax.set_xlabel('Distance from center of the cluster, [Mpc]')\nax.set_ylabel('Relative velocity in the cluster, [km/s]')\nax.set_title('\\n Caustic curve \\n')\n# ax.set_title('iGrID = %d' % (iGrID))\nax.set_ylim(top=y_max*1.1, bottom=-y_max*1.1)\nax.set_xlim((0,10))\nax.grid(True)\n# plt.savefig(\"caustic.png\")\n```\n\n\n```python\n# Image(\"caustic.png\") \n```\n\n\n```python\nfrom pylab import *\nplot(c.r,c.v,'o', c='black')\n# plt.savefig(\"caustic.png\")\n# Image(\"caustic.png\") \n```\n\n\n```python\n# Проверить почему не работает???\n\n# plot(data[data['iGrID']==iGrID]['r_pr'],data[data['iGrID']==iGrID]['v'],'o', c='black')\n# show()\n```\n\nПонять как они определяют расстояния. Очевидно, что немного по-другому. Это может быть причиной различия в оцененных массах на основе каустик и Mtot из таблиц.\n\nTo make two pictures made above look simular we made same changes in the \n- file \"\\__init\\__\"\n- in class Caustic\n- in function run_caustic\n- in function findangle(self,ra,dec,clus_RA,clus_DEC)\n\nBecause with a previous code a projected radius was calculated another way.\n\n\n```python\nm = MassCalc(ri = c.x_range,\n A = c.caustic_profile,\n vdisp = c.vdisp_gal,\n clus_z = galaxydata[:,5].mean(),\n r200=2.0,\n conc1=5,\n beta=0.25,\n fbr=None,\n H0=100.0,)\n```\n\n\n```python\nm.M200\n```\n\n\n\n\n 17403720159393.834\n\n\n\n\n```python\n12427715478374.973 # for native radius calculatiouns\n12427715478374.607 # data[data['iGrID']==iGrID]['sigma'].mean()\n12427715478374.607 # for c.vdisp_gal\n```\n\n\n\n\n 12427715478374.607\n\n\n\nLet's put caustic profile onto the galaxy cluster in a phase space\n\n\n```python\n\n```\n", "meta": {"hexsha": "69147f275c77866a50c36e6339cfca7f10703ec1", "size": 67645, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "caustics/About_caustics_new.ipynb", "max_stars_repo_name": "Azarodnyuk/galaxymass", "max_stars_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-09T13:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-09T13:05:02.000Z", "max_issues_repo_path": "caustics/About_caustics_new.ipynb", "max_issues_repo_name": "Azarodnyuk/galaxymass", "max_issues_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "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": "caustics/About_caustics_new.ipynb", "max_forks_repo_name": "Azarodnyuk/galaxymass", "max_forks_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "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": 124.3474264706, "max_line_length": 27232, "alphanum_fraction": 0.867336832, "converted": true, "num_tokens": 4084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.10818894593571948, "lm_q1q2_score": 0.05324931560569971}} {"text": "```python\n# %load /Users/facai/Study/book_notes/preconfig.py\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\nsns.set(font='SimHei')\nplt.rcParams['axes.grid'] = False\n\nfrom IPython.display import SVG\n\ndef show_image(filename, figsize=None):\n if figsize:\n plt.figure(figsize=figsize)\n\n plt.imshow(plt.imread(filename))\n```\n\nTreeBoost原理和实现(sklearn)简介\n===========================\n\n### 0. 前言\n\nTreeBoost是对GBDT做了更深一步的优化,主要贡献在将整颗树的全局权重值细化到每片叶子的局部权重值。它不像xgboost在树生长时就做出指导,而是在树生长后再修正叶子值。对于工程中的GBDT模块,spark目前是传统的Gradient Boosting,而sklearn采用了TreeBoost,所以本文以sklearn为例进行说明。\n\n本文假设读者已经了解GBDT的基本原理。\n\nsklearn代码版本:\n\n```sh\n~/W/s/sklearn ❯❯❯ git log -n 1\ncommit d161bfaa1a42da75f4940464f7f1c524ef53484f\nAuthor: John B Nelson \nDate: Thu May 26 18:36:37 2016 -0400\n\n Add missing double quote (#6831)\n```\n\nGBDT模块位于`sklearn/ensemble/gradient_boosting.py`文件,类的关系比较简单。\n\n\n```python\nSVG(\"./res/Main.svg\")\n```\n\n\n\n\n \n\n \n\n\n\n### 1. GBDT优化\n\n传统的Gradient Boost算法主要有四步:\n\n1. 对损失导数求偏导;\n2. 训练决策树,拟合偏导;\n3. 寻优模型权值;\n4. 将训练的模型,加到叠加模型中。\n\n可以用数学公式对应表述为[1]:\n\n+ $F_0(x) = \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N L(y_i, \\rho)$\n\n+ For $m=1$ to $M$ do:\n \n 1. $\\tilde{y} = - \\left [ \\frac{\\partial L (y_i, F(x_i))}{\\partial F(x_i)} \\right ]_{F(x) = F_{m-1}(x)}, \\quad i = 1, 2, \\dotsc, N$\n \n 2. $\\mathbf{a}_m = \\operatorname{arg \\, min}_{\\mathbf{a}, \\beta} \\displaystyle \\sum_{i=1}^N \\left [ \\tilde{y}_i - \\beta h(x_i; \\mathbf{a}) \\right ]^2$\n 3. $\\rho_m = \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N L \\left ( y_i, F_{m-1}(x_i) + \\rho h(x_i; \\mathbf{a}_m) \\right)$\n 4. $F_m(x) = F_{m-1}(x) + l_r \\rho_m h(x; \\mathbf{a}_m)$\n \n其中,$L$是损失函数, $l_r$是学习率,$\\rho$是模型的权值,$h(x_i; \\mathbf{a})$是决策树模型,$\\mathbf{a}$是树的参数,$F$是最终累加模型。\n \n利用一些数学方法和损失函数的特性,可以将第3步的权值寻优进行简化。在sklear中单步训练代码对应如下:\n\n```Python\n 748 def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask,\n 749 random_state, X_idx_sorted, X_csc=None, X_csr=None):\n 750 \"\"\"Fit another stage of ``n_classes_`` trees to the boosting model. \"\"\"\n 751 #+-- 8 lines: assert sample_mask.dtype == np.bool----------\n 759\n 760 residual = loss.negative_gradient(y, y_pred, k=k,\n 761 sample_weight=sample_weight)\n 762\n 763 # induce regression tree on residuals\n 764 tree = DecisionTreeRegressor(\n 765 criterion='friedman_mse',\n 766 splitter='best',\n 767 #+--- 7 lines: max_depth=self.max_depth,------------------\n 774 presort=self.presort)\n 775\n 776 #+--- 8 lines: if self.subsample < 1.0:------------------\n 784 tree.fit(X, residual, sample_weight=sample_weight,\n 785 check_input=False, X_idx_sorted=X_idx_sorted)\n 786\n 787 # update tree leaves\n 788 #+-- 5 lines: if X_csr is not None:---------------------\n 793 loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred,\n 794 sample_weight, sample_mask,\n 795 self.learning_rate, k=k)\n 796\n 797 # add tree to ensemble\n 798 self.estimators_[i, k] = tree\n 799\n 800 return y_pred\n```\n\n其中,\n\n+ 760L是求解偏导。\n+ 784L是生成决策树。注意,对于MSE,$\\beta=1$。765L树的评价函数是friedman_mse,它是MSE的变种。我猜测$\\beta$是一致的,后续有时间再深究。\n+ 793L是TreeBoost做的改进,将第3步寻优全局解$\\rho$转化到树内部,后面主要内容就在这。\n+ 798L是加回到累加模型。\n\n\n接下来,我们先就平方差和绝对值两种损失函数,对传统Gradient Boost方法进行第3步的优化,为后续TreeBoost铺路。\n \n[1]: Friedman - Greedy function approximation: A gradient boosting machine\n\n#### 1.0 Least squares regression\n\n这种损失函数定义是 $L(y, F) = \\frac{1}{2} (y - F)^2$,则其导数为$\\frac{\\partial L}{\\partial F} = -(y - F)$。将偏导代入到第1步有:\n\n\\begin{align}\n \\tilde{y} &= - \\left [ \\frac{\\partial L (y_i, F(x_i))}{\\partial F(x_i)} \\right ]_{F(x) = F_{m-1}(x)} \\\\\n &= y_i - F_{m-1}(x_i), \\quad i = 1, 2, \\dotsc, N \\\\\n\\end{align}\n\n将$L$和$\\tilde{y}$代入到第3步中,整理可得:\n\n\\begin{align}\n \\rho_m &= \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N L \\left ( y_i, F_{m-1}(x_i) + \\rho h(x_i; \\mathbf{a}_m) \\right) \\\\\n &= \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N \\frac{1}{2} \\left ( y_i - F_{m-1}(x_i) - \\rho h(x_i; \\mathbf{a}_m) \\right)^2 \\\\\n &= \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N \\frac{1}{2} \\left ( \\tilde{y}_i - \\rho h(x_i; \\mathbf{a}_m) \\right)^2 \\\\\n &= \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N \\left ( \\tilde{y}_i - \\rho h(x_i; \\mathbf{a}_m) \\right)^2 \\\\\n &= \\operatorname{arg \\, min}_\\beta \\displaystyle \\sum_{i=1}^N \\left ( \\tilde{y}_i - \\beta h(x_i; \\mathbf{a}_m) \\right)^2 \\quad \\text{符号替换}\\\\\n &= \\beta_m\n\\end{align}\n\n也就是说,对于平方差这种损失函数,它的最优权值就是第2步中指导决策树生成时的$\\beta$值。\n\n这个算法称为LS_Boost,具体过程为:\n\n+ $F_0(x) = \\bar{y}$\n\n+ For $m=1$ to $M$ do:\n 1. $\\tilde{y}_i = y_i - F_{m-1}(x_i), \\quad i=1, N$\n 2. $(\\rho_m, \\mathbf{a}_m) = \\operatorname{arg \\, min}_{\\mathbf{a}, \\rho} \\displaystyle \\sum_{i=1}^N \\left [ \\tilde{y}_i - \\rho h(x_i; \\mathbf{a}) \\right ]^2$\n 3. $F_m(x) = F_{m-1}(x) + l_r \\rho_m h(x; \\mathbf{a}_m)$\n \nsklearn中代码如下:\n \n```Python\n 274 class LeastSquaresError(RegressionLossFunction):\n 275 \"\"\"Loss function for least squares (LS) estimation.\n 276 Terminal regions need not to be updated for least squares. \"\"\"\n 277 def init_estimator(self):\n 278 return MeanEstimator()\n 279\n 280 def __call__(self, y, pred, sample_weight=None):\n 281 if sample_weight is None:\n 282 return np.mean((y - pred.ravel()) ** 2.0)\n 283 else:\n 284 return (1.0 / sample_weight.sum() *\n 285 np.sum(sample_weight * ((y - pred.ravel()) ** 2.0)))\n 286\n 287 def negative_gradient(self, y, pred, **kargs):\n 288 return y - pred.ravel()\n 289\n 290 def update_terminal_regions(self, tree, X, y, residual, y_pred,\n 291 sample_weight, sample_mask,\n 292 learning_rate=1.0, k=0):\n 293 \"\"\"Least squares does not need to update terminal regions.\n 294\n 295 But it has to update the predictions.\n 296 \"\"\"\n 297 # update predictions\n 298 y_pred[:, k] += learning_rate * tree.predict(X).ravel()\n 299\n 300 def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,\n 301 residual, pred, sample_weight):\n 302 pass\n```\n\n前面说过sklearn中$\\beta=1$,则$l_r \\times \\beta = l_r$,所以`update_terminal_regions`这里直接用学习率和树预测值相乘。\n\n#### 1.1 Least-absolute-deviation (LAD) regression\n\n损失函数定义为 $L(y, F) = | y - F |$,同样地,可以利用导数算出残差:\n\n\\begin{align}\n \\tilde{y} &= - \\left [ \\frac{\\partial L (y_i, F(x_i))}{\\partial F(x_i)} \\right ]_{F(x) = F_{m-1}(x)} \\\\\n &= \\operatorname{sign}(y_i - F_{m-1}(x_i))\\\\\n\\end{align}\n\n$L(y, F)$是分段函数,它的导数在正数区间恒为1,负数区间恒为-1,而在间段点$F=0$处是不可导的,人为规定为0,所以可以用sign函数来描述:\n\n\\begin{equation}\n \\operatorname{sign}(x) := {\n \\begin{cases}\n -1 & {\\text{if }} x<0, \\\\\n 0 & {\\text{if }} x=0, \\\\\n 1 & {\\text{if }} x>0.\n \\end{cases}\n }\n\\end{equation}\n\n\n同样的,将$L$和$\\tilde{y}$代入到第3步中,整理可得:\n\n\\begin{align}\n \\rho_m &= \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N L \\left ( y_i, F_{m-1}(x_i) + \\rho h(x_i; \\mathbf{a}_m) \\right) \\\\\n &= \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N \\big | y_i - F_{m-1}(x_i) - \\rho h(x_i; \\mathbf{a}_m) \\big | \\\\\n &= \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N \\big | h(x_i; \\mathbf{a}_m) \\big | \\cdot \\left | \\frac{y_i - F_{m-1}(x_i)}{h(x_i; \\mathbf{a}_m)} - \\rho \\right | \\\\\n &= \\operatorname{median}_W \\left \\{ \\frac{y_i - F_{m-1}(x_i)}{h(x_i; \\mathbf{a}_m)} \\right \\}_1^N, \\quad w_i = \\big | h(x_i; \\mathbf{a}_m) \\big |\n\\end{align}\n\n这里$\\operatorname{median}_W \\{ \\cdot \\}$是带权$w_i$的[weighted median](https://en.wikipedia.org/wiki/Weighted_median)。\n\n注意,weighted median的概念$\\operatorname{median}_W (x)$,这里的加权,应理解为$x_i$出现了$w_i$次,而不是$x_i \\cdot w_i$数值。 你可以去维基页查看定义,也可以看下面的推导细节。不太好讲,但其实很简单。\n\n在sklearn中,LAD用的TreeBoost去实现,所以没有代码对应。\n\n#### 推导细节\n\n\\begin{align}\n\\rho_m &= \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N \\big | h(x_i; \\mathbf{a}_m) \\big | \\cdot \\left | \\frac{y_i - F_{m-1}(x_i)}{h(x_i; \\mathbf{a}_m)} - \\rho \\right | \\\\\n &= \\operatorname{median}_W \\left \\{ \\frac{y_i - F_{m-1}(x_i)}{h(x_i; \\mathbf{a}_m)} \\right \\}_1^N, \\quad w_i = \\big | h(x_i; \\mathbf{a}_m) \\big |\n\\end{align}\n\n最后一步的过程比较跳,我们在这里详细说下推导。\n\n在这之前,我们简化下符号,以利于理解,\n\n\\begin{align}\n \\rho_m &= \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N \\big | h(x_i; \\mathbf{a}_m) \\big | \\cdot \\left | \\frac{y_i - F_{m-1}(x_i)}{h(x_i; \\mathbf{a}_m)} - \\rho \\right | \\\\\n &= \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N w_i \\cdot | t_i - \\rho | \\\\\n\\end{align}\n\n##### 无加权\n\n首先,我们考虑无加权的情况,即$w_i = 1$。此时有$\\rho_m = \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N | t_i - \\rho |$。\n\n有两种方法来解释为什么$\\rho_m = \\operatorname{median}(t_i)$:\n\n第一种是几何方法,$| t_i - \\rho |$表示两点距离。我们要找的$\\rho_m$,本质上就是离所有点$t_i$总距离最短的点。所以通过作图的方法,直观理解。\n\n\n```python\nshow_image(\"./res/rho_m.png\")\n```\n\n如上图,绿色直线是中位点到各点距离,黄色直线是另一个点的距离,随着这个点外移,总距离越来越长。总结,对于奇数个点,$\\rho_m$是中位点;对于偶数点,$\\rho_m$在两个中间点闭区间上。\n\n第二种方法是代数方法。\n\n首先我们直观地了感受下结果,对于$\\rho_m = \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N | t_i - \\rho | = \\operatorname{arg \\, min} f(\\rho)$,导数是$f'(\\rho) = \\sum_{i=1}^N \\operatorname{sign}(t_i - \\rho)$。在极值点$f'(\\rho) = 0$,而$\\operatorname{sign}(x)$只有$1, -1, 0$三种值,所以要和为0,则必然要求$1$和$-1$的数量相同。而中位点正好满足此条件[2]。\n\n然后,在Mathematics上看到一个较为严密的论证[2]。它先算最左端结果,再向右取区间推进,证明整个过程中距离是先单减再单增的过程,从而证明中位点是最小点,具体如下:\n\n令集合$T$含$N$个元素$t_1 < t_2 < \\dots < t_N$。\n\n1. 对于最左端$\\rho < t_1$,有$f(\\rho) = \\sum_{i=1}^N | t_i - \\rho | = \\sum_{i=1}^N (t_i - \\rho)$。很明显,对于每个子项,有$t_i - \\rho > 0$,且$\\rho \\to t_1$时,$(t_i - \\rho)$单减。也就是说,随着$\\rho$从左向右靠近$t_1$点,所有子项都在减小,则总和$f(\\rho)$单减。 \n\n2. 选定任一区间,$t_k \\leq \\rho \\leq \\rho + d \\leq t_{k+1}$,有:\n\n\\begin{align}\n f(\\rho + d) &= \\displaystyle \\sum_{i=1}^N | t_i - (\\rho + d) | \\\\\n &= \\sum_{i=1}^k (\\rho + d - t_i) + \\sum_{i=k+1}^N (t_i - (\\rho + d)) \\\\\n &= \\sum_{i=1}^k (\\rho - t_i) + \\sum_{i=1}^k d + \\sum_{i=k+1}^N (t_i - \\rho) + \\sum_{i=k+1}^N -d \\\\\n &= \\sum_{i=1}^N | t_i = \\rho | + k d + (N - (k+1) + 1) \\times -d \\\\\n &= f(\\rho) + d \\times ( k - N + (k + 1 ) -1 ) \\\\\n &= f(\\rho) + d \\times (2k - N)\n\\end{align}\n\n则有:\n\n\\begin{equation}\n f(\\rho + d) = \\begin{cases}\n < f(\\rho), \\quad \\text{when } k < \\frac{N}{2} \\\\\n = f(\\rho), \\quad \\text{when } k = \\frac{N}{2} \\\\\n > f(\\rho), \\quad \\text{when } k > \\frac{N}{2} \\\\\n \\end{cases}\n\\end{equation}\n\n也就是说,在$k < \\frac{N}{2}$区间,$f(\\rho)$单减;在$k > \\frac{N}{2}$区间,$f(\\rho)$单增。所以,在中位点$\\frac{N}{2}$处,$f(\\rho)$是最小值。于是得$\\rho_m = \\operatorname{median}(t_i)$。\n\n[2]: http://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations\n\n##### 有加权\n\n\\begin{equation}\n \\rho_m = \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N w_i \\cdot | t_i - \\rho |\n\\end{equation}\n\n对于加权,有点无从下手的感觉。我们可以换个角度,会提供点有意思的想法。\n\n假设$w_i$是正整数,则$w_i \\cdot | t_i - \\rho | = \\sum_{k=1}^{w_i} | t_i - \\rho |$,也就是说,相当于将集合$T$中的$t_i$点扩增到$w_i$个。那么,可以展开为:\n\n\\begin{align}\n \\rho_m &= \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N w_i \\cdot | t_i - \\rho | \\\\\n &= \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^N \\sum_{k=1}^{w_i} | t_i - \\rho | \\\\\n &= \\operatorname{arg \\, min}_\\rho \\sum_{t_i \\in T'} | t_i - \\rho | \\quad \\text{$T'$ 是$t_i$扩增$w_i$倍的集合} \n\\end{align}\n\n于是,有加权问题就变更到无加权的问题。这时,我们可以将解法表示如下: \n\n1. 将$t_i$按升序排列。\n2. 将$w_i$按对应顺序排,计算累积和$c_k = \\sum_{i=1}^k w_i$。\n3. 找到对应中位点$c_m = \\frac{1}{2} c_N$对应的$t_m$,这个$t_m$就是$\\operatorname{median}_W \\{t_i\\}$。\n\n对应的sklearn代码如下:\n\n```Python\n 51 def _weighted_percentile(array, sample_weight, percentile=50):\n 52 \"\"\"Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. \"\"\"\n 53 sorted_idx = np.argsort(array)\n 54\n 55 # Find index of median prediction for each sample\n 56 weight_cdf = sample_weight[sorted_idx].cumsum()\n 57 percentile_idx = np.searchsorted(\n 58 weight_cdf, (percentile / 100.) * weight_cdf[-1])\n 59 return array[sorted_idx[percentile_idx]]\n```\n\n当然,如果$w_i$是分数,应该怎么想,我暂时也没有思路。可以参考下维基定义[Weighted median](https://en.wikipedia.org/wiki/Weighted_median),后续有时间,细究下。\n\n### 2. 从GBDT到TreeBoost\n\n#### 2.0 回归决策树\n\n我们先回顾前面的Gradient Boost方法,其训练公式如下:\n\n+ For $m=1$ to $M$ do:\n \n 1. $\\tilde{y} = - \\left [ \\frac{\\partial L (y_i, F(x_i))}{\\partial F(x_i)} \\right ]_{F(x) = F_{m-1}(x)}, \\quad i = 1, 2, \\dotsc, N$\n \n 2. $\\mathbf{a}_m = \\operatorname{arg \\, min}_{\\mathbf{a}, \\beta} \\displaystyle \\sum_{i=1}^N \\left [ \\tilde{y}_i - \\beta h(x_i; \\mathbf{a}) \\right ]^2$\n 3. $\\rho_m = \\operatorname{arg \\, min}_\\rho \\displaystyle \\sum_{i=1}^N L \\left ( y_i, F_{m-1}(x_i) + \\rho h(x_i; \\mathbf{a}_m) \\right)$\n 4. $F_m(x) = F_{m-1}(x) + \\rho_m h(x; \\mathbf{a}_m)$ \n 注意,为了描述方便,我移除了学习率这个乘数。\n\nTreeBoost将外部的寻优参数内化到决策树内部,从而既让模型更精细,又加快了运行速度。而要让外部参数进入到决策树$h(x_i; \\mathbf{a}_m)$,首要的问题是得打开这个函数,即使用解析式来描述。换句话说,我们需要对决策树建立数学模型。\n\n对于$J$个叶子的回归决策树,可以表述为累加式:\n\n\\begin{equation}\n h(x; \\{b_j, R_j\\}_1^J) = \\displaystyle \\sum_{j=1}^J b_j \\, \\mathbf{1}(x \\in R_j) \n\\end{equation}\n\n其中,$R_j$是各叶子,对应叶子的值是此区域的样本均值$b_j = \\operatorname{ave}_{x_i \\in R_j} y_i$。因为各个叶子是没有交集的,所以这个公式的含义等价于:如果$x \\in R_j$,那么$h(x) = b_j$。\n\n我们将回归决策树的数学式代入Gradient Boost中第四步,可得到:\n\n\\begin{align}\n F_m(x) &= F_{m-1}(x) + \\rho_m h(x; \\mathbf{a}_m) \\\\\n &= F_{m-1}(x) + \\rho_M \\displaystyle \\sum_{j=1}^J b_{jm} \\, \\mathbf{1}(x \\in R_{jm}) \\\\\n &= F_{m-1}(x) + \\sum_{j=1}^J \\color{red}{\\rho_M b_{jm}} \\, \\mathbf{1}(x \\in R_{jm}) \\\\\n &= F_{m-1}(x) + \\sum_{j=1}^J \\color{red}{\\gamma_{jm}} \\, \\mathbf{1}(x \\in R_{jm})\n\\end{align}\n\n请注意,最后一步定义$\\gamma_{jm} = \\rho_M b_{jm}$,只是个简单的代数替换。但它的实质是将权重从对整颗树的全局解移动到了对各个叶子的局部解。也就是说,这个权重值更加细化了,以前是对整颗树寻优,现在是针对各个叶子,各自寻优。此时,将定义代入Gradient Boost第三步,就得到局部权重的最优解:\n\n\\begin{equation}\n \\{\\gamma_{jm}\\}_1^J = \\displaystyle \\operatorname{arg \\, min}_{\\{\\gamma_j\\}_1^J} \\sum_{i=1}^N L \\left ( y_i, F_{m-1}(x_i) + \\sum_{j=1}^J \\gamma_j \\mathbf{1}(x \\in R_{jm}) \\right )\n\\end{equation}\n\n又因为各叶子$R_{jm}$是互无交集,相互独立的,上式的最优解就是各叶子各自的最优解汇总,故可简写为:\n\n\\begin{equation}\n \\gamma_{jm} = \\displaystyle \\operatorname{arg \\, min}_{\\gamma} \\sum_{x_i \\in R_{jm}} L(y_i, F_{m-1}(x_i) + \\gamma)\n\\end{equation}\n\n#### 2.1 LAD_TreeBoost\n\n前面已经讨论过,对于损失函数$L(y,F) = |y - F|$,它的最优解是中位值。\n\n故,对于LAD回归,可得:\n\n\\begin{equation}\n \\gamma_{jm} = \\displaystyle \\operatorname{median}_{x_i \\in R_{jm}} \\{ y_i - F_{m-1}(x_i) \\}\n\\end{equation}\n\n综上,可得到LAD_TreeBoost算法如下:\n\n+ $F_0(x) = \\operatorname{median}\\{y_i\\}_1^N$\n+ For $m=1$ to $M$ do:\n 1. $\\tilde{y}_i = \\operatorname{sign}(y_i - F_{m-1}(x_i)), \\, i=1, N$\n 2. $\\{R_{jm}\\}_1^J = \\text{$J$ terminal node tree} \\big (\\{\\tilde{y}_i, x_i\\}_1^N \\big )$\n 3. $\\gamma_{jm} = \\displaystyle \\operatorname{median}_{x_i \\in R_{jm}} \\{ y_i - F_{m-1}(x_i)\\}, \\, j=1, J$\n 4. $F_m(x) = F_{m-1}(x) + \\displaystyle \\sum_{j=1}^J \\gamma_{jm} \\mathbf{1}(x \\in R_{jm})$\n \n对应的sklearn中代码为\n\n```python\n 305 class LeastAbsoluteError(RegressionLossFunction):\n 306 \"\"\"Loss function for least absolute deviation (LAD) regression. \"\"\"\n 307 def init_estimator(self):\n 308 return QuantileEstimator(alpha=0.5)\n 309\n 310 def __call__(self, y, pred, sample_weight=None):\n 311 if sample_weight is None:\n 312 return np.abs(y - pred.ravel()).mean() \n 313 else:\n 314 return (1.0 / sample_weight.sum() *\n 315 np.sum(sample_weight * np.abs(y - pred.ravel())))\n 316\n 317 def negative_gradient(self, y, pred, **kargs): \n 318 \"\"\"1.0 if y - pred > 0.0 else -1.0\"\"\"\n 319 pred = pred.ravel() \n 320 return 2.0 * (y - pred > 0.0) - 1.0\n 321 \n 322 def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,\n 323 residual, pred, sample_weight):\n 324 \"\"\"LAD updates terminal regions to median estimates. \"\"\"\n 325 terminal_region = np.where(terminal_regions == leaf)[0]\n 326 sample_weight = sample_weight.take(terminal_region, axis=0)\n 327 diff = y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0)\n 328 tree.value[leaf, 0, 0] = _weighted_percentile(diff, sample_weight, percentile=50)\n```\n\n其中320L就是第一步的求导,328L就是第三步将树的叶子改为中位值(percentile=50)。\n\n因为$\\tilde{y}_i$只有两种值$\\tilde{y} \\in \\{-1, 1\\}$,又叶子值是取中位数,所以这个损失的鲁棒性非常强。但求解中位数不如平均数有快速方法,所以性能会受影响。\n\n#### 2.2 M-Regression\n\nLS_Boost运行快,LDA_TreeBoost鲁棒性好,能不能将两者结合起来呢?M-Regression的初衷正是来源于此,它用阈值$\\delta$,比如说三倍方差,将$|y-F|$误差分隔成两部份:在阈值内的认定是正常误差,用LS_Boost来约束;在阈值外认定是长尾和坏值,用LDA_TreeBoost来抵抗。通过调整$\\delta$值来控制平衡,从而达到各取其长的好处。\n\n这里具体对的损失函数叫Huber,定义如下:\n\n\\begin{equation}\n L(y, F) = \\begin{cases}\n \\frac{1}{2} (y - F)^2 \\quad & |y - F| \\leq \\delta \\\\\n \\delta \\cdot \\left (\\big |y - F \\big | - \\frac{\\delta}{2} \\right ) \\quad & |y - F| > \\delta \n \\end{cases}\n\\end{equation}\n\n对应的具体取解推导要再参阅论文,如果后面有时间再来填坑。\n\n在sklearn中对应的是HuberLossFunction类。\n\n#### 2.3 二分类逻辑回归树\n\n这里用的损失函数叫negative binomial log-likelihood[3],定义为:\n\n\\begin{equation}\n L(y, F) = \\log (1 + e^{-2 y F}), \\quad y \\in \\{-1, 1\\}\n\\end{equation}\n\n其中$F(x) = \\frac{1}{2} \\log \\left [ \\frac{\\operatorname{Pr}(y = 1 | x)}{\\operatorname{Pr}(y = -1 | x)} \\right ]$\n\n则第一步残差展开为:\n\n\\begin{align}\n \\tilde{y_i} &= - \\left [ \\frac{\\partial L (y_i, F(x_i))}{\\partial F(x_i)} \\right ]_{F(x) = F_{m-1}(x)} \\\\\n &= - \\frac{1}{1 + e^{-2yF}} \\cdot 1 \\cdot e^{-2yF} \\cdot -2y \\\\\n &= 2y \\frac{e^{-2yF}}{1 + e^{-2yF}} \\\\\n &= \\frac{2y}{1 + e^{2yF}} \\\\\n &= \\frac{2 y_i}{1 + e^{2 y_i F_{m-1}(x_i)}} \\\\\n\\end{align}\n\n同样地,第三步寻优代入损失函数,变为:\n\n\\begin{equation}\n \\rho_m = \\displaystyle \\operatorname{arg \\, min}_\\rho \\sum_{i=1}^{N} \\log \\left ( 1 + e^{-2 y_i \\big ( F_{m-1}(x_i) + \\rho h(x_i; \\mathbf{a}_m) \\big )} \\right )\n\\end{equation}\n\n运用前面LAD_Boost的技巧,很容易得到:\n\n\\begin{equation}\n \\gamma_{jm} = \\displaystyle \\operatorname{arg \\, min}_\\gamma \\sum_{x_i \\in R_{jm}} \\log(1 + e^{-2 y_i ( F_{m-1}(x_i) + \\gamma ) })\n\\end{equation}\n\n上式没有封闭形式的解,根据[3],可用一轮最优化中的牛顿迭代法,得到数值解:\n\n\\begin{equation}\n \\gamma_{jm} = \\displaystyle \\sum_{x_i \\in R_{jm}} \\tilde{y}_i \\Big / \\sum_{x_i \\in R_{jm}} |\\tilde{y}_i| (2 - |\\tilde{y}_i|)\n\\end{equation}\n\n这一步推导,我也还没有细看,以后有精力再细究。\n\n这个算法被称为L2_TreeBoost,总结如下:\n\n+ $F_0(x) = \\frac{1}{2} \\log \\frac{1 + \\bar{y}}{1 - \\bar{y}}$\n\n+ For $m=1$ to $M$ do:\n 1. $\\tilde{y}_i = \\frac{2 y_i}{1 + e^{2 y_i F_{m-1}(x_i)}}, \\quad i=1, N$\n 2. $\\{R_{jm}\\}_1^J = \\text{$J$ terminal node tree} \\big (\\{\\tilde{y}_i, x_i\\}_1^N \\big )$\n 3. $\\gamma_{jm} = \\displaystyle \\sum_{x_i \\in R_{jm}} \\tilde{y}_i \\Big / \\sum_{x_i \\in R_{jm}} |\\tilde{y}_i| (2 - |\\tilde{y}_i|), \\quad j=1, J$\n 4. $F_m(x) = F_{m-1}(x) + \\displaystyle \\sum_{j=1}^J \\gamma_{jm} \\mathbf{1}(x \\in R_{jm})$\n \nsklearn中代码如下:\n\n```python\n 106 class LogOddsEstimator(BaseEstimator):\n 107 \"\"\"An estimator predicting the log odds ratio.\"\"\"\n 108 scale = 1.0\n 109\n 110 def fit(self, X, y, sample_weight=None):\n 111 # pre-cond: pos, neg are encoded as 1, 0\n 112 if sample_weight is None:\n 113 pos = np.sum(y)\n 114 neg = y.shape[0] - pos\n 115 else:\n 116 pos = np.sum(sample_weight * y)\n 117 neg = np.sum(sample_weight * (1 - y))\n 118\n 119 if neg == 0 or pos == 0:\n 120 raise ValueError('y contains non binary labels.')\n 121 self.prior = self.scale * np.log(pos / neg)\n 122\n 123 def predict(self, X):\n 124 check_is_fitted(self, 'prior')\n 125\n 126 y = np.empty((X.shape[0], 1), dtype=np.float64)\n 127 y.fill(self.prior)\n 128 return y\n```\n\n注意,这个初始化$F_0$对公式做了点变形。\n\n```python\n 466 class BinomialDeviance(ClassificationLossFunction):\n 467 # \"\"\"Binomial deviance loss function for binary classification.\n 468 #+-- 10 lines: Binary classification is a special case; here, we only need to-------------------------\n 478\n 479 def init_estimator(self):\n 480 return LogOddsEstimator()\n 481\n 482 #+-- 9 lines: def __call__(self, y, pred, sample_weight=None):---------------------------------------\n 491\n 492 def negative_gradient(self, y, pred, **kargs):\n 493 \"\"\"Compute the residual (= negative gradient). \"\"\"\n 494 return y - expit(pred.ravel())\n 495\n 496 def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,\n 497 residual, pred, sample_weight):\n 498 \"\"\"Make a single Newton-Raphson step.\n 499\n 500 our node estimate is given by:\n 501\n 502 sum(w * (y - prob)) / sum(w * prob * (1 - prob))\n 503\n 504 we take advantage that: y - prob = residual\n 505 \"\"\"\n 506 terminal_region = np.where(terminal_regions == leaf)[0]\n 507 residual = residual.take(terminal_region, axis=0)\n 508 y = y.take(terminal_region, axis=0)\n 509 sample_weight = sample_weight.take(terminal_region, axis=0)\n 510\n 511 numerator = np.sum(sample_weight * residual)\n 512 denominator = np.sum(sample_weight * (y - residual) * (1 - y + residual))\n 513\n 514 if denominator == 0.0:\n 515 tree.value[leaf, 0, 0] = 0.0\n 516 else:\n 517 tree.value[leaf, 0, 0] = numerator / denominator\n 518\n 519 def _score_to_proba(self, score):\n 520 proba = np.ones((score.shape[0], 2), dtype=np.float64)\n 521 proba[:, 1] = expit(score.ravel())\n 522 proba[:, 0] -= proba[:, 1]\n 523 return proba\n```\n\n\n[3]: Jerome Friedman - Additive logistic regression: a statistical view of boosting \n\n模型$F_M(x)$输出的分值需要转换成各类的概率值,519L的`_score_to_proba`处理思路来源如下:\n\n通过联理公式,\n\n\\begin{align}\n & F(x) = \\frac{1}{2} \\log \\left [ \\frac{\\operatorname{Pr}(y = 1 | x)}{\\operatorname{Pr}(y = -1 | x)} \\right ] \\\\\n & \\operatorname{Pr}(y = 1 | x) + \\operatorname{Pr}(y = -1 | x) = 1\n\\end{align}\n\n可以容易解得:\n\n\\begin{align}\n & \\operatorname{Pr}(y = 1 | x) = \\frac{1}{1 + e^{-2 F(x)}} \\\\\n & \\operatorname{Pr}(y = -1 | x) = \\frac{1}{1 + e^{2 F(x)}} \\\\\n\\end{align}\n\n因为$F_M(x)$和$F(x)$有关联,我们可以借用上式将分值近似转换成概率值:\n\n\\begin{align}\n p_{+}(x) &= \\operatorname{\\widehat{Pr}}(y = 1 | x) = \\frac{1}{1 + e^{-2 F_M(x)}} \\\\\n p_{-}(x) &= \\operatorname{\\widehat{Pr}}(y = -1 | x) = \\frac{1}{1 + e^{2 F_M(x)}} \\\\\n\\end{align}\n\n用于二分类时,应用如下公式:\n\n\\begin{equation}\n \\hat{y}(x) = 2 \\cdot \\mathbf{1}[c(-1,1) p_{+}(x) > c(1,-1) p_{-}(x)] - 1\n\\end{equation}\n\n其中,$c(\\hat{y}, y)$是将$y$误认为$\\hat{y}$的代价。\n\n回过头来看`score_to_proba`函数,它其实是上式的简化版,并没有$c(\\cdot)$,同时虽然$p_{+}(x)$和$p_{-}(x)$并非真实概率,但相加等于1,所以只算$p_{+}(x)$。\n\n##### Influence trimming\n\n在寻优$\\gamma_{jm}$时,还有优化的空间:\n\n\\begin{align}\n \\gamma_{jm} &= \\displaystyle \\operatorname{arg \\, min}_\\gamma \\sum_{x_i \\in R_{jm}} \\log(1 + e^{-2 y_i ( F_{m-1}(x_i) + \\gamma ) }) \\\\\n &= \\displaystyle \\operatorname{arg \\, min}_\\gamma \\sum_{x_i \\in R_{jm}} \\log(1 + e^{-2 \\color{blue}{y_i F_{m-1}(x_i)}} \\cdot e^{-2 y_i \\gamma} ) \\\\\n &= \\displaystyle \\operatorname{arg \\, min}_\\gamma \\sum_{x_i \\in R_{jm}} \\phi(x_i)\n\\end{align}\n\n注意,上式中,若$y_i F_{m-1}(x_i)$非常大,则对应的$\\phi(x_i) \\to 0$。也就是说,这些样本对寻优不再有贡献。于是,我们可以定义$w_i = e^{-2 y_i F_{m-1}(x_i)}$作为测量函数,如果它的值小于一定阈值,这个样本就不再参与计算。\n\n另外,对于一个$x_i$,其损失函数$L(y, F(x_i))$如果到达极值点,就相当于是常数,对于整体寻优$\\operatorname{arg \\, min} L(y, F(x))$不再有贡献。而判断极值点可以用二阶导数来度量,所以二阶导也能作为一种测量函数。具体到现在的逻辑回归树,就可以定义为:\n\n\\begin{equation}\n w_i = \\frac{\\partial^2 L}{\\partial F^2} = |\\tilde{y}_i| (2 - |\\tilde{y}_i|)\n\\end{equation}\n\n至于这个移除的阈值,可以用比例来约束。即我们定阈值为$w_{l(\\alpha)}$,而$l(\\alpha)$满足:\n\n\\begin{equation}\n \\displaystyle \\sum_{i=1}^{l(\\alpha)} w_{(i)} = \\alpha \\sum_{i=1}^{N} w_i\n\\end{equation}\n\n其中,$w_{(i)}$是按升序排列的权值。典型值$\\alpha \\in [0.05, 0.2]$,也就是说,可以减少10到20倍的计算量。\n\n#### 2.4 多分类逻辑回归树\n\n多分类是二分类的推广,相对而言公式推导比较复杂,不再详述。它的简化,相当于是对每一个类建一个「是、否」的二分类树,最后对每个类逐一评分,输出分值最高的类。`\n\n### 3. 参数与正则\n#### 3.0 Regularization\nlack of fit(LOF):\n+ regression\n - average absolute error\n+ classification\n - minus twice log-likelihood(deviance)\n - misclassification error-rate\n\n两种shrinkage strategy:\n1. 简单:最终模型:$F_\\nu(x) = \\bar{y} + \\nu \\cdot (F_M(x) - \\bar{y})$\n2. 复杂:每个迭代模型:$F_m(x) = F_{m-1}(x) + \\nu \\cdot \\rho_m h(x; \\mathbf{a}_m, \\quad 0 < \\nu \\leq 1$\n\n#### 3.1 Tree boosting的参数 \n\nmeta-parameter:\n\n+ $M$: the number of iterations.\n+ $\\nu$: the learning rate.\n+ $J$: the fixed number of terminal nodes. \n The best tree size $J$ is governed by the effective interaction order of the target $F*(x)$, while it is unknown. $\\to$ cross-validation.\n\n### 4. 可解释性\n理解贡献比较大的变量\n\n#### 4.0 Relative importance of input variables\n\nThe relative influences $I_j$, of the individual inputs $x_j$, on the variation of $\\hat{F}(x)$ over the joint input variable distributation:\n\n\\begin{equation}\n I_j = \\left ( E_x \\left [ \\frac{\\partial \\hat{F}(x)}{\\partial x_j} \\right ]^2 \\cdot \\operatorname{var}_x[x_j] \\right )^{1/2}\n\\end{equation}\n\n据此,Breiman提出了适合于决策树的公式:\n\n\\begin{equation}\n \\hat{I}_j^2(T) = \\displaystyle \\sum_{t=1}^{J-1} \\hat{i}_t^2 \\mathbf{1}(v_t = j)\n\\end{equation}\n\n其中,$v_t$是以$j$作分割特征的中间节点,$\\hat{i}_t^2$是对应节点的Friedman MSE评价$i^2(R_l, R_r) = \\frac{w_l w_r}{w_l + w_r}(\\bar{y}_l - \\bar{y}_r)^2$。\n\n对于多颗树,就加和取平均:\n\n\\begin{equation}\n \\hat{I}^2_j = \\frac{1}{M} \\displaystyle \\sum_{m=1}^M \\hat{I}^2_j (T_m)\n\\end{equation}\n\n这个思路非常朴素,就是计算各特征对决策树评价函数提升的贡献度。在sklearn中实现如下:\n\n```python\n1201 def feature_importances_(self):\n1202 \"\"\"Return the feature importances (the higher, the more important the\n1203 feature).\n1204\n1205 Returns\n1206 -------\n1207 feature_importances_ : array, shape = [n_features]\n1208 \"\"\"\n1209 self._check_initialized()\n1210\n1211 total_sum = np.zeros((self.n_features, ), dtype=np.float64)\n1212 for stage in self.estimators_:\n1213 stage_sum = sum(tree.feature_importances_\n1214 for tree in stage) / len(stage)\n1215 total_sum += stage_sum\n1216\n1217 importances = total_sum / len(self.estimators_)\n1218 return importances\n```\n\n此时,我们也就明白了为什么765L决策树使用的friedman_mse损失函数了。\n\n#### 4.1 Partial dependence plots\n\nPartial dependence主要是用于可视化一维或二维变量对于整体总结果的影响。它的计算思路非常简单,令有特征集合$X_s \\cup X_c = X$,则$f(X_s = x_s) = \\operatorname{Avg}(f(X_s = x_s, X_{ci}))$。也就是对于特定的$x_s$值,算出它的响应均值。\n\n下图是一个示例[sklearn: Partial Dependence Plots](http://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html)。\n\n\n\n对于一维变量,可以看出,房价与Medlin(平均收入)成正比,与AveOccup(每户人均数)成反比,而与HouseAge(房龄)、AveRoom(房间均数)没有明显关系。再看二维变量(HouseAge - AveOccup),对于每户人均数大于2的情况,房龄与房价关系不大;但当人均数小于2时,则出现了相关性。\n\n[ref: Partial Dependency Plots and GBM](http://adventuresindm.blogspot.jp/2013/01/partial-dependency-plots-and-gbm.html)\n\n### 5. 总结\n\n我们先讲了对GBDT框架的优化,再借此拓展到tree boosting方法,然后略微提了正则和调参的参数,最后介绍了两种用于解释特征变量的方法。\n\n本文基本上相当于翻译了论文Friedman - Greedy function approximation: A gradient boosting machine,如果有不明晰的地方,可以直接查看原文。\n\n\n```python\n\n```\n", "meta": {"hexsha": "49c5a2684543a3f75bbad68b864c6c17bb14253b", "size": 182512, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "machine_learning/tree/gbdt/treeboost/intro.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "machine_learning/tree/gbdt/treeboost/intro.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "machine_learning/tree/gbdt/treeboost/intro.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 198.598476605, "max_line_length": 101016, "alphanum_fraction": 0.7872139914, "converted": true, "num_tokens": 12182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111085480195975, "lm_q2_score": 0.12940272487671914, "lm_q1q2_score": 0.05319886483777082}} {"text": "**Table of contents**\n\n* [Parts of Speech](#pos)\n* [Hidden Markov Models](#hmm)\n* [Maximum likelihood estimation for labelled data](#mle)\n* [Implementation](#imp)\n* [Evaluation](#eval)\n * [Perplexity](#ppl)\n * [Viterbi](#viterbi) \n * [Accuracy](#acc)\n\n \n**Table of Exercises**\n\n* Theory (10 points)\n * [Exercise 4-4](#ex4-4)\n * [Exercise 4-5](#ex4-5)\n * [Exercise 4-6](#ex4-6)\n * [Exercise 4-7](#ex4-7)\n * [Exercise 4-8](#ex4-8)\n * [Exercise 4-9](#ex4-9)\n* Practice (30 points) \n * [Exercise 4-1](#ex4-1)\n * [Exercise 4-2](#ex4-2)\n * [Exercise 4-3](#ex4-3)\n * [Exercise 4-10](#ex4-10)\n * [Exercise 4-11](#ex4-11)\n * [Exercise 4-12](#ex4-12)\n\n\n\n**General notes**\n\n* In this notebook you are expected to use $\\LaTeX$. \n* Use python3.\n* Use NLTK to read annotated data.\n* **Document your code**: TAs are more likely to understand the steps if you document them. If you don't, it's also difficult to give you partial points for exercises that are not completely correct.\n\n# Parts of Speech\n \n**Parts of speech** (also known as PoS, word classes) give us information about a word and its neighbors. \nPoS can can be divided into: closed class and open class.\n\nOpen class words (or **content words**) are nouns, verbs, adjectives, and adverbs, where they refer to objects, actions, and features in the world. They are called open class, since there is no limit to what these words are\nnew ones are added all the time (email, website, selfie, etc.).\n\n**Nouns** suchs as proper nouns are names of persons of entitnes: *Regina*, *Colorado*,\nand *IBM*. Other type are common nouns that refer to objects that for exmaple, can be counted (one car) or homogeneus groups (snow, sand).\n\n**Verbs** consists pf actions and processes, like *draw*, *provide*, and *go*.\n\n***Adjectives** include terms for properties or qualities for concepts like age (*old*, *young*), value (*good*, *bad*).\n\n\n\nClosed class words (or **function words**) are pronouns, determiners, prepositions, and connectives. There is a limited number of these.\n\n\n**Prepositions** occur before noun phrases and indicate spatial or temporal relations, for example, *by* the house.\n\nThe PoS are tags that classifiy words. For example in English uses the 36 tags. And these tags are used to manually annotate a wide variety of corpora, the Brown corpus, the Wall Street Journal corpus.\n\nIn this Lab we are going to work with the English [Penn Treebank](https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html) tag set and the annotated corpus.\n\nOur final goal is the task: \n* **Part-of-speech tagging** (tagging for short) is the process of assigning a part-ofspeech tag to each word in an input text.\n\nFirst, we will download the annotated data from [NLTK](https://www.nltk.org/data.html)\n\n\n```python\n# Read annotated corpora with NLTK\n# first download data\nimport nltk\n#nltk.download()\n# it will open a GUI and you have to double click in \"all\" to download \n# this will download different types of annotated corpora\n```\n\n\n```python\nimport sys\nsys.version\n\n```\n\n\n\n\n '3.5.2 (default, Nov 23 2017, 16:37:01) \\n[GCC 5.4.0 20160609]'\n\n\n\nWith NLTK, we load the annotated **Penn Treebank** corpus.\nThis corpus will be used to train and test our PoS taggers. Let's use the last 100 sentences for test.\n\n\n```python\n# inspect PoS from Treebank\n# we use the universal tagset\ntreebank_sents = nltk.corpus.treebank.tagged_sents(tagset='universal')\n\n# we split our corpus on training, dev and test\ntreebank_training = list(treebank_sents[:3000]) \ntreebank_dev = list(treebank_sents[3000:3100])\ntreebank_test = list(treebank_sents[3100:])\nprint(len(treebank_sents))\nprint(len(treebank_training)) \nprint(len(treebank_dev)) # we use 100 sentences/instances for validation\nprint(len(treebank_test)) # we use 814 sentences/instances for test\n```\n\n 3914\n 3000\n 100\n 814\n\n\n\n```python\n# which is the vocabulary?\n# we can inspect the vocabulary of the corpus \nvocabulary = set([w for (w, t) in nltk.corpus.treebank.tagged_words(tagset='universal')])\nprint(len(vocabulary)) # number of words in our corpus\n# we inspect the universal tagset (this is a general mapping becasue each languge use a different tagset.\ntagset = set([t for (w, t) in nltk.corpus.treebank.tagged_words(tagset='universal')])\n\nprint(tagset) # tags/labes used to annotate the word class\n```\n\n 12408\n {'DET', 'ADP', 'CONJ', 'X', 'ADV', 'NOUN', 'ADJ', 'VERB', 'PRON', 'NUM', 'PRT', '.'}\n\n\n\n```python\n# The observations are pairs: (sentence, tags)\n# so we can use this to get just the sentences (when we need them)\ndef extract_sentences(treebank_corpus):\n sentences = []\n for observations in treebank_corpus:\n sentences.append([x for x, c in observations])\n return sentences\n\n# The observations are pairs: (sentence, tags)\n# so we can use this to get just the tags (when we need them)\ndef extract_tags(treebank_corpus):\n tags = []\n for observations in treebank_corpus:\n tags.append([c for x, c in observations])\n return tags\n```\n\n**Exercise 4-1** **[2 points]** \n\n* **[1 point]** Load the PTB corpus and plot the distribution of POS tags. \n* **[1 point]** Do the same for the Brown corpus. \n\n\n\n```python\nimport itertools\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nfrom collections import Counter\n\ndef distribution(corpus):\n count = defaultdict(int)\n tag_list = list()\n for line in corpus:\n sets, tags = zip(*line)\n tag_list.extend(tags)\n count = Counter(tag_list)\n \n plt.bar(range(len(count)), count.values(), align=\"center\")\n plt.xticks(range(len(count)), list(count.keys()))\n plt.title('Tag distribution')\n plt.show()\n\n\ndistribution(treebank_sents)\n```\n\n\n```python\nbrown_sents = nltk.corpus.brown.tagged_sents(tagset='universal')\ndistribution(brown_sents)\n\n```\n\n**Exercise 4-2** **[1 point]** Load the PTB corpus, find out for each POS tag what is the most likely tag that follows it. \n\n\n```python\nimport operator\n\ndef followed_max(corpus):\n follow_count = defaultdict(int)\n for line in corpus:\n sent, tags = zip(*line)\n for i, tag in enumerate(tags):\n # Check if index is in bound else use EoS symbol\n if i < len(tags) - 1:\n next_tag = tags[i + 1]\n else: next_tag = '-EOS-'\n if tag not in follow_count:\n follow_count[tag] = defaultdict(int)\n follow_count[tag][next_tag] += 1\n\n follow_max = {}\n for tag, counts in follow_count.items():\n follow_max[tag] = max(counts.items(), key=operator.itemgetter(1))[0]\n\n return follow_max\n\nprint(\"PTB POS followed max by: \", followed_max(treebank_sents))\nprint(\"Brown POS followed max by: \", followed_max(brown_sents))\n```\n\n PTB POS followed max by: {'DET': 'NOUN', 'ADP': 'DET', 'CONJ': 'NOUN', 'X': 'VERB', 'ADV': 'VERB', 'NOUN': 'NOUN', 'VERB': 'X', 'PRON': 'VERB', 'NUM': 'NOUN', 'PRT': 'VERB', 'ADJ': 'NOUN', '.': '-EOS-'}\n Brown POS followed max by: {'DET': 'NOUN', 'ADP': 'DET', 'CONJ': 'NOUN', 'X': 'X', 'ADV': 'VERB', 'NOUN': '.', 'VERB': 'VERB', 'PRON': 'VERB', 'NUM': 'NOUN', 'PRT': 'VERB', 'ADJ': 'NOUN', '.': '-EOS-'}\n\n\n**Exercise 4-3** **[1 point]** Find the most frequent verb on the PTB and on the Brown corpus.\n\n\n```python\n\ndef max_verb(corpus):\n count = defaultdict(int)\n for line in corpus:\n for w, t in line:\n if t == \"VERB\":\n count[w] += 1\n return max(count.items(), key=operator.itemgetter(1))\n \nverb, c1 = max_verb(treebank_sents)\nverb2, c2 = max_verb(brown_sents)\nprint(\"Most frequent verb in PTB is :\",verb, \" \\nWith count: \", c1)\nprint(\"Most frequent verb in Brown is:\",verb2, \" \\nWith count: \", c2)\n```\n\n Most frequent verb in PTB is : is \n With count: 671\n Most frequent verb in Brown is: is \n With count: 10010\n\n\n# Hidden Markov Models\n\n* How can we learn a PoS tagger given this dataset?\n\nThe Hidden Markov Model **HMM** is a sequence model. A sequence model or sequence classifier is a\nmodel whose job is to assign a label or class to each unit in a sequence, thus mapping\na sequence of observations to a sequence of labels.\n\nFor example, in PoS the HMM will assing a tag to each word in a sentence: \n\n*Mr. Vinken is chairman of Elsevier N.V. the Dutch publishing group.*\n\nThe output of a tagger would look like one of the annotated sentences form the Treeban corpus:\n\n\n```python\nprint(treebank_training[1])\n```\n\n [('Mr.', 'NOUN'), ('Vinken', 'NOUN'), ('is', 'VERB'), ('chairman', 'NOUN'), ('of', 'ADP'), ('Elsevier', 'NOUN'), ('N.V.', 'NOUN'), (',', '.'), ('the', 'DET'), ('Dutch', 'NOUN'), ('publishing', 'VERB'), ('group', 'NOUN'), ('.', '.')]\n\n\nLet's start by defining the **HMM**\n \nWe consider two phenomena:\n* Transition: we move from one \"state\" to another \"state\" where our state is the POS tag\n* Emission: with a certain \"state\" in mind, we generate a certain word\n\nThis means that in the sentence above, for example, we generate\n1. From the state `BoS` (begin of sequence) we generate the state `NOUN`\n2. Then from `NOUN` we generate the word `Mr.`\n3. We then \"forget\" the word we just emitted and use the fact that our current state is `NOUN` to generate the next state, which is again a `NOUN`\n4. From where we then generate `Vinken`\n5. We proceed like that until we exaust both sequences\n\n\nLet us give names to things, let's model the current class with a random variable $C$ and let's use the random variable $C_{\\text{prev}}$ to model the previous category. For the word we will use the random variable $X$.\nBoth $C$ and $C_{\\text{prev}}$ take on values in the enumeration of a tagset containing $t$ tags, that is, $\\{1, \\ldots, t\\}$. $X$ takes on values in the enumeration of a vocabulary containing $v$ words, that is, $\\{1, \\ldots, v\\}$.\n\nThe **transition** distribution captures how our beliefs in a class vary as a function of the previous class. We will use Categorical distributions for that. In fact, for each possible previous class we get a Categorical distribution over the complete set of classes.\n\n\\begin{align}\n(1) \\qquad C \\mid C_{\\text{prev}}=p \\sim \\text{Cat}(\\lambda_1^{(p)}, \\ldots, \\lambda_t^{(p)})\n\\end{align}\n \n\n**Exercise 4-4** **[1 point]** What is the probability value of $P_{C|C_{\\text{prev}}}(c|p)$?\n\n$\\lambda_c^p$\n\n**Exercise 4-5** **[2 points]**\n\n* **[1 point]** How many cpds do we need in order to represent all transition distributions?\n* **[1 point]** What's the representation cost of such a set of distributions? Use [big-O notation](https://en.wikipedia.org/wiki/Big_O_notation).\n\n\n\nFor every tag we have a distribution of length t.\n- $t$\n- $O(t^2)$\n\n\nThe **emission** distribution captures how our beliefs in a word vary as a function of the word's class. We will again use Categorical distributions for that. In fact, for each possible class, we get a Categorical distribution over the complete vocabulary.\n\n\n\\begin{align}\n(2) \\qquad X \\mid C=c \\sim \\text{Cat}(\\theta_1^{(c)}, \\ldots, \\theta_v^{(c)})\n\\end{align}\n \n\n**Exercise 4-6** **[1 point]** What's the probability value of $P_{X|C}(x|c)$?\n\n$\\theta_x^c$\n\n\n**Exercise 4-7** **[2 points]** \n\n* **[1 point]** How many cpds do we need in order to represent all emission distributions? \n* **[1 point]** What's the representation cost of such a set of distributions? Use [big-O notation](https://en.wikipedia.org/wiki/Big_O_notation).\n\n\n\nFor every tag we have a distribution of length v.\n- $t$ \n- $O(vt)$\n\nNow let's turn to the joint distribution $P_{CX|C_{\\text{prev}}}$ over classes and words and let's focus on a single step where we can assume the previous class is already available. Then the model factorises as follows:\n\n\\begin{align}\n(3) \\qquad P_{CX|C_{\\text{prev}}}(x, c | c_{\\text{prev}}) &= P_{C|C_{\\text{prev}}}(c|c_{\\text{prev}}) P_{X|C}(x|c) \n\\end{align}\n\nIt will turn out useful to know what is the marginal distribution $P_{X|C_{\\text{prev}}}$ over words given the previous class --- where we have marginalised the current class out. \n\n\\begin{align}\n(4) \\qquad P_{X|C_{\\text{prev}}}(x| c_{\\text{prev}}) &= \\sum_{c=1}^t P_{CX|C_{\\text{prev}}}(x, c | c_{\\text{prev}}) \\\\\n &= \\sum_{c=1}^t P_{C|C_{\\text{prev}}}(c|c_{\\text{prev}}) \\times P_{X|C}(x|c) \n\\end{align}\n\nNote that Equation (4) starts by simply summing Equation (3) for all possible values of the current class, that is, for $c$ from 1 to $t$.\n\n\n\nOur ultimate goal with the HMM is to assing a probability to a sentence $x_1^n$. For that we need to combine $n$ pairs $(c_i, x_i)$ and marginalise away their history $c_{i-1}$. Doing so yields the **joint probability**:\n\n\\begin{align}\n(5) \\qquad P_{X_1^nC_1^n|N}(x_1^n, c_1^n|n) &= P_{C|C_{\\text{prev}}}(c_1|c_0)P_{X|C}(x_1|c_1)P_{C|C_{\\text{prev}}}(c_2|c_1)P_{X|C}(x_2|c_1)\\cdots P_{C|C_{\\text{prev}}}(c_n|c_{n-1})P_{X|C}(x_n|c_n) \\\\\n &= \\prod_{i=1}^n P(c_i|c_{i-1})P(x_i|c_i)\n\\end{align}\n\n\nWe can get the **marginal probability** of a sentence by summing over all possible values of all possible class variables. This requires summing for each and every $c_i$ from 1 to $t$ as follows:\n\n\\begin{align}\n(6) \\qquad P_{S|N}(x_1^n|n) &= \\sum_{c_1=1}^t \\cdots \\sum_{c_n=1}^t P(c_1|c_0)P(x_1|c_1)P(c_2|c_1)P(x_2|c_1)\\cdots P(c_n|c_{n-1})P(x_n|c_n) \\\\\n&= \\sum_{c_1=1}^t \\cdots \\sum_{c_n=1}^t \\prod_{i=1}^n P(c_i|c_{i-1})P(x_i|c_i)\n\\end{align}\n\nThis looks pretty bad! If we have to enumerate all possible tag sequences, there would be just too many of them. That is, in the first sum, $c_1$ takes 1 of $t$ values, then for each of those values $c_2$ will take 1 of $t$ values, and so on. This leads to $t^n$ different tag sequences. An exponential number of them!!! We will never manage to enumerate them, compute their joint probabilities and then sum them up. \n\nLuckily, it turns out that in the HMM only two variables interact at a time, that is, $c_i$ interacts with $c_{i-1}$, then $c_i$ interacts with $x_i$, thus to characterise the distribution over $x_i$ we only need to know $c_{i-1}$ and $c_i$ --- which Equation (4) also shows. We can simplify Equation (6) by rearranging the sums and products as in Equation (7) below.\n\n\\begin{align}\n(7) \\qquad P_{S|N}(x_1^n|n) &= \\sum_{c_1=1}^t \\cdots \\sum_{c_n=1}^t \\prod_{i=1}^n P(c_i|c_{i-1})P(x_i|c_i) \\\\\n&= \\prod_{i=1}^n \\sum_{c_{i-1}=1}^t \\sum_{c_i=1}^t P(c_i|c_{i-1})P(x_i|c_i)\n\\end{align}\n\nThis is great news because it reveals that to marginalise the tag sequences we only need to scan over the sentence $i=1, \\ldots, n$ and then scan over the possible combinations of two tags from the tagset. \n\n\n**Exercise 4-8** **[3 points]** What is the algorithmic complexity of computing the marginal probability of a sentence in the HMM model? \n\n$O(nt^2)$\nwhere $n$ is the number of words in the sentence and $t$ is the number of tags in the corpus\n\n\nEquation (5) gives us a simple algorithm to assign joint probabilities to sequences of the kind $(c_1^n, x_1^n)$. \nBecause we chose categorical distributions as in Equations (1) and (2), we can say that \n\n\\begin{align}\nP_{CX|C_{\\text{prev}}}(x, c | p) = \\lambda_{c}^{(p)} \\times \\theta_{x}^{(p)}\n\\end{align}\n\nand therefore Equation (5) is simply\n\n\\begin{align}\n(8) \\qquad P_{X_1^nC_1^n|N}(x_1^n, c_1^n|n) &= \\prod_{i=1}^n P(c_i|c_{i-1})P(x_i|c_i) \\\\\n &= \\prod_{i=1}^n \\lambda_{c_i}^{(c_{i-1})} \\times \\theta_{x_i}^{(c_i)}\n\\end{align}\n\nSimilarly, Equation (7) is great because it gives us an algorithm to assign probabilities to sentences. \nIf we now use our parameters to rewrite Equation (7) we get \n\n\\begin{align}\n(9) \\qquad P_{S|N}(x_1^n|n) &= \\prod_{i=1}^n \\sum_{c_{i-1}=1}^t \\sum_{c_i=1}^t P(c_i|c_{i-1})P(x_i|c_i) \\\\\n&= \\prod_{i=1}^n \\sum_{c_{i-1}=1}^t \\sum_{c_i=1}^t \\lambda_{c_i}^{(c_{i-1})} \\times \\theta_{x_i}^{(c_i)}\n\\end{align}\n\n\n\n# Maximum likelihood estimation for labelled data\n \nAs we know by now, MLE for Categorical CPDs is just a matter of counting and dividing.\n\nThe MLE solution for the transition distribution is therefore\n\n\\begin{align}\n(10) \\qquad \\lambda_c^{(p)} = \\frac{\\text{count(p, c)}}{\\text{count}(p)}\n\\end{align}\n\n**Exercise 4-9** **[1 points]** What is the MLE solution for the emission distribution? Note: use the same style as in Equation (10), that is, state the parameter and the solution. \n\n\\begin{align}\n(10) \\qquad \\theta_v^{(c)} = \\frac{\\text{count(c, v)}}{\\text{count}(c)}\n\\end{align}\n\nNow you will **implement** the HMM, this means you will implement *transition distributions*, *emission distributions*, *Laplace smoothing*, *joint probability*, *marginal probability*, and an algorithm for making *predictions*.\n\n# Implementation\n\nHere you will implement a language model based on an HMM POS tagger. \n\n**Exercise 4-10** **[17 points]** \n\nYou will need to complete the skeleton class below. Read it through before coding. Check the documentation for additional information. Document your steps (this will increase your chance of earning points in case you make mistakes along the way). \n\n* **[8 points]** Implement `estimate_model`: this should take an annotated corpus (such as PTB or Brown) and estimate the CPDs in the model using Laplace smoothing. \n* **[2 points]** Implement `transition_parameter`: see method's documentation\n* **[2 points]** Implement `emission_parameter`: see method's documentation\n* **[1 points]** Implement `joint_parameter`: see method's documentation\n* **[2 points]** Implement `log_joint`: see method's documentation\n* **[2 points]** Implement `log_marginal`: see method's documentation\n\nShow that you methods work by training a model and testing a few examples. This is an example \n\n```python\ntreebank_hmm = HMMLM()\ntreebank_hmm.estimate_model(treebank_training)\nprint(treebank_hmm.joint_parameter('DET', 'NOUN', 'book'))\nsentence = [x for x, _ in treebank_dev[0]]\ntag_sequence = [c for _, c in treebank_dev[0]]\nprint(' '.join(sentence))\nprint(' '.join(tag_sequence))\nprint(treebank_hmm.log_joint(sentence, tag_sequence))\n```\n\nfor which we get\n\n```\n9.959527643028553e-05\nAt Tokyo , the Nikkei index of 225 selected issues , which *T*-1 gained 132 points Tuesday , added 14.99 points to 35564.43 .\nADP NOUN . DET NOUN NOUN ADP NUM VERB NOUN . DET X VERB NUM NOUN NOUN . VERB NUM NOUN PRT NUM .\n-193.71018537\n```\n\n\n\n```python\nimport numpy as np\nfrom collections import defaultdict\n\nclass HMMLM:\n \"\"\"\n This is our HMM language model class.\n \n It will be responsible for estimating parameters by MLE\n as well as computing probabilities using the HMM.\n \n We will use Laplace smoothing by default (because we do not want to assign 0 probabilities).\n \n GUIDELINES:\n - by convention we will use the string '-UNK-' for an unknown POS tag\n - and '' for an unknown word\n - don't forget that with Laplace smoothing the unknown symbols have to be in the support of distributions\n - now you will have 2 types of distributions, so you should deal with unknown symbols for both of them\n - we also need padding for sentences and tag sequences, by convention we will use \n - '-BOS-' and '-EOS-' for padding tag sequences\n - '' and '' for padding sentences\n - do recall that '-BOS-' is **not** a valid tag\n in other words we never *generate* '-BOS-' tags, we only pretend they occur at\n the 0th position of the tag sequence in order to provide conditioning context\n for the first actual tag\n - similarly, '' is not a valid word\n in other words, we never *generate* '' as a word\n in fact '' is optional as no emission event is based on it\n - on the other hand, '-EOS-' is a valid tag\n you should model it as the last event of a tag sequence\n - similarly, '' is a valid word\n you should consider it as the last event of a sentence\n \n You can use whatever data structures you like for cpds\n - we suggest python dict or collections.defaultdict\n but you are free to experiment with list and/or np.array if you like\n \"\"\"\n \n def __init__(self, transition_alpha=1.0, emission_alpha=1.0):\n self._vocab = set()\n self._tagset = set()\n self._emission_cpds = dict()\n self._transition_cpds = dict()\n self._transition_alpha = transition_alpha\n self._emission_alpha = emission_alpha\n \n def tagset(self):\n \"\"\"\n Return the tagset: a set of all tags seen by the model (including '-UNK-').\n \n You can modify this if you judge necessary (for example, because you decided to \n use different datastructures, but do note that we provide you an implementation\n of the Viterbi algorithm that expects this functionality). \n \"\"\" \n # the -BOS- tag is just something for internal representation\n # in case you have added it to the tagset, we are removing it here\n # as keeping it would be bad for algorithms such as Viterbi\n # the -UNK- tag must be in the support (due to Laplace smoothing)\n # thus in case you forgot it, we are adding it now\n return self._tagset - {'-BOS-'} | {'-UNK-'}\n \n def addTag(self, tag):\n \"\"\"\n Adds a tag to the tagset variable\n \"\"\"\n self._tagset.add(tag)\n \n def vocab(self):\n \"\"\"\n Return the vocabulary of words: all words seen by the model (including '').\n \n You can modify this if you judge necessary (for example, because you decided to \n use different datastructures, but do note that we provide you an implementation\n of the Viterbi algorithm that expects this functionality). \n \"\"\" \n # the token is just something for internal representation\n # in case you have added it to the vocabulary, we are removing it here\n # the word must be in the support (due to Laplace smoothing)\n # thus in case you forgot it, we are adding it now\n return self._vocab - {''} | {''}\n \n def addWord(self, word):\n \"\"\"\n Adds a word to the vocab variable\n \"\"\"\n \n self._vocab.add(word)\n \n def preprocess_sentence(self, sentence, bos=True, eos=True):\n \"\"\"\n Preprocess a sentence by lowercasing its words and possibly padding it.\n \n :param sentence: a list of tokens (each a string)\n :param bos: if True you will get at the beginning \n :param eos: if True you will get at the end\n :returns: a list of tokens (lowercased strings)\n \"\"\"\n # lowercase\n sentence = [x.lower() for x in sentence]\n # optional padding\n if bos: \n sentence = [''] + sentence\n if eos:\n sentence = sentence + ['']\n return sentence\n \n def preprocess_tag_sequence(self, tag_sequence, bos=True, eos=True):\n \"\"\"\n Preprocess a tag sequence with optional padding.\n \n :param tag_sequence: a list of tags (each a string)\n :param bos: if True you will get -BOS- at the beginning \n :param eos: if True you will get -EOS- at the end\n :returns: a list of tokens \n \"\"\"\n # optional padding\n if bos:\n tag_sequence = ['-BOS-'] + tag_sequence\n if eos:\n tag_sequence = tag_sequence + ['-EOS-']\n return tag_sequence\n \n def estimate_model(self, treebank):\n \"\"\"\n :param treebank: a sequence of observations as provided by nltk\n each observation is a list of pairs (x_i, c_i) \n and they have not yet been pre-processed \n \n Estimate the model parameters.\n \n This method does not have to return anything, it simply computes the necessary cpds. \n \"\"\"\n \n # Create count table for emission and transition(defaultdict(int))\n emis_count_table = {'-UNK-' : {'': 0}}\n tran_count_table = {'-UNK-' : {'-UNK-': 0}}\n \n print(\"Start counting\")\n for i, tag_sent in enumerate(treebank):\n # Preprocess the sentence and tag_sequence\n sentence, tags = map(list, zip(*tag_sent))\n sentence = self.preprocess_sentence(sentence)\n tags = self.preprocess_tag_sequence(tags)\n \n # Fill count tables\n for i, word in enumerate(sentence[1:], 1):\n tag = tags[i]\n tag_prev = tags[i-1]\n \n # Add word to tag emission_count: P(word|tag)\n if tag not in emis_count_table:\n emis_count_table[tag] = defaultdict(int)\n emis_count_table[tag][word] += 1\n if '' not in emis_count_table[tag]:\n emis_count_table[tag][''] = 0\n \n # Add tag to prevtag in transition_count: P(tag|tag_prev)\n if tag_prev not in tran_count_table:\n tran_count_table[tag_prev] = defaultdict(int)\n tran_count_table[tag_prev][tag] += 1\n if '-UNK-' not in tran_count_table[tag_prev]:\n tran_count_table[tag_prev]['-UNK-'] = 0\n \n # Add tag and word to tagset andd vocab\n self.addTag(tag)\n self.addWord(word)\n \n print(\"Start calculating cpd's\")\n # Parse count tables and convert them to CPD's\n for i, (tag, word_count) in enumerate(emis_count_table.items()):\n print('.', end='')\n self._emission_cpds[tag] = defaultdict(float)\n total_count = sum(word_count.values())\n for word, count in word_count.items():\n prob = (float(count) + self._emission_alpha) / \\\n (total_count + self._emission_alpha * len(self.vocab()))\n self._emission_cpds[tag][word] = prob\n\n for tag_prev, tag_count in tran_count_table.items():\n self._transition_cpds[tag_prev] = defaultdict(float)\n total_count = sum(tag_count.values())\n \n for tag, count in tag_count.items():\n prob = (float(count) + self._transition_alpha) / \\\n (total_count + self._transition_alpha * len(self.tagset()))\n self._transition_cpds[tag_prev][tag] = prob\n \n print(\"\\nFinished cpd's\")\n \n def transition_parameter(self, previous_tag, current_tag):\n \"\"\"\n This method returns the transition probability for tag given the previous tag.\n \n Tips: do not forget that we have a smoothed model, thus \n - if the either tag was never seen, you should pretend it to be '-UNK-'\n \n :param previous_tag: the previous tag (str)\n :param current_tag: the current tag (str)\n :return: transition parameter\n \"\"\"\n if previous_tag not in self._transition_cpds:\n previous_tag = '-UNK-'\n if current_tag not in self._transition_cpds[previous_tag]:\n current_tag = '-UNK-'\n return self._transition_cpds[previous_tag][current_tag] \n \n def emission_parameter(self, tag, word):\n \"\"\"\n This method returns the emission probability for a word given a tag.\n Tips: do not forget that we have a smoothed model, thus \n - if the tag was never seen, you should pretend it to be '-UNK-'\n - similarly, if the word was never seen, you shoud pretend it to be ''\n \n :param tag: the current tag (str)\n :param word: the current word (str)\n :return: the emission probability\n \"\"\"\n if tag not in self._emission_cpds:\n tag = '-UNK-'\n if word not in self._emission_cpds[tag]:\n word = ''\n return self._emission_cpds[tag][word]\n \n def joint_parameter(self, previous_tag, current_tag, word):\n \"\"\"\n This method returns the joint probability of (current tag, word) given the previous tag\n according to Equation (3)\n \n :param previous_tag: the previous tag (str)\n :param current_tag: the current tag (str)\n :param word: the current word (str)\n :returns: P(word, current_tag|previous_tag)\n \"\"\"\n pcp = self.transition_parameter(previous_tag, current_tag)\n pxc = self.emission_parameter(current_tag, word)\n return pcp * pxc\n \n def marginal_x_given_cprev(self, previous_tag, word):\n \"\"\"\n Return P(x|prev) as defined in Equation (4) by marginalising current tag.\n \n :param previous_tag: the previous tag (str)\n :param word: the current word (str)\n \"\"\"\n return np.sum([self.joint_parameter(previous_tag, c, word) for c in self._tagset])\n \n def log_joint(self, sentence, tag_sequence):\n \"\"\"\n Implement the logarithm of the joint probability over a sentence and tag sequence as in Equation (8)\n \n :param sentence: a sequence of words (each a string) not yet preprocessed\n :param tag_sequence: a sequence of tags (eac a string) not yet preprocessed\n :returns: log P(x_1^n, c_1^n|n) as defined in Equation (8)\n \"\"\" \n sentence = self.preprocess_sentence(sentence)\n tag_sequence = self.preprocess_tag_sequence(tag_sequence)\n \n joint_prob = 0\n for i, word in enumerate(sentence[1:], 1):\n tag = tag_sequence[i]\n prev_tag = tag_sequence[i - 1]\n joint_prob += np.log(self.joint_parameter(prev_tag, tag, word))\n return joint_prob\n \n def log_marginal(self, sentence):\n \"\"\"\n Implement the logarithm of the marginal probability of a sentence as in Equation (9)\n by marginalisation of all possible tag sequences. \n \n :param sentence: a sequence of words (each a string) not yet preprocessed\n :returns: log P(x_1^m|n) as defined in Equation (9)\n \"\"\"\n sentence = self.preprocess_sentence(sentence)\n \n return sum([np.log(sum([self.marginal_x_given_cprev(p,w) for p in self.tagset()])) for w in sentence])\n```\n\n\n```python\ntreebank_hmm = HMMLM()\ntreebank_hmm.estimate_model(treebank_training)\n\nprint(treebank_hmm.joint_parameter('DET', 'NOUN', 'book'))\nsentence, tag_sequence = map(list, zip(*treebank_dev[0]))\nprint(' '.join(sentence))\nprint(' '.join(tag_sequence))\nprint(treebank_hmm.log_joint(sentence, tag_sequence))\nprint(treebank_hmm.log_marginal(sentence))\n\n```\n\n Start counting\n Start calculating cpd's\n ..............\n Finished emission cpd's\n ..............\n Finished transition cpd's\n 9.959527643028553e-05\n At Tokyo , the Nikkei index of 225 selected issues , which *T*-1 gained 132 points Tuesday , added 14.99 points to 35564.43 .\n ADP NOUN . DET NOUN NOUN ADP NUM VERB NOUN . DET X VERB NUM NOUN NOUN . VERB NUM NOUN PRT NUM .\n -193.71018536983053\n -123.19211447683843\n\n\n\n```python\nprint(treebank_hmm.joint_parameter('DET', 'VERB', 'cat'))\n\n```\n\n 7.062115274614483e-06\n\n\n# Evaluation\n \nWe can evaluate our models by the computing the log-perplexity, like with the LM or by comparing the predictions of the trained model with an annotated test set.\n\n\n## Perplexity\n\nPerplexity of a model on a test set is the inverse probability of the test set, normalized\nby the number of words. Perplexity is a notion of average branching factor, thus a model with low perplexity can be thought of as a *less confused*. That is, each time it introduces a word given some history it picks from a reduced subset of the entire vocabulary (in other words, it is more certain of how to continue). \n\nIf a dataset contains $t$ tokens where $t = \\sum_{k=1}^m n_k$, then the perplexity of the dataset is\n\n\\begin{equation}\n(11) \\qquad \\text{PP}(\\mathcal T) = \\left( \\prod_{k=1}^m P_{S|N}(\\langle x_1^{(k)}, \\ldots, x_{n_k}^{(k)} \\rangle|n_k; \\boldsymbol \\theta) \\right)^{-1/t}\n\\end{equation}\n\nwhere we have already discarded the length distribution (since it's held constant across models). And the probability of the sentence requires marginalising tag sequences, as shown in Equation (9).\n\nIt's again convenient to use log and define log-perplexity\n\n\\begin{equation}\n(12) \\qquad \\log \\text{PP}(\\mathcal T) = - \\frac{1}{t} \\sum_{k=1}^m \\log P_{S|N}(\\langle x_1^{(k)}, \\ldots, x_{n_k}^{(k)} \\rangle|n_k; \\boldsymbol \\theta) \n\\end{equation}\n\nYou can compare models in terms of the log-perplexity they assign to the same test data. The lower the perplexity, the better the model is.\n\n**Exercise 4-11** **[4 points]** Implement `log_perplexity` below. Train models of PTB and Brown and test both of them on their respective test sets as well as on each other's test set. Report all results.\n\nTo help you have an idea whether you implemented it right, this is an excerpt of what we got with our implementation\n\n```python\ndev_sentences = extract_sentences(treebank_dev)\nlog_perplexity(dev_sentences, treebank_hmm)\n```\n\n```\n101.80708039918399\n```\n\nBy the way, this is how you load the Brown corpus. Let's use the last 1000 sentences for test. You can reduce the size of the training set if your computer cannot handle what we suggest below.\n\n\n```python\n# load the Brown corpus wiht the universal tag set\nbrown_sentences = nltk.corpus.brown.tagged_sents(tagset='universal')\n\n# we split our corpus on training, dev and test\nbrown_training = list(brown_sentences[:56000]) \nbrown_dev = list(brown_sentences[56000:56340])\nbrown_test = list(brown_sentences[56340:])\nprint(len(brown_sentences), len(brown_training), len(brown_dev), len(brown_test))\n```\n\n 57340 56000 340 1000\n\n\n\n```python\ndef log_perplexity(sentences, hmm):\n \"\"\"\n For a dataset of sentences (each sentence is a list of words)\n and an instance of the HMMLM class\n return the log perplexity as defined in Equation (12)\n \"\"\"\n \n t = sum([len(s) + 2 for s in sentences])\n return -1.0 / t * sum([hmm.log_marginal(s) for s in sentences])\n```\n\n\n```python\ndev_sentences = extract_sentences(treebank_dev)\nprint(log_perplexity(dev_sentences, treebank_hmm))\n\nbrown_hmm = HMMLM()\nbrown_hmm.estimate_model(brown_training)\n\nbrown_dev_sentences = extract_sentences(brown_dev)\nprint(log_perplexity(brown_dev_sentences, brown_hmm))\n```\n\n 4.689496628253122\n Start counting\n Start calculating cpd's\n ..............\n Finished emission cpd's\n ..............\n Finished transition cpd's\n 4.668776756438641\n\n\n## Viterbi\n\n\nThe Viterbi algorithm is used to search through the space of possible tag sequences and find the one that score highest.\n\nThe space of tag sequences is very large, consider that we can select any of $t$ tags for each position, thus by simple counting, we are left with $t^n$ possible sequences. Searching through an exponential space is intractable in general. \n\nNot by chance we designed the HMM with certain conditional independence assumptions. In fact, in our HMM model the probability of each word observation really only depends on two decisions, namely, its tag and its preceding tag. We can use that to derive a *tractable* dynamic program. \n\n[Dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) is a kind of *divide and conquer* strategy. We have to identify sub-problems that we can solve efficiently and maintain a memory of partial solutions that we use to build the final one.\n\nFor the Viterbi algorithm we need to solve the problem \"what is the best probability so far\". We will approach this problem with a recursion that computes the probability of the best path of a certain length.\nWe will use the recursive function $\\alpha(i, j)$ which returns the best probability for a path of length $i$ assuming that its last tag is $C_i=j$. For efficiency in our implementation we will map tags to integers.\n\nThe Viterbi recursion is pretty simple, if a path has length $0$ we will assume it has probability $1$. If a path has length $i$ (more than $0$), we reckon that its maximum probability is based on the maximum probability assigned to paths of size $i-1$, where we extend those paths with one steps and check which step yields the best probability.\n\nThe Viterbi recursion is formalised below:\n\n\\begin{align}\n(13)\\qquad \\alpha(i, j) &= \n\\begin{cases}\n1 & \\text{if }i = 0 \\\\\n\\max_{p \\in \\{1, \\ldots, t\\}} \\alpha(i-1, p) \\times \\lambda_{j}^{p} \\times \\theta_{x_i}^{j} & \\text{otherwise}\n\\end{cases}\n\\end{align}\n\nNote that in the second line, we look for paths of size $i-1$ (which my have ended in one of $t$ possible previous tags) and we try to extend them with tag $j$. The probability of each hypothetical extension is the probability of the path we mean to extend $\\alpha(i-1, p)$ times the joint parameters associated with the extension. That is, continuing from previous class $C_{i-1}=p$ with current class $C_i=j$ (that is a transition parameter), and generating the current word $X_i=x_i$ from the current class $C_i=j$ ( that is an emission parameter).\n\nNote that the recursive function takes 2 inputs, $i$ which ranges from 1 to $n$, and $j$ which ranges from 1 to $t$. Thus we need to make at most $nt$ calls to this function. But also note that each time we call it, we have to solve (in the second line) a maximisation over $t$ possible assignments of the previous tag. Therefore the overall complexity of the algorithm is $O(nt^2)$. That's quite an improvement from $O(t^n)$, isn't it?\n\nOf course, crucial to the success of the algorithm is that we use [memoization](https://en.wikipedia.org/wiki/Memoization), a technique by which we store partial solutions and never recompute things.\n\nWe provide you with a **recursive** implementation of the Viterbi algorithm which uses the interface of the HMMLM class that you designed above. You can use this implementation if you want to experiment with PTB and Brown corpus in the exercises below. Read the implementation carefully to learn from it. We have provided extensive documentation.\nOne important note is that we compute everything in log space, that's to rely on better numerical properties of log probabilities.\n\nThe Viterbi recursion gives us a way to compute the *probability* of the best path. To find the actual best path we just need to traverse the table of $\\alpha(i, j)$ values looking for the decision (tag) that is best at each point.\n\n\n\n```python\ndef viterbi_recursion(sentence, hmm):\n \"\"\"\n Computes the best possible tag sequence for a given input\n and also returns it log probability.\n \n This implementation uses recursion.\n \n :returns: tag sequence, log probability\n \"\"\"\n # here we pad the sentence with only\n sentence = hmm.preprocess_sentence(sentence, bos=False, eos=True)\n # this is the length (but recall that padding added 1 token) \n n = len(sentence)\n # this is the complete tagset, which for convenience we will turn into a list\n tagset = list(hmm.tagset())\n t = len(tagset)\n # We need a table to store log alpha(i, j) values\n # - where i is an integer from 0 to n-1 which refers to a position in the list `sentence`\n # i.e. sentence[i]\n # - and j is an integer from 0 to t-1 that refers to a tag in the list `tagset` \n # i.e. tagset[j] \n # - together (i, j) means that we are setting `C_i = tagset[j]` \n # - we will be exploring the space of possible tags per position\n # thus our table has as many as n * t cells\n # - Recall that the value \\log \\alpha(i, j)\n # corresponds to the log probability value of the best\n # path (C_1, ..., C_i) such that C_i = j\n # in other words the log probability of the best sequence up to the ith token where C_i = j\n # At the beginning path probabilities have not been computed, we use a probability of 0 to indicate that\n # as we will be computing log probabilities, we use -inf instead\n # numpy arrays are very handy and we can actually use the quantity -inf\n log_alpha_table = np.full([n, t], -float('inf'))\n # In a best path algorithm we are interested in two things\n # the best score (or best log probability)\n # as well as the path that corresponds to the best score\n # We compute the best score by moving i forward from 0 to n-1 computing the maximum value \n # and we traverse the table backwards following the path that led to the maximum\n # thus we create a table of \"back pointers\"\n # this is an integer for each cell (i, j) that tells us which tag `p` for position `i - 1`\n # leads to the score stored in `log_alpha_table[i, j]`\n back_pointer_table = np.full([n, t], -1, dtype=int)\n\n # Here we define the log alpha recursion\n def log_alpha(i, j):\n \"\"\"\n This function returns\n max_{c_1, ..., c_i=j} log P(c_1, ..., c_i=j) \n where i is a (0-based) position in `sentence`\n and j is a (0-based) position in `tagset`\n \"\"\"\n if i == 0: # we do not need to tag the 0th position and it should not affect the probability\n return 0. # np.log(1)\n # When we implement dynamic programs, we like to re-use computations already made\n # thus first of all we test if we have already computed a value for this cell\n # if so, it will not have a zero probability (-inf in log space)\n if log_alpha_table[i, j] != -float('inf'): \n # then we can simply return it\n return log_alpha_table[i, j]\n # At this point we know we have not yet computed a score for this path\n # thus we proceed to compute it\n # We will have to figure out the log prob of the best prefix\n # and which tag best continues from it\n # There are exactly t classes that may tag this position\n # thus we just go over the tagset trying one at a time\n # and memorise the score we would have if we would select them\n path_max_log_prob = np.full(t, -float('inf'))\n for p in range(t):\n # this is the essential part of the recursion\n # we ask for the best score associated with the previous position \n # had it been tagged with p\n # and we incorporate the probability of C_i = tagset[j] given that C_{i-1} = tagset[p]\n # as well as the probability of X_i = sentence[i] given that C_i = tagset[j]\n path_max_log_prob[p] = log_alpha(i - 1, p) + np.log(hmm.joint_parameter(tagset[p], tagset[j], sentence[i]))\n # From all possibilities, we are only interested in the best\n log_alpha_table[i, j] = np.max(path_max_log_prob)\n # and we also want to store a pointer to the best\n back_pointer_table[i, j] = np.argmax(path_max_log_prob)\n return log_alpha_table[i, j]\n \n # Let's get the index associated with -EOS-\n # which is the tag for the symbol in sentence[-1]\n eos_index = tagset.index('-EOS-')\n # We want the last word in the sentence () to have the tag -EOS-\n # thus we ask \"what's the probability of the best path that ends in -EOS-?\"\n max_log_prob = log_alpha(n - 1, eos_index)\n \n # Here we retrieve the backpointers for the best analysis\n # the best analisys has n tags\n bwd_argmax = [None] * n\n # the last tag is the -EOS- symbol\n bwd_argmax[-1] = eos_index\n # Here we maintain the \"current tag\" c_i\n c_i = eos_index\n for i in range(n - 1, 0, -1): # we go backwards from c_{n-1} to c_1\n # and set the value of c_{i-1} for the current c_i\n bwd_argmax[i - 1] = back_pointer_table[i, c_i]\n # we need, of course, to update c_i\n c_i = bwd_argmax[i - 1]\n \n # Here we translate from ids back to actual tags (strings)\n # we leave the -EOS- symbol out, since it was just a convenience \n # and return both the tag sequence and the total log probability\n return [tagset[c] for c in bwd_argmax[:-1]], max_log_prob\n```\n\n\n```python\n# let's tag a sentence\nviterbi_path, viterbi_log_prob = viterbi_recursion(['i', 'wish', 'i', 'had', 'a', 'book', '.'], treebank_hmm)\nprint(viterbi_path, viterbi_log_prob)\n```\n\n ['PRON', 'VERB', 'PRON', 'VERB', 'DET', 'NOUN', '.'] -42.817371568242855\n\n\n## Accuracy\n\nWe can evaluate the performance of our tagger by comparing its Viterbi predictions to human annotation. \n\nFor this, we will use the gold standard test data (e.g. treebank_test). Evaluation metrics compute a score for a given model (e.g. our HMM tagger) by comparing the predicted labels that the model generated with the test data againts the gold standard annotation.\n\nThe **Accuracy** metric computes the percentage of instances in the test data that our tagger labeled correctly.\nIf we have a dataset of $m$ labelled sequences\n\\begin{equation}\n\\left( \\langle x_1^{(k)}, \\ldots, x_{n_k}^{(k)}\\rangle, \\langle \\star_1^{(k)}, \\ldots, \\star_{n_k}^{(k)}\\rangle \\right)_{k=1}^m\n\\end{equation}\nwe can produce all Viterbi predictions\n\\begin{equation}\n\\left( \\langle x_1^{(k)}, \\ldots, x_{n_k}^{(k)}\\rangle, \\langle c_1^{(k)}, \\ldots, c_{n_k}^{(k)}\\rangle \\right)_{k=1}^m\n\\end{equation}\n\nand compute\n\n\\begin{align}\n(14)\\qquad \\text{accuracy} &= \\frac{\\sum_{k=1}^m \\sum_{i=1}^{n_k} [c_i^{(k)} = \\star_i^{(k)}]}{\\sum_{k=1}^m n_k}\\\\\n&= \\frac{\\text{number of correct predictions}}{\\text{total tokens}} \n\\end{align}\n\n\n\n**Exercise 4-12** **[5 points]** \n\n* **[1 point]** Implement the accuracy function.\n* **[1 point]** Compute accuracy on PTB's test set using a PTB-trained model\n* **[1 point]** Compute accuracy on PTB's test set using a Brown-trained model\n* **[1 point]** Compute accuracy on Brown's test set using a PTB-trained model\n* **[1 point]** Compute accuracy on Brown's test set using a Brown-trained model\n\nFor this exercise you can use the Viterbi implementation we provided (or your own -- its up to you). With our own implementation we got $0.8446$ accuracy for PTB-training and PTB-test, and $0.8960$ for Brown-training and Brown-test.\n\n\n```python\ndef accuracy(gold_sequences, pred_sequences):\n \"\"\"\n Return percentage of instances in the test data that our tagger labeled correctly.\n \n :param gold_sequences: a list of tag sequences that can be assumed to be correct\n :param pred_sequences: a list of tag sequences predicted by Viterbi \n \"\"\"\n count_correct, count_total = 0, 0\n for i, combined in enumerate(zip(pred_sequences, gold_sequences)):\n for p, g in list(zip(*combined)):\n if p == g:\n count_correct += 1\n count_total += 1\n if count_total:\n return count_correct / count_total\n return None\n\ndef predict_corpus(test_set, hmm):\n \"\"\"\n Returns viterbi predictions for all sentences in a given corpus\n \n :param test_set: A corpus of tagged sentences\n :param hmm : A language model\n \"\"\"\n gold_sequences, pred_sequences = list(), list()\n print('Making predictions', end='')\n for i, sequence in enumerate(test_set):\n if i % round(len(test_set) / 10) == 0:\n print('.', end='')\n sentence , tags = map(list, zip(*sequence))\n viterbi_tags, _ = viterbi_recursion(sentence, hmm)\n gold_sequences.append(tags)\n pred_sequences.append(viterbi_tags)\n return gold_sequences, pred_sequences\n \n\nprint(\"PTB -> PTB accuracy: \",round(accuracy(*predict_corpus(treebank_test, treebank_hmm)),4))\nprint(\"PTB -> Brown accuracy: \",round(accuracy(*predict_corpus(treebank_test, brown_hmm)),4))\nprint(\"Brown -> PTB accuracy: \",round(accuracy(*predict_corpus(brown_test, treebank_hmm)),4))\nprint(\"Brown -> Brown accuracy: \",round(accuracy(*predict_corpus(brown_test, brown_hmm)),4))\n \n\n```\n", "meta": {"hexsha": "fae384d83f8a208d14df446896579183c7e227a1", "size": 81918, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lab4/Lab4.ipynb", "max_stars_repo_name": "HarmlessHarm/ntmi", "max_stars_repo_head_hexsha": "16fcb4907efe9af5ce271f36065ab121edcdd308", "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": "Lab4/Lab4.ipynb", "max_issues_repo_name": "HarmlessHarm/ntmi", "max_issues_repo_head_hexsha": "16fcb4907efe9af5ce271f36065ab121edcdd308", "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": "Lab4/Lab4.ipynb", "max_forks_repo_name": "HarmlessHarm/ntmi", "max_forks_repo_head_hexsha": "16fcb4907efe9af5ce271f36065ab121edcdd308", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.8516949153, "max_line_length": 9544, "alphanum_fraction": 0.6577186943, "converted": true, "num_tokens": 13029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.1645164608483867, "lm_q1q2_score": 0.05222184579480447}} {"text": "```python\n%matplotlib inline\n```\n\n\n강화 학습 (DQN) 튜토리얼\n=====================================\n**Author**: `Adam Paszke `_\n **번역**: `황성수 `_\n\n\n이 튜토리얼에서는 `OpenAI Gym `__ \nCartPole-v0 태스크의 DQN (Deep Q Learning) 에이전트를 학습하는데\nPyTorch를 사용하는 방법을 보여드립니다.\n\n**태스크**\n\n에이전트는 연결된 막대가 똑바로 서 있도록 카트를 왼쪽이나 오른쪽으로 \n움직이는 두 가지 동작 중 하나를 선택해야합니다. \n다양한 알고리즘과 시각화 기능을 갖춘 공식 순위표를 \n`Gym website `__ 에서 찾을 수 있습니다.\n\n.. figure:: /_static/img/cartpole.gif\n :alt: cartpole\n\n cartpole\n\n에이전트가 현재 환경 상태를 관찰하고 행동을 선택하면 \n환경이 새로운 상태로 *전환* 되고 작업의 결과를 나타내는 보상도 반환됩니다. \n이 태스크에서는 막대가 지나치게 떨어지면 환경이 종료됩니다.\n\n카트폴 태스크는 에이전트에 대한 입력이 환경 상태(위치, 속도 등)를 나타내는 \n4개의 실제 값이 되도록 설계되었습니다. 그러나 신경망은 순수하게 그 장면을 보고\n태스크를 해결할 수 있습니다 따라서 카트 중심의 화면 패치를 입력으로 사용합니다.\n이 때문에 우리의 결과는 공식 순위표의 결과와 직접적으로 비교할 수 없습니다. \n우리의 태스크는 훨씬 더 어렵습니다.\n불행히도 모든 프레임을 렌더링해야되므로 이것은 학습 속도를 늦추게됩니다.\n\n엄밀히 말하면, 현재 스크린 패치와 이전 스크린 패치 사이의 차이로 상태를 표시 할 것입니다.\n이렇게하면 에이전트가 막대의 속도를 한 이미지에서 고려할 수 있습니다.\n\n**패키지**\n\n먼저 필요한 패키지를 가져옵니다. 첫째, 환경을 위해 \n`gym `__ 이 필요합니다.\n(`pip install gym` 을 사용하여 설치하십시오).\n또한 PyTorch에서 다음을 사용합니다:\n\n- 신경망 (``torch.nn``)\n- 최적화 (``torch.optim``)\n- 자동 미분 (``torch.autograd``)\n- 시각 태스크를 위한 유틸리티들 (``torchvision`` - `a separate\n package `__).\n\n\n\n\n\n```python\nimport gym\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nfrom itertools import count\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\n\n\nenv = gym.make('CartPole-v0').unwrapped\n\n# matplotlib 설정\nis_ipython = 'inline' in matplotlib.get_backend()\nif is_ipython:\n from IPython import display\n\nplt.ion()\n\n# GPU를 사용할 경우\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n```\n\n재현 메모리(Replay Memory)\n-------------------------------\n\n우리는 DQN 학습을 위해 경험 재현 메모리를 사용할 것입니다.\n에이전트가 관찰한 전환(transition)을 저장해고 나중에 이 데이터를 \n재사용 할 수 있습니다. 무작위로 샘플링하면 배치를 구성한는 전환들이\n비상관(decorrelated)하게 됩니다. 이것이 DQN 학습 절차를 크게 안정시키고\n향상시키는 것으로 나타났습니다.\n\n이를 위해서 두개의 클래스가 필요합니다:\n\n- ``Transition`` - 우리 환경에서 단일 전환을 나타내도록 명명된 튜플\n- ``ReplayMemory`` - 최근 관찰된 전이를 보관 유지하는 제한된 크기의 순환 버퍼.\n 또한 학습을 위한 전환의 무작위 배치를 선택하기위한\n ``.sample ()`` 메소드를 구현합니다.\n\n\n\n\n\n```python\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward'))\n\n\nclass ReplayMemory(object):\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n \"\"\"전환 저장\"\"\"\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(*args)\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def __len__(self):\n return len(self.memory)\n```\n\n이제 모델을 정의합시다. 그러나 먼저 DQN이 무엇인지 간단히 요약해 보겠습니다.\n\nDQN 알고리즘\n-------------\n\n우리의 환경은 결정론적이므로 여기에 제시된 모든 방정식은 단순화를 위해\n결정론적으로 공식화됩니다. 강화 학습 자료은 환경에서 확률론적 전환에 \n대한 기대값(expectation)도 포함 할 것입니다.\n\n우리의 목표는 할인된 누적 보상 (discounted cumulative reward)을 \n극대화하려는 정책(policy)을 학습하는 것입니다.\n$R_{t_0} = \\sum_{t=t_0}^{\\infty} \\gamma^{t - t_0} r_t$, 여기서\n$R_{t_0}$ 는 *반환(return)* 입니다. 할인 상수,\n$\\gamma$, 는 $0$ 과 $1$ 의 상수이고 합계가 \n수렴되도록 보장합니다. 에이전트에게 불확실한 먼 미래의 보상이\n가까운 미래의 것에 비해 덜 중요하게 만들고, 이것은 상당히 합리적입니다.\n\nQ-learning의 주요 아이디어는 만일 함수 $Q^*: State \\times Action \\rightarrow \\mathbb{R}$ 를\n가지고 있다면 반환이 어덯게 될지 알려줄 수 있고, \n만약 주어진 상태(state)에서 행동(action)을 한다면, 보상을 최대화하는 \n정책을 쉽게 구축할 수 있습니다:\n\n\\begin{align}\\pi^*(s) = \\arg\\!\\max_a \\ Q^*(s, a)\\end{align}\n\n그러나 세계(world)에 관한 모든 것을 알지 못하기 때문에, \n$Q^*$ 에 도달할 수 없습니다. 그러나 신경망은 \n범용 함수 근사자(universal function approximator)이기 때문에\n간단하게 생성하고 $Q^*$ 를 닮도록 학습 할 수 있습니다. \n\n학습 업데이트 규칙으로, 일부 정책을 위한 모든 $Q$ 함수가 \nBellman 방정식을 준수한다는 사실을 사용할 것입니다:\n\n\\begin{align}Q^{\\pi}(s, a) = r + \\gamma Q^{\\pi}(s', \\pi(s'))\\end{align}\n\n평등(equality)의 두 측면 사이의 차이는 \n시간차 오류(temporal difference error), $\\delta$ 입니다.:\n\n\\begin{align}\\delta = Q(s, a) - (r + \\gamma \\max_a Q(s', a))\\end{align}\n\n오류를 최소화하기 위해서 `Huber\nloss `__ 를 사용합니다.\nHuber loss 는 오류가 작으면 평균 제곱 오차( mean squared error)와 같이\n동작하고 오류가 클 때는 평균 절대 오류와 유사합니다.\n- 이것은 $Q$ 의 추정이 매우 혼란스러울 때 이상 값에 더 강건하게 합니다.\n재현 메모리에서 샘플링한 전환 배치 $B$ 에서 이것을 계산합니다:\n\n\\begin{align}\\mathcal{L} = \\frac{1}{|B|}\\sum_{(s, a, s', r) \\ \\in \\ B} \\mathcal{L}(\\delta)\\end{align}\n\n\\begin{align}\\text{where} \\quad \\mathcal{L}(\\delta) = \\begin{cases}\n \\frac{1}{2}{\\delta^2} & \\text{for } |\\delta| \\le 1, \\\\\n |\\delta| - \\frac{1}{2} & \\text{otherwise.}\n \\end{cases}\\end{align}\n\nQ-네트워크\n^^^^^^^^^^^\n\n우리 모델은 현재와 이전 스크린 패치의 차이를 취하는 \nCNN(convolutional neural network) 입니다. 두가지 출력 $Q(s, \\mathrm{left})$ 와\n$Q(s, \\mathrm{right})$ 가 있습니다. (여기서 $s$ 는 네트워크의 입력입니다)\n결과적으로 네트워크는 주어진 현재 입력에서 각 행동의 *품질* 을 예측하려고 합니다.\n\n\n\n\n\n```python\nclass DQN(nn.Module):\n\n def __init__(self):\n super(DQN, self).__init__()\n self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)\n self.bn1 = nn.BatchNorm2d(16)\n self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)\n self.bn2 = nn.BatchNorm2d(32)\n self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)\n self.bn3 = nn.BatchNorm2d(32)\n self.head = nn.Linear(448, 2)\n\n def forward(self, x):\n x = F.relu(self.bn1(self.conv1(x)))\n x = F.relu(self.bn2(self.conv2(x)))\n x = F.relu(self.bn3(self.conv3(x)))\n return self.head(x.view(x.size(0), -1))\n```\n\n입력 추출\n^^^^^^^^^^^^^^^^\n\n아래 코드는 환경에서 렌더링 된 이미지를 추출하고 처리하는 유틸리티입니다.\n이미지 변환을 쉽게 구성 할 수 있는 ``torchvision`` 패키지를 사용합니다. \n셀(cell)을 실행하면 추출한 예제 패치가 표시됩니다.\n\n\n\n\n\n```python\nresize = T.Compose([T.ToPILImage(),\n T.Resize(40, interpolation=Image.CUBIC),\n T.ToTensor()])\n\n# 이것은 gym 코드를 기반으로 합니다.\nscreen_width = 600\n\n\ndef get_cart_location():\n world_width = env.x_threshold * 2\n scale = screen_width / world_width\n return int(env.state[0] * scale + screen_width / 2.0) # 카트의 중간\n\n\ndef get_screen():\n screen = env.render(mode='rgb_array').transpose(\n (2, 0, 1)) # transpose into torch order (CHW)\n # Strip off the top and bottom of the screen\n screen = screen[:, 160:320]\n view_width = 320\n cart_location = get_cart_location()\n if cart_location < view_width // 2:\n slice_range = slice(view_width)\n elif cart_location > (screen_width - view_width // 2):\n slice_range = slice(-view_width, None)\n else:\n slice_range = slice(cart_location - view_width // 2,\n cart_location + view_width // 2)\n # Strip off the edges, so that we have a square image centered on a cart\n screen = screen[:, :, slice_range]\n # Convert to float, rescare, convert to torch tensor\n # (this doesn't require a copy)\n screen = np.ascontiguousarray(screen, dtype=np.float32) / 255\n screen = torch.from_numpy(screen)\n # Resize, and add a batch dimension (BCHW)\n return resize(screen).unsqueeze(0).to(device)\n\n\nenv.reset()\nplt.figure()\nplt.imshow(get_screen().cpu().squeeze(0).permute(1, 2, 0).numpy(),\n interpolation='none')\nplt.title('Example extracted screen')\nplt.show()\n```\n\n학습\n--------\n\n하이퍼 파라미터와 유틸리티\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n이 셀은 모델과 최적화기를 인스턴스화하고 일부 유틸리티를 정의합니다:\n\n- ``select_action`` - Epsilon Greedy 정책에 따라 행동을 선택합니다.\n 간단히 말해서, 가끔 모델을 사용하여 행동을 선택하고 때로는 단지 하나를\n 균일하게 샘플링 할 것입니다. 임의의 액션을 선택할 확률은 \n ``EPS_START`` 에서 시작해서 ``EPS_END`` 를 향해 지수적으로 감소 할 것입니다.\n ``EPS_DECAY``는 감쇠 속도를 제어합니다.\n- ``plot_durations`` - 지난 100개 에피소드의 평균(공식 평가에서 사용 된 수치)에 따른\n 에피소드의 지속을 도표로 그리기 위한 헬퍼. 도표는 기본 훈련 루프가 \n 포함 된 셀 밑에 있으며, 매 에피소드마다 업데이트됩니다.\n\n\n\n\n\n```python\nBATCH_SIZE = 128\nGAMMA = 0.999\nEPS_START = 0.9\nEPS_END = 0.05\nEPS_DECAY = 200\nTARGET_UPDATE = 10\n\npolicy_net = DQN().to(device)\ntarget_net = DQN().to(device)\ntarget_net.load_state_dict(policy_net.state_dict())\ntarget_net.eval()\n\noptimizer = optim.RMSprop(policy_net.parameters())\nmemory = ReplayMemory(10000)\n\n\nsteps_done = 0\n\n\ndef select_action(state):\n global steps_done\n sample = random.random()\n eps_threshold = EPS_END + (EPS_START - EPS_END) * \\\n math.exp(-1. * steps_done / EPS_DECAY)\n steps_done += 1\n if sample > eps_threshold:\n with torch.no_grad():\n return policy_net(state).max(1)[1].view(1, 1)\n else:\n return torch.tensor([[random.randrange(2)]], device=device, dtype=torch.long)\n\n\nepisode_durations = []\n\n\ndef plot_durations():\n plt.figure(2)\n plt.clf()\n durations_t = torch.tensor(episode_durations, dtype=torch.float)\n plt.title('Training...')\n plt.xlabel('Episode')\n plt.ylabel('Duration')\n plt.plot(durations_t.numpy())\n # 100개의 에피소드 평균을 가져 와서 도표 그리기\n if len(durations_t) >= 100:\n means = durations_t.unfold(0, 100, 1).mean(1).view(-1)\n means = torch.cat((torch.zeros(99), means))\n plt.plot(means.numpy())\n\n plt.pause(0.001) # 도표가 업데이트되도록 잠시 멈춤 \n if is_ipython:\n display.clear_output(wait=True)\n display.display(plt.gcf())\n```\n\n학습 루프\n^^^^^^^^^^^^^\n\n최종적으로 모델 학습을 위한 코드.\n\n여기서, 최적화의 한 단계를 수행하는 ``optimize_model`` 함수를 찾을 수 있습니다.\n먼저 배치 하나를 샘플링하고 모든 Tensor를 하나로 연결하고 \n$Q(s_t, a_t)$ 와 $V(s_{t+1}) = \\max_a Q(s_{t+1}, a)$ 를 계산하고\n그것들을 손실로 합칩니다. 우리가 설정한 정의를 따르면 만약 $s$ 가\n마지막 상태라면 $V(s) = 0$ 이다.\n또한 안정성 추가 위한 $V(s_{t+1})$ 계산을 위해 목표 네트워크를 사용합니다. \n목표 네트워크는 대부분의 시간 동결 상태로 유지되지만, 가끔 정책 \n네트워크의 가중치로 업데이트됩니다.\n이것은 대개 설정한 스텝 숫자이지만 단순화를 위해 에피소드를 사용합니다.\n\n\n\n\n\n```python\ndef optimize_model():\n if len(memory) < BATCH_SIZE:\n return\n transitions = memory.sample(BATCH_SIZE)\n # Transpose the batch (자세한 설명을 위해 http://stackoverflow.com/a/19343/3343043 를 보십시오).\n batch = Transition(*zip(*transitions))\n\n # 최종 상태가 아닌 마스크를 계산하고 배치 요소를 연결합니다.\n non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,\n batch.next_state)), device=device, dtype=torch.uint8)\n non_final_next_states = torch.cat([s for s in batch.next_state\n if s is not None])\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n\n # Q(s_t, a) 계산 - 모델이 Q(s_t)를 계산하고, 취한 행동의 칼럼을 선택한다.\n state_action_values = policy_net(state_batch).gather(1, action_batch)\n\n # 모든 다음 상태를 위한 V(s_{t+1}) 계산\n next_state_values = torch.zeros(BATCH_SIZE, device=device)\n next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()\n # 기대 Q 값 계산\n expected_state_action_values = (next_state_values * GAMMA) + reward_batch\n\n # Huber 손실 계산\n loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))\n\n # 모델 최적화\n optimizer.zero_grad()\n loss.backward()\n for param in policy_net.parameters():\n param.grad.data.clamp_(-1, 1)\n optimizer.step()\n```\n\n아래에서 주요 학습 루프를 찾을 수 있습니다. 처음으로 환경을 \n재설정하고 ``상태`` Tensor를 초기화합니다. 그런 다음 행동을\n샘플링하고, 그것을 실행하고, 다음 화면과 보상(항상 1)을 관찰하고,\n모델을 한 번 최적화합니다. 에피소드가 끝나면 (모델이 실패) \n루프를 다시 시작합니다.\n\n아래에서 `num_episodes` 는 작게 설정됩니다. 노트북을 다운받고\n더많은 에피소드를 실행해 보십시오\n\n\n\n\n\n```python\nnum_episodes = 50\nfor i_episode in range(num_episodes):\n # Initialize the environment and state\n env.reset()\n last_screen = get_screen()\n current_screen = get_screen()\n state = current_screen - last_screen\n for t in count():\n # 행동 선택과 수행\n action = select_action(state)\n _, reward, done, _ = env.step(action.item())\n reward = torch.tensor([reward], device=device)\n\n # 새로운 상태 관찰\n last_screen = current_screen\n current_screen = get_screen()\n if not done:\n next_state = current_screen - last_screen\n else:\n next_state = None\n\n # 메모리에 변이 저장\n memory.push(state, action, next_state, reward)\n\n # 다음 상태로 이동\n state = next_state\n\n # 최적화 한단계 수행(목표 네트워크에서)\n optimize_model()\n if done:\n episode_durations.append(t + 1)\n plot_durations()\n break\n # 목표 네트워크 업데이트\n if i_episode % TARGET_UPDATE == 0:\n target_net.load_state_dict(policy_net.state_dict())\n\nprint('Complete')\nenv.render()\nenv.close()\nplt.ioff()\nplt.show()\n```\n", "meta": {"hexsha": "7a3eadd85408135f45b3b03c2bd62cf34f69152f", "size": 26383, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_downloads/3e605fb25517c6ef58ae9baf400d9fb1/reinforcement_q_learning.ipynb", "max_stars_repo_name": "leejh1230/PyTorch-tutorials-kr", "max_stars_repo_head_hexsha": "ebbf44b863ff96c597631e28fc194eafa590c9eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-05T05:16:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-05T05:16:44.000Z", "max_issues_repo_path": "docs/_downloads/3e605fb25517c6ef58ae9baf400d9fb1/reinforcement_q_learning.ipynb", "max_issues_repo_name": "leejh1230/PyTorch-tutorials-kr", "max_issues_repo_head_hexsha": "ebbf44b863ff96c597631e28fc194eafa590c9eb", "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": "docs/_downloads/3e605fb25517c6ef58ae9baf400d9fb1/reinforcement_q_learning.ipynb", "max_forks_repo_name": "leejh1230/PyTorch-tutorials-kr", "max_forks_repo_head_hexsha": "ebbf44b863ff96c597631e28fc194eafa590c9eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 162.8580246914, "max_line_length": 5136, "alphanum_fraction": 0.684910738, "converted": true, "num_tokens": 5318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.11124120356108878, "lm_q1q2_score": 0.05214883352406034}} {"text": "\n\n\n\n

        Physics Research and Education Bootcamp - Computational | Episode 1

        \n\nLicense: CC BY-NC-SA https://creativecommons.org/licenses/by-nc-sa/4.0/\n\nLast Modification: Sept. 3, 2021\n\n# ***Preambulo***\n\nPrimero carguemos los paquetes de Python necesarios para trabajar.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n```\n\n# **Transporte de Neutrones con *Montecarlo***\n\nHoy aprenderemos como usar el método Montecarlo para estudiar propiedades estadísticas de sistemas con muchas partículas. El procedimiento usado aquí puede ser empleado en otras áreas. Lo importante es tener en mente la clase de conclusiones que pueden obtenerse a través de Montecarlo y su manera de implementación. \n\n# **Teoría**\n\nEl problema del transporte de neutrones dentro de un medio es sumamente complejo. Formalmente se puede describir la evolución de un sistema de muchas particulas a traves de la ecuación de Boltzmann, una ecuación diferencial que toma en cuenta el medio en el cual los neutrones se encuentran, su posición, velocidad y momento angular. \n\n\\\\\n\nUna manera de solucionar este problema es a traves de la aproximación de difusión. En vez de considerar cada párticula de manera independiente, en la ecuación de difusión se aproxima el conjunto de neutrones como un \"gas de neutrones\". De esta manera se puede describir el comportamiento global del ensamble en términos de propiedades estadísticas como el ***camino libre medio*** o ***longitud de difusión***. Esta ecuación se conoce como la ***Ecuación de Difusión***:\n\\begin{align}\nD\\Delta\\phi - \\Sigma_a\\phi = \\dfrac{1}{v}\\dfrac{d\\phi}{dt}\n\\end{align}\n\\\\\n\nEn esta descripción, hablamos de la ***Densidad de Flujo de Neutrones*** ($\\phi$), la velocidad media ($v$) , el coeficiente de difusión ($D$) y la sección eficaz macroscópica de absorción ($\\Sigma_a$).\n\n\\\\\nEsta ecuación tiene varias soluciones, dependiendo de la geometría y el medio de difusiónn. Hoy nos enfocaremos en medios multiplicadores, es decir, medios en los cuales el número de neutrones aumenta con el tiempo. En este caso, es necesario agregar un término a la ecuaciún para tomar en cuenta la producción de neutrones. \n\nEste mecanismo de producción es la fisión nuclear, y denotamos por $\\sigma_f$ la probabilidad de que un neutrón produzca una fisión por unidad de area. Si tomamos en cuenta la densidad del medio, podemos transformar esta cantidad en la sección eficaz macroscópica de fisión ($\\Sigma_f$). Si ademas, por cada fisión se producen en promedio ($\\nu$) nuevos neutrones:\n\\begin{align}\nD\\Delta\\phi - \\Sigma_a\\phi + \\nu\\Sigma_f\\phi = \\dfrac{1}{v}\\dfrac{d\\phi}{dt}\n\\end{align}\nEn el caso de criticalidad, el número de neutrones en el sistema se mantiene constante y tenemos:\n\\begin{align}\nD\\Delta\\phi - \\Sigma_a\\phi + \\nu\\Sigma_f\\phi = 0\n\\end{align}\nEn el caso de un sistema esférico podemos determinar el radio del sistema para que la condición de criticalidad se cumpla:\n\\begin{align}\nR = \\dfrac{\\pi}{Bg}\n\\end{align}\ncon:\n\\begin{align}\nBg^2 = \\dfrac{\\nu\\Sigma_f - \\Sigma_a}{D}\n\\end{align}\n\nEn el caso de que la densidad de neutrones no se mantenga constante (aumente o disminuya) la solucion lamentablemente no es tan sencilla de computar. \n\nPodemos sin embargo, hablar de la cantidad $K_\\mathrm{eff}$ que nos permite cuantificar la diferencia en el número de neutrones entre una generación y otra.\n\n\\begin{align}\nK_\\mathrm{eff} = \\frac{\\mathrm{numero\\,\\, de\\,\\, neutrones \\,\\,actual}}{\\mathrm{numero\\,\\,de\\,\\,neutrones\\,\\,previo}}\n\\end{align}\n\nDe esta manera si:\n\n* $K_\\mathrm{eff}$ > 1 : hablamos de un sistema supercrítico, la densidad de neutrones aumenta exponencialmente\n* $K_\\mathrm{eff}$ = 1 : hablamos de un sistema crítico, la reacción es autosostenible y la cantidad de neutrones permance constante\n* $K_\\mathrm{eff}$ < 1 : hablamos de un sistema subcrítico, la densidad de neutrones disminuye con el tiempo\n\n\\\\\n\nVerificar si un sistema dado es crítico o supercrítico no es trivial. Para esto podemos utilizar el metodo Montecarlo y asi estimar esta proporción de neutrones de una generación a otra.\n\n\\\\\n\nNota: para el caso que vamos a estudiar:\n* $\\Sigma_a$ es la sección eficaz macroscópica de absorción y se refiere a la probabilidad total de que el neutrón sea absorbido y produzca fisión o simplemente active el núcleo que lo recibe.\n* $\\Sigma_f$ es la seccion eficaz macroscópica de fisión y se refiere a la probabilidad de que el neutrón absorbido produzca fisión\n* $\\Sigma_t$ es la probabilidad total de interacción, en el contexto de Difusión podemos entenderlo como el camino libre medio de un neutrón\n* $\\Sigma_s$ es la probabilidad de que el neutrón que interacciona sea desviado\n\n\\\\\n\nEs conveniente tener en mente que:\n\n\\begin{align}\n\\Sigma_t = \\Sigma_s + \\Sigma_a\n\\end{align}\n\nLas unidades de los $\\Sigma_j$ son de $cm^{-1}$\n\n\n\n\n\n# Práctica\n\nNecesitamos un código que nos genere inicialmente neutrones, los mueva a traves del medio y determine si despues de un movimiento ocurre una fisión, absorción o scattering.\n\n\n```python\ndef generar_neutrones(N_neutrones,radio):\n\n #Inicializamos las posiciones iniciales de los neutrones dentro de la esfera\n # Generamos dos coordenadas (r,theta) y luego a traves de las propiedades trigonometricas\n # luego convertimos estas coordenadas polares a cartesianas.\n r0 = np.random.uniform(0,radio,size=N_neutrones)\n theta0 = np.random.uniform(0,2*np.pi-.01,size=N_neutrones)\n x0 = r0*np.cos(theta0)\n y0 = r0*np.sin(theta0)\n # Guardamos las posiciones iniciales dentro de un arreglo para uso posterior\n fission_sites = np.array([x0,y0]).T\n return fission_sites\nr = 2\nPosiciones = generar_neutrones(1000,r)\n\nplt.figure()\nplt.suptitle('Distribucion de puntos iniciales de neutrones',fontweight='bold')\nplt.scatter(Posiciones[:,0],Posiciones[:,1])\nplt.xlabel('x',fontweight='bold')\nplt.ylabel('y',fontweight='bold')\nplt.xlim(-r-1,r+1)\nplt.ylim(-r-1,r+1)\nplt.grid()\n```\n\nDurante el transporte de un neutrón, este puede ser absorbido, desviado o ocasionar una fisión. Si el sistema es supercrítico el programa colapsará debido a límites de memoria ya que en cada ciclo de transporte habra más y más neutrones que seguir. Para evitar esto asignaremos pesos a los neutrones, con los cuales simbolizaremos el aumento o disminución de la cantidad de neutrones.\n\n\\\\\n\nAl final de cada ciclo, contamos el número de fisiones producidas y la posición de interacción. En el siguiente ciclo iniciamos nuevos neutrones desde estos punto de interacción y seguimos su evolución. Tomando el cociente entre los pesos de los neutrones de un ciclo entre el ciclo previo podemos obtener $K_\\mathrm{eff}$\n\n\\\\\n\nNecesitamos ahora un código que mueva un neutrón aleatoreamente por el espacio:\n\nPara el transporte debemos considerar $\\Sigma_a$, $\\Sigma_t$, $\\Sigma_f$ y $\\nu$\n\n\n```python\ndef random_transport(x,y,Sigma_t,niter):\n pos = [[x,y]]\n for i in range(niter):\n new_r = -np.log(1-np.random.random())/Sigma_t # Ya que tenemos solo una distancia promedio necesitamos muestrear las distancias\n new_theta = np.random.uniform(0,2*np.pi-.01) # Muestramos aleatoriamente un angulo\n x += new_r*np.cos(new_theta)\n y += new_r*np.sin(new_theta)\n pos.append([x,y])\n return pos\n \nPosiciones = random_transport(np.random.random(),np.random.random(),1,100)\nPosiciones = np.array(Posiciones)\nplt.figure()\nplt.suptitle('Transporte aleatorio de un neutron',fontweight='bold')\nplt.plot(Posiciones[:,0],Posiciones[:,1])\nplt.scatter(Posiciones[0,0],Posiciones[0,1],label='principio',s=40,c='g')\nplt.scatter(Posiciones[-1,0],Posiciones[-1,1],label='final',s=40,c='r')\nplt.xlabel('x',fontweight='bold')\nplt.ylabel('y',fontweight='bold')\nplt.grid()\nplt.legend()\n\n \n```\n\nAhora necesitamos una lógica para determinar si el neutrón interactúa o no.\nPara esto hacemos uso de las secciones eficaces macroscópicas.\n \n\\\\\nComo hemos visto, para generar muestras de una distribución debemos invertir la ***funcion de densidad cumulativa***. En casos como el nuestro en los cuales esta función no es conocida, tenemos que usar otros métodos para generar muestras.\n\nEl mecanismo que usaremos es el ***rejection sampling***. En terminos sencillos consiste en generar un número aleatorio y compararlo a la probabilidad de que ocurra algun evento. Si la probabilidad es menor, el evento ocurre, si es mayor el evento no ocurre y se procede a evaluar si otro evento distinto ocurrió mediante el mismo mecanismo.\n\n\\\\\n\\begin{align}\n\\alpha \\in U[0,1] \\rightarrow p(\\alpha) \\begin{cases} \n1 &\\text{si } \\alpha \\leq \\dfrac{p_\\mathrm{evento}}{p_\\mathrm{total}} \\\\\n0 &\\text{si } \\alpha > \\dfrac{p_\\mathrm{evento}}{p_\\mathrm{total}}\\\\\n\\end{cases}\n\\end{align}\n\n\\\\\n\nAhora escribimos un código que tome esto en cuenta, lo usaremos para estudiar si durante el trayecto el neutrón colisiona y es desviado, es absorbido o produce fisión.\n\n\\\\\n\n\n\n\n\n```python\ndef random_transport(x,y,Sigma_t,Sigma_a,Sigma_f,niter):\n # Calculamos la seccion eficaz macroscopica de desvio\n Sigma_s = Sigma_t - Sigma_a\n Pos = [[x,y]]\n alive = 1 # Usamos esta variable como un flag para determinar si debemos continuar siguiendo la evolucion de la particula\n Fision = 0\n while alive == 1: \n for i in range(niter):\n new_r = -np.log(1-np.random.random())/Sigma_t # Ya que tenemos solo una distancia promedio necesitamos muestrear las distancias\n new_theta = np.random.uniform(0,2*np.pi-.01) # Muestramos aleatoriamente un angulo\n x += new_r*np.cos(new_theta)\n y += new_r*np.sin(new_theta)\n Pos.append([x,y])\n\n # Verificamos si ocurre una interaccion:\n coll_prob= np.random.random()\n if coll_prob <= Sigma_s/Sigma_t: # La fraccion de la probabidad total de interaccion que ocurra un desvio \n continue # No debemos cambiar nada, proseguimos con la siguiente iteracion.\n else:\n # No hubo desvio (scattering), estudiamos ahora si hubo fision o simple absorcion\n fiss_prob = np.random.random()\n alive = 0\n if fiss_prob <= Sigma_f/Sigma_a:\n Fision = 1\n print(f'Ha ocurrido una fision tras {i+1} iteraciones')\n return Pos\n else:\n print(f'El neutron ha sido absorbido tras {i+1} iteraciones')\n return Pos\n return Pos\n```\n\n\n```python\nPosiciones = random_transport(np.random.random(),np.random.random(),1,0.3,0.1,100)\nPosiciones = np.array(Posiciones)\nplt.figure()\nplt.suptitle('Transporte aleatorio de un neutron',fontweight='bold')\nplt.plot(Posiciones[:,0],Posiciones[:,1])\nplt.scatter(Posiciones[0,0],Posiciones[0,1],label='principio',s=40,c='g')\nplt.scatter(Posiciones[-1,0],Posiciones[-1,1],label='final',s=40,c='r')\nplt.xlabel('x',fontweight='bold')\nplt.ylabel('y',fontweight='bold')\nplt.grid()\nplt.legend()\n\n```\n\nSolo nos falta crear un loop grande que genere ciclos de transporte con los neutrones\n\n\\\\\n\nEl algoritmo que queremos debe:\n\n\n\n1. Generar un grupo de N neutrones distribuidos al azar en el espacio\n2. Seguir la evolución de cada neutron\n3. Al final del ciclo tomar nota de los lugares del espacio donde hubo una interacción y ajustar el vector de pesos de manera proporcional al número de fisiones occuridas.\n4. Comenzar el siguiente ciclo g con N neutrones distribuidos entre los puntos de interacción del ciclo previo.\n\n

        Nota:

        \n\nComo todo algoritmo numérico, es probable que el valor estimado de $K_\\mathrm{eff}$ varíe de un ciclo a otro. Ademas, ya que no tenemos la CDF subyacente de las interacciones y la aproximamos a traves de ***rejection sampling***, es necesario realizar varias iteraciones hasta que la distribución de probabilidad de interacción se vuelva estacionaria y converja asintóticamente a la distribución real. Para esto consideramos un número de ciclos extras, los cuales no consideraremos válidos para estimar $K_\\mathrm{eff}$\n\n(Si has visto Cadenas de Markov, esta noción te parecera familiar a la del ***burn in*** de la traza)\n\n\n### Estimando K_eff\n\nReordenando y combinando lo que hemos escrito:\n\n\n```python\ndef homog_sphere_k(N,Sig_t,Sig_f,Sig_a,nu,radio,inactive_cycles = 5, active_cycles = 20):\n \n Sig_s = Sig_t-Sig_a # Calculamos la seccion eficaz macroscopica de desvio\n\n #Inicializamos las posiciones iniciales de los neutrones dentro de la esfera\n # Generamos dos coordenadas (r,theta) y luego a traves de las propiedades trigonometricas\n # luego convertimos estas coordenadas polares a cartesianas.\n r0 = np.random.uniform(0,radio,size=N)\n theta0 = np.random.uniform(0,2*np.pi-.01,size=N)\n x0 = r0*np.cos(theta0)\n y0 = r0*np.sin(theta0)\n # Guardamos las posiciones iniciales dentro de un arreglo para uso posterior\n fission_sites = np.array([x0,y0]).T\n posiciones = fission_sites.copy()\n # Inicializamos un vector de pesos asignando el numero medio de neutrones por fision\n weights = nu*np.ones(N)\n old_gen = np.sum(weights)\n k = np.zeros(inactive_cycles+active_cycles)\n\n Fs = {}\n\n for cycle in tqdm(range(inactive_cycles+active_cycles)):\n fission_sites = np.empty((1,2)) # Creamos un array vacio 1x2\n fission_site_weights = np.empty(1) # Creamos un array vacio 1x1\n for neut in range(weights.size):\n #Tomamos un neutron de la lista de neutrones\n posicion = posiciones[neut] # posicion del neutron\n weight = weights[neut] # peso asociado\n alive = 1 # Indicamos que esta 'vivo' y hay que seguir su evolucion\n while (alive):\n # Muestramos la distancia a la proxima colision\n new_r = -np.log(1-np.random.random())/Sig_t # Ya que tenemos solo una distancia promedio necesitamos muestrear las distancias\n new_theta = np.random.uniform(0,2*np.pi-.01) # Muestramos aleatoriamente un angulo\n # Actualizamos la posicion del neutron\n posicion[0] += new_r*np.cos(new_theta)\n posicion[1] += new_r*np.sin(new_theta)\n # Verificamos si aun estamos dentro de la esfera\n if (posicion[0]**2 + posicion[1]**2) > radio**2:\n alive = 0 # El neutron ha salido de la esfera, dejamos de seguirlo\n else:\n # Tomamos una muestra de la probabilidad de interaccion\n coll_prob = np.random.random()\n if (coll_prob < Sig_s/Sig_t):\n # Si la probabilidad es menor que la probabilidad de desvio el neutron no interactuo,\n # recalculamos la distancia hasta la siguiente colision\n continue\n else:\n # Si el neutron colisiono, pudo haber ocasinado una fision o ser absorvido\n # para esto tomamos una muestra de la probabilidad de fision\n fiss_prob = np.random.random()\n alive = 0 # \n if (fiss_prob <= Sig_f/Sig_a):\n # Si la probabilidad de fision es menor o igual al cociente \n # entre las secciones eficaces macroscopicas, consideramos que ocurre una fission \n # en la posicion actual\n\n # agregamos la posicion actual al arreglo de los lugares de fision\n fission_sites = np.vstack((fission_sites,posicion.reshape(-1,1).T))\n # agregamos el peso de la particula correspondiente al arreglo de pesos\n fission_site_weights = np.append(fission_site_weights,weight)\n # En caso de no haber fision, el neutron es absorbido. En nuestra approximacion \n # no hacemos nada, sin embargo para mayor fidelidad, deberiamos actualizar la composicion\n # atomica del medio y ajustar las correspondientes secciones eficaces.\n\n # Finalizamos un ciclo\n\n # Borramos la primera entrada del arreglo ya que contiene datos dummy\n fission_sites = np.delete(fission_sites,0,axis=0)\n # Realizamos el mismo procedimiento para este otro arreglo\n fission_site_weights = np.delete(fission_site_weights,0,axis=0)\n Fs[str(cycle)] = fission_sites\n # Determinamos el numero de neutrones a inicializar en el proximo ciclo \n # desde los puntos de interaccion determinados en el ciclo anterior\n num_per_site = int(np.ceil(N/fission_sites.shape[0]))\n # Reiniciamos el vector de posiciones de las particulas:\n posiciones = np.empty((1,2))\n weights = np.empty(1)\n # Creamos los nuevos arreglos de posiciones y pesos para usarlos en el proximo ciclo\n for site in range(fission_sites.shape[0]):\n site_pos = fission_sites[site]\n site_weight = fission_site_weights[site]\n posiciones = np.vstack((posiciones,\n site_pos*np.ones((num_per_site,1))))\n weights = np.append(weights,\n site_weight * nu/num_per_site*np.ones((num_per_site,1)))\n # Borramos la primera entrada de los arreglos al igual que hicimos arriba\n posiciones = np.delete(posiciones,0,axis=0) \n weights = np.delete(weights,0,axis=0) \n # Estimamos el numero de neutrones producidos en la generacion actual\n new_gen = np.sum(weights)\n # Calculamos el valor de Keff correspondiente para el ciclo actual\n k[cycle] = new_gen/old_gen \n old_gen = new_gen\n return k, Fs\n```\n\nAhora aplicamos nuestro cídigo a una esfera de radio 3cm usando los siguientes parámetros:\n\n* $\\Sigma_t = $ `0.3382197087866109`\n* $\\Sigma_f = $ `0.0920156560669456`\n* $\\Sigma_a = $ `0.1049475861087866`\n* $\\nu = $ `2.98`\n* $N$ = `50e3` neutrones por ciclo\n* Ciclos Activos = `100`\n* Ciclos Inactivos = `10`\n\n\n```python\nSt = 0.3382197087866109\nSf = 0.0920156560669456\nSa = 0.1049475861087866\nnu = 2.98\nr = 3\nNciclos_act = 100\nNciclos_inact = 10\nN_neutrones = 50000\n\nK, Fs = homog_sphere_k(N_neutrones,St,Sf,Sa,nu,r,Nciclos_inact,Nciclos_act)\nKmean = np.mean(K[Nciclos_inact:])\nKstd = np.std(K[Nciclos_inact:])\nprint('Keff = {:.4f} +/- {:.4f}'.format(Kmean,Kstd))\n```\n\n 100%|██████████| 110/110 [05:42<00:00, 3.12s/it]\n\n Keff = 0.6910 +/- 0.0058\n\n\n \n\n\n\n```python\nplt.figure()\nplt.suptitle(r'Evolucion de $K_{eff}$ vs Ciclo de Transporte',fontweight='bold')\nplt.plot(np.arange(Nciclos_act+Nciclos_inact),K)\nplt.ylabel(r'K_${eff}$',fontweight='bold')\nplt.xlabel('Ciclo',fontweight='bold')\nplt.grid()\n\n```\n\n# Tarea\n\n* Determine el radio crítico de una esfera de $^{239}\\mathrm{Pu}$. Cual es la masa crítica?\n\n* Modifique el cídigo para considerar ahora una esfera hueca con radio interior $R_{in}$ y radio exterior $R_{ext}$. Determine valores de estos radios para que el sistema sea crítico a densidad normal.\n\nVersion 1.0, Autor : Antonio Figueroa\n\n\n```python\n#libs summary\nimport types\ndef imports():\n for name, val in globals().items():\n if isinstance(val, types.ModuleType):\n yield val.__name__\nlist(imports())\n```\n\n\n\n\n ['builtins',\n 'builtins',\n 'IPython.core.shadowns',\n 'numpy',\n 'matplotlib.pyplot',\n 'types']\n\n\n", "meta": {"hexsha": "8281bbcd9f7f083bb5fcb775667d2d3f5dcb9373", "size": 207796, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Hands On/Dia 5/Transporte_de_Neutrones_Montecarlo.ipynb", "max_stars_repo_name": "FigueroaAC/GPs-for-SpentFuel", "max_stars_repo_head_hexsha": "97bbe469941ce916470c9022afdd242ed270246b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hands On/Dia 5/Transporte_de_Neutrones_Montecarlo.ipynb", "max_issues_repo_name": "FigueroaAC/GPs-for-SpentFuel", "max_issues_repo_head_hexsha": "97bbe469941ce916470c9022afdd242ed270246b", "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": "Hands On/Dia 5/Transporte_de_Neutrones_Montecarlo.ipynb", "max_forks_repo_name": "FigueroaAC/GPs-for-SpentFuel", "max_forks_repo_head_hexsha": "97bbe469941ce916470c9022afdd242ed270246b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 276.3244680851, "max_line_length": 53899, "alphanum_fraction": 0.9010231188, "converted": true, "num_tokens": 5308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.05183889090019357}} {"text": "```python\n%matplotlib notebook\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sympy as sp\nfrom plots import *\n\nsp.init_printing()\nfreqs = [f for f in np.random.standard_cauchy(11) if abs(f) < 10]\nomega = [2+ f for f in freqs] + [1 - f for f in freqs] + [1]\n\nfrom BondGraphTools import version\nimport BondGraphTools as bgt\nassert version == \"0.3.7\"\nscale = 2\n\nfrom matplotlib.font_manager import FontProperties\n\ndef plot_graph(t, x):\n fontP = FontProperties()\n fontP.set_size('small')\n fig = plt.figure(figsize=(scale*4,scale*4))\n plt.plot(t,x)\n ax = fig.gca()\n ax.set_xlabel('t')\n ax.set_title(f\"System response to {impulse}\")\n ax.legend(\n [f\"$x_{i}$\" for i in range(len(x))],\n bbox_to_anchor=(1.,1.),\n loc=1,\n borderaxespad=0.,\n prop=fontP\n )\n return fig\n\ndef print_tree(bond_graph, pre=\"\"):\n print(f\"{pre}{bond_graph}\")\n try:\n for component in reversed(bond_graph.components):\n if pre == \"\": print_tree(component, pre +\"|-\" )\n else: print_tree(component, pre +\"-\" )\n except AttributeError:\n pass\n```\n\n\n```python\n\n```\n\n\n\nTODO:\n2. Add critical values for Kuramoto model.\n3. Add critical values for Nonlinear oscillator model.\n\n- Introduction to complex systems\n- Basic research question\n\nLit Points:\n- Emergence is low dimension dynamics in high dimensional space. (Should be a geometric description; but we're not there yet.)\n- Collective motion requires tradeoffs between coulping strength and population heterogeneity. (Framed in terms of some kind of averaging)\n\n\n\n# On Emergence in Complex Physical Systems\n\n\nhttps://github.com/peter-cudmore\n\n \n\n Dr. Peter Cudmore. \n Systems Biology Labratory, \n The School of Chemical and Biomedical Engineering, \n The University of Melbourne. \n\nMany problems in biology, physics and engineering involve predicting and controlling complex systems, loosely defined as interconnected system-of-systems. Such systems can exhibit a variety of interesting non-equilibrium features such as emergence and phase transitions, which result from mutual interactions between nonlinear subsystems. \n\nModelling these systems is a task in-and-of itself, as systems can span many physical domains and evolve on multiple time scales. Nonetheless, one wishes to analyse the geometry of these models and relate both qualitative and quantitative insights back to the physical system.\n\nBeginning with the modelling and analysis of a coupled optomechanical systems, this talk presents some recent results concerning the existence and stability of emergent oscillations. This forms the basis for a discussion of new directions in symbolic computational techniques for complex physical systems as a means to discuss emergence more generally.\n\n\n## The problem with big systems is that they're _big_...\n\n## Example: Many-body Quantum Optomechanics\n\n
        \n\n(Image courtesy of Knap, M. https://users.ph.tum.de/ga32pex/ )\n\n
        \n
        \n\n(Image courtesy of Marquardt, F.\nhttps://photons-and-matter.org/research/ )\n\n## Example: Human Metabolism\n\n
        \n\n(Image courtesy of Human Metabolism map https://www.vmh.life )\n\n# Example: Ecosystems\n\n
        \n\n## Complex Physical Systems \n\nA dynamical system is said to be a _complex physical system_ when:\n* It is made up of many _interacting_ parts, or subsystems (High-dimensional).\n* The subsystems are not all of the same (Heterogenenous).\n* The subsystems are complicated (Nonlinear and/or Noisy).\n* There are well defined boundaries between the subsystems (Network Topology).\n* **Coupling takes place via resource exchange (Conservation Laws).**\n\n## Complex Systems can exhibit _emergence_.\n\n- _Emergence_ is a phenomenom where the system displays novel new behaviour that could not be produced by individuals alone.\n- _Synchronisation_ is the most studied example of emergence, and can occur in systems of coupled oscillator.\n\n
        How can one predict and control emergent phenomenon?
        \n\n
        \nHow can nonlinear dynamics be \"scaled up\"? \n
        \n\n## Outline of this talk\n\n\n\n\nIn this talk we will:\n\nBriefly discuss synchronisation as it's the best example of emergence.\n\nDiscuss how we might generalise this for energetic systems.\n\n\n\n## Part 1: Synchronised Oscillators\n\n## The Kuramoto Model\n\n_Self-entrainment of a population of coupled non-linear oscillators_ Kuramoto, Y. (1975).\n\nThe phase $\\theta_j$ of each oscillator with a natural frequency $\\omega_j$ is given by\n\n\\begin{equation}\n\\dot{\\theta}_j = \\omega_j + \\frac{K}{n}\\sum_{k=1}^n\\sin(\\theta_k - \\theta_j),\\qquad j=1,\\ldots n\n\\end{equation}\n- When $0\\le K K_c$ more oscillator are recruited to collective.\n\nThe value of $K_c$ depends upon the distribution of $\\{\\omega_j\\}$. For symmetric distribtuions we have\n$$K_c = \\frac{2}{\\pi g(0)}$$\n\n\n\n```python\n# Omega = Cauchy(2,1) so that K_c = 2\np = KuramotoModel(omega=omega, scale=scale)\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nPoints:\n- Wiener -> Winfree -> Kuramoto\n- Comes from studying BZ reaction\n- Motion on a strongly attracive limit cycle (invariant manifold) such that coupling\n- All-to-all coupling on a complete graph.\n- sinusoidal in phase -> linear in complex co-ordinates.\n- Kuramoto showed that at $K_c=2$ a Hopf bifurcation creates a synchronised state, that becomes progressive more stable as $K_c$ increases.\n\n## The Kuramoto Model (Cont.)\n\nKuramoto introduced an 'order parameter' $r$ to measure phase coherence\n\\begin{equation}\nz = r\\mathrm{e}^{\\mathrm{i}\\Theta} = \\frac{1}{n}\\sum_{k=1}^n \\exp{\\mathrm{i}\\theta_k} \\implies r = \\frac{1}{n}\\sum_{k=1}^n \\exp\\mathrm{i}(\\theta_k-\\Theta)\n\\end{equation}\nIt follows that\n$$\n\\Im\\left[\\frac{1}{n}\\sum_{k=1}^n\\exp i(\\theta_k - \\theta_j)\\right] = \n\\Im\\left[r\\exp i(\\Theta - \\theta_j)\\right] \n$$\n\n\nHence\n$$\n\\dot{\\theta}_j = \\omega_j + \\frac{K}{n}\\sum_{k=1}^n\\sin(\\theta_k - \\theta_j)$$\n\nbecomes \n$$\n\\dot{\\theta}_j = \\omega_j + rK\\sin(\\Theta - \\theta_j).\n$$\n\n\n```python\np = KuramotoOrderModel(omega,scale=scale)\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nPoints:\n- Mean phase is a kind of coordinate for the synchronous manifold.\n- Weak interactions with entire populations <=> strong coupling to collective statistics\n- Feedback look means that if coupling increases coherence, then $r$ increases asymptotically to $r_\\infty = \\sqrt{1-K_c/K}$$.\n\n## The Status of the Kuramoto Model \n\n$$\n\\dot{\\theta}_j = \\omega_j + rK\\sin(\\Theta - \\theta_j),\\qquad j = 1,\\ldots n.\\qquad r = \\frac{1}{n}\\sum_{k=1}^n \\exp i (\\theta_k - \\Theta).\n$$\n\n- Identical oscillators evolve on a 3 dimensional manifold (Watanabe and Strogatz, Physica D 1994. Ott and Antonsen, Chaos 2008).\n- Heterogenous oscillator dynamics represented in terms of collective co-ordinates in the thermodynamic limit (Pikovsky and Rosenblum, Physica D, 2011) and for finite-n (Gottwald, Chaos 2015).\n- Active research into applications in biology (particuarly neuroscience), physics and chemsitry.\n- Extensions to noisy, graph coupled and with various different coupling mechanisms.\n- Very few global results for heterogenous oscillators (Dietert, J. Math. Pures Appl. 2016).\n- _No results as yet for geometrical interpretation of transtion to synchrony._\n\n## Some Takeaways\n\n$$\n\\dot{\\theta}_j = \\omega_j + rK\\sin(\\Theta - \\theta_j),\\qquad j = 1,\\ldots n.\\qquad r = \\frac{1}{n}\\sum_{k=1}^n \\exp i (\\theta_k - \\Theta).\n$$\n\n\n1. When thinking about emergence, we want to think about mutual coupling between population statistics and individuals.\n\n2. This means that, for a given system, we need to understand both the individual dynamics _and_ population level dynamics.\n\n\n\n# Part 2: Coupled Optomechanical Systems \n\n## Physics of Many-Body Quantum Optomechanics\n\n\n\nThe Quantum Hamiltonain for the system is \n$$\nH = H_\\text{cavity}+H_\\text{drive}+H_\\text{beams}\n+H_\\text{coupling} + \\mathcal{H}_\\text{diss}\n$$\nwhere\n$$\n\\begin{align}\nH_\\text{cavity} =&\\ \\frac{\\omega_c}{2} a^\\dagger a\\\\\nH_\\text{drive} =&\\ u^\\dagger a + a^\\dagger u\\\\\nH_\\text{beams} =&\\ \\sum_j \\frac{\\omega_j}{2}b_j^\\dagger b\\\\\nH_\\text{coupling} =&\\ \\sum_j \\frac{G}{4}\n(b_j+b^\\dagger_j)a^\\dagger a\\\\\n\\end{align}\n$$\nwhere $a^\\dagger,a ,b_j^\\dagger,b_j,u^\\dagger,u$ are the creation and annihilaton operators of the \noptical mode, vibrational modes and optical forcing respectively.\n\nAlso:\n- $\\omega_c$ is the resonant frequency of the optical cavity\n- $\\omega_j$ is the mechanical resonance of the $j$th beam\n- $G$ is the strengh of opto-mechanical coupling\n- $\\mathcal{H}_\\text{diss}$ is the 'dissipative structure'...\n\n## From Quantum Physics to Semiclassical Dynamics\n\n\n\n1. Derive/produce the (generalised) Langevin equations.\n2. Use the semiclassical approximation to replace operators with averages, so that $a \\rightarrow \\alpha$ and $a^\\dagger \\rightarrow \\alpha^*$\n3. Assume the optical forcing is $\\left = \\nu\\exp[i\\omega_ft]$ and define $\\delta =\\omega_c - \\omega_f$\n4. Perform some rescaling and non-dimensionlisation to get \n$$\n\\begin{align}\n\\dot{\\alpha}&= - (1+i\\delta)\\alpha - i\\alpha \\frac{1}{n}\\sum_{j=1}^n\\Re \\left[\\beta_j\\right] -i\\nu \\\\\n\\dot{\\beta_j} + i\\bar{\\omega}\\beta_j &= -\\gamma \\left[(1+i\\omega'_j)\\beta_j + i\\frac{G}{2}|\\alpha|^2\\right], \\quad j=1,\\ldots, n\n\\end{align}\n$$\nwhere $\\gamma \\ll1$ and $\\omega_j = \\bar{\\omega} + \\gamma\\omega_j'$\n5. Apply the 'method of multiple scales' with $\\tau = \\gamma t$ to get $\\beta(t,\n\\tau) = z(\\tau)\\exp[-i\\bar{\\omega}t]$.\n6. Notice that $\\Re[\\beta] = \\cos(\\omega t +\\phi)$ makes $\\alpha$ look like a F.M oscillator, so has a basis in terms of Bessel functions.\n7. More algebra...\n\n
        ...how much of this can be automated?
        \n\n## On the other side\n\n\n\n \nThe fast time system (for the cavity $\\alpha$):\n\n$$\n\\frac{d\\alpha}{dt} = \n-\\alpha - i(\\delta + r(\\tau)\\cos[\\bar{\\omega}t + \\Theta(\\tau)])\\alpha - i\\nu\n$$\n\n\n \nThe slow time system (coupling induced frequency shift $z_j$):\n\n$$\n\\frac{d z_j}{d\\tau} \n= -(1- i\\omega'_j)z_j + zF(|z|), \\qquad z = re^{i\\Theta} = \\frac{1}{n}\\sum_{j=1}^n z_j\n$$\n\nWith $F:[0,\\infty) \\rightarrow \\mathbb{C}$ a complicated but known and computable function.\n\n## Collective motion on the slow time scale\n\n**Theorem (PC & Holmes. 2015)** \nDefine the _dispersion function_\n$$\nf(\\mu) = \\int_{-\\infty}^\\infty \\frac{g(\\omega)d\\omega}{\\mu - i\\omega}.\n$$\n\n(1) For sufficiently large $n$, the system\n$$\\dot{z}_j\n= -(1- i\\omega_j)z_j + zF(|z|), \\qquad z = \\frac{1}{n}\\sum_{j=1}^n z_j$$\nhas coherent motion on (possibly many multi-stable) invariant manifold(s) characterised by \n$$\nz = re^{i\\Theta},\\quad \\dot{r} = 0, \\qquad \\dot{\\Theta} = \\Omega\n$$\nand \n$$r\\left[F(r) - \\frac{1}{f(1+i\\Omega)}\\right] = 0.$$\n\n(2) For symmetric $g$ solutions are strictly unsable iff \n\n$$\n\\left\\langle\\frac{dF}{dr},\\frac{d}{d\\mu}\\frac{1}{f(\\mu)}\\bigg|_{1+i\\Omega}\\right\\rangle >0,\n$$ \nwhere $\\langle x,y\\rangle = \\Re[xy^*]$ is the geometric inner product for $x,y\\in \\mathbb{C}$. \n\n\n```python\n# F(r) = K/(1+r^2) is stable iff K > 2\nm = DampedCoupledOsc(omega=omega, extent=4, scale=scale)\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nNotes:\n- Only collective motion: S^1.\n- Multistability which can be created and destroyed via Hopf's.\n- Results for general coupling function $F$.\n- Proof involves treating $1/f(\\mu)$ as a conformal map from the RHP.\n\n## Synch corresponds to frequency modulation on the fast time scale\n\n\n\nOn the fast time scale:\n\n$$\\frac{d\\alpha}{dt} = \n-\\alpha - i(\\delta + r(\\tau)\\cos[\\bar{\\omega}t + \\Omega\\tau])\\alpha - i\\nu\n$$\n\nIf we can measure $(r,\\Omega)$, we can determine the internal state.\n\nHere $\\alpha$ falls well into the realm of existing signal processing theory (in particular frequency modulation). Hence, we can associate spectral properties to internal state.\n\n(The maths is hideous though)\n\n\n\n\n## Some Observations\n\n\n\n\n\n  \n\n  \n\n  \n\n\n# Object Oriented Modelling for Complex Physical Systems \n\n \n\n### Inheritance, Composition and Encapsulation\n\n## Ad-hoc modelling.\n\n\n\n1. Use descriptions of physical processes plus network topology to generate some odes.\n2. Do a whole bunch of algebra.\n3. Work out the appropriate coordinates to use based on geometric features (here, a non-standard slow fast system)\n4. More algebra to reduce model.\n5. Investigate the dynamics of the reduced models.\n6. Relate results in reduced model to observables in the original system\n\nIn the case of emergent phenomenon, the 'reduced' subspace involves the whole (or at least a large part of) system. E.g. mean fields.\n\n## Ad-hoc approaches won't scale.\n\n
        \n\nAs an example:\n- individual processes are far more heterogenous\n- network topolgy is complicated\n- many parameters are unknown\n- almost guaranteed to be a differential-algebraic system\n- **too big for one person, or even one lab**\n\nWe must have:\n- Ways to respresent and manipulate such systems,\n- Ways to manage congnitive complexity,\n- Ways to automate model capture and reduction,\n- Ways to effective share work between researchers\n\n## Energy provides an interface.\n\n\n\n\n\n## The Structure of Complex Physical Systems\n\nAn approach based on 'bond graph' modelling, and port-Hamiltonian systems.\n\n- Energy is stored in 'state variables' $q,p$\n- Power is distributed via 'power variables' $e,f$\n- Formally describes the hyrdo-mechanical-electrical analogies.\n\nFor example; \n- Dissipation relates $e,f$ variables. (eg. Ohm's law, friction, etc)\n- Potential storage $q$ to $e$ (eg, capacitors, gravity) \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
        Domain$q$ $f = \\dot{q}$ $p$ $e = \\dot{p}$
        Translational Mechanics position velocity momentum force
        \nRotational Mechanics angle angular velocity angular momentum torque\n
        \nElectronics charge current flux linkage voltage
        \nHydraulics volume flow pressure momentum pressure
        Thermodynamics entropy entropy flow temperature momentum temperature\n
        \n Chemistry moles molar flow chemical potential\n
        \n\n## An Object Oriented Representation of Energetic Systems\n\nObject Oriented Programming (OOP) is a software development paradigm that seeks to manage large, complicated projects by breaking problems into _data_ plus _methods_ that act on the data. \n\nThree big ideas in OOP are:\n1. _Inheritance_ or is-a relationships. \n2. _Composition_ or has-a relationships.\n3. _Encapsulation_ or infomation hiding.\n\nThis allows for _hierarchical_ and _modular_ design which reduces model complexity.\n\n'Energetic systems' draws from:\n- Network based analysis from engineering; in particular circuit electrical analysis and the more general (and less well known) bond graph methodology,\n- Classical mechanics, and in particular recent advances in port based Hamiltonian mechanics,\n- Modern nonlinear dynamics,\n- The effective was of managing complexity within software engineering.\n\n## Inheritance\n\n \n\nFor networked dynamic systems, _inheritance_ means we have:\n- conditions on the dynamical sub-systems.\n- a description of the interface between nodes.\n\n\n\n\n### Definition (Energetic System)\n\nAn energetic system is a tuple $(M, \\mathcal{D}, U,\\Phi)$\nwhere the\n* *state space* $M$ is a manifold of $\\dim(M) = m\\ge 0$\n* *port space* $\\mathcal{D} \\subset \\mathcal{F} \\times \\mathcal{E}$ where, $\\mathcal{E} = \\mathcal{F}^*$ and $ \\dim{\\mathcal{D}} = \\mathcal{F}|_\\mathcal{D} =n$. \n* *control space* $U \\subset C^r:\\mathbb{R}_+ \\rightarrow \\mathbb{R^k}$ with $k\\ge 0$ \n* *constitutive relation* is a smooth map $\\Phi: TM \\times \\mathcal{D} \\times U\\times\\mathbb{R}_+ \\rightarrow\n \\mathbb{R}^{m+n}$ \n such that\n $$\\Phi\\left(\\frac{dx}{dt},x,f,e,u,t\\right)=0.$$\n\n$\\Phi$ relates the _internal state_ $M$ and the _external environment_ (via $\\mathcal{D}$).\n\n\nOne can show that for conservative systems, one can define a storage function $H(x)$, choose $$\\Phi(\\dot{x}, x,f,e,t) = \n\\left(\\begin{matrix}\n\\dot{x} - f\\\\\ne - \\nabla_x H(x)\n\\end{matrix}\\right) = 0$$\nand encode the appropriate sympectic structure in a linear subspace of $\\mathcal{D}$.\n\n \n\n\n \n\n\n\n\n \n\n \n\nThe incoming *power* is $P_\\text{in} = \\left$ for $(f,e)\\in \\mathcal{D}$\n\n\n\n## Inheritance\n\nFor energetic systems-of-systems:\n\n### Nodes are particular _energetic systems_ \nEach node is described by a set of differential-algebraic equations $\\Phi(\\dot{x},x,e,f) = 0$.\n\n### Edges are constraints on port variables.\n\nAn edge represents how state is shared between systems.\n\n\n\n\n\n## Composition\n\n \n\nFor networked dynamic systems _composition_ means that we can replace nodes with subgraphs and vice-versa.\n\n\n\n\n\n## Corollary (Composition)\nIf $\\Psi_1 = (M_1, \\mathcal{D}_1, U_1,\\Phi_1)$ and $\\Psi_2 = (M_2, \\mathcal{D}_2, U_2,\\Phi_2)$ are energetic systems, then \n\n$$\\begin{eqnarray}\\Psi_0 &=& \\Psi_1 \\oplus\\Psi_2\\\\\n&=& \n\\left(M_1\\oplus M_2,\\mathcal{D}_1 \\oplus\\mathcal{D}_2,U_1\\oplus U_2, \\Phi_1\\oplus\\Phi_2\\right)\n\\end{eqnarray}$$\nis also an energetic system.\n\nSuppose (abusing notation) $\\Psi_0 = (\\Psi_1,\\Psi_2)$ is an energetic system with ports \n\n$$(e_i, f_i) \\in \\mathcal{D}_1, \\quad (e_j,f_j) \\in \\mathcal{D}_2$$\n\nThen $\\Phi_0$ with the additional power conserving constraint \n\n$$e_i - e_j = 0\\qquad f_i+f_j=0$$\n\nis also a energetic system\n\n\n\n\n\n## Encapsulation\n\n \n\nFor a networked dynamical system _encapsulation_ means that we can apply simplification methods to a subgraph so that the replacement system is less complicated, while representing the same behaviour.\n\n \n\nOne can also go the other way by replacing a node with a more complicated subgraph.\n\n\n\n## Object Oriented Modelling and Energetic Systems\n\nEnergetic systems provide:\n- _Inheritance_; an abstract base representation of energetic systems.\n- _Composition_; a way to hierarchically compose systems of systems.\n- _Encapsulation_; a framework inside which simplifications can occur.\n\n  \n\n  \n\n  \n\n# Introducing `BondGraphTools`\n\n## `BondGraphTools` a `python` library for energetic systems.\n\n`BondGraphTools` (https://github.com/BondGraphTools) a framework for modelling energetic systems.\n* Based upon an extension of bond graph and port-Hamiltonian modelling.\n* Provies a simple, *minimal* object-oriented interface for constructing models.\n* Implemented in `python` and uses the standard `scipy` stack.\n* Performs symbolic model reduction and simulation.\n* Simulations with DAE solvers in `julia`.\n* Developed with sustainable software practices.\n* Intended to be used in _conjunction_ with other tools.\n\n'Bond Graphs' are a multi-domain port-based graphical modelling technique used predominantly in mechatronics. \nPort-Hamiltonian systems integrate geometric approaches from classical mechanics and control theory with port based modelling. \n\n## Example: Linear Oscillator\n\n\n```python\nclass Linear_Osc(bgt.BondGraph): \n damping_rate = 0.1 #D amping rate common across oscillator array\n \n def __init__(self, freq, index):\n \"\"\"Linear Oscillator Class\n\n Args:\n freq: Natural (undamped) frequency of this oscillator\n index: Oscillator number (used for naming).\n \n Instances of this class are bond graph models of externally forced\n damped harmonic oscillators. \n In the electrical analogy, these is simply an open loop series RLC \n circuit.\"\"\"\n\t\n # Create the components\n r = bgt.new(\"R\", name=\"R\", value=self.damping_rate)\n l = bgt.new(\"I\", name=\"L\", value=1/freq)\n c = bgt.new(\"C\", name=\"C\", value=1/freq)\n port = bgt.new(\"SS\")\n conservation_law = bgt.new(\"1\")\n\t\n # Create the composite model and add the components\n super().__init__(\n name=f\"Osc_{index}\",\n components=(r, l, c, port, conservation_law)\n )\n\t\n # Wire the model up\n for component in (r,l,c):\n bgt.connect(conservation_law, component)\n bgt.connect(port, conservation_law)\n \n # Expose the SS component as an external port\n bgt.expose(port, label=\"P_in\")\n```\n\n`Linear_Osc` \n- _inherits_ from BondGraph, which is a base 'class' containing much of functionality\n- is _composed_ of a variety of subcomponents\n- _encapsulates_ a one port RLC component.\n\n\n\n```python\nexample_osc = Linear_Osc(1000,1)\nexample_osc.constitutive_relations \n```\n\n# Example: Using Linear oscillators for Coupled Cavity\n\n\n\n\n```python\ndef coupled_cavity():\n model = bgt.new(name=\"Cavity Model\")\n\n # Define the interaction Hamiltonain\n coupling_args = {\n \"hamiltonian\":\"(w + G*x_1)*(x_2^2 + x_3^2)/2\",\n \"params\": {\"G\": 1, \"w\": 6}\n }\n \n port_hamiltonian = bgt.new(\"PH\", value=coupling_args)\n \n # Define the symplectic junction structure \n symplectic_gyrator = bgt.new(\"GY\", value=-1) \n em_field = bgt.new(\"1\") \n\n bgt.add(model, port_hamiltonian, symplectic_gyrator, em_field) \n bgt.connect(em_field, (port_hamiltonian, 1))\n bgt.connect(em_field, (symplectic_gyrator, 1))\n bgt.connect((port_hamiltonian, 2), (symplectic_gyrator, 0))\n \n # Construct the open part of the system\n dissipation = bgt.new(\"R\", value=1)\n photon_source = bgt.new('SS')\n \n bgt.add(model, dissipation, photon_source)\n bgt.connect(em_field, dissipation)\n bgt.connect(photon_source, em_field)\n bgt.expose(photon_source)\n \n # Build the oscillator array\n frequencies = [2 + f for f in (-0.3, -0.1, 0, 0.1, 0.3)]\n osc_mean_field = bgt.new(\"0\")\n \n bgt.add(model, osc_mean_field)\n bgt.connect(osc_mean_field, (port_hamiltonian, 0))\n osc_array = [Linear_Osc(freq, index) \n for index, freq in enumerate(frequencies)]\n \n for osc in osc_array:\n bgt.add(model, osc)\n bgt.connect(osc_mean_field, (osc, \"P_in\"))\n \n return model\n```\n\n## Running a simulation\n\n\n```python\ndef experiment(cavity, signal, duration=50):\n laser = bgt.new(\"Se\")\n experiment = bgt.new()\n\n experiment.add(cavity, laser) \n bgt.connect(cavity, laser)\n \n t,x = bgt.simulate(\n experiment, \n timespan=[0, duration], \n x0=[0 for _ in cavity.state_vars], \n control_vars=[signal]\n )\n \n # do post-processing or data shaping here \n\n # This just selects the oscillator\n indicies = [i for i, (_, name) \n in enumerate(cavity.state_vars.values()) \n if name == 'x_0']\n return t, x[:, indicies]\n```\n\n\n```python\ncavity = coupled_cavity()\n\nforcing = \"cos(0.9t)\"\n\nt, x = experiment(cavity, signal=forcing) \n\nfig = plot_graph(t, x) ## Just makes things pretty.\n```\n\n## Getting the equations\n\n\n```python\ncavity.constitutive_relations\n```\n\n\n```python\nprint_tree(cavity)\n```\n\n\n\n## Under the Hood\n\nEach energetic systems is represented in local co-ordinates $\\mathcal{X}_1 \\in \\{(\\dot{x}_1,e_1,f_1,x_1,u_1)\\}$ \n\nMotion on the subspace satisfies $\\Phi_1(X) = L_1 X + V_1(X) =0$, where $L$ are matricies and $V$ is a strictly nonlinear vector field.\n\nSuppose $\\Phi_2$ is a similarly defined subsystem, then the column vector\n$X =[X_1;X_2]$ satisfies\n\n$$0 =LX+V(X) = \\left(\n\\begin{matrix}\nL_1 & 0 \\\\\n0 & L_2 \\end{matrix}\n\\right) X + \n\\left(\\begin{matrix}V_1\\circ \\pi_1 \\\\ V_\\beta\\circ \\pi_\\beta \\end{matrix}\\right)(X) \n$$\n\nwhich gives a way of 'stitching togehtor' systems using power conserving flows via\n\n$$e^j_1 = e^k_2,\\qquad f^j_1 =-f^k_2$$\n\nThen, we apply a bunch of symnbolic linear algebra, and projections/substitutions.\n\n## State of `BondGraphTools`\n\nCurrent Status:\n- In active development (v.0.3.7) and active use within the lab.\n- Documentation at https://bondgraphtools.readthedocs.io/en/latest/\n- Available on PyPI https://pypi.org/project/BondGraphTools/\n- Source on GitHub https://github.com/BondGraphTools/BondGraphTools\n- Manuscript in preparation.\n\n### Planned Future Developments\n- Robust parameter and control value network.\n- Interface for measuring port space.\n- Algorithmic model reduction (particularly manifold reductions).\n- Bifurcation analysis (particularly fixed point tracking).\n\n# In Summary\n\n- Emergence is an interesting and relevant phenomenom that is not well understood.\n- Emergent phenomenom occur due to interactions between subsystems within the context of a larger system.\n- Even in the case of synch, still much is unknowm.\n\n- Emergence can be thought of in terms of low dimensional invariant manifolds.\n- So, it would be useful to be able to \"scale up\" nonlinear analysis tools.\n- But there are problems here particularly in how one represent systems \n\n- `BondGraphTools` provides a way to build and recude big model in symbolic form.\n- It is hoped that this can feed into algorithmic approaches via GSP to begin to answer these questions.\n\n# Thank You!\n\nThanks to\n- Eduardo and Robbie\n- The University of Syndey\n- Prof. Edmund Crampin \n- The Systems Biology Lab at The University of Melbourne\n\n\n \n \n \n \n
        \n\n\n\n\n```python\nfrom BondGraphTools.reaction_builder import Reaction_Network\n\nTCA_reactions = {\n \"Citrate synthase\": \n [\"acetyl-CoA + oxaloacetate + H2O = citrate + CoA-SH\"],\n \"Aconitase\": \n [\"Citrate = cis-Aconitate + H2O\", \"cis-Aconitate + H2O = Isocitrate\"],\n \"Isocitrate dehydrogenase\": \n [\"Isocitrate + NAD = Oxalosuccinate + NADH + H\", \n \"Oxalosuccinate = a-Ketoglutarate + CO2\" ],\n \"a-Ketoglutarate dehydrogenase\": \n [\"a-Ketoglutarate + NAD + CoA-SH = Succinyl-CoA + NADH + H + CO2\"],\n \"Succinyl-CoA synthetase\": \n [\"Succinyl-CoA + ADP + Pi = Succinate + CoA-SH + ATP\"],\n \"Succinate dehydrogenase\": \n [\"Succinate + Q = Fumarate + QH2\"],\n \"Fumarase\":\n [\"Fumarate + H2O = L-Malate\"],\n \"Malate dehydrogenase\":\n [\"L-Malate + NAD = Oxaloacetate + NADH + H\"]\n} \n\ndef TCA_Cycle():\n reaction_net = Reaction_Network(name=\"TCA_Cycle\")\n for enzyme in TCA_reactions:\n for index, reaction in enumerate(TCA_reactions[enzyme]):\n reaction_name = f\"{enzyme} - {index}\"\n reaction_net.add_reaction(reaction, name=reaction_name)\n return reaction_net \n```\n\n\n```python\ntca_bg = TCA_Cycle().as_network_model()\ntca_bg.constitutive_relations\n```\n\n \n\n \n\n# Please check out `BondGraphTools`\n\n# https://github.com/BondGraphTools/\n\n\n```python\n\n```\n", "meta": {"hexsha": "16850f9fdf91fdb111a2f1179ac4f06e3e87f140", "size": 228369, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Sydney2019/seminar.ipynb", "max_stars_repo_name": "peter-cudmore/seminars", "max_stars_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "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": "Sydney2019/seminar.ipynb", "max_issues_repo_name": "peter-cudmore/seminars", "max_issues_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "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": "Sydney2019/seminar.ipynb", "max_forks_repo_name": "peter-cudmore/seminars", "max_forks_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "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": 52.9367176634, "max_line_length": 26777, "alphanum_fraction": 0.6435987371, "converted": true, "num_tokens": 7649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10374863240870875, "lm_q1q2_score": 0.05146905635400707}} {"text": "# 3. Data Pre-processing\n\nData pre-processing techniques generally refer to the addition, deletion, or transformation of training set data. Different models have different sensitivities to the type of predictors in the model; *how* the predictors enter the model is also important.\n\nThe need for data pre-processing is determined by the type of model being used. Some procedures, such as tree-based models, are notably insensitive to the characteristics of the predictor data. Others, like linear regression, are not. In this chapter, a wide array of possible methodologies are discussed. \n\nHow the predictors are encoded, called *feature engineering*, can have a significant impact on model performance. Often the most effective encoding of the data is informed by the modeler's understanding of the problem and thus is not derived from any mathematical techniques.\n\n## 3.1 Case Study: Cell Segmentation in High-Content Screening\n\nThis dataset is from Hill et al. (2007) that consists of 2019 cells. Of these cells, 1300 were judged to be poorly segmented (PS) and 719 were well segmented (WS); 1009 cells were reserved for the training set.\n\n\n```python\nimport numpy as np\nimport pandas as pd\n\ncell_segmentation = pd.read_csv(\"../datasets/segmentationOriginal/segmentationOriginal.csv\")\n```\n\n\n```python\ncell_segmentation.shape\n```\n\n\n\n\n (2019, 120)\n\n\n\nA first look at the dataset.\n\n\n```python\ncell_segmentation.head(5)\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 \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 \n \n \n \n \n \n \n \n
        Unnamed: 0CellCaseClassAngleCh1AngleStatusCh1AreaCh1AreaStatusCh1AvgIntenCh1AvgIntenCh2...VarIntenCh1VarIntenCh3VarIntenCh4VarIntenStatusCh1VarIntenStatusCh3VarIntenStatusCh4WidthCh1WidthStatusCh1XCentroidYCentroid
        01207827637TestPS143.2477051185015.7118643.954802...12.4746767.6090352.71410002210.64297424214
        12207932307TrainPS133.7520370819131.923274205.878517...18.80922556.715352118.38813900032.1612611215347
        23207932463TrainWS106.6463870431028.038835115.315534...17.29564337.67105349.47052400021.1855250371252
        34207932470TrainPS69.1503250298019.456140101.294737...13.81896830.00564324.74953700213.3928300487295
        45207932455TestPS2.8878372285024.275735111.415441...15.40797220.50428845.45045700013.1985610283159
        \n

        5 rows × 120 columns

        \n
        \n\n\n\nThis chapter will use the training set samples to demonstrate data pre-processing techniques.\n\n\n```python\ncell_segmentation.groupby('Case').count()\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 \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
        Unnamed: 0CellClassAngleCh1AngleStatusCh1AreaCh1AreaStatusCh1AvgIntenCh1AvgIntenCh2AvgIntenCh3...VarIntenCh1VarIntenCh3VarIntenCh4VarIntenStatusCh1VarIntenStatusCh3VarIntenStatusCh4WidthCh1WidthStatusCh1XCentroidYCentroid
        Case
        Test1010101010101010101010101010101010101010...1010101010101010101010101010101010101010
        Train1009100910091009100910091009100910091009...1009100910091009100910091009100910091009
        \n

        2 rows × 119 columns

        \n
        \n\n\n\n\n```python\n# separate training and test data\ncell_train = cell_segmentation.ix[cell_segmentation['Case'] == 'Train']\ncell_test = cell_segmentation.ix[cell_segmentation['Case'] == 'Test']\n\ncell_train.head(5)\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 \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 \n \n \n \n \n \n \n \n
        Unnamed: 0CellCaseClassAngleCh1AngleStatusCh1AreaCh1AreaStatusCh1AvgIntenCh1AvgIntenCh2...VarIntenCh1VarIntenCh3VarIntenCh4VarIntenStatusCh1VarIntenStatusCh3VarIntenStatusCh4WidthCh1WidthStatusCh1XCentroidYCentroid
        12207932307TrainPS133.7520370819131.923274205.878517...18.80922556.715352118.38813900032.1612611215347
        23207932463TrainWS106.6463870431028.038835115.315534...17.29564337.67105349.47052400021.1855250371252
        34207932470TrainPS69.1503250298019.456140101.294737...13.81896830.00564324.74953700213.3928300487295
        1112207932484TrainWS109.4164260256018.828571125.938776...13.92293718.64302740.33174700217.5468610211495
        1415207932459TrainPS104.2786540258017.570850124.368421...12.32497117.74714341.92853300217.6603390172207
        \n

        5 rows × 120 columns

        \n
        \n\n\n\n## 3.2 Data Transformation for Individual Predictors\n\nTransformations of predictor variables may be needed for several reasons. Some modeling techniques may have strict requirements, such as the predictors having a commom scale. In other cases, creating a good model may be difficult due to specific characteristics of the data (e.g., outliers).\n\n### Centering and Scaling\n\nTo center a predictor variable, the average predictor value is substracted from all the values. As a result of centering, the predictor has a zero mean. Similarly, to scale the data, each value of the predictor variable is divided by its standard deviation. Scaling the data coerce the values to have a common standard deviation of one. These manipulations are generally used to improve the numerical stability of some calculations, such as PLS. The only real downside to these transformation is a loss of interpretability of the individual values.\n\n### Transformations to Resolve Skewness\n\nAn un-skewed distribution is one that is roughly symmetric. A rule of thumb to consider is that skewed data whose ratio of the highest value to the lowest value is greater than 20 have significant skewness. The sample skewness statistic is defined $$\\text{skewness} = {\\sum (x_i - \\bar{x})^3 \\over (n - 1) v^{3/2}},$$ where $$v = {\\sum (x_i - \\bar{x})^2 \\over (n - 1)}.$$ Note that the skewness for a normal distribution is zero.\n\nThe cell segmentation data contain a predictor that measures the standard deviation of the intensity of the pixels in the actin filaments.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\n# Some nice default configuration for plots\nplt.rcParams['figure.figsize'] = 10, 7.5\nplt.rcParams['axes.grid'] = True\nplt.gray()\n```\n\n\n
        \n\n\n\n```python\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3)\n\nax1.hist(cell_train['VarIntenCh3'].values, bins=20)\nax1.set_xlabel('Natural Units')\nax1.set_ylabel('Count')\n\nax2.hist(np.log(cell_train['VarIntenCh3'].values), bins=20)\nax2.set_xlabel('Log Units')\n\nax3.hist(np.sqrt(cell_train['VarIntenCh3'].values), bins=20)\nax3.set_xlabel('Square Root Units')\n```\n\nThe histogram shows a strong right skewness. The log transformation seems to work well for this dataset. The ratio of the smallest to largest value and the sample skewness statistic all agree with the histogram under natural units.\n\n\n```python\nfrom scipy.stats import skew\n\nr = np.max(cell_train['VarIntenCh3'].values)/np.min(cell_train['VarIntenCh3'].values)\nskewness = skew(cell_train['VarIntenCh3'].values)\n\nprint('Ratio of the smallest to largest value is {0} \\nSample skewness statistic is {1}'.format(r, skewness))\n```\n\n Ratio of the smallest to largest value is 870.8872472030321 \n Sample skewness statistic is 2.395184181238347\n\n\nAlternatively, statistical models can be used to empirically identify an appropriate transformation. One of the most famous transformations is the Box-Cox family, i.e.\n\\begin{equation}\nx^* = \\begin{cases} {x^{\\lambda}-1 \\over \\lambda} & \\text{if} \\ \\lambda \\neq 0 \\\\ log(x) & \\text{if} \\ \\lambda = 0 \\end{cases}\n\\end{equation}\nThis family covers the log ($\\lambda = 0$), square ($\\lambda = 2$), square root ($\\lambda = 0.5$), inverse ($\\lambda = -1$), and others in-between. Using the training data, $\\lambda$ can be estimated using maximum likelihood estimation (MLE). This procedure would be applied independently to each predictor data that contain values **greater than 0**.\n\nThe boxcox() in *scipy.stats* finds the estimated lambda and performs the transformation at the same time.\n\n\n```python\nfrom scipy.stats import boxcox\n\nprint('Estimated lambda is {0}'.format(boxcox(cell_train['VarIntenCh3'].values)[1]))\n```\n\n Estimated lambda is 0.121531931959674\n\n\nTake another predictor for example.\n\n\n```python\nfig, (ax1, ax2) = plt.subplots(1, 2)\n\nax1.hist(cell_train['PerimCh1'].values, bins=20)\nax1.set_xlabel('Natural Units')\nax1.set_ylabel('Count')\n\nax2.hist(boxcox(cell_train['PerimCh1'].values)[0], bins=20)\nax2.set_xlabel('Transformed Data (lambda = {:1.4f})'.format(boxcox(cell_train['PerimCh1'].values)[1]))\n```\n\n## 3.3 Data Transformations for Multiple Predictors\n\nThese transformations act on groups of predictors, typically the entire set under consideration. Of primary importance are methods to resolve outliers and reduce the dimension of the data.\n\n### Transformations to Resolve Outliers\n\nWe generally define outliers as samples that are exceptionally far from the mainstream of the data. Even with a thorough understanding of the data, outliers can be hard to define. However, we can often identify an unusual value by looking at a figure. When one or more samples are suspected to be outliers, the first step is to make sure that the values are scientifically valid and that no data recording errors have occured. Great care should be taken not to hastily remove or change values, especially if the sample size is small. With small sample sizes, apparent outliers might be a result of a skewed distribution where there are not yet enough data to see the skewness. Also, the outlying data may be an indication of a special part of the population under study that is just starting to be sampled. Depending on how the data were collected, a \"cluster\" of valid points that reside outside the mainstream of the data might belong to a different population than the other samples, e.g. *extrapolation* and *applicability domain*. \n\nThere are several predictive models that are resistant to outliers, e.g.\n- Tree based classification models: create splits of the training set.\n- Support Vector Machines (SVM) for classification: disregard a portion if the training set that may be far away from the decision boundary.\n\nIf a model is considered to be sensitive to outliers, one data transformation that can minimize the problem is the *spatial sign*. Mathematically, each sample is divided by its squared norm: $$x_{ij}^* = {x_{ij} \\over \\sqrt{\\sum_{j=1}^p x_{ij}^2}}.$$ Since the denominator is intended to measure the squared distance to the center of the predictor's distribution, it is **important** to center and scale the predictor data prior to using this transformation. Note that, unlike centering and scaling, this manipulation of the predictors transform them as a group. Removing predictor variables after applying the spatial sign transformation may be problematic.\n\n\n```python\n# toy example\nbeta0 = -2.3 # intercept\nbeta1 = 0.8 # slope\nn = 1000\nx1_true = np.random.normal(4, 2, n)\nx2_true = np.zeros(n)\n\n# generate a random sample\nfor i in range(n):\n x2_true[i] = beta0 + beta1*x1_true[i] + np.random.normal(size = 1)\n \n# generate outliers\nx1_outliers = np.random.uniform(-4, -3, 8)\nx2_outliers = np.zeros(8)\nfor i in range(8):\n x2_outliers[i] = x1_outliers[i] + np.random.normal(size = 1)\n\nplt.scatter(x1_true, x2_true)\nplt.plot(x1_outliers, x2_outliers, 'ro', markersize=8)\n```\n\n\n```python\nfrom sklearn.preprocessing import scale\nx1 = scale(np.concatenate([x1_true, x1_outliers]))\nx2 = scale(np.concatenate([x2_true, x2_outliers]))\nx = np.array(zip(x1, x2))\n\n```\n\n\n```python\n\n# spatial sign\ndist = x[:, 0]**2 + x[:, 1]**2\nx1 = x[:, 0]/np.sqrt(dist)\nx2 = x[:, 1]/np.sqrt(dist)\n\nplt.scatter(x1[:-8], x2[:-8])\nplt.plot(x1[-7:], x2[-7:], 'ro', markersize=8)\n```\n\nThe *spatial sign* transformation brings the outliers towards the majority of the data.\n\n### Data Reduction and Feature Extraction\n\nThese methods reduce the data by generating a smaller set of predictors that seek to capture a majority of the information in the original variables. For most data reduction techniques, the new predictors are functions of the original predictors; therefore, all the original predictors are still needed to create the surrogate variables. This class of methods is often called *signal extraction* or *feature extraction* techniques.\n\nPrincipal component analysis (PCA) seeks to find linear combinations of the predictors, known as principal components (PCs), which capture the most possible variance. The first PC is defined as the linear combination of the predictors that captures the most variability of all possible linear combinations. Then, subsequent PCs are derived such that these linear combinations capture the most remaining variability while also being uncorrelated with all previous PCs. Mathematically, \n$$\\text{PC}_j = (a_{j1} \\times \\text{Predictor 1}) + \\cdots + (a_{jP} \\times \\text{Predictor P}).$$\nP is the number of predictors. The coefficients $a_{j1}, \\cdots, a_{jP}$ are called component weights and help us understand which predictors are most important to each PC.\n\nLet us look at an example from the previous dataset.\n\n\n```python\ncell_train_subset = cell_train[['Class', 'FiberWidthCh1', 'EntropyIntenCh1']]\n```\n\n\n```python\ncolors = ['b', 'r']\nmarkers = ['s', 'o']\nc = ['PS', 'WS']\nfor k, m in enumerate(colors):\n i = (cell_train_subset['Class'] == c[k])\n if k == 0:\n plt.scatter(cell_train_subset['FiberWidthCh1'][i], cell_train_subset['EntropyIntenCh1'][i], \n c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n else:\n plt.scatter(cell_train_subset['FiberWidthCh1'][i], cell_train_subset['EntropyIntenCh1'][i], \n c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\nplt.title('Original Data')\nplt.xlabel('Channel 1 Fiber Width')\nplt.ylabel('Entropy intensity of Channel 1')\nplt.legend(loc='upper right')\nplt.show()\n```\n\nCalculate PCs\n\n\n```python\nfrom sklearn.decomposition import PCA\n\npca = PCA()\npca.fit(cell_train_subset[['FiberWidthCh1', 'EntropyIntenCh1']])\nprint('variance explained by PCs {0}'.format(pca.explained_variance_ratio_))\n```\n\n variance explained by PCs [ 0.96900659 0.03099341]\n\n\nThe first PC summarizes 97% of the original variability, while the second summarizes 3%. Hence, it is reasonable to use only the first PC for modeling since it accounts for the majority of the information in the data.\n\n\n```python\ncell_train_subset_pca = pca.transform(cell_train_subset[['FiberWidthCh1', 'EntropyIntenCh1']])\n\ncolors = ['b', 'r']\nmarkers = ['s', 'o']\nc = ['PS', 'WS']\nfor k, m in enumerate(colors):\n i = np.where(cell_train_subset['Class'] == c[k])[0]\n if k == 0:\n plt.scatter(cell_train_subset_pca[i, 0], cell_train_subset_pca[i, 1], \n c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n else:\n plt.scatter(cell_train_subset_pca[i, 0], cell_train_subset_pca[i, 1], \n c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\nplt.title('Transformed')\nplt.xlabel('Principal Component #1')\nplt.ylabel('Principal Component #2')\nplt.legend(loc='upper right')\nplt.show()\n```\n\nThe primary advantage of PCA is that it creates components that are uncorrelated. PCA preprocessing creates new predictors with desirable characteristics for models that prefer predictors to be uncorrelated.\n\nWhile PCA delivers new predictors with desirable characteristics, it must be used with understanding and care. PCA seeks predictor-set variation without regard to any further understanding of the predictors (i.e. measurement scales or distributions) or to knowledge of the modeling objectives (i.e. response variable). Hence, without proper guidance, PCA can generate components that summarize characteristics of the data that are irrelevant to the underlying structure of the data and also to the ultimate modeling objectives.\n\nPCA was applied to the entire set of segmentation data predictors.\n\n\n```python\ncell_train.head(5)\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 \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 \n \n \n \n \n \n \n \n
        Unnamed: 0CellCaseClassAngleCh1AngleStatusCh1AreaCh1AreaStatusCh1AvgIntenCh1AvgIntenCh2...VarIntenCh1VarIntenCh3VarIntenCh4VarIntenStatusCh1VarIntenStatusCh3VarIntenStatusCh4WidthCh1WidthStatusCh1XCentroidYCentroid
        12207932307TrainPS133.7520370819131.923274205.878517...18.80922556.715352118.38813900032.1612611215347
        23207932463TrainWS106.6463870431028.038835115.315534...17.29564337.67105349.47052400021.1855250371252
        34207932470TrainPS69.1503250298019.456140101.294737...13.81896830.00564324.74953700213.3928300487295
        1112207932484TrainWS109.4164260256018.828571125.938776...13.92293718.64302740.33174700217.5468610211495
        1415207932459TrainPS104.2786540258017.570850124.368421...12.32497117.74714341.92853300217.6603390172207
        \n

        5 rows × 120 columns

        \n
        \n\n\n\n\n```python\ncell_train_feature = cell_train.iloc[:, 4:]\ncell_train_feature.head(5)\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 \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 \n \n \n \n \n \n \n \n
        AngleCh1AngleStatusCh1AreaCh1AreaStatusCh1AvgIntenCh1AvgIntenCh2AvgIntenCh3AvgIntenCh4AvgIntenStatusCh1AvgIntenStatusCh2...VarIntenCh1VarIntenCh3VarIntenCh4VarIntenStatusCh1VarIntenStatusCh3VarIntenStatusCh4WidthCh1WidthStatusCh1XCentroidYCentroid
        1133.7520370819131.923274205.87851769.916880164.15345300...18.80922556.715352118.38813900032.1612611215347
        2106.6463870431028.038835115.31553463.941748106.69660200...17.29564337.67105349.47052400021.1855250371252
        369.1503250298019.456140101.29473728.21754431.02807000...13.81896830.00564324.74953700213.3928300487295
        11109.4164260256018.828571125.93877613.60000046.80000000...13.92293718.64302740.33174700217.5468610211495
        14104.2786540258017.570850124.36842122.46153871.20647800...12.32497117.74714341.92853300217.6603390172207
        \n

        5 rows × 116 columns

        \n
        \n\n\n\nBecause PCA seeks linear combinations of predictors that maximize variability, it will naturally first be drawn to summarizing predictors that have more variation. If the original predictors are on measurement scales that differ in orders of magnitude or have skewed distributions, PCA will be focusing its efforts on identifying the data structure based on measurement scales and distributional difference rather than based on the important relationships within the data for the current problem. Hence, it is best to first transform skewed predictors and then center and scale the predictors prior to performing PCA.\n\n\n```python\n# Box-Cox transformation on positive predictors\n# separate positive and non-positive predictors\npos_indx = np.where(cell_train_feature.apply(lambda x: np.all(x > 0)))[0]\ncell_train_feature_pos = cell_train_feature.iloc[:, pos_indx]\nprint(\"# of positive features is {0}\".format(pos_indx.shape[0]))\ncell_train_feature_nonpos = cell_train_feature.drop(cell_train_feature.columns[pos_indx], axis=1, inplace=False)\nprint(\"# of npn-positive features is {0}\".format(cell_train_feature.shape[1] - pos_indx.shape[0]))\n\ncell_train_feature_pos_tr = cell_train_feature_pos.apply(lambda x: boxcox(x)[0])\n\ncell_train_feature_tr = np.c_[cell_train_feature_pos_tr, cell_train_feature_nonpos]\nprint(\"The shape before/after transformation is {0} and {1}\".format(cell_train_feature.shape, cell_train_feature_tr.shape))\n```\n\n # of positive features is 47\n # of npn-positive features is 69\n The shape before/after transformation is (1009, 116) and (1009, 116)\n\n\n\n```python\n# scale and center predictors\nfrom sklearn.preprocessing import scale\n\ncell_train_feature_tr = scale(cell_train_feature_tr, with_mean=True, with_std=True)\n```\n\nThe second caveat of PCA is that it does not consider the modeling obejective or response variable when summarizing variability -- it is an *unsupervised technique*. If the predictive relationship between the predictors and response is not connected to the predictors' variability, then the derived PCs will not provide a suitable relationship with the response. In this case, a *supervised technique*, like PLS will derive components while simultaneously considering the corresponding response.\n\nTo decide how many components to retain after PCA, a heuristic approach is to create a scree plot, which contains the ordered component number (x-axis) and the amount of summarized variability (y-axis). Generally, the component number prior to the tapering off of variation is the maximal component that is retained. In an automated model building process, the optimal number of components can be determined by cross-validation.\n\n\n```python\n# conduct PCA to transformed predictors\nfrom sklearn.decomposition import PCA\n\npca = PCA()\npca.fit(cell_train_feature_tr)\n\n# generate scree plot\nplt.plot(pca.explained_variance_ratio_)\nplt.xlabel('Percent of Total Variance')\nplt.ylabel('Component')\n```\n\n\n```python\nprint(\"The first four components account for {0} of the total variance\".format(pca.explained_variance_ratio_[:4]))\nprint(\"All together they account for {0} of the total variance\".format(np.sum(pca.explained_variance_ratio_[:4])))\n```\n\n The first four components account for [ 0.14015262 0.12569722 0.09394676 0.06393814] of the total variance\n All together they account for 0.4237347251400651 of the total variance\n\n\nVisually examining the principal components is a critical step for assessing data quality and gaining intuition for the problem. To do this, the first few PCs can be plotted against each other and the plot symbols can be colored by the relevant characteristics, such as the class labels. If PCA has captured a sufficient amount of the information in the data, this type of plot can demonstrate clusters of samples or outliers that may prompt a closer examination of the individual data points. Note that the scale of the components tend to become smaller as they account for less and less variation in the data. If axes are displayed on separate scales, there is the potential to over-interpret any patterns that might be seen for components that account for small amounts of variation.\n\n\n```python\n# look at the first 3 PCs\npca = PCA(n_components=3)\ncell_train_feature_pca = pca.fit_transform(cell_train_feature_tr)\n```\n\n\n```python\ncolors = ['b', 'r']\nmarkers = ['s', 'o']\nc = ['PS', 'WS']\n\nfig, axarr = plt.subplots(3, 3, sharex=True, sharey=True)\n\n# PC1 vs PC3\nfor k, m in enumerate(colors):\n i = np.where(cell_train['Class'] == c[k])[0]\n if k == 0:\n line1= axarr[0,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 2], \n c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n else:\n line2= axarr[0,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 2], \n c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\n# PC2 vs PC3\nfor k, m in enumerate(colors):\n i = np.where(cell_train['Class'] == c[k])[0]\n if k == 0:\n axarr[0,1].scatter(cell_train_feature_pca[i, 1], cell_train_feature_pca[i, 2], \n c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n else:\n axarr[0,1].scatter(cell_train_feature_pca[i, 1], cell_train_feature_pca[i, 2], \n c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\n# PC1 vs PC2\nfor k, m in enumerate(colors):\n i = np.where(cell_train['Class'] == c[k])[0]\n if k == 0:\n axarr[1,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 1], \n c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n else:\n axarr[1,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 1], \n c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\naxarr[2,0].text(0.5, -1.0, 'PC1', ha='center', va='center', fontsize=24) \naxarr[1,1].text(0.5, -1.0, 'PC2', ha='center', va='center', fontsize=24) \naxarr[0,2].text(0.5, -1.0, 'PC3', ha='center', va='center', fontsize=24)\nfig.legend([line1, line2], ('PS', 'WS'), loc='upper center', ncol=2, frameon=False)\nfig.subplots_adjust(hspace=0.12, wspace=0.1)\nfig.text(0.5, 0.06, 'Scatter Plot Matrix', ha='center', va='center', fontsize=18)\n```\n\nSince the percentages of variation explained are not large for the first three components, it is important not to over-interpret the resulting image. From this plot, there appears to be some separation between the classes when plotting the first and second components. However, the distribution of the well-segmented cells is roughly contained within the distribution of the poorly identified cells. One conclusion is that the cell types are not easily separated.\n\nAnother exploratory use of PCA is characterizing which predictors are associated with each component. Recall that each component is a linear combination of the predictors and the coefficient for each predictor is called the loading. Loadings close to zero indicate that the predictor variable did not contribute much to that component.\n\n\n```python\n# loadings\npca.components_.shape\n```\n\n\n\n\n (3, 116)\n\n\n\n## 3.4 Dealing with Missing Values\n\nIn many cases, some predictors have no values for a given sample. It is important to understand *why* the values are missing. First and foremost, it is important to know if the pattern of missing data is related to the outcome. This is called *informative missingness* since the missing data pattern is instructional on its own. Informative missingness can induce significant bias in the model.\n\nMissing data should not be confused with *censored* data where the exact value is missing but something is known about its value. When building traditional statistical models focused on interpretation or inference, the censoring is usually taken in to account in a formal manner by making assumptions about the censoring mechanism. For predictive models, it is more common to treat these data as simple missing data or use the censored value as the observed value.\n\nMissing values are more often related to predictive variables than the sample. Because of this, amount of missing data may be concentrated in a subset of predictors rather than occuring randomly across all the predictors. In some cases, the percentage of missing data is substantial enough to remove this predictor from subsequent modeling activities.\n\nThere are cases where the missing values might be concentrated in specific samples. For large datasets, removal of samples based on missing values is not a problem, assuming that the missingness is not informative. In smaller datasets, there is a steep price in removing samples; some of alternative approaches described below may be more appropriate.\n\nIf we do not remove the missing data, there are two general approaches. First, a few predictive models, especially tree-based techniques, can specifically account for missing data. Alternatively, missing data can be imputed. In this case, we can use information in the training set predictors to, in essence, estimate the values of other predictors.\n\nImputation is just another layer of modeling where we try to estimate values of the predictor variables based on other predictor variables. The most relevant scheme for accomplishing this is to use the training set to built an imputation model for each predictor in the daa set. Prior to model training or the prediction of new samples, missing values are filled in using imputation. Note that this extra layer of models adds uncertainty. If we are using resampling to select tuning parameter values or to estimate performance, the imputation should be incorporated within the resampling. This will increase the computational time for building models, but it will also provide honest estimates of model performance.\n\nIf the number of predictors affected by missing values is small, an exploratory analysis of the relationships between the preditors is a good idea. For example, visulization or methods like PCA can be used to determine if there are strong relationships between the predictors. If a variable with missing values is highly correlated with another predictor that has few missing values, a focused model can often be effective for imputation.\n\nOne popular technique for imputation is a $K$-nearest neighbor model. A new sample is imputed by finding the samples in the training set \"closest\" to it and averages these nearby points to fill in the value. One advantage of this approach is that the imputed data are confined to be within the range of the training set values. One disadvantage is that the entire training set is required every time a missing value needs to be imputed. Also, the number of neighbors is a tuning parameter, as is the method for determining \"closeness\" of two points. However, Troyanskaya et al. (2001) found the nearest neighbor approach to be fairly robust to the tuning parameters, as well as the amount of missing data.\n\n\n```python\n# randomly sample 50 test set\nimport random\ncell_test_subset = cell_test.iloc[np.sort(random.sample(range(cell_test.shape[0]), 50))]\n\n# separate features\ncell_test_subset_f = cell_test_subset.iloc[:, 4:].drop('VarIntenCh3', 1)\ncell_test_subset_v = cell_test_subset.iloc[:, 4:]['VarIntenCh3']\ncell_train_f = cell_train_feature.drop('VarIntenCh3', 1)\ncell_train_v = cell_train_feature['VarIntenCh3']\n```\n\n\n```python\n# scale and center before imputation\nfrom sklearn.preprocessing import StandardScaler\n\n# standardize based on training set\nsc_f = StandardScaler()\ncell_train_f_sc = sc_f.fit_transform(cell_train_f)\ncell_test_subset_f_sc = sc_f.transform(cell_test_subset_f)\n\nsc_v = StandardScaler()\ncell_train_v_sc = sc_v.fit_transform(cell_train_v.reshape(-1, 1))\ncell_test_subset_v_sc = sc_v.transform(cell_test_subset_v.reshape(-1, 1))\n```\n\n /Users/aremirata/anaconda3/lib/python3.5/site-packages/ipykernel_launcher.py:10: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead\n # Remove the CWD from sys.path while we load stuff.\n /Users/aremirata/anaconda3/lib/python3.5/site-packages/ipykernel_launcher.py:11: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead\n # This is added back by InteractiveShellApp.init_path()\n\n\n\n```python\n# use 5-nearest neighbor\nfrom sklearn.neighbors import NearestNeighbors\n\nnbrs = NearestNeighbors(n_neighbors = 5)\nnbrs.fit(cell_train_f_sc) # based on training set\ndistance, indices = nbrs.kneighbors(cell_test_subset_f_sc) # neighbors for test set\n\n# imputation\ncell_test_subset_v_pred_knn = np.empty(50)\nfor idx, i in enumerate(indices):\n cell_test_subset_v_pred_knn[idx] = np.mean(cell_train_v_sc[i[1:]])\n```\n\nFind the predictor with highest correlation.\n\n\n```python\nfrom scipy.stats.stats import pearsonr\n\nprint(\"corr('VarIntenCh3', 'DiffIntenDensityCh3') is {0}\".format(pearsonr(cell_train_v, cell_train_f['DiffIntenDensityCh3'])[0]))\n```\n\n corr('VarIntenCh3', 'DiffIntenDensityCh3') is 0.8948715047853233\n\n\n\n```python\n# use linear model\nfrom sklearn.linear_model import LinearRegression\n\nlm = LinearRegression()\nlm.fit(cell_train_f_sc[:, cell_train_f.columns.get_loc('DiffIntenDensityCh3')][:, np.newaxis],\n cell_train_v_sc) # find the predictor with highest correlation\ncell_test_subset_v_pred_lm = \\\nlm.predict(cell_test_subset_f_sc[:, cell_train_f.columns.get_loc('DiffIntenDensityCh3')][:, np.newaxis])\n```\n\nCorrelation between the real and imputed values\n\n\n```python\nprint(\"kNN: {0}\".format(pearsonr(cell_test_subset_v_sc.ravel(), cell_test_subset_v_pred_knn)[0]))\nprint(\"Linear Model: {0}\".format(pearsonr(cell_test_subset_v_sc, cell_test_subset_v_pred_lm)[0][0]))\n```\n\n kNN: 0.9041754173339616\n Linear Model: 0.8714262815406963\n\n\nNote that the better performance of linear model is because of the high correlation (0.895) between these two predictors. kNN is generally more robust since it takes all predictors into consideration.\n\n\n```python\nfig, (ax1, ax2) = plt.subplots(1, 2)\n\nax1.scatter(cell_test_subset_v_sc, cell_test_subset_v_pred_knn)\nax1.set(xlim=(-1.5, 3), ylim=(-1.5, 3))\nax1.plot(ax1.get_xlim(), ax1.get_ylim(), ls=\"--\", c=\".3\")\nax1.set_title('5NN')\n\nax2.scatter(cell_test_subset_v_sc, cell_test_subset_v_pred_lm)\nax2.set(xlim=(-1.5, 3), ylim=(-1.5, 3))\nax2.plot(ax2.get_xlim(), ax2.get_ylim(), ls=\"--\", c=\".3\")\nax2.set_title('Linear Model')\n\nfig.text(0.5, 0.04, 'Original Value (centered and scaled)', ha='center', va='center')\nfig.text(0.06, 0.5, 'Imputed', ha='center', va='center', rotation='vertical')\n```\n\n## 3.5 Removing Predictors\n\nThere are potential advantages to removing predictors prior to modeling. First, fewer predictors means decreased computational time and complexity. Second, if two predictors are highly correlated, this implies that they are measuring the same underlying information. Removing one should not compromise the performance of the model and might lead to a more parsimonious and interpretable model. Third, some models can be crippled by predictors with degenerate distributions, e.g. near-zero variance predictors. In these cases, there can be a significant improvement in model performance and/or stability without the problematic variables.\n\nA rule of thumb for detecting near-zero variance predictors:\n- The fraction of unique values over the sample size is low (say 10%)\n- The ratio of the frequency of the most prevalent value to the frequency of the second most prevalent value is large (say around 20)\n\nIf both of these criteria are true and the model in question is susceptible to this type of predictor, it may be advantageous to remove the variable from the model.\n\n### Between-Predictor Correlations\n\n*Collinearity* is the technical term for the situation where a pair of predictor variables have a substantial correlation with each other. It is also possible to have relationships between multiple predictors at once (called *multicollinearity*).\n\nA direct visualization of the correlation matrix from the training set.\n\n\n```python\n# calculate the correlation matrix\ncorr_dataframe = cell_train_feature.corr()\n\n# compute hierarchical cluster on both rows and columns for correlation matrix and plot heatmap \ndef corr_heatmap(corr_dataframe):\n import scipy.cluster.hierarchy as sch\n \n corr_matrix = np.array(corr_dataframe)\n col_names = corr_dataframe.columns\n \n Y = sch.linkage(corr_matrix, 'single', 'correlation')\n Z = sch.dendrogram(Y, color_threshold=0, no_plot=True)['leaves']\n corr_matrix = corr_matrix[Z, :]\n corr_matrix = corr_matrix[:, Z]\n col_names = col_names[Z]\n im = plt.imshow(corr_matrix, interpolation='nearest', aspect='auto', cmap='bwr')\n plt.colorbar()\n plt.xticks(range(corr_matrix.shape[0]), col_names, rotation='vertical', fontsize=4)\n plt.yticks(range(corr_matrix.shape[0]), col_names[::-1], fontsize=4)\n \n# plot\ncorr_heatmap(corr_dataframe)\n```\n\nNote that the predictor variables have been grouped using a clustering technique so that collinear groups of predictors are adjacent to one another.\n\nWhen the data set consists of too many predictors to examine visually, techniques such as PCA can be used to characterize the magnitude of the problem. For example, if the first principal component accounts for a large percentage of the variance, this implies that there is at least one group of predictors that represent the same information. The PCA loadings can be used to understand which predictors are associated with each component to tease out this relationship.\n\nIn general, there are good reasons to avoid data with highly correlated predictors. First, redundant predictors frequently add more complexity to the model than information they provide to the model. In situations where obtaining the predictor data is costly, fewer variables is obviously better. Using highly correlated predictors in techniques like linear regression can result in highly unstable models, numerical values, and degraded predictive performances.\n\nClassical regression analysis has several tools to diagnose multicollinearity for linear regression. A statistic called the variance inflation factor (VIF) can be used to identify predictors that are impacted. A common rule of thumb is that if VIF > 5, then multicollinearity is high. Note that this method is developed for linear models, it requires more samples than predictor variables and it does not determine which should be removed to resolve the problem\n\nA more heuristic approach is to remove the minimum number of predictors to ensure that all pairwise correlation are below a certain threshold. The algorithm is as follows:\n- Calculate the correlation matrix of the predictors.\n- Determine the two predictors associated with the largest absolute pairwise correlation (A and B).\n- Determine the average absolute correlation between A and the other variables. Do the same for predictor B.\n- If A has a larger average correlation, remove it; otherwise, remove predictor B.\n- Repeat Steps 2-4 until no absolute correlations are above the threshold.\n\nSuppose we wanted to use a model that is particularly sensitive to between predictor correlations, we might apply a threshold of 0.75.\n\nAs previously mentioned, feature extraction methods (e.g., principal components) are another technique for mitigating the effect of strong correlations between predictors. However, these techniques make the connection between the predictors and the outcome more complex. Additionally, since signal extraction methods are usually unsupervised, there is no guarantee that the resulting surrogate preditors have any relationship with the outcome.\n\n## 3.6 Adding Predictors\n\nWhen a predictor is categorical, it is common to decompose the predictor into a set of more specific variables.\n\nLook at the following example for the credit scoring data.\n\n\n```python\ncredit_data = pd.read_csv(\"../datasets/GermanCredit/GermanCredit.csv\")\ncredit_data.head(5)\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 \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 \n \n \n \n \n \n \n \n
        Unnamed: 0DurationAmountInstallmentRatePercentageResidenceDurationAgeNumberExistingCreditsNumberPeopleMaintenanceTelephoneForeignWorker...OtherInstallmentPlans.BankOtherInstallmentPlans.StoresOtherInstallmentPlans.NoneHousing.RentHousing.OwnHousing.ForFreeJob.UnemployedUnskilledJob.UnskilledResidentJob.SkilledEmployeeJob.Management.SelfEmp.HighlyQualified
        01611694467210.01.0...0.00.01.00.01.00.00.00.01.00.0
        124859512222111.01.0...0.00.01.00.01.00.00.00.01.00.0
        231220962349121.01.0...0.00.01.00.01.00.00.01.00.00.0
        344278822445121.01.0...0.00.01.00.00.01.00.00.01.00.0
        452448703453221.01.0...0.00.01.00.00.01.00.00.01.00.0
        \n

        5 rows × 63 columns

        \n
        \n\n\n\n\n```python\ncredit_data.shape\n```\n\n\n\n\n (1000, 63)\n\n\n\nThe predictor based on how much money was in the applicant's saving account is categorical coded into dummy variables.\n\n\n```python\ncredit_data_saving = credit_data[['SavingsAccountBonds.lt.100', 'SavingsAccountBonds.100.to.500', \n 'SavingsAccountBonds.500.to.1000', 'SavingsAccountBonds.gt.1000', \n 'SavingsAccountBonds.Unknown']]\ncredit_data_saving.head(10)\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 \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
        SavingsAccountBonds.lt.100SavingsAccountBonds.100.to.500SavingsAccountBonds.500.to.1000SavingsAccountBonds.gt.1000SavingsAccountBonds.Unknown
        00.00.00.00.01.0
        11.00.00.00.00.0
        21.00.00.00.00.0
        31.00.00.00.00.0
        41.00.00.00.00.0
        50.00.00.00.01.0
        60.00.01.00.00.0
        71.00.00.00.00.0
        80.00.00.01.00.0
        91.00.00.00.00.0
        \n
        \n\n\n\n\n```python\ncredit_data_saving.apply(np.sum)\n```\n\n\n\n\n SavingsAccountBonds.lt.100 603.0\n SavingsAccountBonds.100.to.500 103.0\n SavingsAccountBonds.500.to.1000 63.0\n SavingsAccountBonds.gt.1000 48.0\n SavingsAccountBonds.Unknown 183.0\n dtype: float64\n\n\n\n| Value | n | <100 | 100-500 | 500-1000 | >1000 | Unknown | \n|:---------|:----:|:----:|:-------:|:--------:|:-----:|:-------:|\n| < 100 | 603 | 1 | 0 | 0 | 0 | 0 |\n| 100-500 | 100 | 0 | 1 | 0 | 0 | 0 |\n| 500-1000 | 63 | 0 | 0 | 1 | 0 | 0 |\n| >1000 | 48 | 0 | 0 | 0 | 1 | 0 |\n| Unknown | 183 | 0 | 0 | 0 | 0 | 1 |\n\n\nUsually, each category gets its own dummy variable that is a zero/one indicator for that group. Only four dummy variables are needed here, the fifth can be inferred. However, the decision to include all of the dummy variables can depend on the choice of the model. Models that include an intercept term, such as simple linear model, would have numerical issues if each dummy variable was included in the model. The reason is that, for each sample, these variables all add up to one and this would provide the same information as the intercept. If the model is insensitive to this type of issue, using the complete set of dummy variables would help improve interpretation of the model.\n\nMany of the advanced models automatically generate highly complex, nonlinear relationships between the predictors and the outcome. More simplistic models do not unless the user manually specifices which predictors should be nonlinear and in what way. Another technique to augment the prediction data for classification model is through the \"*class centroids*\", which are the centers of the predictor data for each class. For each predictor, the distance to each class centroid can be calculated and these distances can be added to the model.\n\n## 3.7 Binning Predictors (to avoid)\n\nThere are many issues with the manual binning of continuous data. First, there can be a significant loss of performance in the model. Second, there is a loss of precision in the predictions when the predictors are categorized. Unfortunately, the predictive models that are most powerful are usually the least interpretable. The bottom line is that the perceived improvement in interpretability gained by manual categorization is usually offset by a significant loss in performance.\n\nNote that the argument here is related to the *manual* categorization of predictors prior to model building. There are several models, such as classification/regression trees and multivariate adaptive regression splines, that estimate cut points in the process of model building. The difference between these methodologies and manual binning is that the models ues all the predictors to derive bins based on a single objective (such as maximizing accuracy). They evaluate many variable simultaneously and are usually based on statistically sound methodologies.\n", "meta": {"hexsha": "8fda5679f52a5ece77472938048f10ec14878913", "size": 620066, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Chapter 3.ipynb", "max_stars_repo_name": "aremirata/IntroductionToMachineLearningAndPredictiveAnalytics", "max_stars_repo_head_hexsha": "2a5586fc37c9ea24f96d92a58a4766522e337c4b", "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": "notebooks/Chapter 3.ipynb", "max_issues_repo_name": "aremirata/IntroductionToMachineLearningAndPredictiveAnalytics", "max_issues_repo_head_hexsha": "2a5586fc37c9ea24f96d92a58a4766522e337c4b", "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": "notebooks/Chapter 3.ipynb", "max_forks_repo_name": "aremirata/IntroductionToMachineLearningAndPredictiveAnalytics", "max_forks_repo_head_hexsha": "2a5586fc37c9ea24f96d92a58a4766522e337c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 225.971574344, "max_line_length": 290606, "alphanum_fraction": 0.8766034583, "converted": true, "num_tokens": 16887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.1112412182933608, "lm_q1q2_score": 0.05128406818438347}} {"text": "\n\n# Lecture 10: Audio Equalizers\nAudio Processing, MED4, Aalborg University, 2020\n\nBy \n- Jesper Kjær Nielsen (jkn@create.aau.dk), Audio Analysis Lab, Aalborg University, and\n- Cumhur Erkut (cer@create.aau.dk), Multisensory Experience Lab, Aalborg University \n\nLast edited: 2020-03-29\n\n

        Table of Contents

        \n\n\n## Introduction\nIn the next 20 minutes, you will learn\n\n- what an audio equalizer is\n\n- what it is used for\n\n- what a parametric equalizer is\n\n\n### Why do we need audio equalizers?\nMany phenomena change the sound before it reaches our ears:\n- amplifier\n- loudspeaker\n- room acoustics\n- our hearing\n- etc.\n\nThe main objective of audio equalizers is to **invert (some of) these changes**!\n\n#### Example: hard surfaces boost the bass of a loudspeaker\nWe need an equalizer to compensate for the boost in bass.\n
        \n \n
        \n\n#### Example: loudspeaker tuning\nWe need to tune the filters in the loudspeaker so that the listener hears what is intended.\n
        \n \n
        \n\n#### Example: equalizing compensation for hearing loss\n
        \n \n
        \n\n### A typical parametric equalizer\nA common audio equalizer is a **parametric equalizer** which functions by\n- dividing the frequency range into a number of bands\n- apply filters in each band which can amplify/attenuate the frequency content in this band\n---\nNote that so-called graphic equalizers is an alternative to the parametric equalizer, but we will not cover that here.\n
        \n \n
        \n\n\n### Example of a block diagram of a parametric equalizer\n
        \n \n
        \n\n\nThe filter in each band of the parametric equalizer is called a **parametric equalizer filter**. It can be either a\n- **first and last band**: lowpass or highpass filter with adjustable cut-off frequency and gain (a **shelving filter**)\n- **bands in the middle**: combination of a bandpass (peak) or a bandstop (notch) filter with adjustable center frequency and bandwidth\n\nNote that\n- both of these filters can be implemented using **a second order feedback (IIR) filter**\n- we will go more into depth with these two kinds of parametric equalizer filters later\n\n### Summary\n1. Audio equalizers are useful in many applications such as room compensation and the tuning of hearing aids\n2. A parametric equaliser is used to amplify/attenuate the frequency content within different bands\n\n### Active 5 minutes break\nAs we see later, the basic ingredient is a **parametric equalizer filter** resulting in the **difference equation**\n$$\n y_n = b_0x_n + b_1 x_{n-1} + b_2 x_{n-2} + a_1y_{n-1} + a_2 y_{n-2}\n$$\n\n1. Do you know this filter? Is this a feedforward or a feedback filter?\n2. What are the feedforward and feedback filter coefficients?\n3. Sketch the difference equations using the delay, summation, and multiplication blocks.\n\n
        \n \n
        \n\n\n## Notch and peak filters\nIn the next 20 minutes, you will learn\n- how a parametric equalizer filter can be designed using a notch (bandstop) and peak (bandpass) filter\n- how the notch filter is designed and controlled\n- how the peak filter is designed and controlled\n\nThe **transfer function** of the parametric equalizer filter $H_\\text{eq}(z)$ is\n$$\n H_\\text{eq}(z) = G_0H_\\text{notch}(z) + G H_\\text{peak}(z)\\ .\n$$\n
        \n \n
        \n\n### Notch (bandstop) filter\nWe will use the following notation:\n- $\\omega_1$ and $\\omega_2$: lower and upper cutoff frequencies in radians/sample\n- $\\omega_0=\\sqrt{\\omega_1\\omega_2}$: center frequency in radians/sample\n- $\\Delta\\omega=\\omega_2-\\omega_1$: bandwidth in radians/sample\n- $G_\\text{B}$: gain at the cutoff frequencies.\n
        \n \n
        \n\nIt can be shown that the transfer function of a notch filter is given by\n$$\n H_\\text{notch}(z) = b\\frac{1-2\\cos(\\omega_0)z^{-1}+z^{-2}}{1-2b\\cos(\\omega_0)z^{-1}+(2b-1)z^{-2}}\n$$\nwhere\n- $\\omega_0$ is the center frequency in radians/sample\n- $b=(1+\\beta)^{-1}$ where\n$$\n \\beta = \\frac{\\sqrt{1-G_\\text{B}^2}}{G_\\text{B}}\\tan(\\Delta\\omega/2)\n$$\n- $G_\\text{B}$ is the gain at the cutoff frequencies $\\omega_1$ and $\\omega_2$\n- $\\Delta\\omega$ is the bandwidth (i.e., $\\omega_2-\\omega_1$) in radians/sample.\n\nThe notch filter results in the difference equation\n$$\n y_n = bx_n -2b\\cos(\\omega_0)x_{n-1}+bx_{n-2} + 2b\\cos(\\omega_0)y_{n-1} - (2b-1) y_{n-2}\n$$\n
        \n \n
        \n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as sig\n\ndef computeNotchFilterParameters(digCenterFreq, digBandwidth, cutoffGain):\n beta = (np.sqrt(1-cutoffGain**2)/cutoffGain)*np.tan(digBandwidth/2)\n b0 = 1/(1+beta)\n b1 = -2*b0*np.cos(digCenterFreq)\n b2 = b0\n a1 = -b1\n a2 = -(2*b0-1)\n feedforwardParams = np.array([b0, b1, b2])\n feedbackParams = np.array([a1, a2])\n return feedforwardParams, feedbackParams\n```\n\n\n```python\nsamplingFreq = 44100 # Hz\ncenterFreq = 1000 # Hz\nbandwidth = 250 # Hz\ncutoffGain = np.sqrt(0.5)\nnDtft = 2048\nfeedforwardParams, feedbackParams = computeNotchFilterParameters(centerFreq*2*np.pi/samplingFreq, \\\n bandwidth*2*np.pi/samplingFreq, cutoffGain)\ndigFreqVector, freqResp = sig.freqz(feedforwardParams, np.r_[1,-feedbackParams],nDtft)\nfreqVector = digFreqVector*samplingFreq/(2*np.pi)\nplt.figure(figsize=(14,6))\nplt.plot(freqVector, np.abs(freqResp))\nplt.xlim((0,freqVector[-1])), plt.ylim((0,1)), plt.xlabel('$f$ [Hz]'), plt.ylabel('$|H_{notch}(f)|$');\n```\n\n### Peak (bandpass) filter\nWe will use the following notation:\n- $\\omega_1$ and $\\omega_2$: lower and upper cutoff frequencies in radians/sample\n- $\\omega_0=\\sqrt{\\omega_1\\omega_2}$: center frequency in radians/sample\n- $\\Delta\\omega=\\omega_2-\\omega_1$: bandwidth in radians/sample\n- $G_\\text{B}$: gain at the cutoff frequencies.\n
        \n \n
        \n\nIt can be shown that the transfer function of a notch filter is given by\n$$\n H_\\text{peak}(z) = (1-b)\\frac{1-z^{-2}}{1-2b\\cos(\\omega_0)z^{-1}+(2b-1)z^{-2}}\n$$\nwhere\n- $\\omega_0$ is the center frequency in radians/sample\n- $b=(1+\\beta)^{-1}$ where\n$$\n \\beta = \\frac{G_\\text{B}}{\\sqrt{1-G_\\text{B}^2}}\\tan(\\Delta\\omega/2)\n$$\n- $G_\\text{B}$ is the gain at the cutoff frequencies $\\omega_1$ and $\\omega_2$\n- $\\Delta\\omega$ is the bandwidth (i.e., $\\omega_2-\\omega_1$) in radians/sample.\n\nThe peak filter results in the difference equation\n$$\n y_n = (1-b)x_n - (1-b)x_{n-2} + 2b\\cos(\\omega_0)y_{n-1} - (2b-1) y_{n-2}\n$$\n
        \n \n
        \n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as sig\n\ndef computePeakFilterParameters(digCenterFreq, digBandwidth, cutoffGain):\n beta = (cutoffGain/np.sqrt(1-cutoffGain**2))*np.tan(digBandwidth/2)\n b = 1/(1+beta)\n b0 = 1-b\n b1 = 0\n b2 = -b0\n a1 = 2*b*np.cos(digCenterFreq)\n a2 = -(2*b-1)\n feedforwardParams = np.array([b0, b1, b2])\n feedbackParams = np.array([a1, a2])\n return feedforwardParams, feedbackParams\n```\n\n\n```python\nsamplingFreq = 44100 # Hz\ncenterFreq = 1000 # Hz\nbandwidth = 2500 # Hz\ncutoffGain = np.sqrt(0.5)\nnDtft = 2048\nfeedforwardParams, feedbackParams = computePeakFilterParameters(centerFreq*2*np.pi/samplingFreq, \\\n bandwidth*2*np.pi/samplingFreq, cutoffGain)\ndigFreqVector, freqResp = sig.freqz(feedforwardParams, np.r_[1,-feedbackParams],nDtft)\nfreqVector = digFreqVector*samplingFreq/(2*np.pi)\nplt.figure(figsize=(14,6))\nplt.plot(freqVector, np.abs(freqResp))\nplt.xlim((0,freqVector[-1])), plt.ylim((0,1)), plt.xlabel('$f$ [Hz]'), plt.ylabel('$|H_{peak}(f)|$');\n```\n\n### Summary\n1. A notch (bandstop) filter can be used to remove frequencies\n
        \n \n
        \n2. A peak (bandpass) filter can be used to remove frequencies\n
        \n \n
        \n\n## Parametric equalizer filter\nIn the next 20 minutes, you will learn\n- how we can combine a notch and a peak filter into a parametric equalizer filter\n\nWe can write the transfer function of the peak and notch filters as\n\\begin{align}\n H_\\text{notch}(z) &= \\frac{A_\\text{notch}(z)}{B_\\text{notch}(z)}\\\\\n H_\\text{peak}(z) &= \\frac{A_\\text{peak}(z)}{B_\\text{peak}(z)}\n\\end{align}\nwhere\n\\begin{align}\n A_\\text{notch}(z) &= b_\\text{notch}(1-2\\cos(\\omega_0)z^{-1}+z^{-2})\\\\\n B_\\text{notch}(z) &= 1-2b_\\text{notch}\\cos(\\omega_0)z^{-1}+(2b_\\text{notch}-1)z^{-2}\\\\\n A_\\text{peak}(z) &= (1-b_\\text{peak})(1-z^{-2})\\\\\n B_\\text{peak}(z) &= 1-2b_\\text{peak}\\cos(\\omega_0)z^{-1}+(2b_\\text{peak}-1)z^{-2}\\ .\n\\end{align}\n\nRecall that the **transfer function** of the parametric equalizer filter $H_\\text{eq}(z)$ is\n$$\n H_\\text{eq}(z) = G_0H_\\text{notch}(z) + G H_\\text{peak}(z)\\ .\n$$\n
        \n \n
        \n\nNote that\n- $G_0$ (which is sometimes called the level) is often set to 1\n- $G>G_0$ results in a boost of some frequencies\n- $G\n \n

    \n\nWe have\n\\begin{align}\n H_\\text{eq}(z) &= G_0H_\\text{notch}(z) + G H_\\text{peak}(z)\\\\\n &= \\frac{G_0A_\\text{notch}(z)B_\\text{peak}(z)+GA_\\text{peak}(z)B_\\text{notch}(z)}{B_\\text{notch}(z)B_\\text{peak}(z)}\n\\end{align}\nwith three interesting special cases:\n1. $G_0=G=1$: the signal passes unaltered, i.e., $H_\\text{eq}(z)=1$\n2. $G_0=1$ and $G=0$: the parametric equalizer filter is a notch filter, i.e., $H_\\text{eq}(z)=H_\\text{notch}(z)$\n3. $G_0=0$ and $G=1$: the parametric equalizer filter is a peak filter, i.e., $H_\\text{eq}(z)=H_\\text{peak}(z)$\n\nAfter a lot of math, it can be shown that\n$$\n H_\\text{eq}(z) = \\frac{b_0 + b_1z^{-1}+b_2z^{-2}}{1 - a_1z^{-1}-a_2z^{-2}}\n$$\nwhere we have defined\n\\begin{alignat}{2}\n b_0 &= \\frac{G_0+G\\alpha}{1+\\alpha}\\ , &\\qquad b_1 &= \\frac{-2G_0\\cos(\\omega_0)}{1+\\alpha}\\\\\n b_2 &= \\frac{G_0-G\\alpha}{1+\\alpha}\\ , &\\qquad a_1 &= \\frac{2\\cos(\\omega_0)}{1+\\alpha}\\\\\n a_2 &= -\\frac{1-\\alpha}{1+\\alpha}\\ , &\\qquad \\alpha &= \\sqrt{\\frac{G_\\text{B}^2-G_0^2}{G^2-G_\\text{B}^2}}\\tan(\\Delta\\omega/2)\\ .\n\\end{alignat}\n\n#### Example: design of parametric equalizer filter\nAssume that the user can control the three parameters\n1. center frequency $\\omega_0$\n2. bandwidth $\\Delta\\omega$\n3. boost/cut $G$\n\nWhen design the parametric equalizer filter as\n1. calculate the cutoff gain as either\n$$\n G_\\text{B}^2 = G_0G \\quad\\text{or}\\quad G_\\text{B} = G_0^2/2+G^2/2\n$$\nwith (typically) $G_0=1$.\n2. Compute $\\alpha$ and the filter coefficients $b_0$, $b_1$, $b_2$, $a_1$, and $a_2$ (see above) \n\nThe parametric equalizer filter results in the difference equation\n$$\n y_n = b_0x_n + b_1 x_{n-1} + b_2 x_{n-2} + a_1y_{n-1} + a_2 y_{n-2}\n$$\n
    \n \n
    \n\n\n```python\ndef paramEqFilterCoefficients(digCenterFreq, digBandwidth, gain, level=1):\n if gain == level:\n feedforwardParams = np.array([1, 0, 0])\n feedbackParams = np.array([0, 0])\n else:\n cutoffGain = np.sqrt((gain**2+level**2)/2) # could also be the geometric mean instead\n alpha = np.sqrt((cutoffGain**2-level**2)/(gain**2-cutoffGain**2))*np.tan(digBandwidth/2)\n b0 = (level+gain*alpha)/(1+alpha)\n b1 = -2*level*np.cos(digCenterFreq)/(1+alpha)\n b2 = (level-gain*alpha)/(1+alpha)\n a1 = 2*np.cos(digCenterFreq)/(1+alpha)\n a2 = -(1-alpha)/(1+alpha)\n feedforwardParams = np.array([b0, b1, b2])\n feedbackParams = np.array([a1, a2])\n return feedforwardParams, feedbackParams\n```\n\n\n```python\nsamplingFreq = 44100 # Hz\ncenterFreq = 1000 # Hz\nbandwidth = 2500 # Hz\ngain = 1\nnDtft = 2048\nfeedforwardParams, feedbackParams = paramEqFilterCoefficients(centerFreq*2*np.pi/samplingFreq, \\\n bandwidth*2*np.pi/samplingFreq, gain)\ndigFreqVector, freqResp = sig.freqz(feedforwardParams, np.r_[1,-feedbackParams],nDtft)\nfreqVector = digFreqVector*samplingFreq/(2*np.pi)\nplt.figure(figsize=(14,6))\nplt.plot(freqVector, np.abs(freqResp))\nplt.xlim((0,freqVector[-1])), plt.ylim((0,2)), plt.xlabel('$f$ [Hz]'), plt.ylabel('$|H_{notch}(f)|$');\n```\n\n### Summary\n1. A parametric equalizer filter is a way of boosting or cutting some frequencies using a combination of peak and notch filters.\n2. Typically, the user can control \n - $\\omega_0$: the center frequency,\n - $\\Delta\\omega$: the bandwidth, and\n - $G$: the amount of boost/cut \n\n
    \n \n
    \n\n### Active 5 minutes break\n1. Together with your neighbour, explain as much as you can about the equalizer on the picture (i.e., number of bands, user parameters, etc.)\n
    \n \n
    \n\n## Shelving filters \nIn the next 20 minutes, you will learn\n- what a shelving filter is and why we need them\n- that a shelving filter is a special case of the parametric equalizer filter\n\nRecall that a **parametric equalizer** functions by\n- dividing the frequency range into a number of bands\n- apply filters in each band which can amplify/attenuate the frequency content in this band\n\nWhat about the first (low frequencies) and last (high frequencies) band?\n
    \n \n
    \n\nFor the low and high frequencies, traditional low- and highpass filters are used instead of peak and notch filters. When used as shown below, the filter is called a **shelving filter**!\n\nThe shelving filter exists in two forms:\n1. Low frequency shelving filter\n2. High frequency shelving filter\n\n
    \n \n
    \n\n### Low frequency shelving filter\nThe low frequency shelving filter is simply the **parametric equalizer filter** with $\\omega_0 = 0$ which can be written as\n\\begin{align}\n H_\\text{low}(z) &= \\frac{(b_0-b_2z^{-1})(1-z^{-1})}{(1+a_2z^{-1})(1-z^{-1})}\\\\\n &= \\frac{b_0-b_2z^{-1}}{1+a_2z^{-1}}\n\\end{align}\nsince $\\cos(\\omega_0)=1$ for $\\omega_0=0$ where (as before)\n\\begin{alignat}{2}\n b_0 &= \\frac{G_0+G\\alpha}{1+\\alpha}\\ , &\\qquad b_2 &= \\frac{G_0-G\\alpha}{1+\\alpha}\\\\\n a_2 &= -\\frac{1-\\alpha}{1+\\alpha}\\ , &\\qquad \\alpha &= \\sqrt{\\frac{G_\\text{B}^2-G_0^2}{G^2-G_\\text{B}^2}}\\tan(\\Delta\\omega/2)\\ .\n\\end{alignat}\n\nIn the context of the **low frequency shelving filter**, the meaning of $\\Delta\\omega$ and $G_\\text{B}$ are\n- $\\Delta\\omega$: the cutoff frequency which is sometimes denoted as $\\omega_\\text{c}$\n- $G_\\text{B}$: the gain at the cutoff frequency which is sometimes denoted as $G_\\text{C}$\n\n
    \n \n
    \n\n\n```python\nsamplingFreq = 44100 # Hz\ncenterFreq = 1 # Hz - for low shelving filter\ncutoffFreq = 250 # Hz\ngain = 1\nnDtft = 2048\nfeedforwardParams, feedbackParams = paramEqFilterCoefficients(centerFreq*2*np.pi/samplingFreq, \\\n cutoffFreq*2*np.pi/samplingFreq, gain)\ndigFreqVector, freqResp = sig.freqz(feedforwardParams, np.r_[1,-feedbackParams],nDtft)\nfreqVector = digFreqVector*samplingFreq/(2*np.pi)\nplt.figure(figsize=(14,6))\nplt.plot(freqVector, np.abs(freqResp))\nplt.xlim((0,freqVector[-1])), plt.ylim((0,2)), plt.xlabel('$f$ [Hz]'), plt.ylabel('$|H_{low}(f)|$');\n```\n\n### High frequency shelving filter\nThe high frequency shelving filter is simply the **parametric equalizer filter** with $\\omega_0 = \\pi$ which can be written as\n\\begin{align}\n H_\\text{high}(z) &= \\frac{(b_0+b_2z^{-1})(1-z^{-1})}{(1-a_2z^{-1})(1-z^{-1})}\\\\\n &= \\frac{b_0+b_2z^{-1}}{1-a_2z^{-1}}\n\\end{align}\nsince $\\cos(\\omega_0)=-1$ for $\\omega_0=\\pi$ where (as before)\n\\begin{alignat}{2}\n b_0 &= \\frac{G_0+G\\alpha}{1+\\alpha}\\ , &\\qquad b_2 &= \\frac{G_0-G\\alpha}{1+\\alpha}\\\\\n a_2 &= -\\frac{1-\\alpha}{1+\\alpha}\\ , &\\qquad \\alpha &= \\sqrt{\\frac{G_\\text{B}^2-G_0^2}{G^2-G_\\text{B}^2}}\\tan(\\Delta\\omega/2)\\ .\n\\end{alignat}\n\nIn the context of the **high frequency shelving filter**, the meaning of $\\Delta\\omega$ and $G_\\text{B}$ are\n- $\\Delta\\omega$: the Nyquist frequency minus the cutoff frequency, i.e., $\\Delta\\omega=\\pi-\\omega_\\text{c}$\n- $G_\\text{B}$: the gain at the cutoff frequency which is sometimes denoted as $G_\\text{C}$\n\n
    \n \n
    \n\n\n```python\nsamplingFreq = 44100 # Hz\ncenterFreq = samplingFreq/2 # Hz - for high shelving filter\ncutoffFreq = 20000 # Hz\ngain = 1.5\nnDtft = 2048\nfeedforwardParams, feedbackParams = paramEqFilterCoefficients(centerFreq*2*np.pi/samplingFreq, \\\n np.pi-cutoffFreq*2*np.pi/samplingFreq, gain)\ndigFreqVector, freqResp = sig.freqz(feedforwardParams, np.r_[1,-feedbackParams],nDtft)\nfreqVector = digFreqVector*samplingFreq/(2*np.pi)\nplt.figure(figsize=(14,6))\nplt.plot(freqVector, np.abs(freqResp))\nplt.xlim((0,freqVector[-1])), plt.ylim((0,2)), plt.xlabel('$f$ [Hz]'), plt.ylabel('$|H_{high}(f)|$');\n```\n\n### Multi-band parametric equalizer\nBuilding a multi-band parametric equalizer is simply a question of\n- designing a number of parametric equalizer filters (possibly as low and high shelving filters)\n- connect all the parametric equalizer filters in series\n
    \n \n
    \n\n\n```python\ndef multibandParametricEq(digCenterFreqs, digBandwidths, gains, nDtft=0):\n nBands = np.size(digCenterFreqs)\n feedforwardParams = np.zeros((3,nBands))\n feedbackParams = np.zeros((2,nBands))\n if nDtft > 0:\n freqResp = np.ones(nDtft)\n for ii in np.arange(nBands):\n feedforwardParams[:,ii], feedbackParams[:,ii] = \\\n paramEqFilterCoefficients(digCenterFreqs[ii], digBandwidths[ii], gains[ii])\n if nDtft > 0:\n digFreqVector, iifreqResp = \\\n sig.freqz(feedforwardParams[:,ii], np.r_[1,-feedbackParams[:,ii]],nDtft)\n freqResp = freqResp*iifreqResp\n if nDtft > 0:\n return feedforwardParams, feedbackParams, digFreqVector, freqResp\n else:\n return feedforwardParams, feedbackParams\n```\n\n\n```python\nsamplingFreq = 44100 # Hz\ncenterFreqs = np.array([1, 3000, 10000, samplingFreq/2]) # Hz\nbandwidths = np.array([1000, 1000, 300, 15000]) # Hz\ngains = np.array([1.2, 0.2, 2, 0.8])\nnDtft = 2048\nfeedforwardParams, feedbackParams, digFreqVector, freqResp = \\\n multibandParametricEq(centerFreqs*2*np.pi/samplingFreq, bandwidths*2*np.pi/samplingFreq, gains, nDtft)\n```\n\n\n```python\nfreqVector = digFreqVector*samplingFreq/(2*np.pi)\nplt.figure(figsize=(14,6))\nplt.plot(freqVector, np.abs(freqResp))\nplt.xlim((0,freqVector[-1])), plt.ylim((0,2)), plt.xlabel('$f$ [Hz]'), plt.ylabel('$|H_{high}(f)|$');\n```\n\n### Summary\n1. Shelving filters are low and high pass filters which can either amplify or attenuate low and high frequencies.\n2. Shelving filters are used only for the first and last band of an equalizer.\n3. A shelving filter is a special case of the parametric equalizer filter.\n
    \n \n
    \n", "meta": {"hexsha": "65687ce9dea0b4d58dc2d4c5c029a99eed03ae09", "size": 144369, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectureA_Eq/apLecture10.ipynb", "max_stars_repo_name": "SMC-AAU-CPH/med4-ap-jupyter", "max_stars_repo_head_hexsha": "398fbb0bd06a879127ab020d7dc09121c2c67822", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-03T08:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T04:26:04.000Z", "max_issues_repo_path": "lectureA_Eq/apLecture10.ipynb", "max_issues_repo_name": "SMC-AAU-CPH/med4-ap-jupyter", "max_issues_repo_head_hexsha": "398fbb0bd06a879127ab020d7dc09121c2c67822", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-10T21:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T21:00:48.000Z", "max_forks_repo_path": "lectureA_Eq/apLecture10.ipynb", "max_forks_repo_name": "SMC-AAU-CPH/med4-ap-jupyter", "max_forks_repo_head_hexsha": "398fbb0bd06a879127ab020d7dc09121c2c67822", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-04T12:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T02:40:10.000Z", "avg_line_length": 133.7988878591, "max_line_length": 26884, "alphanum_fraction": 0.8613206436, "converted": true, "num_tokens": 6959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.13296422989056964, "lm_q1q2_score": 0.05117954499048459}} {"text": "```javascript\n%%javascript\n$('#appmode-leave').hide();\n$('#copy-binder-link').hide();\n$('#visit-repo-link').hide();\n```\n\n# Crystal Violet - numerical lab\n\n### Video credit: Creative Studios at The University of Texas at El Paso\n\n\n```python\n# Crystal Violet - numerical lab\nfrom IPython.display import YouTubeVideo\n# Video credit: Creative Studios at The University of Texas at El Paso\nYouTubeVideo('tcv5Xk9ZXpg')\n```\n\n## Introduction to the experiment\nIn this experiment a UV-Vis spectrophotometer will be used to measure the absorbance as the reaction\nbetween crystal violet and hydroxide proceeds. \nThe absorbance versus time data will be used to determine the rate of the reaction with respect to both crystal violet and hydroxide ions.\nCrystal violet has many uses, which include its use as a dye, as a constituent in inks for printing, as an antibacterial and antifungal, to treat mouth ulcers and for the development of fingerprints in forensics.\nThe dye has problems; the process requires the colour to be set in a highly basic washing soda and it has found that the dye looses it’s colour over time during this process. \nThe goal of this experiment is to investigate the decolourisation of the dye by studying the role of sodium hydroxide in the kinetics of crystal violet decolourisation.\n\n## Theory\nThe rate (or velocity) $\\nu\\ [mol L^{-1} s{-1}]$ of a chemical reaction can be expressed in terms of the loss of reactants or the formation of products. For the reaction:\n\n\\begin{equation}\nn_aA + n_bB + \\dots \\to n_xX + n_yY + \\dots\n\\end{equation}\n\nthe rate can be written as\n\n\\begin{equation}\n\\nu = -\\frac{1}{n_a}\\frac{\\mathrm{d[A]}}{\\mathrm{d}t} = -\\frac{1}{n_b}\\frac{\\mathrm{d[B]}}{\\mathrm{d}t} = \\frac{1}{n_x}\\frac{\\mathrm{d[X]}}{\\mathrm{d}t} = \\frac{1}{n_y}\\frac{\\mathrm{d[Y]}}{\\mathrm{d}t} = \\dots\n\\end{equation}\n\nwhere $n_a$, $n_b$, $n_x$ and $n_y$, and [A], [B], [X] and [Y] are the stoichiometric coefficients and molar concentrations of the reactants and products.\nNote that the rate is always a positive quantity, hence the equation have different sign to account for the \\emph{loss} of reactants, or the \\emph{formation} of products.\n\nThe rate, $\\nu$, of a chemical reaction is frequently found to be proportional to the concentrations of the reacting species.\n\n\\begin{equation}\n\\nu = k_r \\mathrm{[A]}^a \\mathrm{[B]}^b \\mathrm{[C]}^c\n\\end{equation}\n\nWhere $k_r$ is the rate constant and $a$, $b$, and $c$ denote the order of the reaction with\nrespect to reactants A, B and C.\nThe sum of the individual orders of the reactants is the overall order of the reaction. \nMost reactions are a complicated series of elementary reactions, and the measured rate is generally the rate of the slowest step. \nTherefore knowledge of the order of each reactant with respect to the overall reaction often allows the specific reaction mechanisms to be theorized.\nThe rate of any reaction can vary with time, and therefore it is impossible to define a general rate of a reaction. \nRather an instantaneous rate can be determined for any particular time. \nIf one can determine the concentation of a reactant (or product) as a function of time, this instantaneous rate will be given by the tangent of the time-concentration curve.\n\nThe time-concentration curve corresponds to the \\emph{integrated} rate law and it is often more useful that the instantaneous rate.\n\n| Reaction Order | Differential form | Intergrated form |\n|:------------------|:-----------------:|------------------:|\n| Zeroth order | $\\nu=k_r\\mathrm{[A]}^0$ | $\\mathrm{[A]} = \\mathrm{[A]}_0 - k_r t$ |\n| First order | $\\nu=k_r\\mathrm{[A]}^1$ | $\\ln\\mathrm{[A]} = \\ln\\mathrm{[A]}_0 - k_r t$ |\n| Second order | $\\nu=k_r\\mathrm{[A]}^2$ | $\\frac{1}{\\mathrm{[A]}} = \\frac{1}{\\mathrm{[A]}_0} + k_r t$ |\n\nwhere the subscript 0 denoted the initial concentration and $t$ is the time of when the concentration, [A], is measured.\n\nFor a **zeroth order** reaction the rate is constant and independent of the concentration of the reactant, [A]. Therefore a plot of the concentration of the reactant vs. time will be linear with a negative slope. The slope can be used to find the rate constant $k_r$, which will have units of (concentration/time).\n\nFor a **first order** reaction the rate is directly proportional to the concentration of the reactant, [A]. Therefore a plot of the natural log of the concentration of the reactant vs. time will be linear with a negative slope. The slope can be used to find the rate constant $k_r$, which will have units of (time)$^{-1}.\n\nFor a **second order** reaction the rate is directly proportional to the square of the concentration of the reactant, [A]. Therefore a plot of the reciprocal of the concentration of the reactant vs. time will be linear with a positive slope. The slope can be used to find the rate constant $k_r$, which will have units of (concentration*time)$^{-1}.\nSecond order reactions can arise when a reaction is first order in two separate reactants. The method of isolation described next, applies to this scenario.\n\n### Isolation method\nWhen an elementary reaction involves more than one reactant, \n\n\\begin{equation}\nn_aA + n_bB + n_cC \\to n_xX + n_yY + \\dots\n\\end{equation}\n\nthe most general form of the instantaneous rate equation includes the concentration of all these species\n\n\\begin{equation}\n\\nu = k_r \\mathrm{[A]}^a \\mathrm{[B]}^b \\mathrm{[C]}^c\n\\end{equation}\n\nIt is then much more difficult to analyse the rate equation in a way similar to that described above for simple zero, first and second order processes. \nThe analysis can be greatly simplified by **isolating** one reactant. \nIn the isolation method, all concentrations the rate equation are kept (as much as possible to) constant, except for one. \nThis is usually achieved by having all but one reactant present in large excess, so the concentration hardly changes during the reaction. \nIn this case, the limiting reagent (for example, A) is said to be isolated, and its concentration is measured as a function of time to determine the kinetics of the reaction. Then we can rewrite the rate equation as\n\n\\begin{equation}\n\\nu = k^\\dagger_r \\mathrm{[A]}^a\n\\end{equation}\n\nWhere $k^\\dagger_r$ is a new “pseudo rate constant” incorporating the values of [B]$^b$ and [C]$^c$.\nNote that the value of $k^\\dagger_r$ depends on the chosen “constant” values of [B] and [C]..\n\n\\begin{equation}\nk^\\dagger_r = k_r \\mathrm{[B]}^b \\mathrm{[C]}^c\n\\end{equation}\n\nNow that A is **isolated**, we can apply the methods of analysis for a single reactant to\nany complicated reaction and determine the order of that reaction with respect to A and $k^\\dagger_r$ . \nThis is done by plotting the relationships for zero, first and second orders, and choosing which plot fits best (*i.e.* which is the most linear). \n\nTo find $b$, $c$ and $k_r$ we can look at a logarithmic form of the pseudo-rate constant\n\n\\begin{equation}\n\\log k^\\dagger_r = b \\log\\mathrm{[B]} + c \\log\\mathrm{[C]} + \\log k_r\n\\end{equation}\n\nThis means that if $k^\\dagger_r$ is found for different values of [B] (while [C] is kept constant and the conditions are still met for isolation of A), then $b$ can be found from a plot\nof $\\log k^\\dagger_r$ versus $\\log\\mathrm{[B]}$. \nA near-integer value of slope can be rounded to the integer, as the order of reaction is expected to be an integer.\nSimilarly, if $k^\\dagger_r$ is found for different values of [C] (while [B] is kept constant and the conditions are still met for isolation of A), then $c$ can be found from a plot of $\\log k^\\dagger_r$ versus $\\log\\mathrm{[C]}$. A near-integer value of slope can be rounded to the integer, as the order of reaction is expected to be an integer.\nFinally, now that $b$, and $c$ have been found, $k_r$ can be found using the intercepts of the $\\log–\\log$ plots.\n\n## The Reaction between Crystal violet and hydroxide\nCrystal violet, CV, and hydroxide react according to the following reaction:\n\n\\begin{equation}\n\\mathrm{CV^+} + \\mathrm{OH^-} \\to \\mathrm{CVOH}\n\\end{equation}\n\nThe reaction rate can therefore be expressed in the form:\n\n\\begin{equation}\n\\nu = k_r \\mathrm{[CV^+]}^a \\mathrm{[OH^-]}^b\n\\end{equation}\n\nThe method of isolation is used by isolating crystal violet and using it to evaluate the order of the reaction with respect to the reactants separately. \nThe rate of the reaction can therefore be written as:\n\n\\begin{equation}\n\\nu = k^\\dagger_r \\mathrm{[CV^+]}^a\n\\end{equation}\n\nwhere\n\n\\begin{equation}\nk^\\dagger_r = k_r \\mathrm{[OH^-]}^b\n\\end{equation}\n\n\n## Relating absorbance and concentration\nSince the absorbance, A, of the crystal violet is monitored as a function of time, it is not necessary to know the actual concentration of the crystal violet at any particular time. Beer’s law can be used to relate the absorbance, Ab and the crystal violet concentration, [CV+] by the equation:\n\n\\begin{equation}\nAb = \\varepsilon\\ l\\ \\mathrm{[CV^+]}\n\\end{equation}\n\nWhere $\\varepsilon$ is the molar absorptivity of crystal violet at the wavelength of the maximum absorption peak, $l$ is the length of the cuvette ($l$ = 1cm) and $\\mathrm{[CV+]}$ is the crystal violet concentration.\nThe absorbance, $Ab$, may therefore be used as a proxy of the crystal violet concentration in all calculations.\n\nThe integrated form equations for zero, first and second order can be rearranged and [CV+]o/[CV+]t substituted for Abo/Abt. This will give theoretical expressions that relate the absorbance values to time and to the rate constant kr’.\n\n### Refences\n\nBackground information from:\n\nAtkins P & de Paula J, Atkins’ Physical Chemistry, ninth edition, Oxford University Press, Oxford\n\nExperiment:\n\nRandall J, Holmquist D & Volz D 2010, Chemistry with Vernier, American Chemical Society\nJ. Chem. Educ. (2015), 92, pp 1692–1695. DOI: 10.1021/ed500876y\n\n## Aims\n1. Determine the rate law \n2. Determine the rate constant \n3. Determine the activation energy\n\n## Virtual experiment procedure\n1. Choose a weight for you samples (benzioc acid, Sucrose and naphthalene)\n2. Choose the amount of water in the calorimeter\n\n\n## Numerical skills \n\n1. fitting of portions of data\n2. error analysis\n\n## Pre-lab questions\n1. Rewrite the integrated form equations for zero, first and second order in terms of absorption.\n 1. What is the main consequence of using the absorbcance instead of the concentration in the calculations ?\n 2. would this affect the results for the reaction order and activation energy ?\n2. Find literature values for the rate law and activation energy for the reaction between crystal violet and hydroxide.\n3. In the **real** experiment the samples will be prepared by mixing comparable amounts of liquid taken from a $2.5\\times10^{-5}$ M stock solution of CV and a 0.25 M stock solution of NaOH. \nIf you run two batches of experiments where you alternatively keep the amount of one of the two solutions constant, which species is **isolated** in the two sets?\n\n## Questions to be answered in the lab report\n1. What is the rate law for the reaction between Crystal Violet and hydroxide ?\n 1. what is the order of the reaction with respect to [CV$^+$] ?\n 2. what is the order of the reaction with respect to [OH$^-$] ?\n2. What is the activation energy for the reaction ?\n3. How do your estimates compare with literature values ?\n\n\n## Launch virtual experiment\n- [Crystal Violet virtual lab](virtualExperiment.ipynb)\n", "meta": {"hexsha": "1e84f8b14f68bda6960ce293bd8084e1a1b96d8a", "size": 14643, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week_06_crystalViolet/crystalViolet.ipynb", "max_stars_repo_name": "blake-armstrong/TeachingNotebook", "max_stars_repo_head_hexsha": "30cdca5bffd552eaecc0368c3e92744c4d6d368c", "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": "week_06_crystalViolet/crystalViolet.ipynb", "max_issues_repo_name": "blake-armstrong/TeachingNotebook", "max_issues_repo_head_hexsha": "30cdca5bffd552eaecc0368c3e92744c4d6d368c", "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": "week_06_crystalViolet/crystalViolet.ipynb", "max_forks_repo_name": "blake-armstrong/TeachingNotebook", "max_forks_repo_head_hexsha": "30cdca5bffd552eaecc0368c3e92744c4d6d368c", "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": 50.147260274, "max_line_length": 359, "alphanum_fraction": 0.6382571877, "converted": true, "num_tokens": 2974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421498454004374, "lm_q2_score": 0.1732882123335211, "lm_q1q2_score": 0.05098398871267873}} {"text": "\n\n# Deep Learning and Applied AI project\n## *Growing 3D Neural Cellar Automaton*\n\n\n\n```python\n# Clone the github repo on content folder\n# of google colab machine\n!git clone https://github.com/francesco-cubito97/DLAI_project_3D_NCA\n\n# Create the model checkpoints folder\n# in a more stable memory, like google drive\nfrom google.colab import drive\ndrive.mount(\"/content/gdrive\")\n```\n\n Cloning into 'DLAI_project_3D_NCA'...\n remote: Enumerating objects: 123, done.\u001b[K\n remote: Counting objects: 100% (30/30), done.\u001b[K\n remote: Compressing objects: 100% (30/30), done.\u001b[K\n remote: Total 123 (delta 18), reused 0 (delta 0), pack-reused 93\u001b[K\n Receiving objects: 100% (123/123), 10.70 MiB | 7.01 MiB/s, done.\n Resolving deltas: 100% (50/50), done.\n Mounted at /content/gdrive\n\n\n\n```python\nMAIN_FOLDER = \"/content/gdrive/MyDrive/DLAI_project_3D_NCA\"\nOBJECTS_FOLDER = \"/content/DLAI_project_3D_NCA/Objects\"\nBINVOX_PATH = \"/content/DLAI_project_3D_NCA\"\n# Here will save the checkpoints\nCHECKPOINTS_FOLDER = MAIN_FOLDER + \"/Checkpoints\"\n\n# Here I will save gifs\nGIFS_FOLDER = MAIN_FOLDER + \"/Gifs\"\n\n# Here I will save losses to generate plots\nLOG_FOLDER = MAIN_FOLDER + \"/Logs\"\n\n# Here there are some pretrained models\nPRETRAINED_FOLDER = \"/content/DLAI_project_3D_NCA/Pretrained_models\"\n\nimport sys\nsys.path.append(MAIN_FOLDER)\nsys.path.append(BINVOX_PATH)\n```\n\n\n```python\n# Create all folder and clear all old contents if exist\n!mkdir -p $MAIN_FOLDER && rm -f $MAIN_FOLDER/*\n!mkdir -p $CHECKPOINTS_FOLDER && rm -f $CHECKPOINTS_FOLDER/*\n!mkdir -p $GIFS_FOLDER && rm -f $GIFS_FOLDER/*\n!mkdir -p $LOG_FOLDER && rm -f $LOG_FOLDER/*\n```\n\n rm: cannot remove '/content/gdrive/MyDrive/DLAI_project_3D_NCA/Checkpoints': Is a directory\n rm: cannot remove '/content/gdrive/MyDrive/DLAI_project_3D_NCA/Gifs': Is a directory\n rm: cannot remove '/content/gdrive/MyDrive/DLAI_project_3D_NCA/Logs': Is a directory\n\n\n\n```python\n# Import all needed components\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import Image\nimport imageio\nimport os\nfrom typing import Optional, Callable, Dict, Union\n\n# Deep Learning libraries\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nfrom torchvision import datasets, models, transforms\n\n# Visualization libraries\nfrom torchsummary import summary\nimport binvox_rw #Taken from https://github.com/dimatura/binvox-rw-py\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import to_rgb\n%matplotlib inline\nsns.set()\n# Reproducibility stuff\nimport random\nseed = 7\ntorch.manual_seed(seed)\nnp.random.seed(seed)\nrandom.seed(seed)\ntorch.cuda.manual_seed(seed)\n\n# This can be set also to False with performance improvement\ntorch.backends.cudnn.deterministic = True \ntorch.backends.cudnn.benchmark = False\n```\n\n\n```python\n# Global variables\nBINVOX_PATHS = {\n \"cow\": \"/cow_minecraft_14x8x16.binvox\",\n \"fox\": \"/fox_minecraft_7x10x16.binvox\",\n \"wolf\": \"/wolf_minecraft_16x5x9.binvox\",\n}\nfor p in BINVOX_PATHS:\n BINVOX_PATHS[p] = OBJECTS_FOLDER + BINVOX_PATHS[p]\n print(f\"Element: {p}, path:{BINVOX_PATHS[p]}\")\n\n# Some useful color\nCOLORS = {\n \"cow\": to_rgb(\"#f2cB68\"),\n \"fox\": to_rgb(\"#df5d5d\"),\n \"wolf\": to_rgb(\"#42b0c1\")\n}\n\n# Training variables\nN_CHANNELS = 32\nDIM = 16\nPADDING = 4\nTOT_ITERATIONS = 16000\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(f'Using device: {DEVICE}')\n```\n\n Element: cow, path:/content/DLAI_project_3D_NCA/Objects/cow_minecraft_14x8x16.binvox\n Element: fox, path:/content/DLAI_project_3D_NCA/Objects/fox_minecraft_7x10x16.binvox\n Element: wolf, path:/content/DLAI_project_3D_NCA/Objects/wolf_minecraft_16x5x9.binvox\n Using device: cuda:0\n\n\n\n```python\ndef loadBinvox(path):\n '''\n Load binvox model and convert it into numpy array\n for simplicity\n \n Params\n ------\n - path: path of the model\n\n Returns\n -------\n - voxels numpy array\n '''\n with open(path, 'rb') as f:\n voxels = binvox_rw.read_as_3d_array(f)\n \n return np.array(voxels.data, dtype=bool)\n\ndef plotVoxels(voxels, title : str=\"Voxels models\", figsize : tuple=(10, 10), c=None) -> None:\n '''\n Plot voxels starting from numpy array\n \n Params\n ------\n - voxels: numpy array of boolean voxels\n - figsize: dimension in inches of image\n - c: color to use in rgba. Can be a single float, a list of 3/4 float in [0, 1] or [0, 255] range or a 4D array of RGB/RGBA colors, one for each voxel\n \n Returns\n -------\n - `None`\n '''\n fig = plt.figure(figsize=figsize)\n \n ax = fig.add_subplot(projection=\"3d\")\n\n if c is not None: colors = c # Set to middle gray\n else: colors = [0.5, 0.5, 0.5]\n \n ax.voxels(voxels, facecolor=colors, edgecolor=[1.0, 1.0, 1.0])\n \n # Change point of view of camera\n #ax.set_title(f\"View {abs(i*(360//tot))} degree\")\n #ax.view_init(0, i*(360//tot))\n\n fig.suptitle(title, fontsize=figsize[0]*4)\n plt.show()\n\ndef createBox(obj):\n '''\n Calculate the box around a 3d object\n \n Params\n ------\n - obj: space in which lies the 3d object\n\n Returns\n -------\n - 3d box object\n '''\n # Get coordinates of the object\n coord = (obj > 0).nonzero()\n\n # Calculate where each dimension starts and ends\n # for the object\n start_x = torch.min(coord[:, 0]) \n size_x = torch.max(coord[:, 0]) - start_x + 1\n \n start_y = torch.min(coord[:, 1])\n size_y = torch.max(coord[:, 1]) - start_y + 1\n \n start_z = torch.min(coord[:, 2])\n size_z = torch.max(coord[:, 2]) - start_z + 1\n \n\n # Create the parallelepiped with the defined dimensions\n x = slice(start_x, start_x + size_x)\n y = slice(start_y, start_y + size_y)\n z = slice(start_z, start_z + size_z)\n\n parallelepiped = torch.zeros_like(obj)\n parallelepiped[x, y, z] = 1.0\n\n return parallelepiped.clone().detach()\n\ndef centerObj(obj):\n '''\n Centralize a 3d object in the space in which it lies\n \n Params\n ------\n - obj: the object that should be centralized\n\n Returns\n -------\n - The centered object\n '''\n # Get center of the space\n center_s = torch.tensor([obj.shape[0]//2, obj.shape[1]//2, obj.shape[2]//2])\n\n ## To center the object we need to count how many\n ## vertices of distance there are between the\n ## center position and the center of the parallelepiped\n\n # Get the box around the object\n p = createBox(obj)\n \n # Get the parallelepiped coordinates\n coord = (p > 0).nonzero()\n \n # Sum all voxels coordinates and average to get centroid\n sum = coord.sum(dim=0)\n centroid = torch.div(sum, coord.shape[0], rounding_mode=\"floor\")\n\n # Get the shift value in voxels between the two centers\n shift = tuple(center_s - centroid)\n\n\n # Move the object to the center of the space\n # based on the box center calculated\n obj = torch.roll(obj, shift, (0, 1, 2))\n\n # Get the parallelepiped coordinates\n coord = (obj > 0).nonzero()\n \n # Average to get centroid\n sum = coord.sum(dim=0)\n centroid = torch.div(sum, coord.shape[0], rounding_mode=\"floor\")\n\n return obj\n\n# One temptative to speed up the training\ndef erosion3D(obj):\n '''\n Morphological 3d erosion of object\n \n Params\n ------\n - obj: the object that should be eroded\n\n Returns\n -------\n - Eroded object\n '''\n # Create a copy of the object \n o = obj.clone().detach()\n # Create the 3D average pool operation\n avgP1 = nn.AvgPool3d((1, 1, 3), stride=(1, 1, 1))\n avgP2 = nn.AvgPool3d((1, 3, 1), stride=(1, 1, 1))\n avgP3 = nn.AvgPool3d((3, 1, 1), stride=(1, 1, 1))\n # Return the mask of elements\n mask1 = F.pad(avgP1(o) < 1.0, [1, 1, 0, 0, 0, 0])\n mask2 = F.pad(avgP2(o) < 1.0, [0, 0, 1, 1, 0, 0])\n mask3 = F.pad(avgP3(o) < 1.0, [0, 0, 0, 0, 1, 1])\n \n print(mask1.shape, mask2.shape, mask3.shape)\n\n # Invert the mask\n mask = ~(mask1 & mask2 & mask3)\n \n # Multiply the mask to the original\n # object to erode it\n return o * mask.float()\n```\n\n\n```python\n# Loading all binvox models and visualizing them\ntarget_objects = {\n \"cow\": None,\n \"fox\": None,\n \"wolf\": None\n}\n\no = \"cow\"\nvx = loadBinvox(BINVOX_PATHS[o])\n# Rotate to adjust\ntarget_objects[o] = torch.tensor(np.rot90(vx, k=1, axes=(2, 1)).copy())\ntarget_objects[o] = F.pad(target_objects[o], [PADDING, PADDING, PADDING, PADDING, PADDING, PADDING])\ntarget_objects[o] = centerObj(target_objects[o]).float()\n\no = \"fox\"\nvx = loadBinvox(BINVOX_PATHS[o])\ntarget_objects[o] = torch.tensor(np.rot90(vx, k=1, axes=(0, 1)).copy())\ntarget_objects[o] = F.pad(target_objects[o], [PADDING, PADDING, PADDING, PADDING, PADDING, PADDING])\ntarget_objects[o] = centerObj(target_objects[o]).float()\n\no = \"wolf\"\nvx = loadBinvox(BINVOX_PATHS[o])\ntarget_objects[o] = torch.tensor(np.rot90(np.rot90(vx, k=2, axes=(0, 1)), k=1, axes=(1, 2)).copy())\ntarget_objects[o] = F.pad(target_objects[o], [PADDING, PADDING, PADDING, PADDING, PADDING, PADDING])\ntarget_objects[o] = centerObj(target_objects[o]).float()\n\n\nfor key in target_objects:\n print(target_objects[key].shape)\n\n```\n\n torch.Size([24, 24, 24])\n torch.Size([24, 24, 24])\n torch.Size([24, 24, 24])\n\n\n\n```python\n# Visualize the result\nfor key in target_objects:\n plotVoxels(target_objects[key].numpy(), figsize=(5, 5), c=COLORS[key])\n print(\"Object shape\", target_objects[key].shape)\n```\n\n## Project details\nNow the steps are consequential. We should obtain a neural network able to output at each time step a new configuration of the final object in 3D voxels, each one with a certain probability of existence that is dependent, like in the original paper, on a value that we will call $\\alpha$, that will represent the live itself.\nIn our case:\n\\begin{align}\n 0 \\le \\alpha \\le 1\n\\end{align}\nand will have the folling meaning:\n- $0\\le \\alpha < 0.1$: dead cell\n- $0.1\\le \\alpha < 0.5$: growing cell \n- $0.5\\le \\alpha \\le1$: mature cell\n\nThe network will be composed of an initial layer that will make a 3D convolutional operation with *Sobel Filter* (taken from [here](https://https://stackoverflow.com/questions/7330746/implement-3d-sobel-operator)):\n>\n>\n>\n\nThe central cell will be passed directly, without any filter (identity filter).\n\n\n\n```python\n#@title Sobel filters and identity filter\n# 3D Sobel filters to make a comparison with the one\n# found during training\nSF_X = torch.tensor([\n [[-1, 0, 1],\n [-2, 0, 2],\n [-1, 0, 1]],\n [[-2, 0, 2],\n [-4, 0, 4],\n [-2, 0, 2]],\n [[-1, 0, 1],\n [-2, 0, 2],\n [-1, 0, 1]],\n ]).float()\n# Normalize the values for the application of the convolutions \n# with the (filter.x * filter.y * filter.z) neighbors\nneighbors = SF_X.shape[0] * SF_X.shape[1] * SF_X.shape[2] - 1\n\nSF_X = SF_X/neighbors\nSF_Y = torch.einsum(\"xyz -> xzy\", SF_X)\nSF_Z = torch.einsum(\"xyz -> zyx\", SF_X)\n\nprint(SF_X , \"\\n\")\nprint(SF_Y , \"\\n\")\nprint(SF_Z , \"\\n\")\n\n# Identity filter\nIDF = torch.tensor([0, 1, 0]).float()\nIDF = torch.einsum(\"a, b, c -> abc\", IDF, IDF, IDF)\nprint(IDF)\n```\n\n tensor([[[-0.0385, 0.0000, 0.0385],\n [-0.0769, 0.0000, 0.0769],\n [-0.0385, 0.0000, 0.0385]],\n \n [[-0.0769, 0.0000, 0.0769],\n [-0.1538, 0.0000, 0.1538],\n [-0.0769, 0.0000, 0.0769]],\n \n [[-0.0385, 0.0000, 0.0385],\n [-0.0769, 0.0000, 0.0769],\n [-0.0385, 0.0000, 0.0385]]]) \n \n tensor([[[-0.0385, -0.0769, -0.0385],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.0385, 0.0769, 0.0385]],\n \n [[-0.0769, -0.1538, -0.0769],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.0769, 0.1538, 0.0769]],\n \n [[-0.0385, -0.0769, -0.0385],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.0385, 0.0769, 0.0385]]]) \n \n tensor([[[-0.0385, -0.0769, -0.0385],\n [-0.0769, -0.1538, -0.0769],\n [-0.0385, -0.0769, -0.0385]],\n \n [[ 0.0000, 0.0000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.0000, 0.0000, 0.0000]],\n \n [[ 0.0385, 0.0769, 0.0385],\n [ 0.0769, 0.1538, 0.0769],\n [ 0.0385, 0.0769, 0.0385]]]) \n \n tensor([[[0., 0., 0.],\n [0., 0., 0.],\n [0., 0., 0.]],\n \n [[0., 0., 0.],\n [0., 1., 0.],\n [0., 0., 0.]],\n \n [[0., 0., 0.],\n [0., 0., 0.],\n [0., 0., 0.]]])\n\n\n\n```python\ndef randVoxel(obj):\n '''\n Select randomly a voxel in a 3d object\n \n Params\n ------\n - obj: the object in which pick the random voxel\n\n Returns\n -------\n - `None`\n '''\n # Get the list of possible coordinates where to pick the random value\n coord = (obj > 0.0).nonzero()\n\n # Pick the seed between coordinates\n n = torch.randint(coord.shape[0], []).item()\n \n return tuple(coord[n])\n\ndef initCA(dim, channels, obj, random_seed=False):\n '''\n Initialize virtual 3D cells lattice\n \n Params\n ------\n - dim: dimension of the 3d space\n - channels: channels of the 3d space\n - obj: the object from which pick the seed voxel\n - random_seed: use a random cell in the object\n\n Returns\n -------\n - Tensor of cells with seed\n '''\n # Create the lattice of dim x dim x dim dimension\n cells = torch.zeros((channels, dim, dim, dim), dtype=torch.float32)\n \n # Get the random voxel\n if random_seed: \n vx = randVoxel(obj)\n \n x, y, z = vx[0], vx[1], vx[2]\n # The seed cell will have all features values equal to one\n cells[:, x, y, z] = 1.0\n\n # Return only the central seed\n else:\n cells[:, dim//2, dim//2, dim//2] = 1.0\n \n return cells\n\n# Cells space\ndim = DIM+2*PADDING\ncells = initCA(dim, N_CHANNELS, target_objects[\"cow\"])\ncellsN = torch.einsum(\"cdhw -> dhwc\", cells)\n\n# Extract the alpha channel\nalpha = cells[:1, ...].clone().detach()\nalphaN = torch.einsum(\"cdhw -> dhwc\", alpha)\n\n# Set RGBA colors of cells. Died cells wiil have alpha = 0.0\ncolorsN = torch.zeros((dim, dim, dim, 4))\ncolorsN[..., :3] = torch.tensor(COLORS[\"cow\"]) # To have a gray color\ncolorsN[..., 3:] = alphaN\nprint(cells[cells > 0].shape)\n\nax = plt.figure(figsize=(10, 10)).add_subplot(projection='3d')\nax.voxels(cellsN[..., 0].numpy(), facecolors=colorsN, edgecolor=\"white\")\nplt.show()\n```\n\n\n```python\n# Utils\ndef countParameters(model: torch.nn.Module) -> int:\n \"\"\" \n Counts the number of trainable parameters of a module\n \n Params\n ------\n - model: model that contains the parameters to count\n \n Returns\n -------\n - the number of parameters in the model\n \"\"\"\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\ndef getLivingMask(x):\n \"\"\"\n Create a mask of alive cells seeing at alpha channel\n \n Params\n ------\n - x: input 3d object\n\n Returns\n -------\n - boolean mask of living cells\n \"\"\"\n # The alpha values are in the first channel\n alpha = x[:, :1, :, :, :].clone()\n # Return a boolean mask that is true in 3x3x3 neighbors\n # maximum with an alpha value higher than 0.1, so if the maximum neighbor\n # cell is mature\n return F.max_pool3d(alpha, kernel_size=3, stride=1, padding=1) > 0.1\n\ndef normWeights(weight):\n '''\n Normalize weights to avoid exploding gradients problem\n \n Params\n ------\n - weight: weights data to be normalized\n \n Returns\n -------\n - normalized weights\n '''\n w = weight.view(1, -1).clone().detach()\n with torch.no_grad():\n # Inplace division\n w.div_(torch.norm(w, dim=1, keepdim=True))\n \n return w.view(weight.shape)\n\ndef weightsInit(smodel, slow_train=False):\n '''\n Initialize weights 3D convolutional layers in sequential component\n \n Params\n ------\n - smodel: sequential model\n - slow_train: init the last layer with zeros to slow the convergency\n\n Returns\n -------\n - `None`\n '''\n for idx, layer in enumerate(smodel):\n if isinstance(layer, nn.Conv3d) and idx != 4:\n print(f\"Layer {layer} initialized with He initialization\")\n nn.init.kaiming_uniform_(layer.weight, mode='fan_in', nonlinearity='leaky_relu')\n \n elif idx == 4:\n # Initialize the last 1x1x1 convolutional layer with zeros\n # otherwise the network will not learn to construct step-by-step\n # like a Cellular Automaton does\n print(f\"Layer {layer} initialized with zeros\")\n nn.init.zeros_(layer.weight)\n \n \n```\n\n\n```python\n# Create 3D CA module like an RNN\n# to use backpropagation through time\nclass CA3D(nn.Module):\n def __init__(self, input_channels: int, kernel_size: int, output_size: int, depthwise_filter=None, device=\"cuda\") -> None:\n '''\n CA3D Neural Network initialzation\n \n Params\n ------\n - input_channels: number of input channels\n - kernel_size: dimension of filters in depthwise convolutions\n - output_size: number of channels in output\n - depthwise_filter: kernel values of 3x3x3 depthwise filter\n - device: device in which the module is executed \n\n Returns\n -------\n - `None`\n '''\n super(CA3D, self).__init__()\n self.input_channels = input_channels\n self.kernel_size = kernel_size\n self.output_size = output_size\n self.fire_rate = 0.5\n self.device = device\n\n # Must be trained end-to-end\n # I would like to obtain the same shape of output that\n # I would obtain using Sobel Filters\n self.identity_kernel = IDF.view(1, 1, self.kernel_size, self.kernel_size, self.kernel_size).repeat(self.input_channels, 1, 1, 1, 1).to(self.device)\n \n # The result from this filter must be concatenated with the result\n # obtained applying the identity filter\n self.depthwise_filter = nn.Conv3d(in_channels=input_channels, out_channels=3*input_channels, \n kernel_size=kernel_size, padding=\"same\",\n groups=input_channels, bias=False)\n \n if depthwise_filter is not None:\n # Use an already filled filter\n self.depthwise_filter.weight.data = depthwise_filter\n self.depthwise_filter.requires_grad_(False)\n \n self.dmodel = nn.Sequential(\n # First 3d convolution: 128 -> 192, 1x1 conv\n nn.Conv3d(input_channels*4, input_channels*6, kernel_size=1, bias=False),\n # Activation function\n nn.LeakyReLU(),\n # Second 3d convolution: 192 -> 96, 1x1 conv\n nn.Conv3d(input_channels*6, input_channels*3, kernel_size=1, bias=False),\n # Activation function\n nn.LeakyReLU(),\n # Third 3d convolution: 96 -> 32, 1x1 conv\n nn.Conv3d(input_channels*3, output_size, kernel_size=1, bias=False)\n )\n\n def neighPerc(self, x):\n '''\n 3x3x3 neighbors perception using gradients plus identity value\n \n Params\n ------\n - x: 3d model in input\n\n Returns\n -------\n - Perception tensor\n '''\n # Apply the Depthwise 3d convolution\n # First apply identity filter depthwise\n id_res = F.conv3d(x, self.identity_kernel, padding=\"same\", groups=self.input_channels)\n \n # Apply the filter trained depthwise \n filter_res = self.depthwise_filter(x)\n\n # Concatenate the two results\n perception = torch.concat([id_res, filter_res], 1)\n \n return perception\n\n def forward(self, x, fire_rate=None, perception_result=False, bef_alive=False):\n '''\n Forward-pass through the network to create computational graph\n \n Params\n ------\n - x: Input 3d object\n - fire_rate: updatable cells minumum value\n\n Returns\n -------\n - Output 3d object\n '''\n pre_life_mask = getLivingMask(x)\n \n # Depthwise convolutions over 3x3x3 neighborhood\n perception = self.neighPerc(x)\n \n # Perception of neighbors gradients values\n neigh_grad = self.dmodel(perception)\n\n if fire_rate is None:\n fire_rate = self.fire_rate\n # Stochastic update of the alpha channel\n # Get a boolean mask to update only cells \n # with a value smaller than or equal to fire_rate\n update_mask = torch.rand(x[:, :1, ...].shape, device=self.device) <= fire_rate\n \n # Control the update only of the alpha channel\n x = x + (neigh_grad * update_mask.float())\n\n post_life_mask = getLivingMask(x)\n # Alive mask, maintain alive only the\n # cells alive before and after computations\n life_mask = pre_life_mask & post_life_mask\n out = x * life_mask.float()\n\n # Visulize the perception\n if perception_result and bef_alive:\n return perception, x, out\n\n return out \n```\n\n\n```python\n#@title Choose the model to train\nmodel_type = \"Trainable perception filter\" #@param [\"Trainable perception filter\", \"Fixed perception filter\"]\n# Model with trainable initial filter\n# Instantiate the model\nif model_type == \"Trainable perception filter\":\n mod = \"tpf\"\n ca3d = CA3D(input_channels=N_CHANNELS, kernel_size=3, output_size=N_CHANNELS, device=DEVICE)\nelse:\n # Compose sobel filters\n mod = \"fpf\"\n l = []\n for f in [SF_X, SF_Y, SF_Z]:\n l.append(f.view(1, 1, 3, 3, 3).repeat(N_CHANNELS, 1, 1, 1, 1))\n sobel_filter = torch.concat(l, 0)\n\n ca3d = CA3D(input_channels=N_CHANNELS, kernel_size=3, output_size=N_CHANNELS, depthwise_filter=sobel_filter, device=DEVICE)\n\n# Initialize last three layers of model\nweightsInit(ca3d.dmodel)\n\nca3d = ca3d.to(DEVICE)\n\n# Visualize layers and output dimensions\nprint(ca3d)\nprint(f\"Number of parameters: {countParameters(ca3d)}\")\nprint(\"\\n\\n\")\nsummary(ca3d, cells.shape, batch_size=1)\n```\n\n Layer Conv3d(128, 192, kernel_size=(1, 1, 1), stride=(1, 1, 1), bias=False) initialized with He initialization\n Layer Conv3d(192, 96, kernel_size=(1, 1, 1), stride=(1, 1, 1), bias=False) initialized with He initialization\n Layer Conv3d(96, 32, kernel_size=(1, 1, 1), stride=(1, 1, 1), bias=False) initialized with zeros\n CA3D(\n (depthwise_filter): Conv3d(32, 96, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=same, groups=32, bias=False)\n (dmodel): Sequential(\n (0): Conv3d(128, 192, kernel_size=(1, 1, 1), stride=(1, 1, 1), bias=False)\n (1): LeakyReLU(negative_slope=0.01)\n (2): Conv3d(192, 96, kernel_size=(1, 1, 1), stride=(1, 1, 1), bias=False)\n (3): LeakyReLU(negative_slope=0.01)\n (4): Conv3d(96, 32, kernel_size=(1, 1, 1), stride=(1, 1, 1), bias=False)\n )\n )\n Number of parameters: 48672\n \n \n \n ----------------------------------------------------------------\n Layer (type) Output Shape Param #\n ================================================================\n Conv3d-1 [1, 96, 24, 24, 24] 2,592\n Conv3d-2 [1, 192, 24, 24, 24] 24,576\n LeakyReLU-3 [1, 192, 24, 24, 24] 0\n Conv3d-4 [1, 96, 24, 24, 24] 18,432\n LeakyReLU-5 [1, 96, 24, 24, 24] 0\n Conv3d-6 [1, 32, 24, 24, 24] 3,072\n ================================================================\n Total params: 48,672\n Trainable params: 48,672\n Non-trainable params: 0\n ----------------------------------------------------------------\n Input size (MB): 1.69\n Forward/backward pass size (MB): 74.25\n Params size (MB): 0.19\n Estimated Total Size (MB): 76.12\n ----------------------------------------------------------------\n\n\n## **Training phase**\n\n\n```python\n#@title Choose the target\nobj = \"fox\" #@param [\"cow\", \"fox\", \"wolf\"]\ntarget = target_objects[obj][None, None, :, :, :].clone().detach()\n\nplotVoxels(target[0, 0].numpy(), title=\"Target object\", c=COLORS[obj])\nprint(f\"Target object shape: {target.shape}, dtype: {target.dtype}\")\n\n# Initialize the cells\nseed = initCA(target.shape[2], N_CHANNELS, target[0, 0])[None, ...]\nplotVoxels(seed[0, 0].numpy(), title=\"Initial state\", c=COLORS[obj])\nprint(f\"Seed shape: {seed.shape}, dtype: {seed.dtype}\")\n\n# Loss criterion\nlossFunc = nn.L1Loss()\ndef error(x, target):\n return lossFunc(torch.clamp(x[:, 0], min=0.0, max=1.0), target[:, 0])\n\nprint(f\"Initial loss value: {error(seed, target)}\")\n\n# Optimizer with L2-regularization and momentum\nlr = 5e-3 if mod == \"fpf\" else 3e-3\nwd = 1e-5\nm = 0.8\nopt = optim.SGD(ca3d.parameters(), lr=lr, weight_decay=wd)\n\n```\n\n\n```python\ndef loadCheckpoint(path, model, opt):\n '''\n Load a model checkpoint specifing the path\n \n Params\n ------\n - path: path of the model checkpoint\n - model: reference to the model\n - opt: reference to the optimazer\n\n Returns\n -------\n - epoch and loss of the model checkpoint\n '''\n checkpoint = torch.load(path)\n model.load_state_dict(checkpoint['model_state_dict'])\n opt.load_state_dict(checkpoint['optimizer_state_dict'])\n \n return checkpoint['n_iter'], checkpoint['loss']\n \n\ndef saveCheckpoint(path, model_sd, opt_sd, n_iter, loss):\n '''\n Save a model checkpoint into a specified path location\n \n Params\n ------\n - path: path in which save the modelcheckpoint\n - model_sd: model state dictionary\n - opt_sd: optimizer state dictionary\n - n_iter: last number iteration of the model\n - loss: loss at last iteration\n\n Returns\n -------\n - `None`\n '''\n torch.save({\n 'n_iter': n_iter,\n 'model_state_dict': model_sd,\n 'optimizer_state_dict': opt_sd,\n 'loss': loss\n }, path)\n```\n\n\n```python\ndef trainStep(x, target, model: torch.nn.Module, opt: torch.optim.Optimizer, device: str = \"cuda\"):\n '''\n Training iteration of the model\n \n Params\n ------\n - x: Input 3d object\n - target: Target 3d object\n - model: model to train\n - opt: optimizer\n - device: type of device in which make calculous\n\n Returns\n -------\n - Model output and loss reached\n '''\n model.train()\n \n # Send to device\n x, target = x.to(device), target.to(device)\n # Try with a random number of iterations\n n_iter = torch.randint(85, 100, []).item()\n\n # Create a local variable\n _x = x.clone().detach()\n _x.requires_grad_(True)\n \n for i in range(n_iter):\n # Iterate the model without backpropagate\n # to use always the same set of learned rules\n # (otherwise calling backpropagation the rules changes)\n _x = model(_x)\n\n # Truncated Backpropagation through time\n # Every 5 iterations backpropagate\n '''\n if (i+1)%5 == 0:\n opt.zero_grad()\n loss = error(_x, target)\n \n #if(i+1)%50: print(f\"Internal loss: {loss}\")\n #wandb.log({\"Internal_loss\": loss})\n \n loss.backward()\n # Avoid exploding gradient\n #nn.utils.clip_grad_norm_(model.parameters(), .7)\n\n opt.step()\n\n _x = _x.clone().detach()\n _x.requires_grad_(True)\n #print(\"Done!\")'''\n \n # Each #iter steps \n # Calculate the loss and backpropagate through time\n opt.zero_grad()\n loss = error(_x, target)\n \n loss.backward()\n # Avoid exploding gradient\n #nn.utils.clip_grad_norm_(model.parameters(), .7)\n opt.step()\n\n return _x.clone().detach(), loss.clone().detach()\n```\n\n\n```python\n# Training iterations \nx = seed.clone().detach()\nx.requires_grad_(True)\n\nlosses = []\n\nchecks = [1000, 1500, 2000, 3000, 4000, 6000, 8000, 12000, 16000]\ni = 0\n\nfor n_iter in range(1, TOT_ITERATIONS+1): \n # Start each new iteration with single cell\n out, loss = trainStep(x, target, model=ca3d, opt=opt, device=DEVICE)\n\n # Print the reached loss\n print(f\"At iteration: {n_iter: 4d} Reached loss: {loss}\\n\")\n \n losses.append(loss.item())\n\n # Early stopping\n if(loss.item() <= 0.001):\n print(\"Reached early stopping point!\")\n saveCheckpoint(f\"{CHECKPOINTS_FOLDER}/checkpoint_{mod}_{n_iter}_{obj}.pth\", ca3d.state_dict(), opt.state_dict(), n_iter, loss)\n\n # Save loss and empty list\n torch.save(torch.tensor(losses), f\"{LOG_FOLDER}/losses_{mod}_{n_iter}_{obj}.pt\")\n break\n\n # Save checkpoint\n if n_iter%checks[i] == 0:\n i += 1\n saveCheckpoint(f\"{CHECKPOINTS_FOLDER}/checkpoint_{mod}_{n_iter}_{obj}.pth\", ca3d.state_dict(), opt.state_dict(), n_iter, loss)\n \n # Save loss and empty list\n torch.save(torch.tensor(losses), f\"{LOG_FOLDER}/losses_{mod}_{n_iter}_{obj}.pt\")\n losses = []\n```\n\n\n```python\n# Format the path\nloss_conc = np.array([])\nfor c in range(i):\n path = f\"{LOG_FOLDER}/losses_{mod}_{checks[c]}_{obj}.pt\"\n inp = torch.load(path).to(DEVICE)\n loss_conc = np.concatenate((loss_conc, inp.cpu().numpy()))\n\nprint(loss_conc.shape)\n \n```\n\n (1000,)\n\n\n\n```python\n# Plot the result of training\nfrom cycler import cycler\nax = plt.figure(figsize=(10, 8)).subplots()\nax.set_prop_cycle(cycler(color=[\"tab:blue\", \"tab:orange\"]))\nax.plot(loss_conc, linestyle=(0, (3, 10, 1, 10)), linewidth=1.5)\n\nax.set_title(f\"Losses plot {mod} filter {obj}\")\n\nl = f\"Fixed {obj}\" if mod == \"fpf\" else f\"Trained {obj}\"\nplt.legend([l], ncol=2, loc='upper left')\nplt.savefig(f\"{MAIN_FOLDER}/plot_loss_cow.png\")\n```\n\n## **Model Evaluation**\n\n\n```python\n# Load the last network that should be the most robust\nif i != 0:\n _iter, _loss = loadCheckpoint(f\"{CHECKPOINTS_FOLDER}/checkpoint_{mod}_{checks[i-1]}_{obj}.pth\", ca3d, opt)\n\n print(f\"Checkpoint saved at iteration number: {_iter}, Loss: {_loss}\")\nelse:\n print(\"Error! Execute training section at least 1000 iterations or \\nskip this section and use pretrained model\")\n```\n\n Checkpoint saved at iteration number: 1000, Loss: 0.017115643247961998\n\n\n\n```python\n#@title To use pretrained models\nmod = \"fpf\" #@param [\"fpf\", \"tpf\"] \nobj = \"cow\" #@param [\"cow\", \"fox\"]\n_iter, _loss = loadCheckpoint(f\"{PRETRAINED_FOLDER}/checkpoint_{mod}_{16000}_{obj}.pth\", ca3d, opt)\n\nprint(f\"Checkpoint saved at iteration number: {_iter}, Loss: {_loss}\")\n```\n\n Checkpoint saved at iteration number: 16000, Loss: 0.005899389274418354\n\n\n\n```python\n# Visualize the capability to represent the cow\ndef eval_model(model, saved_out, save_intermediate=False):\n '''\n Evaluate the model\n Params\n ------\n - model: the model to be evaluated\n - saved_out: list of saved output tensors\n - save_intermediate: boolean, if true the function returns perception tensor, updating tensor and final output at 80th time step\n \n Returns\n -------\n - the modified saved_out\n '''\n # Iterate to 100 times to create the object\n for i in range(1, 100):\n \n model.eval()\n \n with torch.no_grad():\n inp = torch.load(saved_out[-1]).to(DEVICE)\n if i == 80 and save_intermediate==True:\n p, b, out_ext = ca3d(inp, perception_result=True, bef_alive=True)\n else: out = ca3d(inp)\n \n filename = f\"{i}\"\n torch.save(out.cpu().clone().detach(), filename)\n saved_out.append(filename)\n\n del out\n del inp\n torch.cuda.empty_cache()\n\n print(f\"Number of saved outputs: {len(saved_out)}\")\n if save_intermediate:\n return p, b, out_ext\n \n```\n\n\n```python\n# Visualize the outputs\ndef visualizeOutputs(saved_out, dim, iter_gif=100):\n for i in range(len(saved_out)):\n cells = torch.zeros((1, N_CHANNELS, dim, dim, dim)) \n # A cell will exist only if its values is different from zero\n alpha = torch.load(saved_out[i%iter_gif])[0, :1, ...].cpu()\n \n # Clamp largest/smallest values\n alpha = torch.clamp(alpha, min=0, max=1)\n cells[0, :1, ...] = alpha\n cellsN = cells.numpy()[0, 0, ...]\n\n # Adapt alpha channel to be visualizable\n alpha = torch.einsum(\"cdhw -> dhwc\", alpha)\n alphaN = alpha.numpy()\n\n colorsN = np.zeros((dim, dim, dim, 4)) \n colorsN[..., :3] = COLORS[obj] # This is to obtain gray in r,g,b\n colorsN[..., 3:4] = alphaN\n\n # The first channel represent the alpha and will be\n # the unique relevant for us\n ax = plt.figure().add_subplot(projection=\"3d\")\n ax.voxels(cellsN, facecolors=colorsN, edgecolors=colorsN)\n \n # Save the frame\n plt.savefig(saved_out[i%iter_gif] + \".png\")\n plt.close()\n\n # Create a gif with each model saved images\n if (i+1)%iter_gif == 0:\n print(f\"Creating the gif for model_n_{i+1}...\")\n # Build gif\n with imageio.get_writer(f'{GIFS_FOLDER}/{obj}_model_{mod}_n_{i+1}.gif', mode='I') as writer:\n for k in range(iter_gif):\n # Extract path and free saved_x\n path = saved_out[0]\n del saved_out[0]\n\n # Compose the gif\n try:\n image = imageio.imread(path + \".png\")\n writer.append_data(image)\n # Remove useless files from disk\n os.remove(path)\n os.remove(path + \".png\")\n except:\n print(f\"Not found file: {path}.png at iteration {i} and gif iteration {k}\")\n \n \n print(f\"Done! Now saved are {len(saved_out)}\")\n```\n\n\n```python\n# Visualize the capability to represent the object\nx = seed.clone().detach().to(DEVICE)\n\n# Iterate to 100 times to create the object\ntorch.save(x.cpu().clone().detach(), \"0\")\nsaved_out = []\nsaved_out.append(\"0\")\n\neval_model(ca3d, saved_out)\n```\n\n Number of saved outputs: 100\n\n\n\n```python\n# Await some minutes and the result will be\n# created and saved in \"/content/gdrive/MyDrive/DLAI_project_3D_NCA/Gifs\" \n# location on google drive\nvisualizeOutputs(saved_out, dim=DIM+2*PADDING)\n```\n\n Creating the gif for model_n_100...\n Done! Now saved are 0\n\n", "meta": {"hexsha": "7d6e01af81628f41f399632682fc3e11d4c45ecc", "size": 577207, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Final_DLAI_project_Growing3D_NCA.ipynb", "max_stars_repo_name": "francesco-cubito97/DLAI_project_3DCA", "max_stars_repo_head_hexsha": "f70a66aab11fc44433f3a8ad1886739419f02775", "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": "Final_DLAI_project_Growing3D_NCA.ipynb", "max_issues_repo_name": "francesco-cubito97/DLAI_project_3DCA", "max_issues_repo_head_hexsha": "f70a66aab11fc44433f3a8ad1886739419f02775", "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": "Final_DLAI_project_Growing3D_NCA.ipynb", "max_forks_repo_name": "francesco-cubito97/DLAI_project_3DCA", "max_forks_repo_head_hexsha": "f70a66aab11fc44433f3a8ad1886739419f02775", "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": 153.2272365277, "max_line_length": 102057, "alphanum_fraction": 0.8314330907, "converted": true, "num_tokens": 9855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438009916360314, "lm_q2_score": 0.10521053950871516, "lm_q1q2_score": 0.05096189156028764}} {"text": "```julia\n\"\"\"Tutorial: CEPA0 and CCD\"\"\"\n\n__author__ = [\"D. Menendez\", \"Adam S. Abbott\"]\n__credit__ = [\"D. Menendez\", \"Adam S. Abbott\", \"Justin M. Turney\"]\n\n__copyright__ = \"(c) 2014-2020, The Psi4Julia Developers\"\n__license__ = \"BSD-3-Clause\"\n__date__ = \"2020-08-02\"\n```\n\n\n\n\n \"2020-08-02\"\n\n\n\n# Introduction\nIn this tutorial, we will implement the coupled-electron pair approximation (CEPA0) and coupled-cluster doubles (CCD) methods using our spin orbital framework covered in the [previous tutorial](8a_Intro_to_spin_orbital_postHF.ipynb).\n\n\n### I. Coupled Cluster Theory\n\nIn single reference coupled cluster theory, dynamic correlation is acquired by operating an exponential operator on some reference determinant, such as a Hartree-Fock wavefunction, to obtain the coupled cluster wavefunction given by:\n\n\\begin{equation}\n\\mid \\mathrm{\\Psi_{CC}} \\rangle = \\exp(\\hat{T}) \\mid \\mathrm{\\Phi} \\rangle \n\\end{equation}\n\nwhere $\\hat{T} = T_1 + T_2 + ... + T_n$ is the sum of \"cluster operators\" which act on our reference wavefunction to excite electrons from occupied ($i, j, k$...) to virtual ($a, b, c$...) orbitals. In second quantization, these cluster operators are expressed as:\n\n\\begin{equation}\nT_k = \\left(\\frac{1}{k!}\\right)^2 \\sum_{\\substack{i_1 \\ldots i_k \\\\ a_1 \\ldots a_k }} t_{i_1 \\ldots i_k}^{a_1 \\ldots a_k} a_{a_1}^{\\dagger} \\ldots a_{a_k}^{\\dagger} a_{i_k} \\ldots a_{i_1}\n\\end{equation}\n\nwhere $t$ is the $t$-amplitude, and $a^{\\dagger}$ and $a$ are creation and annihilation operators.\n\n### II. Coupled Cluster Doubles\nFor CCD, we only include the doubles cluster operator:\n\n\\begin{equation}\n\\mid \\mathrm{\\Psi_{CCD}} \\rangle = \\exp(T_2) \\mid \\mathrm{\\Phi} \\rangle\n\\end{equation}\n\nThe CCD Schrödinger equation is\n\n\\begin{equation}\n\\hat{H} \\mid \\mathrm{\\Psi_{CCD}} \\rangle = E \\mid \\mathrm{\\Psi_{CCD}}\\rangle\n\\end{equation}\n\nThe details will not be covered here, but if we project the CCD Schrödinger equation on the left by our Hartree-Fock reference determinant $ \\langle \\mathrm{\\Phi}\\mid $, assuming intermediate normalization $\\langle \\Phi \\mid \\mathrm{\\Psi_{CCD}} \\rangle = 1$, we obtain:\n\n\\begin{equation}\n \\langle \\Phi \\mid \\hat{H} \\space \\exp(T_2) \\mid \\Phi \\rangle = E\n\\end{equation}\n\nwhich is most easily evaluated with a diagrammatic application of Wick's theorem. Assuming Brillouin's theorem applies (that is, our reference is a Hartree-Fock wavefunction) we obtain:\n\n\\begin{equation}\nE_{\\mathrm{CCD}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}\n\\end{equation}\n\nA somewhat more involved derivation is that of the $t$-amplitudes. These are obtained in a similar fashion to the energy expression, this time projecting the CCD Schrödinger equation on the left by a doubly-excited reference determinant $ \\langle\\Phi_{ij}^{ab}\\mid $:\n\n\\begin{equation}\n\\langle\\Phi_{ij}^{ab}\\mid \\hat{H} \\space \\exp(T_2) \\mid \\Phi \\rangle\n\\end{equation}\n\nI will spare you the details of solving this expectation value as well. But, if one evaluates the diagrams via Wick's theorem and simplifies, the $t$-amplitudes are given by:\n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} - \\tfrac{1}{2}\\hat{P}_{(a \\space / \\space b)} \\bar{g}_{kl}^{cd} t_{ac}^{ij} t_{bd}^{kl} - \\tfrac{1}{2} \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ab}^{ik} t_{cd}^{jl} + \\tfrac{1}{4} \\bar{g}_{kl}^{cd} t_{cd}^{ij} t_{ab}^{kl} + \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ac}^{ik} t_{bd}^{jl} \\right)\n\\end{equation}\n\nwhere $(\\mathcal{E}_{ab}^{ij})^{-1}$ is the orbital energy denominator, more familiarly known as\n\n\\begin{equation}\n(\\mathcal{E}_{ab}^{ij})^{-1} = \\frac{1}{\\epsilon_i + \\epsilon_j - \\epsilon_a - \\epsilon_b}\n\\end{equation}\n\nand $\\bar{g}_{pq}^{rs}$ is the antisymmetrized two-electron integral in physicist's notation $\\langle pq \\mid\\mid rs \\rangle$. $\\hat{P}$ is the *antisymmetric permutation operator*. This operator acts on a term to produce the sum of the permutations of the indicated indices, with an appropriate sign factor. Its effect is best illustrated by an example. Consider the fourth term, which is really four terms in one. \n\n$\\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk}$ produces: \n\n1. The original: $ \\quad \\bar{g}_{ak}^{ic} t_{bc}^{jk} \\\\ $\n\n2. Permuation of $a$ and $b$: $ \\quad \\textrm{-} \\bar{g}_{bk}^{ic} t_{ac}^{jk} \\\\ $\n\n3. Permuation of $i$ and $j$: $ \\quad \\, \\, \\textrm{-} \\bar{g}_{ak}^{jc} t_{bc}^{ik} \\\\ $\n\n4. Permuation of $a$ and $b$, $i$ and $j$: $ \\quad \\bar{g}_{bk}^{jc} t_{ac}^{ik} \\\\ $\n\n\nNote that each permutation adds a sign change. This shorthand notation keeps the equation in a more manageable form. \n\nSince the $t$-amplitudes and the energy depend on $t$-amplitudes, we must iteratively solve these equations until they reach self consistency, and the energy converges to some threshold.\n\n### III. Retrieving MP2 and CEPA0 from the CCD equations\nIt is interesting to note that if we only consider the first term of the expression for the doubles amplitude $t_{ab}^{ij}$ and plug it into the energy expression, we obtain the MP2 energy expression:\n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\bar{g}_{ab}^{ij} \n\\end{equation}\n\n\\begin{equation}\nE_{\\mathrm{MP2}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} \\bar{g}_{ab}^{ij} (\\mathcal{E}_{ab}^{ij})^{-1}\n\\end{equation}\n\nFurthermore, if we leave out the quadratic terms in the CCD amplitude equation (terms containing two $t$-amplitudes), we obtain the coupled electron-pair approximation (CEPA0):\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} \\right)\n\\end{equation}\n\nThe CEPA0 energy expression is identical:\n\n\\begin{equation}\nE_{\\mathrm{CEPA0}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}\n\\end{equation}\n\nUsing our spin orbital setup for the MO coefficients, orbital energies, and two-electron integrals used in the [previous tutorial](8a_Intro_to_spin_orbital_postHF.ipynb), we are equipped to program the expressions for the CEPA0 and CCD correlation energy.\n\n### Implementation: CEPA0 and CCD\nAs usual, we import Psi4, NumPy, and TensorOperations, and set the appropriate options. \n\n\n```julia\n# ==> Import statements & Global Options <==\nusing PyCall: pyimport\npsi4 = pyimport(\"psi4\")\nnp = pyimport(\"numpy\")\nusing TensorOperations: @tensor\nusing Formatting: printfmt\n\npsi4.set_memory(Int(2e9))\nnumpy_memory = 2\npsi4.core.set_output_file(\"output.dat\", false)\n```\n\n \n Memory set to 1.863 GiB by Python driver.\n\n\n\n```julia\n# ==> Molecule & Psi4 Options Definitions <==\nmol = psi4.geometry(\"\"\"\n0 1\nO\nH 1 1.1\nH 1 1.1 2 104\nsymmetry c1\n\"\"\")\n\npsi4.set_options(Dict(\"basis\" => \"6-31g\",\n \"scf_type\" => \"pk\",\n \"reference\" => \"rhf\",\n \"mp2_type\" => \"conv\",\n \"e_convergence\" => 1e-8,\n \"d_convergence\" => 1e-8))\n```\n\nNote that since we are using a spin orbital setup, we are free to use any Hartree-Fock reference we want. Here we choose RHF. For convenience, we let Psi4 take care of the Hartree-Fock procedure, and return the wavefunction object.\n\n\n```julia\n# Get the SCF wavefunction & energies\nscf_e, scf_wfn = psi4.energy(\"scf\", return_wfn=true)\n```\n\n\n\n\n (-75.95252904632221, PyObject )\n\n\n\nLoad in information about the basis set and orbitals using MintsHelper and the wavefunction:\n\n\n```julia\nmints = psi4.core.MintsHelper(scf_wfn.basisset())\nnbf = mints.nbf() # number of basis functions\nnso = 2nbf # number of spin orbitals\nnalpha = scf_wfn.nalpha() # number of alpha electrons\nnbeta = scf_wfn.nbeta() # number of beta electrons\nnocc = nalpha + nbeta # number of occupied orbitals\nnvirt = 2nbf - nocc # number of virtual orbitals\n```\n\n\n\n\n 16\n\n\n\nSpin-block our MO coefficients and two-electron integrals, just like in the spin orbital MP2 code:\n\n\n```julia\nCa = np.asarray(scf_wfn.Ca())\nCb = np.asarray(scf_wfn.Cb())\nC = [Ca zero(Ca); zero(Cb) Cb]; # direct sum\n\n# Result: | Ca 0 |\n# | 0 Cb|\n```\n\n\n```julia\n# Get the two electron integrals using MintsHelper\nI = np.asarray(mints.ao_eri())\n\n\"\"\" \nFunction that spin blocks two-electron integrals\nUsing `np.kron`, we project I into the space of the 2x2 identity, tranpose the result\nand project into the space of the 2x2 identity again. This doubles the size of each axis.\nThe result is our two electron integral tensor in the spin orbital form.\n\"\"\"\nfunction spin_block_tei(I)\n identity = [ 1.0 0.0; 0.0 1.0]\n I = np.kron(identity, I)\n np.kron(identity, permutedims(I, reverse(1:4)))\nend\n\n# Spin-block the two electron integral array\nI_spinblock = spin_block_tei(I);\n```\n\nConvert two-electron integrals to antisymmetrized physicist's notation:\n\n\n```julia\n# Converts chemist's notation to physicist's notation, and antisymmetrize\n# (pq|rs) ↦ ⟨pr|qs⟩\n# Physicist's notation\ntmp = permutedims(I_spinblock, (1, 3, 2, 4))\n# Antisymmetrize:\n# ⟨pr||qs⟩ = ⟨pr|qs⟩ - ⟨pr|sq⟩\ngao = tmp - permutedims(tmp, (1, 2, 4, 3));\n```\n\nObtain the orbital energies, append them, and sort the columns of our MO coefficient matrix according to the increasing order of orbital energies. \n\n\n```julia\n# Get orbital energies \neps_a = np.asarray(scf_wfn.epsilon_a())\neps_b = np.asarray(scf_wfn.epsilon_b())\neps = vcat(eps_a, eps_b)\n\n# Before sorting the orbital energies, we can use their current arrangement to sort the columns\n# of C. Currently, each element i of eps corresponds to the column i of C, but we want both\n# eps and columns of C to be in increasing order of orbital energies\n\n# Sort the columns of C according to the order of increasing orbital energies \nC = C[:, sortperm(eps)] \n\n# Sort orbital energies in increasing order\nsort!(eps);\n```\n\nFinally, we transform our two-electron integrals to the MO basis. Here, we denote the integrals as `gmo` to differentiate from the chemist's notation integrals `I_mo`.\n\n\n```julia\n# Transform gao, which is the spin-blocked 4d array of physicist's notation, \n# antisymmetric two-electron integrals, into the MO basis using MO coefficients \ngmo = @tensor begin\n gmo[P,Q,R,S] := gao[p,Q,R,S] * C[p,P]\n gmo[p,Q,R,S] := gmo[p,q,R,S] * C[q,Q]\n gmo[p,q,R,S] := gmo[p,q,r,S] * C[r,R]\n gmo[p,q,r,S] := gmo[p,q,r,s] * C[s,S]\nend\nnothing\n```\n\nConstruct the 4-dimensional array of orbital energy denominators:\n\n\n```julia\n# Define slices, create 4 dimensional orbital energy denominator tensor\nn = [CartesianIndex()]\no = [p ≤ nocc for p in 1:nso]\nv = [p > nocc for p in 1:nso]\ne_denom = @. inv(-eps[v, n, n, n] - eps[n, v, n, n] + eps[n, n, o, n] + eps[n, n, n, o]);\n```\n\nWe now have everything we need to construct our $t$-amplitudes and iteratively solve for our CEPA0 and CCD energy. To build the $t$-amplitudes, we first construct an empty 4-dimensional array to store them. \n\n\n```julia\n# Create space to store t amplitudes\nt_amp = zeros(nvirt, nvirt, nocc, nocc);\n```\n\n# Implementation: CEPA0\nFirst we will program CEPA0. Recall the expression for the $t$-amplitudes:\n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} \\right)\n\\end{equation}\n\nThese terms translate naturally into code using Julia's `@tensor` function. To access only the occupied and virtual indices of `gmo` we use our slices defined above. The permutation operator terms can be easily obtained by transposing the original result accordingly. To construct each iteration's $t$-amplitude: \n\n~~~julia\nmp2 = @view gmo[v, v, o, o]\n@tensor cepa1[ a,b,i,j] := 0.5(gmo[v,v,v,v])[a,b,c,d] * t_amp[c,d,i,j]\n@tensor cepa2[ a,b,i,j] := 0.5(gmo[o,o,o,o])[k,l,i,j] * t_amp[a,b,k,l]\n@tensor cepa3a[a,b,i,j] := (gmo[v,o,o,v])[a,k,i,c] * t_amp[b,c,j,k]\ncepa3b = -permutedims(cepa3a, (2, 1, 3, 4)) # a <-> b\ncepa3c = -permutedims(cepa3a, (1, 2, 4, 3)) # i <-> j\ncepa3d = permutedims(cepa3a, (2, 1, 4, 3)) # a <-> b, i <-> j\ncepa3 = cepa3a + cepa3b + cepa3c + cepa3d\n\nt_amp_new = @. e_denom * (mp2 + cepa1 + cepa2 + cepa3)\n~~~\n\nTo evaluate the energy, $E_{\\mathrm{CEPA0}} = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}$,\n\n~~~julia\nE_CEPA0 = 1/4 * @tensor scalar((gmo[o,o,v,v])[i,j,a,b] * t_amp_new[a,b,i,j])\n~~~\n\nPutting it all together, we initialize the energy, set the max iterations, and iterate the energy until it converges to our convergence criterion:\n\n\n```julia\n# Initialize energy\nE_CEPA0 = let E_CEPA0 = 0.0, gmo=gmo, o=o,v=v, e_denom = e_denom, t_amp = t_amp\n\n MAXITER = 50\n\n for cc_iter in 1:MAXITER\n E_old = E_CEPA0\n \n # Collect terms\n mp2 = @view gmo[v,v,o,o]\n @tensor cepa1[ a,b,i,j] := 0.5(gmo[v,v,v,v])[a,b,c,d] * t_amp[c,d,i,j]\n @tensor cepa2[ a,b,i,j] := 0.5(gmo[o,o,o,o])[k,l,i,j] * t_amp[a,b,k,l]\n @tensor cepa3a[a,b,i,j] := (gmo[v,o,o,v])[a,k,i,c] * t_amp[b,c,j,k]\n cepa3b = -permutedims(cepa3a, (2, 1, 3, 4))\n cepa3c = -permutedims(cepa3a, (1, 2, 4, 3))\n cepa3d = permutedims(cepa3a, (2, 1, 4, 3))\n cepa3 = cepa3a + cepa3b + cepa3c + cepa3d\n\n # Update t amplitude\n t_amp_new = @. e_denom * (mp2 + cepa1 + cepa2 + cepa3)\n\n # Evaluate Energy\n E_CEPA0 = 1/4 * @tensor scalar((gmo[o,o,v,v])[i,j,a,b] * t_amp_new[a,b,i,j])\n t_amp = t_amp_new\n dE = E_CEPA0 - E_old\n printfmt(\"CEPA0 Iteration {1:3d}: Energy = {2:4.12f} dE = {3:1.5e}\\n\", cc_iter, E_CEPA0, dE)\n\n if abs(dE) < 1.e-8\n @info \"CEPA0 Iterations have converged!\"\n break\n end\n\n if cc_iter == MAXITER\n psi4.core.clean()\n error(\"Maximum number of iterations exceeded.\")\n end\n end\n E_CEPA0\nend\n\nprintfmt(\"\\nCEPA0 Correlation Energy: {:5.15f}\\n\", E_CEPA0)\nprintfmt(\"CEPA0 Total Energy: {:5.15f}\\n\", E_CEPA0 + scf_e)\n```\n\n CEPA0 Iteration 1: Energy = -0.142119840107 dE = -1.42120e-01\n CEPA0 Iteration 2: Energy = -0.142244391124 dE = -1.24551e-04\n CEPA0 Iteration 3: Energy = -0.146403555808 dE = -4.15916e-03\n CEPA0 Iteration 4: Energy = -0.147737944685 dE = -1.33439e-03\n CEPA0 Iteration 5: Energy = -0.148357998476 dE = -6.20054e-04\n CEPA0 Iteration 6: Energy = -0.148640319256 dE = -2.82321e-04\n CEPA0 Iteration 7: Energy = -0.148774677462 dE = -1.34358e-04\n CEPA0 Iteration 8: Energy = -0.148840007175 dE = -6.53297e-05\n CEPA0 Iteration 9: Energy = -0.148872387868 dE = -3.23807e-05\n CEPA0 Iteration 10: Energy = -0.148888687346 dE = -1.62995e-05\n CEPA0 Iteration 11: Energy = -0.148897003346 dE = -8.31600e-06\n CEPA0 Iteration 12: Energy = -0.148901297751 dE = -4.29440e-06\n CEPA0 Iteration 13: Energy = -0.148903540226 dE = -2.24248e-06\n CEPA0 Iteration 14: Energy = -0.148904723489 dE = -1.18326e-06\n CEPA0 Iteration 15: Energy = -0.148905354026 dE = -6.30537e-07\n CEPA0 Iteration 16: Energy = -0.148905693171 dE = -3.39145e-07\n CEPA0 Iteration 17: Energy = -0.148905877194 dE = -1.84023e-07\n CEPA0 Iteration 18: Energy = -0.148905977873 dE = -1.00678e-07\n CEPA0 Iteration 19: Energy = -0.148906033377 dE = -5.55039e-08\n CEPA0 Iteration 20: Energy = -0.148906064192 dE = -3.08158e-08\n CEPA0 Iteration 21: Energy = -0.148906081412 dE = -1.72194e-08\n CEPA0 Iteration 22: Energy = -0.148906091090 dE = -9.67815e-09\n \n CEPA0 Correlation Energy: -0.148906091090053\n CEPA0 Total Energy: -76.101435137412267\n\n\n ┌ Info: CEPA0 Iterations have converged!\n └ @ Main In[13]:29\n\n\nSince `t_amp` is initialized to zero, the very first iteration should be the MP2 correlation energy. We can check the final CEPA0 energy with Psi4. The method is called `lccd`, or linear CCD, since CEPA0 omits the terms with two cluster amplitudes.\n\n\n```julia\npsi4.compare_values(psi4.energy(\"lccd\"), E_CEPA0 + scf_e, 6, \"CEPA0 Energy\")\n```\n\n \tCEPA0 Energy......................................................PASSED\n\n\n\n\n\n true\n\n\n\n# Implementation: CCD\n\nTo code CCD, we only have to add in the last four terms in our expression for the $t$-amplitudes: \n\n\\begin{equation}\nt_{ab}^{ij} = (\\mathcal{E}_{ab}^{ij})^{-1} \\left( \\bar{g}_{ab}^{ij} + \\tfrac{1}{2} \\bar{g}_{ab}^{cd} t_{cd}^{ij} + \\tfrac{1}{2} \\bar{g}_{kl}^{ij} t_{ab}^{kl} + \\hat{P}_{(a \\space / \\space b)}^{(i \\space / \\space j)} \\bar{g}_{ak}^{ic} t_{bc}^{jk} - \\underline{\\tfrac{1}{2}\\hat{P}_{(a \\space / \\space b)} \\bar{g}_{kl}^{cd} t_{ac}^{ij} t_{bd}^{kl} - \\tfrac{1}{2} \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ab}^{ik} t_{cd}^{jl} + \\tfrac{1}{4} \\bar{g}_{kl}^{cd} t_{cd}^{ij} t_{ab}^{kl} + \\hat{P}^{(i \\space / \\space j)} \\bar{g}_{kl}^{cd} t_{ac}^{ik} t_{bd}^{jl}} \\right)\n\\end{equation}\n\nwhich we readily translate into `@tensor`'s:\n\n~~~julia\n@tensor ccd1a[a,b,i,j] := (gmo[o,o,v,v])[k,l,c,d] * t_amp[a,c,i,j] * t_amp[b,d,k,l]\nccd1b = -permutedims(ccd1a, (2, 1, 3, 4))\nccd1 = -0.5(ccd1a + ccd1b)\n\n@tensor ccd2a[a,b,i,j] := (gmo[o,o,v,v])[k,l,c,d] * t_amp[a,b,i,k] * t_amp[c,d,j,l]\nccd2b = -permutedims(ccd2a, (1, 2, 4, 3))\nccd2 = -0.5(ccd2a + ccd2b)\n\n@tensor ccd3[a,b,i,j] := 1/4 * (gmo[o,o,v,v])[k,l,c,d] * t_amp[c,d,i,j] * t_amp[a,b,k,l]\n\n@tensor ccd4a[a,b,i,j] := (gmo[o,o,v,v])[ k,l,c,d] * t_amp[a,c,i,k] * t_amp[b,d,j,l]\nccd4b = -permutedims(ccd4a, (1, 2, 4, 3))\nccd4 = (ccd4a + ccd4b)\n~~~\n\nand the energy expression is identical to CEPA0:\n\\begin{equation}\nE_{CCD } = \\tfrac{1}{4} \\bar{g}_{ij}^{ab} t_{ab}^{ij}\n\\end{equation}\n\nAdding the above terms to our CEPA0 code will compute the CCD correlation energy (may take a minute or two to run):\n\n\n```julia\n# Initialize energy\nE_CCD = let E_CCD = 0.0, o=o,v=v, e_denom=e_denom, t_amp=t_amp\n\n MAXITER = 50\n\n # Create space to store t amplitudes \n t_amp = zeros(nvirt, nvirt, nocc, nocc)\n for cc_iter in 1:MAXITER\n E_old = E_CCD\n\n # Collect terms\n mp2 = @view gmo[v,v,o,o]\n @tensor cepa1[ a,b,i,j] := 0.5(gmo[v,v,v,v])[a,b,c,d] * t_amp[c,d,i,j]\n @tensor cepa2[ a,b,i,j] := 0.5(gmo[o,o,o,o])[k,l,i,j] * t_amp[a,b,k,l]\n @tensor cepa3a[a,b,i,j] := (gmo[v,o,o,v])[a,k,i,c] * t_amp[b,c,j,k]\n cepa3b = -permutedims(cepa3a, (2, 1, 3, 4))\n cepa3c = -permutedims(cepa3a, (1, 2, 4, 3))\n cepa3d = permutedims(cepa3a, (2, 1, 4, 3))\n cepa3 = cepa3a + cepa3b + cepa3c + cepa3d\n\n @tensor ccd1a_ref[a,b,i,j] := (gmo[o,o,v,v])[k,l,c,d] * t_amp[a,c,i,j] * t_amp[b,d,k,l]\n @tensor ccd1a_tmp[c,b] := (gmo[o,o,v,v])[k,l,c,d] * t_amp[b,d,k,l]\n @tensor ccd1a[a,b,i,j] := ccd1a_tmp[c,b] * t_amp[a,c,i,j]\n println(isapprox(ccd1a_ref, ccd1a))\n \n ccd1b = -permutedims(ccd1a, (2, 1, 3, 4))\n ccd1 = -0.5(ccd1a + ccd1b)\n\n @tensor ccd2a_ref[a,b,i,j] := (gmo[o,o,v,v])[k,l,c,d] * t_amp[a,b,i,k] * t_amp[c,d,j,l]\n @tensor ccd2a_tmp[j,k] := (gmo[o,o,v,v])[k,l,c,d] * t_amp[c,d,j,l]\n @tensor ccd2a[a,b,i,j] := ccd2a_tmp[j,k] * t_amp[a,b,i,k]\n println(isapprox(ccd2a_ref, ccd2a))\n \n ccd2b = -permutedims(ccd2a, (1, 2, 4, 3))\n ccd2 = -0.5(ccd2a + ccd2b)\n\n @tensor ccd3_ref[a,b,i,j] := 1/4 * (gmo[o,o,v,v])[k,l,c,d] * t_amp[c,d,i,j] * t_amp[a,b,k,l]\n @tensor ccd3_tmp[k,l,i,j] := (gmo[o,o,v,v])[k,l,c,d] * t_amp[c,d,i,j]\n @tensor ccd3[a,b,i,j] := 1/4 * ccd3_tmp[k,l,i,j] * t_amp[a,b,k,l]\n println(isapprox(ccd3_ref, ccd3))\n\n @tensor ccd4a_ref[a,b,i,j] := (gmo[o,o,v,v])[ k,l,c,d] * t_amp[a,c,i,k] * t_amp[b,d,j,l]\n @tensor ccd4a_tmp[l,a,i,d] := (gmo[o,o,v,v])[ k,l,c,d] * t_amp[a,c,i,k]\n @tensor ccd4a[a,b,i,j] := ccd4a_tmp[l,a,i,d] * t_amp[b,d,j,l]\n println(isapprox(ccd4a_ref, ccd4a))\n \n ccd4b = -permutedims(ccd4a, (1, 2, 4, 3))\n ccd4 = ccd4a + ccd4b\n\n # Update Amplitude\n t_amp_new = @. e_denom * (mp2 + cepa1 + cepa2 + cepa3 + ccd1 + ccd2 + ccd3 + ccd4)\n\n # Evaluate Energy\n E_CCD = 1/4 * @tensor scalar((gmo[o,o,v,v])[i,j,a,b] * t_amp_new[a,b,i,j])\n t_amp = t_amp_new\n dE = E_CCD - E_old\n printfmt(\"CCD Iteration {1:3d}: Energy = {2:4.12f} dE = {3:1.5e}\\n\", cc_iter, E_CCD, dE)\n\n if abs(dE) < 1.e-8\n @info \"CCD Iterations have converged!\"\n break\n end\n\n if cc_iter == MAXITER\n psi4.core.clean()\n error(\"Maximum number of iterations exceeded.\")\n end\n end\n E_CCD\nend\n\nprintfmt(\"\\nCCD Correlation Energy: {:15.12f}\\n\", E_CCD)\nprintfmt(\"CCD Total Energy: {:15.12f}\\n\", E_CCD + scf_e)\n```\n\n true\n true\n true\n true\n CCD Iteration 1: Energy = -0.142119840107 dE = -1.42120e-01\n true\n true\n true\n true\n CCD Iteration 2: Energy = -0.142920457961 dE = -8.00618e-04\n true\n true\n true\n true\n CCD Iteration 3: Energy = -0.146174466311 dE = -3.25401e-03\n true\n true\n true\n true\n CCD Iteration 4: Energy = -0.147222337053 dE = -1.04787e-03\n true\n true\n true\n true\n CCD Iteration 5: Energy = -0.147660207822 dE = -4.37871e-04\n true\n true\n true\n true\n CCD Iteration 6: Energy = -0.147845022862 dE = -1.84815e-04\n true\n true\n true\n true\n CCD Iteration 7: Energy = -0.147926013534 dE = -8.09907e-05\n true\n true\n true\n true\n CCD Iteration 8: Energy = -0.147962311493 dE = -3.62980e-05\n true\n true\n true\n true\n CCD Iteration 9: Energy = -0.147978892019 dE = -1.65805e-05\n true\n true\n true\n true\n CCD Iteration 10: Energy = -0.147986584027 dE = -7.69201e-06\n true\n true\n true\n true\n CCD Iteration 11: Energy = -0.147990200750 dE = -3.61672e-06\n true\n true\n true\n true\n CCD Iteration 12: Energy = -0.147991921640 dE = -1.72089e-06\n true\n true\n true\n true\n CCD Iteration 13: Energy = -0.147992749316 dE = -8.27677e-07\n true\n true\n true\n true\n CCD Iteration 14: Energy = -0.147993151327 dE = -4.02011e-07\n true\n true\n true\n true\n CCD Iteration 15: Energy = -0.147993348360 dE = -1.97033e-07\n true\n true\n true\n true\n CCD Iteration 16: Energy = -0.147993445735 dE = -9.73748e-08\n true\n true\n true\n true\n CCD Iteration 17: Energy = -0.147993494226 dE = -4.84909e-08\n true\n true\n true\n true\n CCD Iteration 18: Energy = -0.147993518542 dE = -2.43158e-08\n true\n true\n true\n true\n CCD Iteration 19: Energy = -0.147993530812 dE = -1.22701e-08\n true\n true\n true\n true\n CCD Iteration 20: Energy = -0.147993537039 dE = -6.22685e-09\n \n CCD Correlation Energy: -0.147993537039\n CCD Total Energy: -76.100522583361\n\n\n ┌ Info: CCD Iterations have converged!\n └ @ Main In[15]:60\n\n\nUnfortunately, Psi4 does not have a CCD code to compare this to. However, Psi4 does have Bruekner CCD, an orbital-optimized variant of CCD. We can qualitatively compare our energies to this energy. The Bruekner-CCD energy should be a little lower than our CCD energy due to the orbital optimization procedure.\n\n\n```julia\npsi4_bccd = psi4.energy(\"bccd\", ref_wfn = scf_wfn)\nprintfmt(\"\\nPsi4 BCCD Correlation Energy: {:15.12f}\\n\", psi4_bccd - scf_e)\nprintfmt(\"Psi4 BCCD Total Energy: {:15.12f}\\n\", psi4_bccd)\n```\n\n \n Psi4 BCCD Correlation Energy: -0.149207663736\n Psi4 BCCD Total Energy: -76.101736710059\n\n\n## References\n\n1. Modern review of coupled-cluster theory, included diagrammatic derivations of the CCD equations:\n\t> [[Bartlett and Musial:2007](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.79.291)] Rodney J. Bartlett and Monika Musial, \"Coupled-cluster theory in quantum chemistry\" *Rev. Mod. Phys.* **79**, 291 (2007)\n \n2. Background on CEPA:\n >Kutzelnigg, Werner 1977 *Methods of Electronic Structure Theory* ed. H. F. Schaefer III (Plenum, New York), p 129\n\n3. More CEPA:\n > [Koch and Kutzelnigg:1981](https://link.springer.com/article/10.1007/BF00553396) S. Koch and W. Kutzelnigg, *Theor. Chim. Acta* **59**, 387 (1981). \n\n4. Original CCD Paper:\n > [Čížek:1966](http://aip.scitation.org/doi/abs/10.1063/1.1727484) Jiří Čížek, \"On the Correlation Problem in Atomic and Molecular Systems. Calculation of Wavefunction Components in Ursell‐Type Expansion Using Quantum‐Field Theoretical Methods\" *J. Chem. Phys* **45**, 4256 (1966) \n\n5. Useful notes on diagrams applied to post-HF methods:\n > A. V. Copan, \"Diagram notation\" accessed with https://github.com/CCQC/chem-8950/tree/master/2017\n\n", "meta": {"hexsha": "022d5c14a1ba2e418fddcdc74145fe4bc8fb1258", "size": 34367, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorials/08_CEPA0_and_CCD/8b_CEPA0_and_CCD.ipynb", "max_stars_repo_name": "zyth0s/psi4julia", "max_stars_repo_head_hexsha": "beb0384028f1a3654b8a2f8690b7db5bd9c24b86", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-02-13T22:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-17T07:34:10.000Z", "max_issues_repo_path": "Tutorials/08_CEPA0_and_CCD/8b_CEPA0_and_CCD.ipynb", "max_issues_repo_name": "zyth0s/psi4julia", "max_issues_repo_head_hexsha": "beb0384028f1a3654b8a2f8690b7db5bd9c24b86", "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": "Tutorials/08_CEPA0_and_CCD/8b_CEPA0_and_CCD.ipynb", "max_forks_repo_name": "zyth0s/psi4julia", "max_forks_repo_head_hexsha": "beb0384028f1a3654b8a2f8690b7db5bd9c24b86", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7015765766, "max_line_length": 618, "alphanum_fraction": 0.5337969564, "converted": true, "num_tokens": 9127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.11436852165386972, "lm_q1q2_score": 0.05095455427561188}} {"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols\ninit_printing()\n```\n\n# Independence\n# Spanning\n# Basis\n# Dimension\n\n## Independence\n\nSticking with the theme of linearly independent vectors, we note that vectors are indeed linearly independent under the following conditions:\n\n1. If no combination of the vectors results in the zero vector (other than the trivial cases of a scalar multiple of $0$ of each of the vectors)\n2. For the respective dimensional space, they do not lie on a line, plane, or hyperplane through the origin\n\nLet's consider the example of the matrix (of coefficients), named `A` below.\n\n\n```python\nA= Matrix([[1, 2, 4], [3, 1, 4]])\nA\n```\n\n### How many vectors in the nullspace?\n\nThis is a matrix with a rank of $2$ ($2$ pivots) and $3$ unknowns and $2$ rows. Thus, $\\text{rank}\\left(A\\right)=m=2$ (a full row rank). We are left with $n-r$ free variables, i.e. $3 - 2 = 1$. Importantly, this means that we will have one vector in the nullspace.\n\n\n```python\nA.rref() # Reduced row-echelon form\n```\n\n\n```python\nA.nullspace() # Null -sapce vector\n```\n\nWe note the two equations in three unknowns (set to the zero vector) in (1) below.\n\n$$\\begin{align}&{x_1}+2{x_2}+4{x_3}=0\\\\&3{x_1}+{x_2}+4{x_3}=0\\end{align}\\tag{1}$$\n\nAfter Gauss-Jordan elimination we have (2).\n\n$$\\begin{align}&{x_1}+\\frac{4}{5}{x_3}=0\\\\&{x_2}+\\frac{8}{5}{x_3}=0\\end{align}\\tag{2}$$\n\nFor the null space, we set $x_3=1$. From this follows that ${x_2}=-\\frac{8}{5}$ and then ${x_1}=-\\frac{4}{5}$ confirming the results of the `.nullspace()` method above.\n\n### Another way to state independence\n\nConsider the columns of any matrix $A$ as vectors $\\underline{v}_1,\\underline{v}_2,\\ldots,\\underline{v}_n$. If $\\text{rank}\\left(A\\right)=n$ (the number of columns) then the nullspace only contains the zero vector and the column vectors are linearly independent.\n\n## Spanning\n\nWe have introduced the concept of _spanning_ a (sub)space. If we have a set of linearly independent vectors such that all their linear combinations (including the zero vectors) _fill_ a (sub)space, we state that is _spans_ that (sub)space. We are particularly interested in a set of (column) vectors (in a matrix) that are linearly independent and span a (sub)space, because this leads us to the next topic of _basis vectors_.\n\n## Basis\n\nBasis vectors (in a space $W$) are vectors with the properties, (a) they are linearly independent and (b) they span the space (linear combinations of them fill the space).\n\nUp until now we looked at columns in a matrix $A$. It is more common in textbooks to look at a space first and ask about basis vectors, spanning vectors, dimension, and so on.\n\nSo let's look at $\\mathbb{R}^3$. The obvious set of basis vectors are shown in (3).\n\n$$\\hat{i},\\quad\\hat{j},\\quad\\hat{k}\\tag{3}$$\n\nWhat about the vectors in (4). Are they linearly independent and do they span $\\mathbb{R}^3$?\n\n$$\\begin{bmatrix}1\\\\1\\\\2\\end{bmatrix},\\quad\\begin{bmatrix}2\\\\2\\\\5\\end{bmatrix}\\tag{4}$$\n\n\n```python\nA = Matrix([[1, 2], [1, 2], [2, 5]])\nA\n```\n\n\n```python\nA.rref()\n```\n\nHere we have $\\text{rank}\\left(A\\right)=2$, $n=2$, and $n-r=0$, i.e. $0$ vectors in the nullspace. They cannot possibly be a basis for $\\mathbb{R}^3$ and do not span $\\mathbb{R}^3$.\n\n\n```python\nA.nullspace()\n```\n\nAll their linear combinations will only fill a plane through the origin. Their (trivial) zero combination does result in the zero vector, though, so they do fill a subspace of $\\mathbb{R}^3$.\n\nIf we added a column vector that is a linear combination of the original two columns, it will also fall in the plane. There will be a vector in the nullspace other than the zero vector, though.\n\n\n```python\nA = Matrix([[1, 2, 3], [1, 2, 3], [2, 5, 7]]) # Adding a linear combination of columns one and two\nA.nullspace() # Calculation the nullspace\n```\n\n\n```python\nA.rref()\n```\n\nWe see that we have a row with zero values. This means that we have a column without a pivot and thus a free variable.\n\nLet's add another, just for fun. Here we duplicate the first row.\n\n\n```python\nA = Matrix([[1, 2, 3], [1, 2, 3], [2, 5, 8]])\nA\n```\n\n\n```python\nA.rref()\n```\n\nAgain, a column without a pivot and sure enough, we'll find a vector (other than the zero vector) in the nullspace.\n\n\n```python\nA.nullspace()\n```\n\n### The special case of a square matrix\n\nIf we have a square matrix, we need only look at it's determinant: _Is it invertible_? (More about matrix inverses later).\n\n\n```python\nA.det() # .det() calculates the determinant\n```\n\nThe determinant is $0$ (as expected) and we have a vector in the nullspace.\n\n## Dimension\n\nGiven a (sub)space, every basis for that (sub)space has the same number of vectors (there are usually more than one basis for every (sub)space. This called the _dimension_ of the (sub)space.\n\n## Example\n\n* Consider the column space\n\n\n```python\nA = Matrix([[1, 2, 3, 1], [1, 1, 2, 1], [1, 2, 3, 1]])\nA\n```\n\nThere are $n=4$ unknowns, $m=3$ unknowns. We note that column $1$ = column $4$. We note that with $4$ unknowns we are dealing with $\\mathbb{R}^4$. In essence, there are at most three independent columns, thus the matrix cannot be a basis for $\\mathbb{R}^4$.\n\n\n```python\nA.nullspace()\n```\n\n\n```python\nA.rref()\n```\n\nAs we can see here, (5), columns three and four have free variables, i.e. no pivots.\n\n$$\\begin{align}&{x}_{1}+0{x}_{2}+{x}_{3}+{x}_{4}=0\\\\&0{x}_{1}+1{x}_{2}+{x}_{3}+{0}_{4}=0\\\\&{x}_{4}={c}_{2}\\\\&{x}_{3}={c}_{1}\\\\ \\therefore \\quad &{x}_{2}=-{c}_{1}\\\\ \\therefore \\quad &{x}_{1}=-{c}_{1}-{c}_{2}\\end{align}\\tag{5}$$\n\nWe express this more fully in (6).\n\n$$ \\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ { x }_{ 3 } \\\\ { x }_{ 4 } \\end{bmatrix}=\\begin{bmatrix} -{ c }_{ 1 }-{ c }_{ 2 } \\\\ -{ c }_{ 1 } \\\\ { c }_{ 1 } \\\\ { c }_{ 2 } \\end{bmatrix}=\\begin{bmatrix} -{ c }_{ 1 } \\\\ -{ c }_{ 1 } \\\\ { c }_{ 1 } \\\\ 0 \\end{bmatrix}+\\begin{bmatrix} -{ c }_{ 2 } \\\\ 0 \\\\ 0 \\\\ { c }_{ 2 } \\end{bmatrix}={ c }_{ 1 }\\begin{bmatrix} -1 \\\\ -1 \\\\ 1 \\\\ 0 \\end{bmatrix}+{ c }_{ 2 }\\begin{bmatrix} -1 \\\\ 0 \\\\ 0 \\\\ 1 \\end{bmatrix} \\tag {6} $$\n\nThe rank of matrix $A$ is $2$ (it is the number of pivot columns). This matrix space thus have two basis vectors (column vectors $1$ and $2$) and we say the dimension of this space is $2$. Remember, a matrix has a rank, which is the dimension of a column space (the column space representing the space 'produced' by the column vectors). We talk about the rank of a matrix, $\\text{rank}\\left(A\\right)$ and the column space of a matrix, $\\text{C}\\left(A\\right)$.\n\nIn summary, we have two basis above (they span a space). Any two vectors that are not linearly dependent will also span this space, they can't help but to, $\\text{dim}\\text{C}\\left(A\\right)=r$. The nullspace will have $n-r$ vectors (the dimension of the nullspace equal the number of free variables).\n\n\n```python\n\n```\n", "meta": {"hexsha": "4c34bbe9ae760bd6d716c441048f46b46af9e361", "size": 41724, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_9_Independence_Spanning_Basis_Dimension.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_9_Independence_Spanning_Basis_Dimension.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/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_9_Independence_Spanning_Basis_Dimension.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": 48.6293706294, "max_line_length": 2532, "alphanum_fraction": 0.7043667913, "converted": true, "num_tokens": 2816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.115960721309117, "lm_q1q2_score": 0.0507703287633644}} {"text": "```python\nfrom IPython.core.display import HTML\ncss_file = './custom.css'\nHTML(open(css_file, \"r\").read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n###### Content provided under a Creative Commons Attribution license, CC-BY 4.0; code under MIT License. (c)2014 [David I. Ketcheson](http://davidketcheson.info)\n\n##### version 0.1 - May 2014\n\n# Hyperbolic Conservation Laws\n\n\\begin{equation*}\n\\newcommand{Dx}{\\Delta x}\n\\newcommand{Dt}{\\Delta t}\n\\newcommand{imh}{{i-1/2}}\n\\newcommand{iph}{{i+1/2}}\n\\end{equation*}\nMany models of wave phenomena are governed by *hyperbolic conservation laws*. In this short course, we will learn about hyperbolic conservation laws and their numerical solution.\n\n## Conservation of mass\n\nImagine a fluid flowing in a narrow tube. We'll use $q$ to indicate the density of the fluid and $u$ to indicate its velocity. Both of these are functions of space and time: $q = q(x,t)$; $u=u(x,t)$. The total mass in the section of tube $[x_1,x_2]$ is\n\n\\begin{equation}\n\\int_{x_1}^{x_2} q(x,t) dx.\n\\end{equation}\n\nThis total mass can change in time due to fluid flowing in or out of this section of the tube. We call the rate of flow the *flux*, and represent it with the function $f(q)$. Thus the net rate of flow of mass into (or out of) the interval $[x_1,x_2]$ at time $t$ is\n\n$$f(q(x_1,t)) - f(q(x_2,t)).$$\n\nWe just said that this rate of flow must equal the time rate of change of total mass; i.e.\n\n$$\\frac{d}{dt} \\int_{x_1}^{x_2} q(x,t) dx = f(q(x_1,t)) - f(q(x_2,t)).$$\n\nNow since $\\int_{x_1}^{x_2} \\frac{\\partial}{\\partial x} f(q) dx = f(q(x_2,t)) - f(q(x_1,t))$, we can rewrite this as\n\n$$\\frac{d}{dt} \\int_{x_1}^{x_2} q(x,t) dx = -\\int_{x_1}^{x_2} \\frac{\\partial}{\\partial x} f(q) dx.$$\n\nUnder certain smoothness assumptions on $q$, we can move the time derivative inside the integral. We'll also put everything on the left side, to obtain\n\n$$\\int_{x_1}^{x_2} \\left(\\frac{\\partial}{\\partial t}q(x,t) + \\frac{\\partial}{\\partial x} f(q)\\right) dx = 0.$$\n\nSince this integral is zero for *any* choice of $x_1,x_2$, it must be that the integrand (the expression in parentheses) is actually zero *everywhere*! Therefore we can write the **differential conservation law**\n\n$$q_t + f_x = 0.$$\n\nHere and throughout the course, we use subscripts to denote partial derivatives.\nThis equation expresses the fact that the total mass is conserved -- since locally the mass can change only due to a net inflow or outflow.\n\n## Advection\n\nIn order to solve the conservation law above, we need an expression for the flux, $f$. The rate of flow is just mass times velocity: $f=u q$. Thus we obtain the **continuity equation**\n\n$$q_t + (uq)_x = 0.$$\n\nIn general, we need another equation to determine the velocity $u(x,t)$. In [Lesson 4](Lesson_04_Fluid_dynamics.ipynb) we'll look at the full equations of fluid dynamics, but for now let's consider the simplest case, in which all of the fluid flows at a single, constant velocity $u(x,t)=a$. Then the continuity equation becomes the **advection equation**\n\n$$q_t + a q_x = 0.$$\n\nThis equation has a very simple solution. If we are given the density $q(x,0)=q_0(x)$ at time zero, then the solution is just\n\n$$q(x,t) = q_0(x-at).$$\n\nLet's plot the solution of the advection equation on the interval $[0,1]$ for the initial condition\n$$q_0(x) = e^{-2(x-1/2)^2}.$$\n\nFirst, let's import all the modules we'll need.\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom clawpack.visclaw.JSAnimation import IPython_display\n```\n\nNext, we'll set up a grid and the initial condition:\n\n\n```python\nx = np.linspace(0,1,1000) # Spatial grid\nt = np.linspace(0,1) # Temporal grid\na = 1.0 # Advection speed\n\ndef q_0(x): # Initial condition\n return np.exp(-200.*(x-0.2)**2)\n```\n\nFinally, let's make an animation of the solution. It will take a few moments to run this code. For now, you don't need to worry about understanding all of the plotting code below. Just play with the animation until you have a feel for how the solution behaves.\n\n\n```python\nfig = plt.figure(figsize=(8,4)) # Create an empty figure\nax = plt.axes()\nline, = ax.plot([], [],linewidth=2) # Create an empty line plot\nplt.axis((0,1,-0.1,1.1)) # Set the bounds of the plot\n\ndef plot_q(t):\n line.set_data(x,q_0(x-a*t)) # Replace the line plot with the solution at time t\n \nanimation.FuncAnimation(fig, plot_q, frames=t) # Animate the solution\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 Once \n Loop \n Reflect \n
    \n\n
    \n\n\n\n\n\n\n\nAs you can see, the initial pulse just moves to the right at speed $a$ as time advances. This isn't very interesting, but it captures the most important feature of hyperbolic equations: waves travel at finite speed.\n\n## Characteristics\n\nNotice that the solution value is constant along the line $x-at=x_0$, in the $x-t$ plane, for each value of $x_0$. These lines are called **characteristics**; they are the trajectories along which solution information is transmitted. The value $a$ is referred to as the **characteristic velocity**. The code below plots some of these characteristics.\n\nWhen we learn about more complicated conservation laws, we'll see that information still travels along characteristics, but those characteristics aren't necessarily straight lines.\n\n\n```python\nfig = plt.figure(figsize=(8,4))\nax = plt.axes()\n\nfor x_0 in np.linspace(0,1,10):\n ax.plot(x,(x-x_0)/a,'-k')\nplt.ylim(0,1)\n```\n\n## A finite volume method for advection\n\nWe can easily solve the advection equation exactly. But the advection equation is a prototype for more complicated conservation laws that we will only be able to solve approximately by using numerical methods. In order to better understand these methods, we will discuss them first in the context of the advection equation.\n\nFor simplicity, we'll suppose that we wish to solve the advection equation on the interval $[0,1]$. We introduce a set of equally spaced *grid cells* of width $\\Dx$, and write $x_i$ to mean the center of cell $i$. Thus the first cell is the interval $[0,\\Dx]$ and $x_1=\\Dx/2$. We will also write $x_\\imh$ or $x_\\iph$ to denote the left or right boundary of cell $i$, respectively.\n\nWe write $Q_i$ to denote the *average* value of the solution over cell $i$:\n\n$$Q_i = \\frac{1}{\\Dx} \\int_{x_\\imh}^{x_\\iph} q \\ dx.$$\n\nThe simplest finite volume method is obtained by supposing that the solution is actually *equal* to $Q_i$ over all of cell $i$.\n\n\n\nSuppose $a>0$. Then the flux into cell $i$ from the left is $a Q_{i-1}$ and the flux out of cell $i$ to the right is $a Q_i$. Then our integral conservation law reads\n\n$$Q_i'(t) = -\\frac{a}{\\Dx}\\left(Q_i - Q_{i-1}\\right).$$\n\nApplying a forward difference in time we obtain the *upwind method*\n\n$$Q^{n+1}_i = Q^n_i -\\frac{a}{\\Dx}\\left(Q_i - Q_{i-1}\\right).$$\n\nWe call this the upwind method because the solution behaves as if it were being blown by a wind to the right, and the method uses the value $Q_{i-1}$ from the upwind direction.\n\nHere is a bit of Python code to solve the advection equation using the upwind method.\n\n\n```python\na = 1.0 # advection speed\n\nm = 50 # number of cells\ndx = 1./m # Size of 1 grid cell\nx = np.arange(-dx/2, 1.+dx/2, dx) # Cell centers, including ghost cells\n\nt = 0. # Initial time\nT = 0.5 # Final time\ndt = 0.8 * dx / a # Time step\n\nQ = np.exp(-200*(x-0.2)**2) # Initial data\nQnew = np.empty(Q.shape)\n\nwhile t < T:\n \n # Extrapolation at boundaries:\n Qnew[0] = Q[1]\n Qnew[-1] = Q[-2]\n \n for i in range(1,len(x)):\n Qnew[i] = Q[i] - a*dt/dx * (Q[i]-Q[i-1])\n \n Q = Qnew.copy()\n t = t + dt\n \nplt.plot(x,Q,linewidth = 2)\nplt.title('t = '+str(t));\n```\n\nNotice how we set up a grid that contains an extra cell at each end, outside of the problem domain $[0,1]$. These are called **ghost cells** and are often useful in handling the solution at the grid boundaries.\n\n\n\n The technique we have used to set the ghost cell values above, by copying the last value inside the grid to the ghost cells, is known as **zero-order extrapolation**. It is useful for allowing waves to pass out of the domain (so-called *non-reflecting* boundaries). Note that we don't actually need the ghost cell at the right end for the upwind method, but for other methods we will.\n\nThe upwind method is simple, but it is not very accurate. Notice how the computed solution becomes wider and shorter over time. This behavior is referred to as *dissipation*.\n\n### Exercise\n\nNow do the following with the code above:\n\n1. Set $m=1000$ or more and notice that it takes some time to compute the solution. Rewrite the inner loop (over $i$) as a single line with no loop, using numpy slicing. For large values of $m$, the code with slicing is much faster.\n1. Notice that the last step of the simulation goes past time $T$. Modify the code so that the last step is adjusted to exactly reach $T$.\n2. Change the code so that animation of the solution versus time is plotted. You will want to accumulate frames of the solution in a list and then use the same kind of code we used above to animate the exact solution.\n3. Add some code to plot the exact solution.\n\n*Extra credit*: change the left boundary condition so that there is a sinusoidal wave coming in from the left:\n$$u(0,t) = \\sin(20 \\pi t).$$\nWhat do you notice about the sinusoid as it moves into the domain?\n\n\n```python\n\n```\n\nAfter making it through the exercise above, you should feel pretty comfortable with the basics of scientific programming in Python.\n\n## The CFL condition\n\nTake a look at the line of code that sets the time step:\n```python\n dt = 0.8 * dx / a \n```\nYou might be wondering where that formula came from. Rearranging that equation, we have\n$$a \\frac{\\Delta t}{\\Delta x} = 0.8.$$\nThe quantity $\\nu = a \\frac{\\Delta t}{\\Delta x}$ is the distance the exact solution moves during each time step, in units of grid cells. It is referred to as the *CFL number* or just the *Courant number* after the authors Courant, Friedrichs and Lewy who [established its importance](http://www.stat.uchicago.edu/~lekheng/courses/302/classics/courant-friedrichs-lewy.pdf). Try the following values of $\\nu$ in the code above, and compare the results with those you obtained already using $\\nu=0.8$.\n1. $\\nu = 1.0$\n2. $\\nu = 1.5$\n3. $\\nu = 0.1$\n\nFinally, try setting $a$ to a negative value. What happens?\n\nThe results you have observed can be explained as follows. Over a time step of size $\\Dt$, the solution moves by an amount $a \\Dt$. So $q(x_i,t_n)$ should be given exactly by $q(x_i-a\\Dt,t_{n-1})$. This is referred to as the *domain of dependence* of the solution.\n\nThe upwind method uses the values $Q_i^{n-1}$ and $Q_{i-1}^{n-1}$ to compute $Q_i^n$. The points $(x_{i-1},t_n)$ and $(x_i,t_n)$ (as well as the locations of solution values they depend, and the ones those depend on, and so forth) are the *numerical domain of dependence*.\n\nFor this to work, the true domain of dependence $x_i-a\\Dt$ must lie within the numerical domain of dependence, as $\\Dt,\\Dx \\to 0$. This is known as the [CFL condition](http://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition).\n\nFor the upwind method, that means that we must have\n$$x_i - \\Dx \\le x_i - a \\Dt \\le x_i$$\nor in other words\n$$0 \\le a \\frac{\\Dt}{\\Dx} \\le 1.$$\n\nIf the CFL condition is violated, the information that is used by the numerical method doesn't include the true information that influences the exact solution, so the numerical solution cannot be convergent.\n\n## The Lax-Friedrichs method\n\nThe upwind method gets its name from the fact that it uses the value $U_{i-1}$ and not $U_{i+1}$. Assuming $a>0$, the correct solution value $U_i^{n+1}$ should come from a point to the left of $x_i$ at time $t_n$ (i.e., the wind blows to the right, so $x_{i-1}$ is *upwind* of $x_i$).\n\nThis bias is fine for the advection equation, where we know everything moves in the same direction. But for more complicated conservation laws, things may move in either direction. It will be useful to have a method that uses information from both directions. The simplest such method is known as the **Lax-Friedrichs** method. For the conservation law $q_t + f(q)_x$, this method is\n\n$$Q_i^{n+1} = \\frac{1}{2}(Q_{i-1}^n + Q_{i+1}^n) - \\frac{\\Dt}{2\\Dx}\\left(f(Q_{i+1}^n) - f(Q_{i-1}^n)\\right).$$\n\nNotice that the flux difference term clearly approximates $f(q)_x$. Meanwhile, the value of $q$ itself is approximated by taking the average of two neighboring values. This average makes this method dissipative too (but it ensures that the solution is stable).\n\n### Exercise\n\n1. What does the CFL condition imply for the time step when using the Lax-Friedrichs method?\n\n2. In the cell below, implement the Lax-Friedrichs method for advection.\n\n\n```python\n\n```\n\n*Extra credit*: Compute the norm of the difference between the approximate and exact solution. How does it change if you decrease $\\Dx$?\n\n## Accuracy\n\nThe methods we have used so far (i.e., the *upwind method* and the *Lax-Friedrichs method*) are both dissipative. Furthermore, both of these methods are only *first order accurate*, meaning that if we reduce the values of $\\Dt$ and $\\Dx$ by a factor of two, the overall error decreases only by a factor of two. In [Lesson 3](Lesson_03_High-resolution_methods.ipynb), we will learn about more accurate methods. But first, in [Lesson 2](Lesson_02_Traffic.ipynb) we'll look at a model for traffic flow.\n", "meta": {"hexsha": "a4b526f6e71d812d628e1cc52678da55f179b0e3", "size": 761630, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lesson_01_Advection.ipynb", "max_stars_repo_name": "nemethedr/HyperPython", "max_stars_repo_head_hexsha": "ce3d8ccd898fcb3d54f04af283d92b2436ba3eaa", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2015-02-16T17:36:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T11:40:54.000Z", "max_issues_repo_path": "Lesson_01_Advection.ipynb", "max_issues_repo_name": "volpatto/HyperPython", "max_issues_repo_head_hexsha": "ce3d8ccd898fcb3d54f04af283d92b2436ba3eaa", "max_issues_repo_licenses": ["CC-BY-4.0", "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_01_Advection.ipynb", "max_forks_repo_name": "volpatto/HyperPython", "max_forks_repo_head_hexsha": "ce3d8ccd898fcb3d54f04af283d92b2436ba3eaa", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2015-02-16T17:36:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T21:09:44.000Z", "avg_line_length": 85.2507275576, "max_line_length": 515, "alphanum_fraction": 0.8055735725, "converted": true, "num_tokens": 5011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010666848732088, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.05068302753313061}} {"text": "**Notas para contenedor de docker:**\n\nComando de docker para ejecución de la nota de forma local:\n\nnota: cambiar `dir_montar` por la ruta de directorio que se desea mapear a `/datos` dentro del contenedor de docker.\n\n```\ndir_montar=#aquí colocar la ruta al directorio a montar, por ejemplo: \n#dir_montar=/Users/erick/midirectorio.\n```\n\nEjecutar:\n\n```\n$docker run --rm -v $dir_montar:/datos --name jupyterlab_prope_r_kernel_tidyverse -p 8888:8888 -d palmoreck/jupyterlab_prope_r_kernel_tidyverse:3.0.16 \n\n```\n\nIr a `localhost:8888` y escribir el password para jupyterlab: `qwerty`\n\nDetener el contenedor de docker:\n\n```\ndocker stop jupyterlab_prope_r_kernel_tidyverse\n```\n\n\nDocumentación de la imagen de docker `palmoreck/jupyterlab_prope_r_kernel_tidyverse:3.0.16` en [liga](https://github.com/palmoreck/dockerfiles/tree/master/jupyterlab/prope_r_kernel_tidyverse).\n\n---\n\nPara ejecución de la nota usar:\n\n[docker](https://www.docker.com/) (instalación de forma **local** con [Get docker](https://docs.docker.com/install/)) y ejecutar comandos que están al inicio de la nota de forma **local**. \n\nO bien dar click en alguno de los botones siguientes:\n\n[](https://mybinder.org/v2/gh/palmoreck/dockerfiles-for-binder/jupyterlab_prope_r_kernel_tidyerse?urlpath=lab/tree/Propedeutico/Python/clases/2_calculo_DeI/1_aproximacion_a_derivadas_e_integrales.ipynb) esta opción crea una máquina individual en un servidor de Google, clona el repositorio y permite la ejecución de los notebooks de jupyter.\n\n[](https://repl.it/languages/python3) esta opción no clona el repositorio, no ejecuta los notebooks de jupyter pero permite ejecución de instrucciones de Python de forma colaborativa con [repl.it](https://repl.it/). Al dar click se crearán nuevos ***repl*** debajo de sus users de ***repl.it***.\n\n\n## Se sugiere apoyar esta nota con la lectura de los capítulos 5 y 6 del libro de texto de J. Kiusalaas \"Numerical Methods in Engineering with Python 3\".\n\n# Función\n\nUna función, $f$, es una regla de correspondencia entre un conjunto nombrado dominio, $D_f$ y otro conjunto nombrado codominio, $C_f$.\n\nNotación: $f: A \\rightarrow B$ es una función de un conjunto $\\text{dom}f \\subseteq A$ en un conjunto $B$.\n\n---\n\n**Observación**\n\n$\\text{dom}f$ (el dominio de $f$) podría ser un subconjunto propio de $A$, esto es, algunos elementos de $A$ y otros no, son mapeados a elementos de $B$.\n\n---\n\n**Ejemplos**\n\n* La regla de correspondencia que asocia a cada estudiante su clave única.\n\n* La regla de correspondencia que asocia a cada persona una casilla para votar en elecciones.\n\n* $f: \\mathbb{R} \\rightarrow \\mathbb{R}$ con $f(x) = x^2$. \n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\nx = np.linspace(-1,1,100) #100 puntos equidistantes entre -1,1\n```\n\n\n```python\ny = lambda x: x**2\n```\n\n\n```python\ny_eval = y(x)\n```\n\n\n```python\nplt.plot(x,y_eval)\nplt.title('y=x^2')\nplt.show()\n```\n\n# Derivada de una función\n\nConsideremos en lo que sigue $f: \\mathbb{R} \\rightarrow \\mathbb{R}$.\n\n$f$ es diferenciable en $x_0 \\in (a,b)$ si $\\displaystyle \\lim_{x \\rightarrow x_0} \\frac{f(x)-f(x_0)}{x-x_0}$ existe y escribimos:\n\n$$f^{(1)}(x_0) = \\displaystyle \\lim_{x \\rightarrow x_0} \\frac{f(x)-f(x_0)}{x-x_0}.$$\n\n$f$ es diferenciable en $[a,b]$ si es diferenciable en cada punto de $[a,b]$. Análogamente definiendo la variable $h=x-x_0$ se tiene:\n\n\n$f^{(1)}(x_0) = \\displaystyle \\lim_{h \\rightarrow 0} \\frac{f(x_0+h)-f(x_0)}{h}$ que típicamente se escribe como:\n\n$$f^{(1)}(x) = \\displaystyle \\lim_{h \\rightarrow 0} \\frac{f(x+h)-f(x)}{h}.$$\n\n---\n\n**Comentario** \n\nSi $f$ es diferenciable en $x_0$ entonces $f(x) \\approx f(x_0) + f^{(1)}(x_0)(x-x_0)$. Gráficamente:\n\n\n\n---\n\n**Notación:** $\\mathcal{C}^n([a,b])=\\{\\text{funciones } f:\\mathbb{R} \\rightarrow \\mathbb{R} \\text{ con } n \\text{ derivadas continuas en el intervalo [a,b]}\\}$.\n\n---\n\n**Observación**\n\nEn la definición anterior se calculan límites los cuales pueden calcularse con el paquete *SymPy*.\n\n\n```python\nimport sympy\n```\n\n**Límite de $\\frac{\\sin(x)}{x}$ para $x \\rightarrow 0$:**\n\n\n```python\nx = sympy.Symbol(\"x\")\n```\n\n\n```python\nquotient = sympy.sin(x)/x\n```\n\n\n```python\nsympy.limit(quotient,x,0)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n---\n\n**Límite de $\\frac{\\cos(x+h) - \\cos(x)}{h}$ para $h \\rightarrow 0$:**\n\n\n```python\nx, h = sympy.symbols(\"x, h\")\n```\n\n\n```python\nquotient = (sympy.cos(x+h) - sympy.cos(x))/h\n```\n\n\n```python\nsympy.limit(quotient, h, 0)\n```\n\n\n\n\n$\\displaystyle - \\sin{\\left(x \\right)}$\n\n\n\nLo anterior corresponde a la **derivada de $\\cos(x)$**:\n\n\n```python\nx = sympy.Symbol(\"x\")\n```\n\n\n```python\nsympy.cos(x).diff(x)\n```\n\n\n\n\n$\\displaystyle - \\sin{\\left(x \\right)}$\n\n\n\n**Si queremos evaluar la derivada podemos usar:**\n\n\n```python\nsympy.cos(x).diff(x).subs(x,sympy.pi/2)\n```\n\n\n\n\n$\\displaystyle -1$\n\n\n\n**Otra forma:**\n\n\n```python\nsympy.Derivative(sympy.cos(x), x)\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d x} \\cos{\\left(x \\right)}$\n\n\n\n\n```python\nsympy.Derivative(sympy.cos(x), x).doit_numerically(sympy.pi/2)\n```\n\n\n\n\n$\\displaystyle -1.0$\n\n\n\n# Errores absolutos y relativos de una aproximación\n\nSi `aprox` es mi cantidad con la que aproximo a mi objetivo `obj` entonces el error absoluto de `aprox` y el error relativo de `aprox` es:\n\n$$ErrAbs(\\text{aprox}) = |\\text{aprox} - \\text{obj}|.$$\n\n\n$$ErrRel(\\text{aprox}) = \\frac{ErrAbs(\\text{aprox})}{|\\text{obj}|}.$$\n\n---\n\n**Observación**\n\n* Obsérvese que `obj` debe ser distinto de cero para que el error relativo esté bien definido.\n\n* si $ErrRel(aprox) \\approx 10^{-k}$ se dice que `aprox` aproxima a `obj` con alrededor de $k$ dígitos correctos. Por ejemplo si $k=3$ entonces la cantidad `aprox` aproxima a la cantidad `obj` con alrededor de $3$ dígitos de precisión.\n\n---\n\n# Aproximación a una función por el teorema de Taylor\n\nLas fórmulas de aproximación a las derivadas por diferencias finitas y a integrales definidas en un intervalo por las reglas de cuadratura Newton-Cotes pueden obtenerse con los **polinomios de Taylor** presentes en el teorema del mismo autor, el cual, bajo ciertas hipótesis nos proporciona una expansión de una función alrededor de un punto. Otras opciones son con polinomios de Lagrange, ver [Lagrange_polynomial](https://en.wikipedia.org/wiki/Lagrange_polynomial). El teorema de Taylor es el siguiente:\n\nSea $f \\in \\mathcal{C}^n([a,b])$, $f^{(n+1)}$ existe en [a,b]. Si $x_0 \\in [a,b]$ entonces $\\forall x \\in [a,b]$ se tiene: $f(x) = P_n(x) + R_n(x)$ donde: \n\n$$P_n(x) = \\displaystyle \\sum_{k=0}^n \\frac{f^{(k)}(x_0)(x-x_0)^k}{k!} \\quad (f^{(0)} = f)$$ y $$R_n(x) = \\frac{f^{(n+1)}(\\xi_x)(x-x_0)^{(n+1)}}{(n+1)!}$$ con $\\xi_x$ entre $x_0, x$ y $x_0$ se llama centro.\n\n## Ejemplo\n\nAproximemos a la función $\\frac{1}{x}$ en el intervalo $[1,2]$ con polinomios de Taylor de orden $n$ con $n \\in \\{0,1,2\\}$ con centro en $x_0=1.5$. Los polinomios de Taylor son: \n\n$$P_0(x) = f(x_0) = \\frac{2}{3} \\quad \\text{(constante)}$$\n\n$$P_1(x) = f(x_0) + f^{(1)}(x_0)(x-x_0) = \\frac{2}{3} - \\frac{1}{x_0^2}(x-x_0) =\\frac{2}{3} - \\frac{1}{1.5^2}(x-1.5) \\quad \\text{(lineal)}$$\n\n$$P_2(x) = f(x_0) + f^{(1)}(x_0)(x-x_0) + \\frac{f^{(2)}(x_0)(x-x_0)^2}{2} = \\frac{2}{3} - \\frac{1}{x_0^2}(x-x_0) + \\frac{1}{x_0^3}(x-x_0)^2 = \\frac{2}{3} -\\frac{1}{1.5^2}(x-1.5) + \\frac{1}{1.5^3}(x-1.5)^2 \\quad \\text{(cuadrático)}$$\n\n---\n\n**Ejercicio**\n\nGraficar la función y los polinomios constante, lineal y cuadrático en una sola gráfica con `matplotlib` en el intervalo [1,2]. ¿Cuánto es la aproximación de los polinomios en x=1.9? Calcula el error relativo de tus aproximaciones.\n\n\n---\n\n**Comentario** \n\nOtras aproximaciones a una función se pueden realizar con:\n\n* Interpoladores polinomiales (representación por Vandermonde, Newton, Lagrange).\n\n---\n\n# Diferenciación numérica por diferencias finitas\n\nLas fórmulas de diferencias finitas pueden obtenerse con el teorema de Taylor. Por ejemplo:\n\nSea $f \\in \\mathcal{C}^1([a,b])$ y $f^{(2)}$ existe y está acotada $\\forall x \\in [a,b]$ entonces, si $x+h \\in [a,b]$ con $h>0$ por el teorema de Taylor se tiene:\n\n$$f(x+h) = f(x) + f^{(1)}(x)h + f^{(2)}(\\xi_{x+h})\\frac{h^2}{2}$$ con $\\xi_{x+h} \\in [x,x+h]$\n\nY al despejar $f^{(1)}(x)$ se tiene la **aproximación por diferencias hacia delante a la primera derivada de $f$**: \n\n$$f^{(1)}(x) = \\frac{f(x+h)-f(x)}{h} - f^{(2)}(\\xi_{x+h})\\frac{h}{2}$$\n\n---\n\n**Observación**\n\n\nLa aproximación por diferencias finitas a la primer derivada de la función tiene un error de orden $\\mathcal{O}(h)$ por lo que una elección de $h$ igual a $.1 = 10^{-1}$ generará aproximaciones con alrededor de un dígito correcto.\n\n---\n\nAsí también pueden obtenerse la versión centrada y aproximaciones a la segunda derivada de $f$:\n\n**Aproximación por diferencias hacia delante para la segunda derivada**\n\n$$\\frac{d^2f(x)}{dx} \\approx \\frac{f(x+2h)-2f(x+h)+f(x)}{h^2}$$\n\n**Aproximación por diferencias centradas a la primer y segunda derivada**\n\n$$ \\frac{df(x)}{dx} \\approx \\frac{f(x+h)-f(x-h)}{2h}$$\n\n$$ \\frac{d^2f(x)}{dx} \\approx \\frac{f(x+h)-2f(x)+f(x-h)}{h^2}$$\n\n**Interpretación geométrica de aproximación por diferencias centradas a la primer derivada de $f$:**\n\n\n\n---\n\n**Ejercicio** \n\nAproximar la primera y segunda derivadas de la función `arctan` con diferencias finitas centradas en el punto $x=0.5$\n\n\n\n\n```python\ndef central_approx_diff(f,x,h=0.0001): #el parámetro h tiene un valor default\n df =(f(x+h) - f(x-h))/(2.0*h) #primera derivada\n ddf =(f(x+h) - 2.0*f(x) + f(x-h))/h**2 #segunda derivada\n return df,ddf\n```\n\n\n```python\nimport math\n```\n\n\n```python\n#Ejemplo de llamada a función utilizando el parámetro de default de h=0.0001\nx = 0.5 #punto donde se realizará la aproximación\ndf, ddf = central_approx_diff(math.atan, x)\nprint('Primera derivada:', df)\nprint('Segunda derivada:', ddf)\n```\n\n Primera derivada: 0.7999999995730867\n Segunda derivada: -0.6399999918915711\n\n\n\n```python\n#Ejemplo de llamada a función utilizando h=1e-6\nh = 1e-6\nx = 0.5\ndf, ddf = central_approx_diff(math.atan, 0.5,h)\nprint('Primera derivada:', df)\nprint('Segunda derivada:', ddf)\n```\n\n Primera derivada: 0.799999999995249\n Segunda derivada: -0.639877040242709\n\n\n\n```python\n#derivadas analíticas:\nd = 1/(1+x**2)\ndd = (-2*x)/(1+x**2)**2\nprint(d)\nprint(dd)\n```\n\n 0.8\n -0.64\n\n\n\n```python\ndef relative_absolute_error(aprox, obj):\n if(np.abs(obj) > 0):\n return np.abs(aprox-obj)/np.abs(obj)\n else:\n return np.abs(aprox-obj)\n```\n\n\n```python\nrel_err_df = relative_absolute_error(df, d)\n```\n\n\n```python\nrel_err_df\n```\n\n\n\n\n 5.938860514476119e-12\n\n\n\n\n```python\nrel_err_ddf = relative_absolute_error(ddf, dd)\n```\n\n\n```python\nrel_err_ddf\n```\n\n\n\n\n 0.00019212462076725195\n\n\n\n---\n\n**Comentario** \n\nOtra forma de evaluar las aproximaciones realizadas es con módulos o paquetes de Python creados para este propósito en lugar de crear nuestras funciones como la de `relative_absolute_error`. En la siguiente celda instalamos el paquete [pytest](https://docs.pytest.org/en/latest/) y mostramos cómo evaluar la calidad de la aproximación con la función [approx](https://docs.pytest.org/en/latest/reference.html#pytest-approx) de este paquete.\n\n---\n\n\n```python\n!pip3 install -q --user pytest\n```\n\n \u001b[33m WARNING: The scripts py.test and pytest are installed in '/home/propeuser/.local/bin' which is not on PATH.\n Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\u001b[0m\n\n\n\n```python\nfrom pytest import approx\n```\n\n\n```python\ndf == approx(d)\n```\n\n\n\n\n True\n\n\n\n\n```python\nddf == approx(dd)\n```\n\n\n\n\n False\n\n\n\nY podemos usar un valor definido de tolerancia definido para hacer la prueba (por default se tiene una tolerancia de $10^{-6}$).\n\n\n```python\nddf == approx(dd, rel=1e-3,abs=1e-3)\n```\n\n\n\n\n True\n\n\n\n---\n\n**Ejercicios** \n\n\nLa diferenciación numérica por diferencias finitas **no es un proceso con una alta exactitud** pues los problemas del redondeo de la aritmética en la máquina se hacen presentes en el mismo. Como ejemplo de esta situación hágase el siguiente ejercicio 1.\n\n\n1) **(Tarea) Realizar una gráfica de log(error relativo) vs log(h) (h en el eje horizontal) para aproximar la segunda derivada de $f(x)=e^{-x}$ en $x=1$ con $h \\in \\{10^{-16}, 10^{-14}, \\dots , 10^{-1}\\}$ y diferencias hacia delante. Valor a aproximar: $f^{(2)}(1) = e^{-1}$. Usar:**\n\n$$\\frac{d^2f(x)}{dx} \\approx \\frac{f(x+2h)-2f(x+h)+f(x)}{h^2}$$\n\n2) **Crear un módulo con nombre `central_finite_derivative.py` en el que se tengan dos funciones de Python que aproximen la primera y segunda derivada de una función en un punto `x`. Ambas funciones reciben `fun`, `x` y `h` donde: `fun` es la función a calcularse su primera y segunda derivadas, `x` es el punto donde se realiza la aproximación y `h` es el parámetro de espaciado entre `x` y `x+h` igual a $h=10^{-6}$. La salida de cada función es un `float`. \nFunción de prueba: `math.atan` y `x=0.9`.**. \n\n**Los nombres de las funciones y sus salidas son:**\n\n| central_finite_derivative.py | parámetros de entrada |salida|\n|:---:|:---:|:---:|\n| approx_first_derivative | fun (function), x (float) ,h (float) | float|\n| approx_second_derivative | fun (function), x (float), h (float)| float|\n\n**3) (Tarea) Mismo ejercicio que 2) pero función de prueba: `math.asin` y `x=0.5`.**\n\n---\n\n## Diferenciación numérica en más dimensiones\n\nLa anterior aproximación por diferencias finitas también puede utilizarse para aproximar el gradiente de una función $f: \\mathbb{R}^n \\rightarrow \\mathbb{R}$ considerando que:\n\n$$\\nabla f(x) = \n\\begin{array}{l}\n\\left[ \\begin{array}{c}\n\\frac{\\partial f(x)}{\\partial x_1}\\\\\n\\vdots\\\\\n\\frac{\\partial f(x)}{\\partial x_n}\n\\end{array}\n\\right] = \\left[ \n\\begin{array}{c} \n\\displaystyle \\lim_{h \\rightarrow 0} \\frac{f(x+he_1) - f(x)}{h}\\\\\n\\vdots\\\\\n\\displaystyle \\lim_{h \\rightarrow 0} \\frac{f(x+he_n) - f(x)}{h}\n\\end{array}\n\\right]\n\\end{array} \\in \\mathbb{R}^n$$\n\ncon $e_i$ vectores canónicos (poseen 1 en la posición $i$ y cero en las restantes) para $i=1, \\dots, n$.\n\n---\n\n**Observación** \n\nEl gradiente de una función como se definió arriba también es una función, de hecho: $\\nabla f: \\mathbb{R}^n \\rightarrow \\mathbb{R}^n$.\n\n---\n\nEn este contexto el teorema de Taylor para el polinomio de grado 2 se puede escribir como: $$P_2(x) = f(x_0) + \\nabla f(x_0)^T(x-x_0) + \\frac{1}{2}(x-x_0)^T\\nabla^2f(x_0)(x-x_0) $$\n\n# Integración numérica\n\nLas reglas o métodos por cuadratura nos ayudan a aproximar integrales con sumas de la forma:\n\n$$\\displaystyle \\int_a^bf(x)dx \\approx \\displaystyle \\sum_{i=0}^nw_if(x_i)$$\n\ndonde: $w_i$ es el peso para el nodo $x_i$. Los valores $f(x_i)$ se asumen conocidos.\n\nTodas las reglas o métodos por cuadratura se obtienen con interpoladores polinomiales del integrando (por ejemplo usando la representación de Lagrange) o también con el teorema Taylor.\n\nSe realizan aproximaciones numéricas por:\n* Desconocimiento de la función en todo el intervalo $[a,b]$ y sólo se conoce en los nodos su valor.\n* Inexistencia de antiderivada o primitiva del integrando. Por ejemplo: \n\n$$\\displaystyle \\int_a^be^{-\\frac{x^2}{2}}dx$$ con $a,b$ números reales.\n\nDependiendo de la ubicación de los nodos y pesos es el método de cuadratura que resulta:\n\n* Newton-Cotes si los nodos y pesos son equidistantes como la regla del rectángulo, trapecio y Simpson (con el teorema de Taylor es posible obtener tales fórmulas).\n* Cuadratura Gaussiana si se desea obtener reglas o fórmulas que tengan la mayor exactitud posible. Ejemplos de este tipo de cuadratura se tiene la regla por cuadratura Gauss-Legendre en [-1,1] o Gauss-Hermite para el caso de integrales en $[-\\infty, \\infty]$ con integrando $e^{-x^2}f(x)$.\n\n---\n\n**Observación**\n\nCon *SymPy* también es posible calcular integrales definidas o indefinidas.\n\n\n**Integral indefinida de $\\sin(x)$:**\n\n\n```python\nx = sympy.Symbol('x')\n```\n\n\n```python\nsympy.integrate(sympy.sin(x))\n```\n\n\n\n\n$\\displaystyle - \\cos{\\left(x \\right)}$\n\n\n\n**Integral definida de: $\\displaystyle \\int_0^\\infty e^{-x}dx$:**\n\n\n```python\nsympy.integrate(sympy.exp(-x), (x, 0, sympy.oo))\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n**otra forma:**\n\n\n```python\nsympy.Integral(sympy.exp(-x), (x, 0, sympy.oo))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{0}^{\\infty} e^{- x}\\, dx$\n\n\n\n\n```python\nsympy.Integral(sympy.exp(-x), (x, 0, sympy.oo)).doit()\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n---\n\n## Newton-Cotes\n\n## Regla simple del rectángulo o del punto medio\n\nDenotaremos a esta regla como $Rf$. En este caso se aproxima el integrando $f$ por un polinomio de grado **cero** con nodo en $x_1 = \\frac{a+b}{2}$. Entonces: \n\n$$\\displaystyle \\int_a^bf(x)dx \\approx \\int_a^bf(x_1)dx = (b-a)f(x_1)=(b-a)f\\left( \\frac{a+b}{2} \\right ) = hf(x_1)$$\n\ncon $h=b-a, x_1=\\frac{a+b}{2}$.\n\n\n\n\n\n### Ejemplo de implementación de regla simple de rectángulo\n\nUtilizar la regla simple del rectángulo para aproximar la integral $\\displaystyle \\int_0^1e^{-x^2}dx \\approx 0.7468241328124271$.\n\n\n```python\nf=lambda x: math.exp(-x**2) #integrand function\n```\n\n\n```python\ndef Rf(f,a,b):\n node=(a+b)/2 #middle point\n h=b-a\n return h*f(node) #polynomial of zero degree\n```\n\n\n```python\nRf(f,0,1)\n```\n\n\n\n\n 0.7788007830714049\n\n\n\nPara contrastar con nuestra implementación usamos la función de `quad` dentro del paquete `scipy`. Ver [liga1 a quad](https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html), [liga 2 a quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html#scipy.integrate.quad) y [liga 3 a quad](https://github.com/scipy/scipy/blob/v1.4.1/scipy/integrate/quadpack.py#L44-L432) para referencias sobre `quad`.\n\n\n```python\nfrom scipy.integrate import quad\n```\n\n\n```python\nobj,err = quad(f, 0, 1)\n```\n\n\n```python\nobj\n```\n\n\n\n\n 0.7468241328124271\n\n\n\n\n```python\nerr\n```\n\n\n\n\n 8.291413475940725e-15\n\n\n\n\n```python\nrelative_absolute_error(Rf(f,0,1), obj )\n```\n\n\n\n\n 0.04281684114646715\n\n\n\n\n```python\nRf(f,0,1) == approx(obj)\n```\n\n\n\n\n False\n\n\n\n\n```python\nRf(f,0,1) == approx(obj, abs=1e-1, rel=1e-1)\n```\n\n\n\n\n True\n\n\n\n## Regla compuesta del rectángulo\n\nEn cada subintervalo construído como $[a_{i-1},a_i]$ con $i=1,\\dots,n$ se aplica la regla simple $Rf$, esto es:\n\n$$\\displaystyle \\int_{a_{i-1}}^{a_i}f(x)dx \\approx R_i(f) \\forall i=1,\\dots,n.$$\n\nDe forma sencilla se puede ver que la regla compuesta del rectángulo $R_c(f)$ se escribe:\n\n$$R_c(f) = \\displaystyle \\sum_{i=1}^n(a_i-a_{i-1})f\\left( \\frac{a_i+a_{i-1}}{2}\\right) = \\frac{h}{n}\\sum_{i=1}^nf\\left( \\frac{a_i+a_{i-1}}{2}\\right)$$\n\ncon $h=b-a$ y $n$ número de subintervalos.\n\n\n\n\n---\n\n**Nota**\n\nLos nodos para el caso del rectángulo se obtienen con la fórmula: $x_i = a +(i+\\frac{1}{2})\\hat{h}, \\forall i=0,\\dots,n-1, \\hat{h}=\\frac{h}{n}$. Por ejemplo si $a=1, b=2$ y $\\hat{h}=\\frac{1}{4}$ (por tanto $n=4$ subintervalos) entonces:\n\nLos subintervalos que tenemos son: $\\left[1,\\frac{5}{4}\\right], \\left[\\frac{5}{4}, \\frac{6}{4}\\right], \\left[\\frac{6}{4}, \\frac{7}{4}\\right]$ y $\\left[\\frac{7}{4}, 2\\right]$. \n\n\nLos nodos están dados por: \n\n$$x_0 = 1 + \\left(0 + \\frac{1}{2} \\right)\\frac{1}{4} = 1 + \\frac{1}{8} = \\frac{9}{8}$$\n\n$$x_1 = 1 + \\left(1 + \\frac{1}{2}\\right)\\frac{1}{4} = 1 + \\frac{3}{2}\\cdot \\frac{1}{4} = \\frac{11}{8}$$\n\n$$x_2 = 1 + \\left(2 + \\frac{1}{2}\\right)\\frac{1}{4} = 1 + \\frac{5}{8}\\cdot \\frac{1}{4} = \\frac{13}{8}$$\n\n$$x_3 = 1 + \\left(3 + \\frac{1}{2}\\right)\\frac{1}{4} = 1 + \\frac{7}{2}\\cdot \\frac{1}{4} = \\frac{15}{8}$$\n\n---\n\n### Ejemplo de implementación de regla compuesta de rectángulo\n\nUtilizar la regla compuesta del rectángulo para aproximar la integral $\\int_0^1e^{-x^2}dx \\approx 0.7468241328124271$.\n\n\n```python\nf=lambda x: np.exp(-x**2)\n```\n\n\n```python\ndef Rcf(f,a,b,n): #Rcf: composite rectangle method\n \"\"\"\n Compute numerical approximation using rectangle or mid-point\n method in an interval.\n Nodes are generated via formula: x_i = a+(i+1/2)h_hat for\n i=0,1,...,n-1 and h_hat=(b-a)/n\n Args:\n \n f (float): function expression of integrand.\n \n a (float): left point of interval.\n \n b (float): right point of interval.\n \n n (int): number of subintervals.\n \n Returns:\n \n sum_res (float): numerical approximation to integral\n of f in the interval a,b\n \"\"\"\n h_hat = (b-a)/n\n sum_res = 0\n for i in range(n):\n x = a+(i+1/2)*h_hat\n sum_res += f(x)\n return h_hat*sum_res\n```\n\n\n```python\na = 0\nb = 1\n```\n\n\n```python\naprox_1=Rcf(f,a,b,1) #1 subinterval\naprox_1\n```\n\n\n\n\n 0.7788007830714049\n\n\n\n\n```python\naprox_2=Rcf(f,a,b,2) #2 subintervals\naprox_2\n```\n\n\n\n\n 0.7545979437721995\n\n\n\n\n```python\naprox_3=Rcf(f,a,b,10**3)#1000 subintervals\naprox_3\n```\n\n\n\n\n 0.746824163469049\n\n\n\nY se puede evaluar el error de aproximación con el error relativo:\n\n\n```python\nobj, err = quad(f, a, b)\n(relative_absolute_error(aprox_1,obj), relative_absolute_error(aprox_2,obj), relative_absolute_error(aprox_3,obj))\n```\n\n\n\n\n (0.04281684114646715, 0.010409158754012628, 4.1049318789768585e-08)\n\n\n\n\n```python\nobj\n```\n\n\n\n\n 0.7468241328124271\n\n\n\n## Regla del trapecio\n\nDe forma sencilla se puede ver que la regla compuesta del trapecio $T_c(f)$ se escribe como:\n\n$$T_c(f) = \\displaystyle \\frac{h}{2n}\\left[f(x_0)+f(x_n)+2\\displaystyle\\sum_{i=1}^{n-1}f(x_i)\\right]$$\n\ncon $h=b-a$ y $n$ número de subintervalos.\n\n---\n\n**Nota**\n\nLos nodos para el caso del trapecio se obtienen con la fórmula: $x_i = a +i\\hat{h}, \\forall i=0,\\dots,n, \\hat{h}=\\frac{h}{n}$.\n\n---\n\n**(Tarea) Ejercicio:**\n\n**En un módulo con nombre `numerical_integration.py` aproximar el valor de la integral $\\displaystyle \\int_0^{\\pi}sin(x)dx = 2$ con regla compuesta del trapecio con $n=10^4$ subintervalos. Para este caso utilizar la función:**\n\n```\ndef Tcf(f,a,b,n): #Tcf: composite trapezoidal method for f\n \"\"\"\n Compute numerical approximation using trapezoidal method in \n an interval.\n Nodes are generated via formula: x_i = a+ih_hat for i=0,1,...,n and h_hat=(b-a)/n\n Args:\n f (function): function expression of integrand\n a (float): left point of interval\n b (float): right point of interval\n n (float): number of subintervals\n Returns:\n sum_res (float): numerical approximation to integral of f in the interval a,b\n \"\"\"\n```\n\n---\n\n## Regla de Simpson\n\n**Revisar sección 6.2 del libro de texto de J. Kiusalaas Numerical Methods in Engineering with Python 3 para la fórmula de Simpson.**\n\n## Cuadratura Gaussiana\n\nUna distinción con la cuadratura por Newton-Cotes es que en este caso los pesos y nodos se eligen para tener una regla o fórmula que integre de forma exacta a los polinomios de grado menor o igual que $2n+1$ con $n \\in \\{0,1,2,\\dots\\}$. Esto es:\n\n$$\\displaystyle \\int_a^b w(x)Q_m(x)dx = \\sum_{i=0}^nw_iQ_m(x_i)$$ con $Q_m$ polinomio de grado $m \\leq 2n+1$ y $w(x)$ función de ponderación.\n\n## Gauss-Legendre\n\nSi se elige la base canónica de polinomios $\\{1, x, x^2, \\dots x^{2n+1}\\}$, $w(x)=1$ (no ponderación), el intervalo $[-1,1]$ y la solución del siguiente sistema de ecuaciones podemos obtener la regla por cuadratura conocida con el nombre de Gauss-Legendre. \n\n---\n\n**Comentario**\n\nOtra forma de obtener esta regla es vía los polinomios de Legendre, ver [Legendre polynomials](https://en.wikipedia.org/wiki/Legendre_polynomials)\n\n---\n\nTeniendo el objetivo de integrar de forma exacta los polinomios de la base canónica para el caso de $n=1$, resultan las siguientes ecuaciones:\n\n$$2=\\displaystyle \\int_{-1}^{1}1dx = w_0 \\cdot 1 + w_1\\cdot1$$\n\n$$0 = \\displaystyle \\int_{-1}^1xdx = w_0x_0 + w_1x_1$$\n\n$$\\frac{2}{3} = \\displaystyle \\int_{-1}^1x^2dx = w_0x_0^2 + w_1x_1^2$$\n\n$$0 = \\displaystyle \\int_{-1}^1x^3dx = w_0x_0^3 + w_1x_1^3$$\n\nel cual es un sistema de 4 ecuaciones no lineales con 4 incógnitas: $(w_0, x_0), (w_1, x_1)$ cuya solución es: $w_0 = w_1 = 1$ y $x_0 =-\\sqrt{\\frac{1}{3}} \\approx -0.57735, x_1 = \\sqrt{\\frac{1}{3}} \\approx 0.57735$.\n\nYa se han calculado los pesos y nodos para diferentes valores de los grados de los polinomios. A continuación se tiene la siguiente tabla para $n \\in \\{0,1,2,3,4\\}$ y una integral definida en el intervalo $[-1,1]$:\n\n|n |grado|# (num de nodos + num de pesos)|pesos: $w_i, w_{i+1}$ |nodos: $x_i, x_{i+1}$ |\n|---|:----:|:---:|:-------:|:-----------------:|\n|0 |1|2|2|0|\n|1 |3|4|1,1|-$\\sqrt{\\frac{1}{3}}$,$\\sqrt{\\frac{1}{3}}$|\n|2 |5|6|$\\frac{5}{9}$, $\\frac{8}{9}$, $\\frac{5}{9}$ |$-\\sqrt{\\frac{3}{5}}$, 0, $\\sqrt{\\frac{3}{5}}$ |\n|3 |7|8|0.347855, 0.652145, 0.652145, 0.347855|-0.861136,-0.339981,0.339981,0.861136|\n|4 |9|10|0.236927, 0.478629, 0.568889, 0.478629, 0.236927 | -0.90618, -0.538469, 0, 0.538469, 0.90618|\n\n\nY para una integral en $[a,b]$ se utiliza la fórmula de cambio de variable:\n\n$$\\displaystyle \\int_{a}^{b}f(t)dt \\approx \\frac{(b-a)}{2} \\displaystyle \\sum_{i=0}^nw_if \\left (\\frac{1}{2}[(b-a)x_i+a+b] \\right )$$\n\ncon los pesos definidos para el intervalo $[-1,1]$\n\n### Ejemplo con la cuadratura de Gauss-Legendre utilizando dos nodos aproximar la integral $\\int_0^1e^{-t^2}dt \\approx 0.7468241328124271$\n\n**Solución:** Utilizamos $f(t) = e^{-t^2}$ en:\n\n$$\\displaystyle \\int_{a}^{b}f(t)dt \\approx \\frac{(b-a)}{2} \\displaystyle \\sum_{i=0}^nw_if \\left (\\frac{1}{2}[(b-a)x_i+a+b] \\right )$$\n\npor lo que se tiene:\n\n\n$$\n\\begin{eqnarray}\n\\int_0^1e^{-t^2}dt &=& \\frac{(1-0)}{2} \\displaystyle \\sum_{i=0}^2w_i \\cdot \\exp\\left[-\\left ({\\frac{1}{2}[(1-0)x_i + 0 + 1]} \\right) ^2 \\right] \\nonumber \\\\\n&=& \\frac{1}{2} \\left ( 1\\cdot \\exp \\left[ -\\left ( \\frac{1}{2} \\left[-\\sqrt{\\frac{1}{3}}+1 \\right] \\right)^2 \\right] + 1\\cdot \\exp \\left[ -\\left ( \\frac{1}{2} \\left[\\sqrt{\\frac{1}{3}}+1 \\right] \\right)^2 \\right] \\right) \\nonumber \\\\\n\\end{eqnarray}\n$$\n\ny haciendo los cálculos en Python:\n\n\n```python\ncte0 = -(1/2*(-math.sqrt(1/3)+1))**2\ncte1 = -(1/2*(math.sqrt(1/3)+1))**2\nw0 = 1\nw1 = 1\napprox_GL = 1/2*(w0*math.exp(cte0) + w1*math.exp(cte1))\n```\n\n\n```python\napprox_GL\n```\n\n\n\n\n 0.7465946882828597\n\n\n\n\n```python\nobj\n```\n\n\n\n\n 0.7468241328124271\n\n\n\n\n```python\nrelative_absolute_error(approx_GL, obj)\n```\n\n\n\n\n 0.00030722698890749486\n\n\n\n---\n\n**(Tarea) Ejercicio: aproximar la integral de:**\n\n$$\\displaystyle \\int_0^1e^{-\\frac{t^2}{2}}dt \\approx .855624391892149$$\n\n**con cuadratura Gauss-Legendre**\n\n**1) En el módulo `numerical_integration.py` crear la función:**\n\n```\ndef GLf(f,a,b,n): #GLf: Gauss-Legendre quadrature for f\n \"\"\"\n Compute numerical approximation using quadrature Gauss-Legendre.\n Weights and nodes are obtained with table for n=0,1,2,3,4\n Args:\n f (function): function expression of integrand\n a (float): left point of interval\n b (float): right point of interval\n n (float): number of subintervals\n Returns:\n sum_res (float): numerical approximation to integral of f in the interval a,b\n \"\"\"\n```\n\n**2) Realizar una gráfica de la forma error relativo vs $n$ ($n$ en el eje horizontal).**\n\n\n---\n\n## Otras reglas de cuadratura Gaussiana\n\nLas reglas de cuadratura Gaussiana como se escribió en la sección anterior buscan tener la mayor exactitud posible para integrar polinomios de grado menor o igual $2n+1$. Diferentes elecciones de polinomios resultan en distintas reglas. Entre las más populares se encuentran:\n\n* Gauss-Chebyshev.\n* Gauss-Laguerre.\n* Gauss-Hermite.\n* Cuadratura Gaussiana con singularidad logarítmica.\n\nY se puede probar que los nodos en la regla de cuadratura de cada una de las reglas anteriores son las raíces de los polinomios que las definen.\n\n**Revisar sección 6.4 el libro de texto de J. Kiusalaas Numerical Methods in Engineering with Python 3 para la expresiones de las reglas anteriores y los valores de los pesos y nodos de cada regla anterior para diferentes números de nodos. Como ayuda está el documento: [Gauss-Hermite-2-nodos.pdf](https://drive.google.com/file/d/1w7fGm0oOAoYlVeL_S61O1IGAdpaMBkJM/view?usp=sharing) para su consulta.**\n\n---\n\n**Ejercicio**\n\n**(Tarea) Aproximar las integrales: $$(2\\pi\\sigma^2)^{-\\frac{1}{2}}\\displaystyle \\int_{-\\infty}^\\infty te^{\\frac{-(t-\\mu)^2}{2\\sigma^2}}dt$$**\n\n$$(2\\pi\\sigma^2)^{-\\frac{1}{2}}\\displaystyle \\int_{-\\infty}^\\infty t^2e^{\\frac{-(t-\\mu)^2}{2\\sigma^2}}dt$$\n\n**donde: $\\sigma=0.25, \\mu=0.15$ cuyos valores respectivamente son: $0.15, 0.085$ con cuadratura de Gauss-Hermite y $n=5$. Para lo anterior, realizar cambio de variable $x=\\frac{t-\\mu}{\\sqrt{2\\sigma^2}}, dt=\\sqrt{2\\sigma^2}dx$. En el módulo de `numerical_integration.py` crear una función:**\n\n\n```\ndef GHf(f,mu, sigma): #GHf: Gauss-Hermite quadrature for f\n \"\"\"\n Compute numerical approximation using quadrature Gauss-Hermite.\n Weights and nodes are obtained with table in Kiusalaas for n=6\n Args:\n f (function): function expression of integrand\n mu (float): mean\n sigma (float): standard deviation\n Returns:\n sum_res (float): numerical approximation to integral of f in the interval a,b\n \"\"\"\n\n```\n\n---\n\n## Integración numérica en más dimensiones\n\n**Revisar sección 6.5 del libro de texto de J. Kiusalaas Numerical Methods in Engineering with Python 3 integrales múltiples hasta el ejemplo 6.14.**\n\n### The curse of dimensionality\n\nComo puede observarse en el desarrollo de la sección 6.5, la aproximación por integración numérica a integrales múltiples por los métodos por Newton-Cotes o cuadratura Gaussiana implican sustituir la integral $\\int$ sobre una región por una $\\sum$ y evaluaciones del integrando en un conjunto de nodos multiplicados por pesos (suma ponderada). Esto para dimensiones igual a dos o tres es viable pero para dimensiones altas no es computacionalmente práctico. \n\nLa razón de lo anterior tiene que ver con la cantidad de nodos y finalmente evaluaciones del integrando que se tienen que realizar para tener una aproximación con una exactitud aceptable. Por ejemplo, la regla del rectángulo o del trapecio tienen un error de orden $\\mathcal{O}(\\hat{h}^2)$ independientemente de si se está aproximando integrales de una o más dimensiones. \n\nSupóngase que se utilizan $n$ nodos para tener un valor de espaciado igual a $\\hat{h}$ en una dimensión, entonces para $\\mathcal{D}$ dimensiones se requerirían $N=n^\\mathcal{D}$ evaluaciones del integrando, o bien, si se tiene un valor de $N$ igual a $10, 000$ y $\\mathcal{D}=4$ dimensiones el error sería del orden $\\mathcal{O}(N^{-2/\\mathcal{D}})$ lo que implicaría un valor de $\\hat{h}=.1$ para aproximadamente sólo **dos dígitos** correctos en la aproximación (para el enunciado anterior recuérdese que $\\hat{h}$ es proporcional a $n^{-1}$ y $n$ = $N^{1/\\mathcal{D}}$). Este esfuerzo enorme de evaluar $N$ veces el integrando para una exactitud pequeña se debe al problema de generar puntos para *llenar* un espacio $\\mathcal{D}$-dimensional y se conoce con el nombre de la maldición de la dimensionalidad, [***the curse of dimensionality***](https://en.wikipedia.org/wiki/Curse_of_dimensionality).\n\nComo alternativa a los métodos por cuadratura anteriores para las integrales de más dimensiones se tienen los métodos de integración por el método Monte Carlo que generan aproximaciones con una exactitud moderada (del orden de $\\mathcal{O}(n^{-1/2})$) para un número de puntos moderado independiente de la dimensión. Tales métodos de integración son similares a los métodos por cuadratura en el sentido que se eligen puntos en los que se evaluará el integrando para sumar sus valores pero la diferencia con estos métodos, es que en el método de integración por Monte Carlo los puntos son seleccionados de una forma **aleatoria** (de hecho es pseudo-aleatoria pues se generan con un programa de computadora) en lugar de generarse con una fórmula.\n\nLos métodos por integración por Monte Carlo requieren el concepto de **variables aleatorias**.\n\n## Referencias\n\n\n* [SymPy](https://www.sympy.org/en/index.html) y [Numerical Python by Robert Johansson, Apress](https://www.apress.com/gp/book/9781484242452)\n", "meta": {"hexsha": "ba1b04f3c6b9adb27d6fc75317fe56e031ffb018", "size": 76401, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/clases/2_calculo_DeI/1_aproximacion_a_derivadas_e_integrales.ipynb", "max_stars_repo_name": "Juanes8/Propedeutico", "max_stars_repo_head_hexsha": "a6f54e3eceddd4df4deec002a6041853bf5b5497", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2019-07-07T07:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T18:17:36.000Z", "max_issues_repo_path": "Python/clases/2_calculo_DeI/1_aproximacion_a_derivadas_e_integrales.ipynb", "max_issues_repo_name": "Juanes8/Propedeutico", "max_issues_repo_head_hexsha": "a6f54e3eceddd4df4deec002a6041853bf5b5497", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2019-06-12T01:15:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-01T18:20:04.000Z", "max_forks_repo_path": "Python/clases/2_calculo_DeI/1_aproximacion_a_derivadas_e_integrales.ipynb", "max_forks_repo_name": "Juanes8/Propedeutico", "max_forks_repo_head_hexsha": "a6f54e3eceddd4df4deec002a6041853bf5b5497", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102, "max_forks_repo_forks_event_min_datetime": "2019-06-07T15:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T03:05:41.000Z", "avg_line_length": 32.6360529688, "max_line_length": 15980, "alphanum_fraction": 0.6234080706, "converted": true, "num_tokens": 10873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.15610490333452268, "lm_q1q2_score": 0.050614735615551965}} {"text": "# Funciones de utilidad y aversión al riesgo\n\nAntes de comenzar la clase, por favor entrar [este enlace](http://cursos.iteso.mx/course/view.php?id=1480)\n\n\n\nEn el módulo anterior aprendimos \n- qué es un portafolio, cómo medir su rendimiento esperado y su volatilidad; \n- un portafolio de activos riesgosos tiene menos riesgo que la suma ponderada de los riesgos individuales,\n- y que esto se logra mediante el concepto de diversificación;\n- la diversificación elimina el riesgo idiosincrático, que es el que afecta a cada compañía en particular,\n- sin embargo, el riesgo de mercado no se puede eliminar porque afecta a todos por igual.\n- Finalmente, aprendimos conceptos importantes como frontera de mínima varianza, portafolios eficientes y el portafolio de mínima varianza, que son claves en el problema de selección óptima de portafolios.\n\nMuy bien, sin embargo, para plantear el problema de selección óptima de portafolios necesitamos definir la función que vamos a optimizar: función de utilidad.\n\n**Objetivos:**\n- ¿Cómo tomamos decisiones según los economistas?\n- ¿Cómo toman decisiones los inversionistas?\n- ¿Qué son las funciones de utilidad?\n\n*Referencia:*\n- Notas del curso \"Portfolio Selection and Risk Management\", Rice University, disponible en Coursera.\n___\n\n## 1. Introducción\n\nLa teoría económica comienza con una suposición muy importante: \n- **cada individuo actúa para obtener el mayor beneficio posible con los recursos disponibles**.\n- En otras palabras, **maximizan su propia utilidad**\n\n¿Qué es utilidad?\n- Es un concepto relacionado con la felicidad, pero más amplio.\n- Por ejemplo, yo obtengo utilidad de lavar mis dientes o comer sano. Ninguna de las dos me brindan felicidad, pero lo primero mantendrá mis dientes sanos y en el largo plazo, lo segundo probablemente contribuirá a una buena vejez.\n\nLos economistas no se preocupan en realidad por lo que nos da utilidad, sino simplemente que cada uno de nosotros tiene sus propias preferencias.\n- Por ejemplo, a mi me gusta el café, el fútbol, los perros, la academia, viajar, entre otros.\n- Ustedes tienen sus propias preferencias también.\n\nLa vida es compleja y con demasiada incertidumbre. Debemos tomar decisiones a cada momento, y estas decisiones involucran ciertos \"trade-off\".\n- Por ejemplo, normalmente tenemos una compensación entre utilidad hoy contra utilidad en el futuro.\n- Debemos balancear nuestro consumo hoy contra nuestro consumo luego.\n- Por ejemplo, ustedes gastan cerca de cuatro horas a la semana viniendo a clases de portafolios, porque esperan que esto contribuya a mejorar su nivel de vida en el futuro.\n\nDe manera que los economistas dicen que cada individuo se comporta como el siguiente optimizador:\n\n\\begin{align}\n\\max & \\quad\\text{Utilidad}\\\\\n\\text{s. a.} & \\quad\\text{Recursos disponibles}\n\\end{align}\n\n¿Qué tiene que ver todo esto con el curso?\n- En este módulo desarrollaremos herramientas para describir las preferencias de los inversionistas cuando se encuentran con decisiones de riesgo y rendimiento.\n- Veremos como podemos medir la actitud frente al riesgo, ¿cuánto te gusta o disgusta el riesgo?\n- Finalmente, veremos como podemos formular el problema de maximizar la utilidad de un inversionista para tomar la decisión de inversión óptima.\n___\n\n## 2. Funciones de utilidad.\n\n¿Cómo tomamos decisiones?\nPor ejemplo:\n- Ustedes tienen que decidir si venir a clase o quedarse en su casa viendo Netflix, o ir al gimnasio.\n- Tienen que decidir entre irse de fiesta cada fin, o ahorrar para salir de vacaciones.\n\nEn el caso de un portafolio, la decisión que se debe tomar es **¿cuáto riesgo estás dispuesto a tomar por qué cantidad de rendimiento?**\n\n**¿Cómo evaluarías el \"trade-off\" entre tener cetes contra una estrategia muy riesgosa con un posible altísimo rendimiento?**\n\nDe manera que veremos como tomamos decisiones cuando tenemos distintas posibilidades. Específicamente, hablaremos acerca de las **preferencias**, como los economistas usan dichas preferencias para explicar las decisiones y los \"trade-offs\" en dichas decisiones.\n\nUsamos las **preferencias** para describir las decisiones que tomamos. Las preferencias nos dicen cómo un individuo evalúa los \"trade-offs\" entre distintas elecciones.\n\nPor definición, las preferencias son únicas para cada individuo. En el problema de selección de portafolios:\n- las preferencias que dictan cuánto riesgo estás dispuesto a asumir por cuánto rendimiento, son específicas para cada uno de ustedes.\n- Sus respuestas a esa pregunta pueden ser muy distintas, porque tenemos distintas preferencias.\n\nAhora, nosotros no podemos *cuantificar* dichas preferencias.\n- Por esto usamos el concepto de utilidad, para medir qué tan satisfecho está un individuo con sus elecciones.\n- Así que podemos pensar en la utilidad como un indicador numérico que describe las preferencias,\n- o un índice que nos ayuda a clasificar diferentes decisiones.\n- En términos simples, **la utilidad nos ayuda a transmitir a números la noción de cómo te sientes**;\n- mientras más utilidad, mejor te sientes.\n\n**Función de utilidad**: manera sistemática de asignar una medida o indicador numérico para clasificar diferentes escogencias.\n\nEl número que da una función de utilidad no tiene significado alguno. Simplemente es una manera de clasificar diferentes decisiones.\n\n**Ejemplo.**\n\nPodemos escribir la utilidad de un inversionista como función de la riqueza,\n\n$$U(W).$$\n\n- $U(W)$ nos da una medida de qué tan satisfechos estamos con el nivel de riqueza que tenemos. \n- $U(W)$ no es la riqueza como tal, sino que la función de utilidad traduce la cantidad de riqueza en un índice numérico subjetivo.\n\n¿Cómo luciría gráficamente una función de utilidad de riqueza $U(W)$?\n\n Ver en el tablero \n- ¿Qué caracteristicas debe tener?\n- ¿Cómo es su primera derivada?\n- ¿Cómo es su segunda derivada?\n- Tiempos buenos: riqueza alta (¿cómo es la primera derivada acá?)\n- Tiempos malos: poca riqueza (¿cómo es la primera derivada acá?)\n\n\n```python\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nimport numpy as np\n```\n\n\n```python\nW = np.linspace(0, 1.5, 100)\nU1 = W\nU2 = W**2\nU3 = W**0.5\n```\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(W, U1, label=r'$U_1(W)=W$')\nplt.plot(W, U2, label=r'$U_2(W)=W^2$')\nplt.plot(W, U3, label=r'$U_3(W)=\\sqrt{W}$')\nplt.grid()\nplt.legend(loc='best')\nplt.xlabel('Wealth ($W$)')\nplt.ylabel('Utility ($U$)')\n#plt.axis([0, 0.4, 0, 0.8])\n#plt.axis([1, 1.2, 1, 1.2])\n```\n\n## 3. Aversión al riesgo\n\nUna dimensión importante en la toma de decisiones en finanzas y economía es la **incertidumbre**. Probablemente no hay ninguna decisión en economía que no involucre riesgo.\n\n- A la mayoría de las personas no les gusta mucho el riesgo.\n- De hecho, estudios del comportamiento humano de cara al riesgo, sugieren fuertemente que los seres humanos somos aversos al riesgo.\n- Por ejemplo, la mayoría de hogares poseen seguros para sus activos.\n- Así, cuando planteamos el problema de selección óptima de portafolios, suponemos que el inversionista es averso al riesgo.\n\n¿Qué significa esto en términos de preferencias? ¿Cómo lo medimos?\n \n- Como seres humanos, todos tenemos diferentes genes y preferencias, y esto aplica también a la actitud frente al riesgo.\n- Por tanto, la aversión al riesgo es clave en cómo describimos las preferencias de un inversinista.\n- Individuos con un alto grado de aversión al riesgo valorarán la seguridad a un alto precio, mientras otros no tanto.\n- De manera que alguien con alta aversión al riesgo, no querrá enfrentarse a una situación con resultado incierto y querrá pagar una gran prima de seguro para eliminar dicho riesgo.\n- O equivalentemente, una persona con alta aversión al riesgo requerirá una compensación alta si se decide a asumir ese riesgo.\n\nEl **grado de aversión al riesgo** mide qué tanto un inversionista prefiere un resultado seguro a un resultado incierto.\n\nLo opuesto a aversión al riesgo es **tolerancia al riesgo**.\n \n Ver en el tablero gráficamente, cómo se explica la aversión al riesgo desde las funciones de utilidad. \n\n**Conclusión:** la concavidad en la función de utilidad dicta qué tan averso al riesgo es el individuo.\n\n\n```python\ndef straight(x1, y1, x2, y2, x):\n m = (y2 - y1) / (x2 - x1)\n return m * (x - x1) + y1\n```\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(W, U3, label=r'$U_3(W)=\\sqrt{W}$')\nx1, x2 = 0.1, 1.0\ny1, y2 = x1**0.5, x2**0.5\nplt.axvline(x=x1, ls='--', color='grey')\nplt.axvline(x=x2, ls='--', color='grey')\nplt.axhline(y=y1, ls='--', color='grey')\nplt.axhline(y=y2, ls='--', color='grey')\nplt.plot(x1, y1, '*b', ms=5)\nplt.plot(x2, y2, '*g', ms=5)\nplt.plot(0.5 * x1 + 0.5 * x2, 0.5 * y1 + 0.5 * y2, 'or', ms=5)\nplt.plot(0.5 * x1 + 0.5 * x2, (0.5 * x1 + 0.5 * x2)**0.5, 'om', ms=5)\nplt.plot(W, straight(x1, y1, x2, y2, W))\nplt.grid()\nplt.legend(loc='best')\nplt.xlabel('Wealth ($W$)')\nplt.ylabel('Utility ($U$)')\n```\n\n\n```python\n0.5 * 0.1 + 0.5 * 1.0\n```\n\n\n\n\n 0.55\n\n\n\n\n```python\n0.5 * y1 + 0.5 * y2\n```\n\n\n\n\n 0.658113883008419\n\n\n\n### ¿Cómo medimos el grado de aversión al riesgo de un individuo?\n\n¿Saben cuál es su coeficiente de aversión al riesgo? Podemos estimarlo.\n\nSuponga que se puede participar en la siguiente lotería:\n- usted puede ganar $\\$1000$ con $50\\%$ de probabilidad, o\n- puede ganar $\\$500$ con $50\\%$ de probabilidad.\n\nEs decir, de entrada usted tendrá $\\$500$ seguros pero también tiene la posibilidad de ganar $\\$1000$.\n\n¿Cuánto estarías dispuesto a pagar por esta oportunidad?\n\nBien, podemos relacionar tu respuesta con tu coeficiente de aversión al riesgo.\n\n| Coeficiente de aversión al riesgo | Cantidad que pagarías |\n| --------------------------------- | --------------------- |\n| 0 | 750 |\n| 0.5 | 729 |\n| 1 | 707 |\n| 2 | 667 |\n| 3 | 632 |\n| 4 | 606 |\n| 5 | 586 |\n| 10 | 540 |\n| 15 | 525 |\n| 20 | 519 |\n| 50 | 507 |\n\nLa mayoría de la gente está dispuesta a pagar entre $\\$540$ (10) y $\\$707$ (1). Es muy raro encontrar coeficientes de aversión al riesgo menores a 1. Esto está soportado por una gran cantidad de encuestas.\n\n- En el mundo financiero, los consultores financieros utilizan cuestionarios para medir el coeficiente de aversión al riesgo.\n\n**Ejemplo.** Describir en términos de aversión al riesgo las siguientes funciones de utilidad que dibujaré en el tablero.\n___\n\n# Anuncios\n\n## 1. Quiz la siguiente clase (pendientes del chat).\n## 2. Tarea 4 entrega 2 para hoy, viernes 13 de marzo.\n## 3. Tarea 5 entrega 2 para martes 17 de marzo.\n\n\n\n
    \nCreated with Jupyter by Esteban Jiménez Rodríguez.\n
    \n", "meta": {"hexsha": "2de917aaf2dc10f408158f5f17f90dfce65e003d", "size": 66941, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Modulo3/Clase10_FuncionesUtilidad.ipynb", "max_stars_repo_name": "Noesns/porinvp2020", "max_stars_repo_head_hexsha": "a4ddfecc3b1aa75ff9ce0c7f2708fcfc75e9ff97", "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": "Modulo3/Clase10_FuncionesUtilidad.ipynb", "max_issues_repo_name": "Noesns/porinvp2020", "max_issues_repo_head_hexsha": "a4ddfecc3b1aa75ff9ce0c7f2708fcfc75e9ff97", "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": "Modulo3/Clase10_FuncionesUtilidad.ipynb", "max_forks_repo_name": "Noesns/porinvp2020", "max_forks_repo_head_hexsha": "a4ddfecc3b1aa75ff9ce0c7f2708fcfc75e9ff97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-03T18:17:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T18:17:18.000Z", "avg_line_length": 139.751565762, "max_line_length": 25236, "alphanum_fraction": 0.8691235566, "converted": true, "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982564942392716, "lm_q2_score": 0.1943678133521021, "lm_q1q2_score": 0.050501743331318585}} {"text": "```python\nimport sys\n```\n\n\n```python\nsys.path\n```\n\n\n\n\n ['',\n '/usr/local/anaconda2/lib/python27.zip',\n '/usr/local/anaconda2/lib/python2.7',\n '/usr/local/anaconda2/lib/python2.7/plat-linux2',\n '/usr/local/anaconda2/lib/python2.7/lib-tk',\n '/usr/local/anaconda2/lib/python2.7/lib-old',\n '/usr/local/anaconda2/lib/python2.7/lib-dynload',\n '/usr/local/anaconda2/lib/python2.7/site-packages/Sphinx-1.3.5-py2.7.egg',\n '/usr/local/anaconda2/lib/python2.7/site-packages/setuptools-20.3-py2.7.egg',\n '/usr/local/anaconda2/lib/python2.7/site-packages',\n '/usr/local/anaconda2/lib/python2.7/site-packages/IPython/extensions',\n '/home/claudius/.ipython']\n\n\n\n\n```python\nimport os\n```\n\n\n```python\nos.getcwd()\n```\n\n\n\n\n '/data3/claudius/Big_Data/DADI/dadiExercises'\n\n\n\nI have cloned the $\\delta$a$\\delta$i repository into '/home/claudius/Downloads/dadi' and have compiled the code. Now I need to add that directory to the PYTHONPATH variable:\n\n\n```python\nsys.path.insert(0, '/home/claudius/Downloads/dadi')\n```\n\n\n```python\nsys.path\n```\n\n\n\n\n ['/home/claudius/Downloads/dadi',\n '',\n '/usr/local/anaconda2/lib/python27.zip',\n '/usr/local/anaconda2/lib/python2.7',\n '/usr/local/anaconda2/lib/python2.7/plat-linux2',\n '/usr/local/anaconda2/lib/python2.7/lib-tk',\n '/usr/local/anaconda2/lib/python2.7/lib-old',\n '/usr/local/anaconda2/lib/python2.7/lib-dynload',\n '/usr/local/anaconda2/lib/python2.7/site-packages/Sphinx-1.3.5-py2.7.egg',\n '/usr/local/anaconda2/lib/python2.7/site-packages/setuptools-20.3-py2.7.egg',\n '/usr/local/anaconda2/lib/python2.7/site-packages',\n '/usr/local/anaconda2/lib/python2.7/site-packages/IPython/extensions',\n '/home/claudius/.ipython']\n\n\n\nNow, I should be able to import $\\delta$a$\\delta$i\n\n\n```python\nimport dadi\n```\n\n\n```python\ndir(dadi)\n```\n\n\n\n\n ['Demographics1D',\n 'Demographics2D',\n 'Godambe',\n 'Inference',\n 'Integration',\n 'Misc',\n 'Numerics',\n 'PhiManip',\n 'Plotting',\n 'Spectrum',\n 'Spectrum_mod',\n 'Triallele',\n '__builtins__',\n '__doc__',\n '__file__',\n '__name__',\n '__package__',\n '__path__',\n 'integration_c',\n 'logging',\n 'numpy',\n 'tridiag']\n\n\n\n\n```python\nimport pylab\n```\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nx = pylab.linspace(0, 4*pylab.pi, 1000)\n```\n\n\n```python\npylab.plot(x, pylab.sin(x), '-r')\n```\n\n\n```sh\n%%sh \n# this allows me to execute a shell command\n\nls\n```\n\n ERY.FOLDED.sfs\n ERY.FOLDED.sfs.dadi_format\n ERY.FOLDED.sfs.dadi_format~\n EryPar.unfolded.2dsfs\n EryPar.unfolded.2dsfs.dadi_format\n EryPar.unfolded.2dsfs.dadi_format~\n examples\n example_YRI_CEU.ipynb\n First_Steps_with_dadi.ipynb\n new.bib\n PAR.FOLDED.sfs\n PAR.FOLDED.sfs.dadi_format\n PAR.FOLDED.sfs.dadi_format~\n\n\nI have turned the 1D folded SFS's from `realSFS` into $\\delta$d$\\delta$i format by hand according to the description in section 3.1 of the manual. I have left out the masking line from the input file.\n\n\n```python\nfs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format')\n```\n\n\n```python\nfs_ery\n```\n\n\n\n\n Spectrum([-- 7833.03869 7414.699839 4109.279415 3614.717256 3095.973324 2031.460887\n 1584.656928 2583.652317 1142.075255 1052.346021 1765.773415 1255.138799\n 1072.516527 1417.916128 395.75047 1947.087637 367.072082 --], folded=True, pop_ids=None)\n\n\n\n$\\delta$a$\\delta$i is detecting that the spectrum is folded (as given in the input file), but it is also automatically masking the 0th and 18th count category. This is a not a good behaviour.\n\n\n```python\n# number of segregating sites\n\nfs_ery.data[1:].sum()\n```\n\n\n\n\n 43649.777914000006\n\n\n\n## Single population statistics\n\n### $\\pi$\n\n\n```python\nfs_ery.pi()\n```\n\n\n\n\n 13545.692898679737\n\n\n\nI have next added a masking line to the input file, setting it to '1' for the first position, i. e. the 0-count category.\n\n\n```python\nfs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format', mask_corners=False)\n```\n\n$\\delta$a$\\delta$i is issuing the following message when executing the above command:\n\n`WARNING:Spectrum_mod:Creating Spectrum with data_folded = True, but mask is not True for all entries which are nonsensical for a folded Spectrum.`\n\n\n```python\nfs_ery\n```\n\n\n\n\n Spectrum([-- 7833.03869 7414.699839 4109.279415 3614.717256 3095.973324 2031.460887\n 1584.656928 2583.652317 1142.075255 1052.346021 1765.773415 1255.138799\n 1072.516527 1417.916128 395.75047 1947.087637 367.072082 966.622924], folded=True, pop_ids=None)\n\n\n\nI do not understand this warning from $\\delta$a$\\delta$i. The 18-count category is sensical for a folded spectrum with even sample size, so should not be masked. Anyway, I do not understand why $\\delta$a$\\delta$i is so reluctant to keep all positions, including the non-variable one.\n\n\n```python\nfs_ery.pi()\n```\n\n\n\n\n 13545.692898679737\n\n\n\nThe function that returns $\\pi$ produces the same output with or without the last count category masked ?! I think that is because even if the last count class (966.62...) is masked, it is still included in the calculation of $\\pi$. However, there is no obvious unmasking in the `pi` function. Strange!\n\nThere are (at least) two formulas that allow the calculation of $\\pi$ from a folded sample allele frequency spectrum. One is given in Wakeley2009, p.16, equation (1.4):\n$$\n\\pi = \\frac{1}{n \\choose 2} \\sum_{i=1}^{n/2} i(n-i)\\eta_{i}\n$$\nHere, $n$ is the number of sequences and $\\eta_{i}$ is the SNP count in the i'th minor sample allele frequency class.\n\nThe other formula is on p. 45 in Gillespie \"Population Genetics - A concise guide\":\n$$\n\\hat{\\pi} = \\frac{n}{n-1} \\sum_{i=1}^{S_{n}} 2 \\hat{p_{i}}(1-\\hat{p_{i}})\n$$\nThis is the formula that $\\delta$a$\\delta$i's `pi` function uses, with the modification that it multiplies each $\\hat{p_{i}}$ by the count in the i'th class of the SFS, i. e. the sum is not over all SNP's but over all SNP frequency classes.\n\n\n```python\n# Calcualting pi with the formula from Wakeley2009\n\nn = 36 # 36 sequences sampled from 18 diploid individuals\npi_Wakeley = (sum( [i*(n-i)*fs_ery[i] for i in range(1, n/2+1)] ) * 2.0 / (n*(n-1)))/pylab.sum(fs_ery.data)\n# note fs_ery.data gets the whole fs_ery list, including masked entries\npi_Wakeley\n```\n\n\n\n\n 0.0065187712427359126\n\n\n\nThis is the value of $\\pi_{site}$ that I calculated previously and included in the first draft of the thesis.\n\n\n```python\nfs_ery.mask\n```\n\n\n\n\n array([ True, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False, False], dtype=bool)\n\n\n\n\n```python\nfs_ery.data # gets all data, including the masked one\n```\n\n\n\n\n array([ 1.59481822e+06, 7.83303869e+03, 7.41469984e+03,\n 4.10927941e+03, 3.61471726e+03, 3.09597332e+03,\n 2.03146089e+03, 1.58465693e+03, 2.58365232e+03,\n 1.14207525e+03, 1.05234602e+03, 1.76577342e+03,\n 1.25513880e+03, 1.07251653e+03, 1.41791613e+03,\n 3.95750470e+02, 1.94708764e+03, 3.67072082e+02,\n 9.66622924e+02])\n\n\n\n\n```python\n# Calculating pi with the formula from Gillespie:\n\nn = 18 \np = pylab.arange(0, n+1)/float(n)\np\n```\n\n\n\n\n array([ 0. , 0.05555556, 0.11111111, 0.16666667, 0.22222222,\n 0.27777778, 0.33333333, 0.38888889, 0.44444444, 0.5 ,\n 0.55555556, 0.61111111, 0.66666667, 0.72222222, 0.77777778,\n 0.83333333, 0.88888889, 0.94444444, 1. ])\n\n\n\n\n```python\n# Calculating pi with the formula from Gillespie:\n\nn / (n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p))\n```\n\n\n\n\n 13545.692898679737\n\n\n\nThis is the same as the output of dadi's `pi` function on the same SFS. \n\n\n```python\n# the sample size (n) that dadi stores in this spectrum object and uses as n in the pi function\nfs_ery.sample_sizes[0]\n```\n\n\n\n\n 18\n\n\n\n\n```python\n# what is the total number of sites in the spectrum\npylab.sum(fs_ery.data)\n```\n\n\n\n\n 1638467.9999990002\n\n\n\nSo, 1.6 million sites went into the ery spectrum.\n\n\n```python\n# pi per site\nn / (n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data)\n```\n\n\n\n\n 0.0082672917009596787\n\n\n\nApart from the incorrect small sample size correction by $\\delta$a$\\delta$i in case of folded spectra ($n$ refers to sampled sequences, not individuals), Gillespie's formula leads to a much higher estimate of $\\pi_{site}$ than Wakeley's. Why is that?\n\n\n```python\n# with correct small sample size correction\n2 * n / (2* n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data)\n```\n\n\n\n\n 0.0080310833666465443\n\n\n\n\n```python\n# Calculating pi with the formula from Gillespie:\n\nn = 18 \np = pylab.arange(0, n+1)/float(n)\np = p/2 # with a folded spectrum, we are summing over minor allele freqs only\npi_Gillespie = 2*n / (2*n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data)\npi_Gillespie\n```\n\n\n\n\n 0.0065187712427359117\n\n\n\n\n```python\npi_Wakeley - pi_Gillespie\n```\n\n\n\n\n 8.6736173798840355e-19\n\n\n\nAs can be seen from the insignificant difference (must be due to numerical inaccuracies) between the $\\pi_{Wakeley}$ and the $\\pi_{Gillespie}$ estimates, they are equivalent with the calculation for folded spectra given above as well as the correct small sample size correction. **Beware: $\\delta$a$\\delta$i does not handle folded spectra correctly**.\n\nIt should be a relatively easy to fix the `pi` function to work correctly with folded spectra. Care should be taken to also correctly handle uneven sample sizes.\n\n\n```python\nfs_ery.folded\n```\n\n\n\n\n True\n\n\n\nI think for now it would be best to import unfolded spectra from `realSFS` and fold them if necessary in dadi.\n\n\n```python\nfs_par = dadi.Spectrum.from_file('PAR.FOLDED.sfs.dadi_format')\n```\n\n\n```python\npylab.plot(fs_ery, 'r', label='ery')\npylab.plot(fs_par, 'g', label='par')\npylab.legend()\n```\n\n---\n\n### ML estimate of $\\theta$ from 1D folded spectrum\n\nI am trying to fit eq. 4.21 of Wakeley2009 to the oberseved 1D folded spectra.\n\n$$\nE[\\eta_i] = \\theta \\frac{\\frac{1}{i} + \\frac{1}{n-i}}{1+\\delta_{i,n-i}} \\qquad 1 \\le i \\le \\big[n/2\\big]\n$$\n\nEach frequency class, $\\eta_i$, provides an estimate of $\\theta$. However, I would like to find the value of $\\theta$ that minimizes the deviation of the above equation from all observed counts $\\eta_i$.\n\nI am following the example given here: https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#example-of-solving-a-fitting-problem\n\n$$\n\\frac{\\delta E}{\\delta \\theta} = \\frac{\\frac{1}{i} + \\frac{1}{n-i}}{1+\\delta_{i,n-i}} \\qquad 1 \\le i \\le \\big[n/2\\big]\n$$\n\nI have just one parameter to optimize.\n\n\n```python\nfrom scipy.optimize import least_squares\n```\n\n\n```python\ndef model(theta, eta, n):\n \"\"\"\n theta: scaled population mutation rate parameter [scalar]\n eta: the folded 1D spectrum, including 0-count cat. [list] \n n: number of sampled gene copies, i. e. 2*num_ind [scalar]\n \n returns a numpy array\n \"\"\"\n i = pylab.arange(1, eta.size)\n delta = pylab.where(i == n-i, 1, 0)\n return theta * 1/i + 1/(n-i) / (1 + delta)\n```\n\n\n```python\n?pylab.where\n```\n\n\n```python\n# test\ni = pylab.arange(1, 19)\nn = 36\nprint i == n-i\n#\nprint pylab.where(i == n-i, 1, 0)\n# get a theta estimate from pi:\ntheta = pi_Wakeley * fs_ery.data.sum() \nprint theta\n#\nprint len(fs_ery)\n#\nmodel(theta, fs_ery, 36)\n```\n\n [False False False False False False False False False False False False\n False False False False False True]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]\n 10680.7980805\n 19\n\n\n\n\n\n array([ 10680.79808054, 5340.39904027, 3560.26602685, 2670.19952013,\n 2136.15961611, 1780.13301342, 1525.82829722, 1335.09976007,\n 1186.75534228, 1068.07980805, 970.98164369, 890.06650671,\n 821.59985235, 762.91414861, 712.05320537, 667.54988003,\n 628.28224003, 593.37767114])\n\n\n\n\n```python\ndef fun(theta, eta, n):\n \"\"\"\n return residuals between model and data\n \"\"\"\n return model(theta, eta, n) - eta[1:]\n```\n\n\n```python\ndef jac(theta, eta, n, test=False):\n \"\"\"\n creates a Jacobian matrix\n \"\"\"\n J = pylab.empty((eta.size-1, theta.size))\n i = pylab.arange(1, eta.size, dtype=float)\n delta = pylab.where(i == n-i, 1, 0)\n num = 1/i + 1/(n-i)\n den = 1 + delta\n if test:\n print i\n print num\n print den\n J[:,0] = num / den\n return J\n```\n\n\n```python\n# test\njac(theta, fs_ery, 36, test=True)\n```\n\n [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.\n 16. 17. 18.]\n [ 1.02857143 0.52941176 0.36363636 0.28125 0.23225806 0.2\n 0.1773399 0.16071429 0.14814815 0.13846154 0.13090909 0.125\n 0.12040134 0.11688312 0.11428571 0.1125 0.11145511 0.11111111]\n [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2]\n\n\n\n\n\n array([[ 1.02857143],\n [ 0.52941176],\n [ 0.36363636],\n [ 0.28125 ],\n [ 0.23225806],\n [ 0.2 ],\n [ 0.1773399 ],\n [ 0.16071429],\n [ 0.14814815],\n [ 0.13846154],\n [ 0.13090909],\n [ 0.125 ],\n [ 0.12040134],\n [ 0.11688312],\n [ 0.11428571],\n [ 0.1125 ],\n [ 0.11145511],\n [ 0.05555556]])\n\n\n\n\n```python\n# starting value\ntheta0 = theta # pi_Wakeley from above\n```\n\n\n```python\n# sum over unmasked entries, i. e. without 0-count category, i. e. returns number of variable sites\nfs_ery.sum()\n```\n\n\n\n\n 43649.777914000006\n\n\n\n\n```python\n# optimize\nres = least_squares(fun, x0=theta0, jac=jac, bounds=(0,fs_ery.sum()), \n kwargs={'eta': fs_ery, 'n': 36}, verbose=1)\n```\n\n Both `ftol` and `xtol` termination conditions are satisfied.\n Function evaluations: 8, initial cost: 9.6784e+06, final cost 9.5162e+06, first-order optimality 1.08e-01.\n\n\n\n```python\nres.success\n```\n\n\n\n\n True\n\n\n\n\n```python\n?least_squares\n```\n\n\n```python\nprint res.x\nprint theta\n```\n\n [ 10367.32782801]\n 10680.7980805\n\n\n\n```python\npylab.rcParams['figure.figsize'] = [12.0, 8.0]\n```\n\n\n```python\nimport matplotlib.pyplot as plt\n\nplt.rcParams['font.size'] = 14.0\n\ni = range(1, len(fs_ery))\neta_model = model(res.x, eta=fs_ery, n=36) # get predicted values with optimal theta\n\nplt.plot(i, fs_ery[1:], \"bo\", label=\"data from ery\") # plot observed spectrum\n\nymax = max( fs_ery[1:].max(), eta_model.max() )\nplt.axis([0, 19, 0, ymax*1.1]) # set axis range\n\nplt.xlabel(\"minor allele frequency (i)\")\nplt.ylabel(r'$\\eta_i$', fontsize='large', rotation='horizontal')\nplt.title(\"folded SFS of ery\")\n\nplt.plot(i, eta_model, \"go-\", \n label=\"\\nneutral model\" \n + \"\\n\"\n + r'$\\theta_{opt} = $' + str(round(res.x, 1))\n ) # plot model prediction with optimal theta\n\nplt.legend()\n```\n\nThe counts in each frequency class should be Poisson distributed with rate equal to $E[\\eta_i]$ as given above. The lowest frequency class has the highest rate and therefore also the highest variance\n\n\n```python\n#?plt.ylabel\n```\n\n\n```python\n#print plt.rcParams\n```\n\n\n```python\nfs_ery[1:].max()\n```\n\n\n\n\n 7833.0386900000003\n\n\n\n\n```python\n#?pylab\n```\n\n\n```python\nos.getcwd()\n```\n\n\n\n\n '/data3/claudius/Big_Data/DADI/dadiExercises'\n\n\n\n\n```sh\n%%sh\n\nls\n```\n\n ERY.FOLDED.sfs\n ERY.FOLDED.sfs.dadi_format\n ERY.FOLDED.sfs.dadi_format~\n EryPar.unfolded.2dsfs\n EryPar.unfolded.2dsfs.dadi_format\n EryPar.unfolded.2dsfs.dadi_format~\n examples\n example_YRI_CEU.ipynb\n First_Steps_with_dadi.ipynb\n new.bib\n PAR.FOLDED.sfs\n PAR.FOLDED.sfs.dadi_format\n PAR.FOLDED.sfs.dadi_format~\n\n\nThe following function will take the file name of a file containing the flat 1D folded frequency spectrum of one population and plots it together with the best fitting neutral expectation.\n\n\n```python\ndef plot_folded_sfs(filename, n, pop = ''):\n # read in spectrum from file\n data = open(filename, 'r')\n sfs = pylab.array( data.readline().split(), dtype=float )\n data.close() # should close connection to file\n #return sfs\n \n # get starting value for theta from Watterson's theta\n S = sfs[1:].sum()\n T_total = sum([1.0/i for i in range(1, n)]) # onhe half the expected total length of the genealogy\n theta0 = S / T_total # see eq. 4.7 in Wakeley2009\n \n # optimize\n res = least_squares(fun, x0=theta0, jac=jac, bounds=(0, sfs.sum()), \n kwargs={'eta': sfs, 'n': 36}, verbose=1)\n #print \"Optimal theta per site is {0:.4f}\".format(res.x[0]/sfs.sum())\n #print res.x[0]/sfs.sum()\n \n #return theta0, res\n \n # plot\n plt.rcParams['font.size'] = 14.0\n\n i = range(1, len(sfs))\n eta_model = model(res.x, eta=sfs, n=36) # get predicted values with optimal theta\n\n plt.plot(i, sfs[1:], \"rs\", label=\"data of \" + pop) # plot observed spectrum\n\n ymax = max( sfs[1:].max(), eta_model.max() )\n plt.axis([0, 19, 0, ymax*1.1]) # set axis range\n\n plt.xlabel(\"minor allele frequency (i)\")\n plt.ylabel(r'$\\eta_i$', fontsize='large', rotation='horizontal')\n plt.title(\"folded SFS\")\n plt.text(5, 10000, \n r\"Optimal neutral $\\theta$ per site is {0:.4f}\".format(res.x[0]/sfs.sum()))\n\n plt.plot(i, eta_model, \"go-\", \n label=\"\\nneutral model\" \n + \"\\n\"\n + r'$\\theta_{opt} = $' + str(round(res.x, 1))\n ) # plot model prediction with optimal theta\n\n plt.legend()\n```\n\n\n```python\nplot_folded_sfs('PAR.FOLDED.sfs', n=36, pop='par')\n```\n\n\n```python\nplot_folded_sfs('ERY.FOLDED.sfs', n=36, pop='ery')\n```\n\n### Univariate function minimizers or 1D scalar minimisation\n\nSince I only have one value to optimize, I can use a slightly simpler approach than used above:\n\n\n```python\nfrom scipy.optimize import minimize_scalar\n```\n\n\n```python\n?minimize_scalar\n```\n\n\n```python\n# define cost function\ndef f(theta, eta, n):\n \"\"\"\n return sum of squared deviations between model and data\n \"\"\"\n return sum( (model(theta, eta, n) - eta[1:])**2 ) # see above for definition of the 'model' function\n```\n\nIt would be interesting to know whether the cost function is convex or not.\n\n\n```python\ntheta = pylab.arange(0, fs_ery.data[1:].sum()) # specify range of theta\ncost = [f(t, fs_ery.data, 36) for t in theta]\nplt.plot(theta, cost, 'b-', label='ery')\nplt.xlabel(r'$\\theta$')\nplt.ylabel('cost')\nplt.title(\"cost function for ery\")\nplt.legend(loc='best')\n```\n\n\n```python\n?plt.legend\n```\n\nWithin the specified bounds (the observed $\\theta$, i. e. derived from the data, cannot lie outside these bounds), the cost function is convex. This is therefore an easy optimisation problem. See [here](http://www.scipy-lectures.org/advanced/mathematical_optimization/index.html) for more details.\n\n\n```python\nres = minimize_scalar(f, bounds = (0, fs_ery.data[1:].sum()), method = 'bounded', args = (fs_ery.data, 36))\n```\n\n\n```python\nres\n```\n\n\n\n\n fun: 18987280.758395974\n message: 'Solution found.'\n nfev: 6\n status: 0\n success: True\n x: 10198.886010965949\n\n\n\n\n```python\n# number of segregating sites\n\nfs_par.data[1:].sum()\n```\n\n\n\n\n 43755.705189\n\n\n\n\n```python\nres = minimize_scalar(f, bounds = (0, fs_par.data[1:].sum()), method = 'bounded', args = (fs_par.data, 36))\n```\n\n\n```python\nres\n```\n\n\n\n\n fun: 60127046.281448714\n message: 'Solution found.'\n nfev: 6\n status: 0\n success: True\n x: 11828.17091399114\n\n\n\nThe fitted values of $\\theta$ are similar to the ones obtained above with the `least_squares` function. The estimates for ery deviate more than for par.\n\n\n```python\nfrom sympy import *\n```\n\n\n```python\nx0 , x1 = symbols('x0 x1')\n```\n\n\n```python\ninit_printing(use_unicode=True)\n```\n\n\n```python\ndiff(0.5*(1-x0)**2 + (x1-x0**2)**2, x0)\n```\n\n\n```python\ndiff(0.5*(1-x0)**2 + (x1-x0**2)**2, x1)\n```\n\nWow! Sympy is a replacement for Mathematica. There is also Sage, which may include even more functionality.\n\n\n```python\nfrom scipy.optimize import curve_fit\n```\n\n`Curve_fit` is another function that can be used for optimization.\n\n\n```python\n?curve_fit\n```\n\n\n```python\ndef model(i, theta):\n \"\"\"\n i: indpendent variable, here minor SNP frequency classes\n theta: scaled population mutation rate parameter [scalar]\n \n returns a numpy array\n \"\"\"\n n = len(i)\n delta = pylab.where(i == n-i, 1, 0)\n return theta * 1/i + 1/(n-i) / (1 + delta)\n```\n\n\n```python\ni = pylab.arange(1, fs_ery.size)\n\npopt, pcov = curve_fit(model, i, fs_ery.data[1:])\n```\n\n\n```python\n# optimal theta\nprint popt\n```\n\n [ 10198.84901849]\n\n\n\n```python\nperr = pylab.sqrt(pcov)\nperr\n```\n\n\n\n\n array([[ 837.89916279]])\n\n\n\n\n```python\nprint str(int(popt[0] - 1.96*perr[0])) + ' < ' + str(int(popt[0])) + ' < ' + str(int(popt[0] + 1.96*perr[0]))\n```\n\n 8556 < 10198 < 11841\n\n\n\n```python\npopt, pcov = curve_fit(model, i, fs_par.data[1:])\nperr = pylab.sqrt(pcov)\nprint str(int(popt[0] - 1.96*perr[0])) + ' < ' + str(int(popt[0])) + ' < ' + str(int(popt[0] + 1.96*perr[0]))\n```\n\n 8905 < 11828 < 14750\n\n\nI am not sure whether these standard errors (perr) are correct. It may be that it is assumed that errors are normally distributed, which they are not exactly in this case. They should be close to Poisson distributed (see Fu1995), which should be fairly similar to normal with such high expected values as here.\n\nIf the standard errors are correct, then the large overlap of the 95% confidence intervals would indicate that the data do not provide significant support for a difference in $\\theta$ between par and ery.\n\n## Parametric bootstrap from the observed SFS\n\n\n```python\n%pwd\n```\n\n\n\n\n u'/data3/claudius/Big_Data/DADI/dadiExercises'\n\n\n\n\n```python\n% ll\n```\n\n total 660\r\n lrwxrwxrwx 1 claudius 53 Feb 17 15:37 \u001b[0m\u001b[01;36mERY.FOLDED.sfs\u001b[0m -> /data3/claudius/Big_Data/ANGSD/SFS/ERY/ERY.FOLDED.sfs\r\n -rw-rw-r-- 1 claudius 462 Mar 15 12:48 ERY.FOLDED.sfs.dadi_format\r\n -rw-rw-r-- 1 claudius 462 Mar 15 12:45 ERY.FOLDED.sfs.dadi_format~\r\n lrwxrwxrwx 1 claudius 37 Feb 18 17:46 \u001b[01;36mEryPar.unfolded.2dsfs\u001b[0m -> ../../ANGSD/FST/EryPar.unfolded.2dsfs\r\n -rw-rw-r-- 1 claudius 13051 Feb 18 19:00 EryPar.unfolded.2dsfs.dadi_format\r\n -rw-rw-r-- 1 claudius 13051 Feb 18 18:31 EryPar.unfolded.2dsfs.dadi_format~\r\n drwxrwxr-x 5 claudius 4096 Feb 17 13:45 \u001b[01;34mexamples\u001b[0m/\r\n -rw-rw-r-- 1 claudius 18014 Mar 15 21:39 example_YRI_CEU.ipynb\r\n -rw-rw-r-- 1 claudius 596246 Mar 17 15:45 First_Steps_with_dadi.ipynb\r\n -rw-rw-r-- 1 claudius 1012 Mar 16 09:54 new.bib\r\n lrwxrwxrwx 1 claudius 53 Feb 17 15:37 \u001b[01;36mPAR.FOLDED.sfs\u001b[0m -> /data3/claudius/Big_Data/ANGSD/SFS/PAR/PAR.FOLDED.sfs\r\n -rw-rw-r-- 1 claudius 412 Feb 17 16:29 PAR.FOLDED.sfs.dadi_format\r\n -rw-rw-r-- 1 claudius 218 Feb 17 15:51 PAR.FOLDED.sfs.dadi_format~\r\n\n\n\n```python\n! cat ERY.FOLDED.sfs.dadi_format\n```\n\n # this is the ML estimate of the folded sample frequency spectrum for erythropus, estimated with realSFS of ANGSD\r\n # this is the spectrum in dadi format (see section 3.1 of the manual)\r\n 19 folded\r\n 1594818.222085 7833.038690 7414.699839 4109.279415 3614.717256 3095.973324 2031.460887 1584.656928 2583.652317 1142.075255 1052.346021 1765.773415 1255.138799 1072.516527 1417.916128 395.750470 1947.087637 367.072082 966.622924 \r\n 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n\n\n\n```python\nfs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format', mask_corners=False)\n```\n\n\n```python\nfs_ery\n```\n\n\n\n\n Spectrum([-- 7833.03869 7414.699839 4109.279415 3614.717256 3095.973324 2031.460887\n 1584.656928 2583.652317 1142.075255 1052.346021 1765.773415 1255.138799\n 1072.516527 1417.916128 395.75047 1947.087637 367.072082 966.622924], folded=True, pop_ids=None)\n\n\n\n\n```python\nfs_ery.pop_ids = ['ery']\n```\n\n\n```python\n# get a Poisson sample from the observed spectrum\n\nfs_ery_param_boot = fs_ery.sample()\n```\n\n\n```python\nfs_ery_param_boot\n```\n\n\n\n\n Spectrum([-- 7727.0 7286.0 4114.0 3578.0 3064.0 2051.0 1574.0 2532.0 1177.0 1083.0\n 1722.0 1219.0 1025.0 1382.0 403.0 1910.0 377.0 --], folded=True, pop_ids=['ery'])\n\n\n\n\n```python\nfs_ery_param_boot.data\n```\n\n\n\n\n array([ 0., 7727., 7286., 4114., 3578., 3064., 2051., 1574.,\n 2532., 1177., 1083., 1722., 1219., 1025., 1382., 403.,\n 1910., 377., 933.])\n\n\n\n\n```python\n%psource fs_ery.sample\n```\n\n**There must be a way to get more than one bootstrap sample per call.**\n\n\n```python\nfs_ery_param_boot = pylab.array([fs_ery.sample() for i in range(100)])\n```\n\n\n```python\n# get the first 3 boostrap samples from the doubleton class\n\nfs_ery_param_boot[:3, 2]\n```\n\n\n\n\n array([ 7274., 7463., 7430.])\n\n\n\nIt would be good to get the 5% and 95% quantiles from the bootstrap samples of each frequency class and add those intervals to the plot of the observed frequency spectrum and the fitted neutral spectrum. This would require to find a quantile function and to find out how to add lines to a plot with matplotlib.\n\nIt would also be good to use the predicted counts from the neutral model above with the fitted $\\theta$ as parameters for the bootstrap with `sample()` and add 95% confidence intervals to the predicted neutral SFS. I have done this in R instead (see `/data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd`)\n\n---\n\n### Using unfolded spectra\n\nI edited the 2D SFS created for estimating $F_{ST}$ by `realSFS`. I have convinced myself that `realSFS` outputs a flattened 2D matrix as expected by $\\delta$a$\\delta$i's `Spectrum.from_file` function (see section 3.1 of the manual with my comments). Note, that in the manual, \"samples\" stands for number of allele copies, so that the correct specification of dimensions for this 2D unfolded SFS of 18 diploid individuals in each of 2 populations is 37 x 37.\n\n\n```python\n# read in the flattened 2D SFS\nEryPar_unfolded_2dsfs = dadi.Spectrum.from_file('EryPar.unfolded.2dsfs.dadi_format', mask_corners=True)\n```\n\n\n```python\n# check dimension\nlen(EryPar_unfolded_2dsfs[0,])\n```\n\n\n```python\nEryPar_unfolded_2dsfs.sample_sizes\n```\n\n\n\n\n array([36, 36])\n\n\n\n\n```python\n# add population labels\nEryPar_unfolded_2dsfs.pop_ids = [\"ery\", \"par\"]\n```\n\n\n```python\nEryPar_unfolded_2dsfs.pop_ids\n```\n\n\n\n\n ['ery', 'par']\n\n\n\n### Marginalizing\n\n$\\delta$a$\\delta$i offers a function to get the marginal spectra from multidimensional spectra. Note, that this marginalisation is nothing fancy. In `R` it would be taking either the `rowSums` or the `colSums` of the matrix.\n\n\n```python\n# marginalise over par to get 1D SFS for ery\n\nfs_ery = EryPar_unfolded_2dsfs.marginalize([1]) \n# note the argument is an array with dimensions, one can marginalise over more than one dimension at the same time,\n# but that is only interesting for 3-dimensional spectra, which I don't have here\n```\n\n\n```python\nfs_ery\n```\n\n\n\n\n Spectrum([-- 5504.293033999999 4934.276604000001 2566.124531 2396.011968\n 1553.2582019999998 1297.416363 841.8906099999998 1361.1500360000002\n 488.49162899999993 610.185385 845.894307 475.48793400000005 845.864915\n 171.41514700000002 661.7809339999999 260.92126999999994 332.462328\n 577.679207 212.03316999999998 469.402014 197.154764 399.04286399999995\n 113.996089 335.46549500000003 260.04657000000003 223.011465 236.792219\n 329.313785 346.363423 120.226742 505.32778799999994 230.19171200000002\n 451.244682 407.265961 600.9017859999999 --], folded=False, pop_ids=['ery'])\n\n\n\n\n```python\n# marginalise over ery to get 1D SFS for par\nfs_par = EryPar_unfolded_2dsfs.marginalize([0])\n```\n\n\n```python\nfs_par\n```\n\n\n\n\n Spectrum([-- 7797.888484000002 10825.498380000005 4798.473355000001 2640.397539\n 2157.0349559999995 1011.531934 726.7379290000001 1698.623407 493.287427\n 453.03942799999993 816.1893790000003 677.1919899999999 266.613834\n 327.9128799999999 449.9266600000001 452.58292199999994 123.233246\n 385.56443 478.09934499999997 216.15979699999997 269.61825899999997\n 169.752214 219.371672 467.7375149999999 234.94620899999998\n 230.09612900000002 244.87403099999997 160.987576 226.845337\n 466.00908100000004 505.19249 273.09656199999995 269.669384 549.555371\n 336.129774 --], folded=False, pop_ids=['par'])\n\n\n\nNote, that these marginalised 1D SFS's are not identical to the 1D SFS estimated directly with `realSFS`. This is because, for the estimation of the 2D SFS, `realSFS` has only taken sites that had data from at least 9 individuals in *each* population (see `assembly.sh`, lines 1423 onwards).\n\nThe SFS's of par and ery had conspicuous shape differences. It would therefore be good to plot them to see, whether the above commands have done the correct thing.\n\n\n```python\n# plot 1D spectra for each population\npylab.plot(fs_par, 'g', label=\"par\")\npylab.plot(fs_ery, 'r', label=\"ery\")\npylab.legend()\n```\n\nThese marginal unfolded spectra look similar in shape to the 1D folded spectra of each subspecies (see above).\n\n\n```python\nfs_ery.pi() / pylab.sum(fs_ery.data)\n```\n\n\n```python\nfs_ery.data\n```\n\n\n\n\n array([ 27952.979034, 5504.293034, 4934.276604, 2566.124531,\n 2396.011968, 1553.258202, 1297.416363, 841.89061 ,\n 1361.150036, 488.491629, 610.185385, 845.894307,\n 475.487934, 845.864915, 171.415147, 661.780934,\n 260.92127 , 332.462328, 577.679207, 212.03317 ,\n 469.402014, 197.154764, 399.042864, 113.996089,\n 335.465495, 260.04657 , 223.011465, 236.792219,\n 329.313785, 346.363423, 120.226742, 505.327788,\n 230.191712, 451.244682, 407.265961, 600.901786,\n 1458.220459])\n\n\n\n\n```python\nn = 36 # 36 sequences sampled from 18 diploid individuals\npi_Wakeley = (sum( [i*(n-i)*fs_ery[i] for i in range(1, n)] ) * 2.0 / (n*(n-1)))\npi_Wakeley = pi_Wakeley / pylab.sum(fs_ery.data)\npi_Wakeley\n```\n\n$\\delta$a$\\delta$i's `pi` function seems to calculate the correct value of $\\pi$ for this unfolded spectrum. However, it is worrying that $\\pi$ from this marginal spectrum is about 20 times larger than the one calculated from the directly estimated 1D folded spectrum (see above the $\\pi$ calculated from the folded 1D spectrum). \n\n\n```python\nfs_par.pi() / pylab.sum(fs_par.data)\n```\n\n\n```python\npylab.sum(fs_par.data)\n```\n\n\n```python\npylab.sum(EryPar_unfolded_2dsfs.data)\n```\n\nThe sum over the marginalised 1D spectra should be the same as the sum over the 2D spectrum !\n\n\n```python\n# from dadi's marginalise function:\nfs_ery.data\n```\n\n\n\n\n array([ 27952.979034, 5504.293034, 4934.276604, 2566.124531,\n 2396.011968, 1553.258202, 1297.416363, 841.89061 ,\n 1361.150036, 488.491629, 610.185385, 845.894307,\n 475.487934, 845.864915, 171.415147, 661.780934,\n 260.92127 , 332.462328, 577.679207, 212.03317 ,\n 469.402014, 197.154764, 399.042864, 113.996089,\n 335.465495, 260.04657 , 223.011465, 236.792219,\n 329.313785, 346.363423, 120.226742, 505.327788,\n 230.191712, 451.244682, 407.265961, 600.901786,\n 1458.220459])\n\n\n\n\n```python\nsfs2d = EryPar_unfolded_2dsfs.copy()\n```\n\n\n```python\n# this should get the marginal spectrum for ery\nery_mar = [pylab.sum(sfs2d.data[i]) for i in range(0, len(sfs2d))]\nery_mar\n```\n\n\n```python\n# this should get the marginal spectrum for ery and then take the sum over it\nsum([pylab.sum(sfs2d.data[i]) for i in range(0, len(sfs2d))])\n```\n\n\n```python\n# look what happens if I include masking\nsum([pylab.sum(sfs2d[i]) for i in range(0, len(sfs2d))])\n```\n\n\n```python\nfs_ery.data - ery_mar\n```\n\n\n\n\n array([ -1.06991366e+06, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n -2.87751595e+02])\n\n\n\nSo, during the marginalisation the masking of data in the fixed categories (0, 36) is the problem, producing incorrectly marginalised counts in those masked categories. This is shown in the following:\n\n\n```python\nsfs2d[0]\n```\n\n\n\n\n Spectrum([-- 6546.449601 9367.767974 3791.122626 1749.224237 1598.038967 656.869675\n 412.970591 974.236078 142.404132 211.95951 521.906868 156.263585 5.346426\n 159.363508 220.258071 175.985792 19.108475 57.580136 167.053354 34.227901\n 87.965634 46.427042 86.934511 141.736163 52.391344 3.808952 47.21001\n 11.204495 38.908948 74.130926 0.03966 46.362627 39.973018 59.216701\n 1.520393 247.011103], folded=False, pop_ids=['ery', 'par'])\n\n\n\n\n```python\npylab.sum(sfs2d[0])\n```\n\n\n```python\n# from dadi's marginalise function:\nfs_ery.data\n```\n\n\n\n\n array([ 27952.979034, 5504.293034, 4934.276604, 2566.124531,\n 2396.011968, 1553.258202, 1297.416363, 841.89061 ,\n 1361.150036, 488.491629, 610.185385, 845.894307,\n 475.487934, 845.864915, 171.415147, 661.780934,\n 260.92127 , 332.462328, 577.679207, 212.03317 ,\n 469.402014, 197.154764, 399.042864, 113.996089,\n 335.465495, 260.04657 , 223.011465, 236.792219,\n 329.313785, 346.363423, 120.226742, 505.327788,\n 230.191712, 451.244682, 407.265961, 600.901786,\n 1458.220459])\n\n\n\n\n```python\n# dividing by the correct number of sites to get pi per site:\nfs_ery.pi() / pylab.sum(sfs2d.data)\n```\n\nThis is very close to the estimate of $\\pi$ derived from the folded 1D spectrum of ery! (see above)\n\n\n```python\nfs_par.pi() / pylab.sum(sfs2d.data)\n```\n\nThis is also nicely close to the estimate of $\\pi_{site}$ of par from its folded 1D spectrum.\n\n---\n\n### Tajima's D\n\n\n```python\nfs_ery.Watterson_theta() / pylab.sum(sfs2d.data)\n```\n\n\n```python\nfs_ery.Tajima_D()\n```\n\n\n```python\nfs_par.Tajima_D()\n```\n\nNow, I am calculating Tajima's D from the ery marginal spectrum by hand in order to check whether $\\delta$a$\\delta$i is doing the right thing.\n\n\n```python\nn = 36\npi_Wakeley = (sum( [i*(n-i)*fs_ery.data[i] for i in range(1, n+1)] ) \n * 2.0 / (n*(n-1)))\n #/ pylab.sum(sfs2d.data)\npi_Wakeley\n```\n\n\n```python\n# number of segregating sites\n# this sums over all unmasked positions in the array\npylab.sum(fs_ery)\n```\n\n\n```python\nfs_ery.S()\n```\n\n\n```python\nS = pylab.sum(fs_ery)\ntheta_Watterson = S / pylab.sum(1.0 / (pylab.arange(1, n)))\ntheta_Watterson\n```\n\n\n```python\n# normalizing constant, see page 45 in Gillespie\na1 = pylab.sum(1.0 / pylab.arange(1, n))\n#print a1\na2 = pylab.sum(1.0 / pylab.arange(1, n)**2.0)\n#print a2\nb1 = (n+1.0)/(3.0*(n-1))\n#print b1\nb2 = 2.0*(n**2 + n + 3)/(9.0*n*(n-1))\n#print b2\nc1 = b1 - (1.0/a1)\n#print c1\nc2 = b2 - (n+2.0)/(a1*n) + a2/a1**2\n#print c2\nC = ((c1/a1)*S + (c2/(a1**2.0 + a2))*S*(S-1))\nC = C**(1/2.0)\n```\n\n\n```python\nery_Tajimas_D = (pi_Wakeley - theta_Watterson) / C\nprint '{0:.6f}'.format(ery_Tajimas_D)\n```\n\n -0.054767\n\n\n\n```python\nery_Tajimas_D - fs_ery.Tajima_D()\n```\n\n$\\delta$a$\\delta$i seems to do the right thing. Note, that the estimate of Tajima's D from this marginal spectrum of ery is slightly different from the estimate derived from the folded 1D spectrum of ery (see /data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd). The folded 1D spectrum resulted in a Tajima's D estimate of $\\sim$0.05, i. e. a difference of almost 0.1. Again, the 2D spectrum is based on only those sites for which there were at least 9 individiuals with data in *both* populations, whereas the 1D folded spectrum of ery included all sites for which there were 9 ery individuals with data (see line 1571 onwards in `assembly.sh`).\n\n\n```python\nfs_par.Tajima_D()\n```\n\nMy estimate from the folded 1D spectrum of par was -0.6142268 (see /data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd). \n\n### Multi-population statistics\n\n\n```python\nEryPar_unfolded_2dsfs.S()\n```\n\nThe 2D spectrum contains counts from 60k sites that are variable in *par* or *ery* or both.\n\n\n```python\nEryPar_unfolded_2dsfs.Fst()\n```\n\nThis estimate of $F_{ST}$ according to Weir and Cockerham (1984) is well below the estimate of $\\sim$0.3 from ANGSD according to Bhatia/Hudson (2013). Note, however, that this estimate showed a positive bias of around 0.025 in 100 permutations of population labels of individuals. Taking the positive bias into account, both estimates of $F_{ST}$ are quite similar.\n\nThe following function `scramble_pop_ids` should generate a 2D SFS with counts as if individuals were assigned to populations randomly. Theoretically, the $F_{ST}$ calculated from this SFS should be 0.\n\n\n```python\n%psource EryPar_unfolded_2dsfs.scramble_pop_ids\n```\n\n\n```python\n# plot the scrambled 2D SFS\n\ndadi.Plotting.plot_single_2d_sfs(EryPar_unfolded_2dsfs.scramble_pop_ids(), vmin=1)\n```\n\nSo, this is how the 2D SFS would look like if _ery_ and _par_ were not genetically differentiated.\n\n\n```python\n# get Fst for scrambled SFS\n\nEryPar_unfolded_2dsfs.scramble_pop_ids().Fst()\n```\n\nThe $F_{ST}$ from the scrambled SFS is much lower than the $F_{ST}$ of the observed SFS. That should mean that there is significant population structure. However, the $F_{ST}$ from the scrambled SFS is not 0. I don't know why that is.\n\n\n```python\n\n```\n\n---\n\n\n```python\n# folding\n\nEryPar_folded_2dsfs = EryPar_unfolded_2dsfs.fold()\n```\n\n\n```python\nEryPar_folded_2dsfs\n```\n\n\n\n\n Spectrum([[-- 6651.315570000001 9534.20133 ..., 59.216701 19.075761999999997\n 208.9562905]\n [4407.352191 453.932731 409.549382 ..., 3.9669600000000003\n 4.851331999999999 --]\n [3746.5561820000003 295.73506799999996 261.799583 ..., 1e-06 -- --]\n ..., \n [26.699661 1.593931 1e-06 ..., -- -- --]\n [78.253372 4.851332 -- ..., -- -- --]\n [208.9562905 -- -- ..., -- -- --]], folded=True, pop_ids=['ery', 'par'])\n\n\n\n\n```python\nEryPar_folded_2dsfs.mask\n```\n\n\n\n\n array([[ True, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, True],\n [False, False, False, ..., False, True, True],\n ..., \n [False, False, False, ..., True, True, True],\n [False, False, True, ..., True, True, True],\n [False, True, True, ..., True, True, True]], dtype=bool)\n\n\n\n### Plotting\n\n\n```python\ndadi.Plotting.plot_single_2d_sfs(EryPar_unfolded_2dsfs, vmin=1)\n```\n\n\n```python\ndadi.Plotting.plot_single_2d_sfs(EryPar_folded_2dsfs, vmin=1)\n```\n\nThe folded 2D spectrum is *not* a minor allele frequency spectrum as are the 1D folded spectra of ery and par. This is because an allele that is minor in one population can be the major allele in the other. What is not counted are the alleles that are major in *both* populations, i. e. the upper right corner.\n\nFor the 2D spectrum to make sense it is crucial that allele frequencies are polarised the same way in both populations, either with an outgroup sequence or arbitrarily with respect to the reference sequence (as I did here).\n\n#### How to fold a 1D spectrum\n\n\n```python\n# unfolded spectrum from marginalisation of 2D unfolded spectrum\nfs_ery\n```\n\n\n\n\n Spectrum([-- 5504.293033999999 4934.276604000001 2566.124531 2396.011968\n 1553.2582019999998 1297.416363 841.8906099999998 1361.1500360000002\n 488.49162899999993 610.185385 845.894307 475.48793400000005 845.864915\n 171.41514700000002 661.7809339999999 260.92126999999994 332.462328\n 577.679207 212.03316999999998 469.402014 197.154764 399.04286399999995\n 113.996089 335.46549500000003 260.04657000000003 223.011465 236.792219\n 329.313785 346.363423 120.226742 505.32778799999994 230.19171200000002\n 451.244682 407.265961 600.9017859999999 --], folded=False, pop_ids=['ery'])\n\n\n\n\n```python\nlen(fs_ery)\n```\n\n\n```python\nfs_ery.fold()\n```\n\n\n\n\n Spectrum([-- 6105.194819999999 5341.542565000001 3017.369213 2626.2036799999996\n 2058.5859899999996 1417.643105 1188.2540329999997 1690.4638210000003\n 725.2838479999999 833.19685 1105.940877 810.9534290000001 959.861004\n 570.4580109999999 858.9356979999999 730.323284 544.495498 577.679207 -- --\n -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --], folded=True, pop_ids=['ery'])\n\n\n\nLet's use the formula (1.2) from Wakeley2009 to fold the 1D spectrum manually:\n$$\n\\eta_{i} = \\frac{\\zeta_{i} + \\zeta_{n-i}}{1 + \\delta_{i, n-i}} \\qquad 1 \\le i \\le [n/2]\n$$\n$n$ is the number of gene copies sampled, i. e. haploid sample size. $[n/2]$ is the largest integer less than or equal to n/2 (to handle uneven sample sizes). $\\zeta_{i}$ are the unfolded frequencies and $\\delta_{i, n-i}$ is Kronecker's $\\delta$ which is 1 if $i = n-i$ and zero otherwise (to avoid counting the unfolded n/2 frequency class twice with even sample sizes).\n\n\n```python\nfs_ery_folded = fs_ery.copy() # make a copy of the UNfolded spectrum\nn = len(fs_ery)-1\nfor i in range(len(fs_ery)):\n fs_ery_folded[i] += fs_ery[n-i]\n if i == n/2.0:\n fs_ery_folded[i] /= 2\nfs_ery_folded[0:19]\n```\n\n\n\n\n Spectrum([-- 6105.194819999999 5341.542565000001 3017.369213 2626.2036799999996\n 2058.5859899999996 1417.643105 1188.2540329999997 1690.4638210000003\n 725.2838479999999 833.19685 1105.940877 810.9534290000001 959.861004\n 570.4580109999999 858.9356979999999 730.323284 544.495498 577.679207], folded=False, pop_ids=['ery'])\n\n\n\n\n```python\nisinstance(fs_ery_folded, pylab.ndarray)\n```\n\n\n\n\n True\n\n\n\n\n```python\nmask = [True] \nmask.extend([False] * 18)\nmask.extend([True] * 18)\nprint mask\nprint sum(mask)\n```\n\n [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]\n 19\n\n\n\n```python\nmask = [True] * 37\nfor i in range(len(mask)):\n if i > 0 and i < 19:\n mask[i] = False\nprint mask\nprint sum(mask)\n```\n\n [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]\n 19\n\n\nHere is how to flatten an array of arrays with list comprehension:\n\n\n```python\nmask = [[True], [False] * 18, [True] * 18]\nprint mask\n```\n\n [[True], [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False], [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]]\n\n\n\n```python\nprint [elem for a in mask for elem in a]\n```\n\n [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]\n\n\nSet new mask for the folded spectrum:\n\n\n```python\nfs_ery_folded.mask = mask\n```\n\n\n```python\nfs_ery_folded.folded = True\n```\n\n\n```python\nfs_ery_folded - fs_ery.fold()\n```\n\n\n\n\n Spectrum([-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n -- -- -- -- -- -- -- -- -- -- -- --], folded=True, pop_ids=['ery'])\n\n\n\nThe `fold()` function works correctly for 1D spectra, at least. How about 2D spectra?\n\n$$\n\\eta_{i,j} = \\frac{\\zeta_{i,j} + \\zeta_{n-i, m-j}}{1 + \\delta_{i, n-i; j, m-j}} \n \\qquad 1 \\le i+j \\le \\Big[\\frac{n+m}{2}\\Big]\n$$\n\n\n```python\nEryPar_unfolded_2dsfs.sample_sizes\n```\n\n\n\n\n array([36, 36])\n\n\n\n\n```python\nEryPar_unfolded_2dsfs._total_per_entry()\n```\n\n\n\n\n array([[ 0, 1, 2, ..., 34, 35, 36],\n [ 1, 2, 3, ..., 35, 36, 37],\n [ 2, 3, 4, ..., 36, 37, 38],\n ..., \n [34, 35, 36, ..., 68, 69, 70],\n [35, 36, 37, ..., 69, 70, 71],\n [36, 37, 38, ..., 70, 71, 72]])\n\n\n\n\n```python\n# copy the unfolded 2D spectrum for folding\nimport copy\nsfs2d_folded = copy.deepcopy(EryPar_unfolded_2dsfs)\n```\n\n\n```python\nn = len(sfs2d_folded)-1\nm = len(sfs2d_folded[0])-1\nfor i in range(n+1):\n for j in range(m+1):\n sfs2d_folded[i,j] += sfs2d_folded[n-i, m-j]\n if i == n/2.0 and j == m/2.0:\n sfs2d_folded[i,j] /= 2\n```\n\n\n```python\nmask = sfs2d_folded._total_per_entry() > (n+m)/2\nmask\n```\n\n\n\n\n array([[False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, True],\n [False, False, False, ..., False, True, True],\n ..., \n [False, False, False, ..., True, True, True],\n [False, False, True, ..., True, True, True],\n [False, True, True, ..., True, True, True]], dtype=bool)\n\n\n\n\n```python\nsfs2d_folded.mask = mask\nsfs2d_folded.fold = True\n```\n\n\n```python\ndadi.Plotting.plot_single_2d_sfs(sfs2d_folded, vmin=1)\n```\n\nI am going to go through every step in the `fold` function of dadi:\n\n\n```python\n# copy the unfolded 2D spectrum for folding\nimport copy\nsfs2d_unfolded = copy.deepcopy(EryPar_unfolded_2dsfs)\n```\n\n\n```python\ntotal_samples = pylab.sum(sfs2d_unfolded.sample_sizes)\ntotal_samples\n```\n\n\n```python\ntotal_per_entry = dadi.Spectrum(sfs2d_unfolded._total_per_entry(), pop_ids=['ery', 'par'])\n#total_per_entry.pop_ids = ['ery', 'par']\ndadi.Plotting.plot_single_2d_sfs(total_per_entry, vmin=1)\n```\n\n\n```python\ntotal_per_entry = sfs2d_unfolded._total_per_entry()\ntotal_per_entry\n```\n\n\n\n\n array([[ 0, 1, 2, ..., 34, 35, 36],\n [ 1, 2, 3, ..., 35, 36, 37],\n [ 2, 3, 4, ..., 36, 37, 38],\n ..., \n [34, 35, 36, ..., 68, 69, 70],\n [35, 36, 37, ..., 69, 70, 71],\n [36, 37, 38, ..., 70, 71, 72]])\n\n\n\n\n```python\nwhere_folded_out = total_per_entry > total_samples/2\nwhere_folded_out\n```\n\n\n\n\n array([[False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, True],\n [False, False, False, ..., False, True, True],\n ..., \n [False, False, False, ..., True, True, True],\n [False, False, True, ..., True, True, True],\n [False, True, True, ..., True, True, True]], dtype=bool)\n\n\n\n\n```python\noriginal_mask = sfs2d_unfolded.mask\noriginal_mask\n```\n\n\n\n\n array([[ True, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, False],\n ..., \n [False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, True]], dtype=bool)\n\n\n\n\n```python\npylab.logical_or([True, False, True], [False, False, True])\n```\n\n\n\n\n array([ True, False, True], dtype=bool)\n\n\n\n\n```python\n# get the number of elements along each axis\nsfs2d_unfolded.shape\n```\n\n\n```python\n[slice(None, None, -1) for i in sfs2d_unfolded.shape]\n```\n\n\n\n\n [slice(None, None, -1), slice(None, None, -1)]\n\n\n\n\n```python\nmatrix = pylab.array([\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]\n])\nreverse_slice = [slice(None, None, -1) for i in matrix.shape]\nreverse_slice\n```\n\n\n\n\n [slice(None, None, -1), slice(None, None, -1)]\n\n\n\n\n```python\nmatrix[reverse_slice]\n```\n\n\n\n\n array([[12, 11, 10, 9],\n [ 8, 7, 6, 5],\n [ 4, 3, 2, 1]])\n\n\n\n\n```python\nmatrix[::-1,::-1]\n```\n\n\n\n\n array([[12, 11, 10, 9],\n [ 8, 7, 6, 5],\n [ 4, 3, 2, 1]])\n\n\n\nWith the variable length list of slice objects, one can generalise the reverse of arrays with any dimensions.\n\n\n```python\nfinal_mask = pylab.logical_or(original_mask, dadi.Numerics.reverse_array(original_mask))\nfinal_mask\n```\n\n\n\n\n array([[ True, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, False],\n ..., \n [False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, True]], dtype=bool)\n\n\n\nHere, folding doesn't mask new cells.\n\n\n```python\n?pylab.where\n```\n\n\n```python\npylab.where(matrix < 6, matrix, 0)\n```\n\n\n\n\n array([[1, 2, 3, 4],\n [5, 0, 0, 0],\n [0, 0, 0, 0]])\n\n\n\n\n```python\n# this takes the part of the spectrum that is non-sensical if the derived allele is not known\n# and sets the rest to 0\nprint pylab.where(where_folded_out, sfs2d_unfolded, 0)\n```\n\n [[ 0. 0. 0. ..., 0. 0. 0. ]\n [ 0. 0. 0. ..., 0. 0. 33.96861 ]\n [ 0. 0. 0. ..., 0. 1.593931\n 26.499772]\n ..., \n [ 0. 0. 0. ..., 21.754621 30.856007\n 232.64872 ]\n [ 0. 0. 3.966959 ..., 16.189377 19.283053\n 298.187262]\n [ 0. 17.555369 0. ..., 166.433356 104.865969\n 287.751595]]\n\n\n\n```python\n# let's plot the bit of the spectrum that we are going to fold onto the rest:\ndadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(pylab.where(where_folded_out, sfs2d_unfolded, 0)), vmin=1)\n```\n\n\n```python\n# now let's reverse this 2D array, i. e. last row first and last element of each row first:\n_reversed = dadi.Numerics.reverse_array(pylab.where(where_folded_out, sfs2d_unfolded, 0))\n_reversed\n```\n\n\n\n\n array([[ 287.751595, 104.865969, 166.433356, ..., 0. ,\n 17.555369, 0. ],\n [ 298.187262, 19.283053, 16.189377, ..., 3.966959,\n 0. , 0. ],\n [ 232.64872 , 30.856007, 21.754621, ..., 0. ,\n 0. , 0. ],\n ..., \n [ 26.499772, 1.593931, 0. , ..., 0. ,\n 0. , 0. ],\n [ 33.96861 , 0. , 0. , ..., 0. ,\n 0. , 0. ],\n [ 0. , 0. , 0. , ..., 0. ,\n 0. , 0. ]])\n\n\n\n\n```python\ndadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(_reversed), vmin=1)\n```\n\nThe transformation we have done with the upper-right diagonal 2D array above should be identical to projecting it across a vertical center line (creating an upper left triangular matrix) and then projecting it across a horizontal center line (creating the final lower left triangular matrix). Note, that this is not like mirroring the upper-right triangular 2D array across the 36-36 diagonal!\n\n\n```python\n# This shall now be added to the original unfolded 2D spectrum.\nsfs2d_folded = pylab.ma.masked_array(sfs2d_unfolded.data + _reversed) \n```\n\n\n```python\ndadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(sfs2d_folded), vmin=1)\n```\n\n\n```python\nsfs2d_folded.data\n```\n\n\n\n\n array([[ 1.07020142e+06, 6.65131557e+03, 9.53420133e+03, ...,\n 5.92167010e+01, 1.90757620e+01, 2.47011103e+02],\n [ 4.40735219e+03, 4.53932731e+02, 4.09549382e+02, ...,\n 3.96696000e+00, 9.70266300e+00, 3.39686100e+01],\n [ 3.74655618e+03, 2.95735068e+02, 2.61799583e+02, ...,\n 2.00000000e-06, 1.59393100e+00, 2.64997720e+01],\n ..., \n [ 2.66996610e+01, 1.59393100e+00, 0.00000000e+00, ...,\n 2.17546210e+01, 3.08560070e+01, 2.32648720e+02],\n [ 7.82533720e+01, 1.00000000e-06, 3.96695900e+00, ...,\n 1.61893770e+01, 1.92830530e+01, 2.98187262e+02],\n [ 1.70901478e+02, 1.75553690e+01, 0.00000000e+00, ...,\n 1.66433356e+02, 1.04865969e+02, 2.87751595e+02]])\n\n\n\n\n```python\nsfs2d_folded.data[where_folded_out] = 0\nsfs2d_folded.data\n```\n\n\n\n\n array([[ 1.07020142e+06, 6.65131557e+03, 9.53420133e+03, ...,\n 5.92167010e+01, 1.90757620e+01, 2.47011103e+02],\n [ 4.40735219e+03, 4.53932731e+02, 4.09549382e+02, ...,\n 3.96696000e+00, 9.70266300e+00, 0.00000000e+00],\n [ 3.74655618e+03, 2.95735068e+02, 2.61799583e+02, ...,\n 2.00000000e-06, 0.00000000e+00, 0.00000000e+00],\n ..., \n [ 2.66996610e+01, 1.59393100e+00, 0.00000000e+00, ...,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n [ 7.82533720e+01, 1.00000000e-06, 0.00000000e+00, ...,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n [ 1.70901478e+02, 0.00000000e+00, 0.00000000e+00, ...,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]])\n\n\n\n\n```python\ndadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(sfs2d_folded), vmin=1)\n```\n\n\n```python\nsfs2d_folded.shape\n```\n\n\n```python\nwhere_ambiguous = (total_per_entry == total_samples/2.0)\nwhere_ambiguous\n```\n\n\n\n\n array([[False, False, False, ..., False, False, True],\n [False, False, False, ..., False, True, False],\n [False, False, False, ..., True, False, False],\n ..., \n [False, False, True, ..., False, False, False],\n [False, True, False, ..., False, False, False],\n [ True, False, False, ..., False, False, False]], dtype=bool)\n\n\n\nSNP's with joint frequencies in the True cells are counted twice at the moment due to the folding and the fact that the sample sizes are even.\n\n\n```python\n# this extracts the diagonal values from the UNfolded spectrum and sets the rest to 0\nambiguous = pylab.where(where_ambiguous, sfs2d_unfolded, 0)\ndadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(ambiguous), vmin=1)\n```\n\nThese are the values in the diagonal before folding.\n\n\n```python\nreversed_ambiguous = dadi.Numerics.reverse_array(ambiguous)\ndadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(reversed_ambiguous), vmin=1)\n```\n\nThese are the values that got added to the diagonal during folding. Comparing with the previous plot, one can see for instance that the value in the (0, 36) class got added to the value in the (36, 0) class and vice versa. The two frequency classes are equivalent, since it is arbitrary which allele we call minor in the total sample (of 72 gene copies). These SNP's are therefore counted twice.\n\n\n```python\na = -1.0*ambiguous + 0.5*ambiguous + 0.5*reversed_ambiguous\nb = -0.5*ambiguous + 0.5*reversed_ambiguous\na == b\n```\n\n\n\n\n array([[ True, True, True, ..., True, True, True],\n [ True, True, True, ..., True, True, True],\n [ True, True, True, ..., True, True, True],\n ..., \n [ True, True, True, ..., True, True, True],\n [ True, True, True, ..., True, True, True],\n [ True, True, True, ..., True, True, True]], dtype=bool)\n\n\n\n\n```python\nsfs2d_folded += -0.5*ambiguous + 0.5*reversed_ambiguous\n```\n\n\n```python\nfinal_mask = pylab.logical_or(final_mask, where_folded_out)\nfinal_mask\n```\n\n\n\n\n array([[ True, False, False, ..., False, False, False],\n [False, False, False, ..., False, False, True],\n [False, False, False, ..., False, True, True],\n ..., \n [False, False, False, ..., True, True, True],\n [False, False, True, ..., True, True, True],\n [False, True, True, ..., True, True, True]], dtype=bool)\n\n\n\n\n```python\nsfs2d_folded = dadi.Spectrum(sfs2d_folded, mask=final_mask, data_folded=True, pop_ids=['ery', 'par'])\n```\n\n\n```python\npylab.rcParams['figure.figsize'] = [12.0, 8.0]\n```\n\n\n```python\ndadi.Plotting.plot_single_2d_sfs(sfs2d_folded, vmin=1)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n---\n\n### Model specification\n\n\n```python\n\n```\n", "meta": {"hexsha": "ec84c1e57785dba75f10d0b99dbfbe9afb5d3bfe", "size": 619669, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb", "max_stars_repo_name": "claudiuskerth/PhDthesis", "max_stars_repo_head_hexsha": "66cb32c9bc481af8f80cd971e35cdc56717a60de", "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": "Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb", "max_issues_repo_name": "claudiuskerth/PhDthesis", "max_issues_repo_head_hexsha": "66cb32c9bc481af8f80cd971e35cdc56717a60de", "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": "Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb", "max_forks_repo_name": "claudiuskerth/PhDthesis", "max_forks_repo_head_hexsha": "66cb32c9bc481af8f80cd971e35cdc56717a60de", "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": 118.528882938, "max_line_length": 41194, "alphanum_fraction": 0.8654991616, "converted": true, "num_tokens": 19123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.13117321866710235, "lm_q1q2_score": 0.05049016489601431}} {"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# AdaBoost\n\n## The gist\n\nAdaBoost, shortening for *adaptive boosting* is a boosting ensemble method used both in classification and in regression problems. The authors won the Goedel prize for the work in 2003, whose original paper is in [[1]](#paper) but a nice reading over the general idea, by the same authors is in [[2]](#boosting-gentle).\n\nThe idea is to fit a sequence of weak learners (a weak learner is one that is just slightly better than a random guesser) on repeatedly modified versions of the training set, then combine their predictions through a weighted majority voting system. \n\nIn the first iteration, you give the same weight to all $n$ training samples, $w_i = \\frac{1}{n}$; in successive iterations the weights are modified in such a way that the training samples which were incorrectly predicted in the previous iteration will see their weights increased while those which were correctly predicted will see their weights decreased. This way, the weak learner is forced to focus on the points more difficult to predict: this is the adaptive part of the idea. The resulting combination of these weak learners will be a strong learner. \n\nAs per current literature, AdaBoost with decision trees as the learners is considered one of the best classifiers.\n\n## The algorithm\n\nThis part follows [the Wikipedia page](https://en.wikipedia.org/wiki/AdaBoost). Let's see we have a binary classification problem, class variables being $y_i \\in \\{1, -1\\}$ and sample points $(x_1, y_1), \\ldots, (x_n, y_n)$, where $x_i \\in X$ (feature matrix).\n\n* Call a weak learner $h$\n* At iteration $t$, you'll have built a combination of weak learners into a strong learner\n\n$$\nH_t(x_i) = \\sum_{i=1}^t \\alpha_i h_i(x_i) \\ ,\n$$\n\nso that\n\n$$\nH_t(x_i) = H_{t-1}(x_i) + \\alpha_t h_t(x_i)\n$$\n\nThis way we have built a linear combination of weak learners over several iterations. The weights $\\alpha_i$ of each learner remain to be attributed in the most effective way. If we consider the error $E$ on $H_t$ as the sum of the exponential losses on each data point, \n\n$$\nE = \\sum_{i=1}^n e^{-y_i H_t(x_i)}\n$$\n\n(note that the argument of the exponential will be a 1 if the point is well classified and a -1 if not) which by posing $w_i^1 = 1$ and $w_i^t = e^{-y_i H_{t-1}(x_i)}$ ($w_i$ represents a weight to the error) we can rewrite as\n\n$$\nE = \\sum_{i=1}^n w_i^t e^{-y_i \\alpha_t h_t(x_i)} \\ .\n$$\n\nWe can now split the sum between the points which are well classified and those misclassified:\n\n$$\n\\begin{align}\n E &= \\sum_{i: y_i = h_t(x_i)} w_i^t e^{-\\alpha_t} + \\sum_{i: y_i \\neq h_t(x_i)} w_i^t e^{\\alpha^t} \\\\\n &= \\sum_{i=1}^n w_i^t e^{-\\alpha_t} + \\sum_{i: y_i \\neq h_t(x_i)} w_i^t [e^\\alpha_t - e^{-\\alpha_t}]\n\\end{align}\n$$\n\nIn the last expression above, the only part depending on the weak classifiers is the second sum, so the weak classifier that minimises $E$ is the one minimising this sum, which means the one that minimises $\\sum_{i: y_i \\neq h_t(x_i)} w_i^t$, so the one with the lowest weighted error.\n\nIf we derive $E$ with respect to $\\alpha_t$, we obtain \n\n$$\n\\alpha_t = \\frac{1}{2} \\log{\\frac{\\sum_{i: y_i = h_t(x_i)} w_i^t}{\\sum_{i: y_i \\neq h_t(x_i)} w_i^t}}\n$$\n\nNow, the weighted error rate of the weak classifiers is\n\n$$\n\\epsilon_t = \\frac{\\sum_{i: y_i \\neq h_t(x_i)} w_i^t}{\\sum_{i=1}^n w_i^t} \\ ,\n$$\n\nso it follows that we can write the $\\alpha_t$ which minimises $E$ as\n\n$$\n\\alpha_t = \\frac{1}{2} \\log{\\frac{1-\\epsilon_t}{\\epsilon_t}}\n$$\n\nwhich is $\\frac{1}{2}$ times the logit negative function. \n\nTo summarise then, the AdaBoost algorithm consists of\n\n1. Choose the weak classifier which minimised the error $E$\n2. Use it to compute the classifiers weighted error $\\epsilon_t$\n3. Use this to compute the weights $\\alpha_t$\n4. use this to compute the boosted (strong) classifier $H_t$\n\nNote that there exist several variants of the original AdaBoost. \n\n## References\n\n1. Y Freund, R E Schapire, [**A decision-theoretic generalization of on-line learning and an application to boosting**](http://cns.bu.edu/~gsc/CN710/FreundSc95.pdf), *J of computer and system sciences* 55.1, 1997\n2. Y Freund, R E Schapire, [**A short introduction to boosting**](https://cseweb.ucsd.edu/~yfreund/papers/IntroToBoosting.pdf)\n\n\n```python\n\n```\n", "meta": {"hexsha": "5ff4a63b54000b049a07bf98af35a40eb28cc207", "size": 9185, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ml-algorithms/supervised/adaboost.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/adaboost.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/adaboost.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": 37.4897959184, "max_line_length": 569, "alphanum_fraction": 0.5375068046, "converted": true, "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421495978593415, "lm_q2_score": 0.17106118533966355, "lm_q1q2_score": 0.05032875976564334}}